@remnic/core 9.7.14 → 9.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (950) hide show
  1. package/dist/access-admin-ops-surface.d.ts +13 -6
  2. package/dist/access-admin-ops-surface.js +88 -74
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-boundary.d.ts +35 -17
  5. package/dist/access-boundary.js +89 -77
  6. package/dist/access-citation.d.ts +28 -0
  7. package/dist/access-citation.js +9 -0
  8. package/dist/access-cli.js +197 -181
  9. package/dist/access-cli.js.map +1 -1
  10. package/dist/access-errors.d.ts +16 -1
  11. package/dist/access-errors.js +7 -3
  12. package/dist/access-http.d.ts +25 -19
  13. package/dist/access-http.js +103 -90
  14. package/dist/access-identity-continuity-surface.d.ts +13 -8
  15. package/dist/access-identity-continuity-surface.js +88 -74
  16. package/dist/access-lcm-surface.d.ts +16 -9
  17. package/dist/access-lcm-surface.js +88 -74
  18. package/dist/access-mcp.d.ts +23 -16
  19. package/dist/access-mcp.js +99 -87
  20. package/dist/access-memory-search-fanout.d.ts +93 -0
  21. package/dist/access-memory-search-fanout.js +18 -0
  22. package/dist/access-observe-write-surface.d.ts +26 -8
  23. package/dist/access-observe-write-surface.js +88 -74
  24. package/dist/access-operations-batch.js +95 -83
  25. package/dist/access-operations.d.ts +26 -19
  26. package/dist/access-operations.js +97 -85
  27. package/dist/access-recall-concurrency.d.ts +250 -0
  28. package/dist/access-recall-concurrency.js +157 -0
  29. package/dist/access-recall-response.d.ts +130 -0
  30. package/dist/access-recall-response.js +147 -0
  31. package/dist/access-recall-surface.d.ts +15 -7
  32. package/dist/access-recall-surface.js +88 -74
  33. package/dist/access-schema.d.ts +34 -34
  34. package/dist/access-schema.js +8 -6
  35. package/dist/{access-service-CPhSnLOH.d.ts → access-service-DEL4qCrc.d.ts} +25 -32
  36. package/dist/access-service.d.ts +13 -6
  37. package/dist/access-service.js +92 -75
  38. package/dist/access-surface-catalog.d.ts +23 -16
  39. package/dist/access-surface-catalog.js +1 -0
  40. package/dist/access-surface-catalog.js.map +1 -1
  41. package/dist/access-token-capabilities.d.ts +2 -1
  42. package/dist/access-token-capabilities.js +4 -2
  43. package/dist/action-confidence.d.ts +3 -1
  44. package/dist/active-memory-bridge.d.ts +3 -1
  45. package/dist/active-memory-bridge.js +4 -4
  46. package/dist/active-recall.d.ts +4 -1
  47. package/dist/active-recall.js +23 -13
  48. package/dist/active-recall.js.map +1 -1
  49. package/dist/adapters/index.js +4 -4
  50. package/dist/adapters/registry.js +2 -2
  51. package/dist/{auto-sync-AAMTVZMK.js → auto-sync-UZG3XQZ5.js} +14 -8
  52. package/dist/{auto-sync-AAMTVZMK.js.map → auto-sync-UZG3XQZ5.js.map} +1 -1
  53. package/dist/behavior-learner.d.ts +3 -1
  54. package/dist/behavior-signals.d.ts +3 -1
  55. package/dist/bootstrap.d.ts +12 -7
  56. package/dist/bootstrap.js +2 -2
  57. package/dist/bounded-jsonl-state.d.ts +54 -0
  58. package/dist/bounded-jsonl-state.js +10 -0
  59. package/dist/boxes.js +2 -2
  60. package/dist/briefing.d.ts +5 -2
  61. package/dist/briefing.js +37 -27
  62. package/dist/buffer-surprise-report.d.ts +3 -1
  63. package/dist/buffer.d.ts +60 -2
  64. package/dist/buffer.js +3 -3
  65. package/dist/bulk-import/index.d.ts +5 -3
  66. package/dist/calibration.d.ts +3 -1
  67. package/dist/calibration.js +6 -6
  68. package/dist/capabilities.d.ts +7 -7
  69. package/dist/capabilities.js +1 -1
  70. package/dist/{capsule-crypto-CZJSLEFG.js → capsule-crypto-YO5QJ6L3.js} +3 -3
  71. package/dist/capsule-crypto-YO5QJ6L3.js.map +1 -0
  72. package/dist/{capsule-merge-Z2HUO6IK.js → capsule-merge-5KKJQBWQ.js} +4 -4
  73. package/dist/{catalog-uX9sT9ws.d.ts → catalog-BWqHb5HT.d.ts} +1 -1
  74. package/dist/causal-behavior.d.ts +3 -1
  75. package/dist/causal-behavior.js +6 -6
  76. package/dist/causal-chain.js +4 -4
  77. package/dist/causal-consolidation.d.ts +3 -1
  78. package/dist/causal-consolidation.js +46 -37
  79. package/dist/causal-consolidation.js.map +1 -1
  80. package/dist/causal-retrieval.js +6 -6
  81. package/dist/causal-trajectory-graph.d.ts +3 -1
  82. package/dist/causal-trajectory-graph.js +1 -1
  83. package/dist/causal-trajectory.js +1 -1
  84. package/dist/{chunk-A3GOMRJG.js → chunk-23L3IXFD.js} +2 -2
  85. package/dist/chunk-2CGLBUW3.js +15 -0
  86. package/dist/chunk-2CGLBUW3.js.map +1 -0
  87. package/dist/{chunk-MRHFJV44.js → chunk-2DQ2XREU.js} +2 -2
  88. package/dist/{chunk-ASKEM4AR.js → chunk-2EJOEICD.js} +1823 -1483
  89. package/dist/chunk-2EJOEICD.js.map +1 -0
  90. package/dist/{chunk-L2B3EE7B.js → chunk-2QMKMVHH.js} +2 -2
  91. package/dist/{chunk-6CALL5VN.js → chunk-2UFO7X4Q.js} +7 -7
  92. package/dist/{chunk-2MR3MFQB.js → chunk-2VEOKUPP.js} +3 -3
  93. package/dist/chunk-2Z24E5W2.js +22 -0
  94. package/dist/chunk-2Z24E5W2.js.map +1 -0
  95. package/dist/{chunk-RHOZ5LLO.js → chunk-347WD2LE.js} +2 -2
  96. package/dist/{chunk-5S7Z5SHA.js → chunk-34RC5RT7.js} +2 -2
  97. package/dist/{chunk-KGWXHWAH.js → chunk-3QAH2S33.js} +3 -3
  98. package/dist/{chunk-37CTGERM.js → chunk-3WCASNQZ.js} +12 -1
  99. package/dist/chunk-3WCASNQZ.js.map +1 -0
  100. package/dist/{chunk-ZIDSD6VC.js → chunk-3Y224NYC.js} +3 -3
  101. package/dist/{chunk-RBQLJSJ7.js → chunk-44XZ75OQ.js} +46 -10
  102. package/dist/chunk-44XZ75OQ.js.map +1 -0
  103. package/dist/{chunk-VFSP73LP.js → chunk-45GF7Y3V.js} +2 -2
  104. package/dist/{chunk-7ICYQUOL.js → chunk-4BJQODZF.js} +2514 -1526
  105. package/dist/chunk-4BJQODZF.js.map +1 -0
  106. package/dist/{chunk-JMBVCAR4.js → chunk-57OWKFUQ.js} +17 -6
  107. package/dist/chunk-57OWKFUQ.js.map +1 -0
  108. package/dist/{chunk-OEHCMALU.js → chunk-5I4M26Q7.js} +5 -5
  109. package/dist/{chunk-2E6G7FCE.js → chunk-5Q7EVV4X.js} +7 -7
  110. package/dist/{chunk-LC7OODWZ.js → chunk-5SB7SC2G.js} +80 -49
  111. package/dist/chunk-5SB7SC2G.js.map +1 -0
  112. package/dist/{chunk-VZ5OJE4X.js → chunk-5VQJBH2G.js} +2 -2
  113. package/dist/{chunk-PUBTHW5O.js → chunk-6DRPPQEJ.js} +2 -2
  114. package/dist/{chunk-NWTGD4AN.js → chunk-6KIQT7RG.js} +10 -9
  115. package/dist/chunk-6KIQT7RG.js.map +1 -0
  116. package/dist/{chunk-4LEF6XWJ.js → chunk-6O22TZSB.js} +3 -3
  117. package/dist/{chunk-ZQ7UBUZ6.js → chunk-6QYST5XN.js} +6 -6
  118. package/dist/{chunk-W4PGTAS2.js → chunk-6WAFYNVT.js} +3 -3
  119. package/dist/chunk-6ZMAMSHS.js +20 -0
  120. package/dist/chunk-6ZMAMSHS.js.map +1 -0
  121. package/dist/{chunk-R5VAVVHP.js → chunk-72A4L5JJ.js} +2 -2
  122. package/dist/{chunk-X64YLC24.js → chunk-72VAXGEI.js} +5 -13
  123. package/dist/chunk-72VAXGEI.js.map +1 -0
  124. package/dist/{chunk-IKQTFQMI.js → chunk-755Q3DGF.js} +22 -3
  125. package/dist/chunk-755Q3DGF.js.map +1 -0
  126. package/dist/{chunk-F7AU34FC.js → chunk-76GLCM57.js} +160 -127
  127. package/dist/chunk-76GLCM57.js.map +1 -0
  128. package/dist/{chunk-D7FOKIY5.js → chunk-7AMFUATK.js} +12 -9
  129. package/dist/{chunk-D7FOKIY5.js.map → chunk-7AMFUATK.js.map} +1 -1
  130. package/dist/{chunk-BFVEEB7W.js → chunk-7ON2JW73.js} +57 -22
  131. package/dist/chunk-7ON2JW73.js.map +1 -0
  132. package/dist/chunk-7RNBVZZO.js +270 -0
  133. package/dist/chunk-7RNBVZZO.js.map +1 -0
  134. package/dist/{chunk-3FAMU5TX.js → chunk-A6USBZTO.js} +2 -2
  135. package/dist/{chunk-TXVD7PLT.js → chunk-A72SWTWW.js} +7 -7
  136. package/dist/{chunk-FC77VUX5.js → chunk-A7Q43EUZ.js} +2 -2
  137. package/dist/{chunk-UJBESW6X.js → chunk-AE7WMV4V.js} +7 -7
  138. package/dist/{chunk-J2HSAU72.js → chunk-AIK5W3IW.js} +29 -1
  139. package/dist/chunk-AIK5W3IW.js.map +1 -0
  140. package/dist/{chunk-OKUEZOGW.js → chunk-AITCS2RC.js} +2 -2
  141. package/dist/{chunk-OC35KQIN.js → chunk-AJ7QCSIS.js} +4 -4
  142. package/dist/{chunk-FNMFJWBY.js → chunk-ANEUPF6O.js} +5 -5
  143. package/dist/chunk-AREGMX2J.js +50 -0
  144. package/dist/chunk-AREGMX2J.js.map +1 -0
  145. package/dist/chunk-AVPXXV6J.js +448 -0
  146. package/dist/chunk-AVPXXV6J.js.map +1 -0
  147. package/dist/{chunk-2A3OXAP2.js → chunk-B7RWBZXW.js} +2 -2
  148. package/dist/{chunk-GWTFLF2P.js → chunk-BJMBJZ2Y.js} +59 -59
  149. package/dist/chunk-BJMBJZ2Y.js.map +1 -0
  150. package/dist/{chunk-N3JDIRBW.js → chunk-BLAKS3CP.js} +4 -4
  151. package/dist/{chunk-M7VGG3ID.js → chunk-BV5WMSIJ.js} +9 -9
  152. package/dist/{chunk-2BFLDH5F.js → chunk-BXLOS5AJ.js} +2 -2
  153. package/dist/{chunk-UXKMMNJD.js → chunk-C23BYTJV.js} +6 -6
  154. package/dist/{chunk-JZHHREBL.js → chunk-C3AKM55W.js} +2 -2
  155. package/dist/{chunk-RP7YXA67.js → chunk-C5JF6EZ7.js} +2 -2
  156. package/dist/{chunk-FBNWOMCE.js → chunk-C6XBRYVD.js} +16 -15
  157. package/dist/chunk-C6XBRYVD.js.map +1 -0
  158. package/dist/{chunk-FTYDWKO6.js → chunk-CEN6DW6X.js} +12 -2
  159. package/dist/chunk-CEN6DW6X.js.map +1 -0
  160. package/dist/chunk-CGASUJVP.js +421 -0
  161. package/dist/chunk-CGASUJVP.js.map +1 -0
  162. package/dist/{chunk-DDGV7NAX.js → chunk-CQMEM5CC.js} +2 -2
  163. package/dist/{chunk-A7B4RMQG.js → chunk-CXZQOVIE.js} +12 -12
  164. package/dist/chunk-D3V3UMET.js +44 -0
  165. package/dist/chunk-D3V3UMET.js.map +1 -0
  166. package/dist/{chunk-7N2RUBAP.js → chunk-DDA47TES.js} +2 -2
  167. package/dist/{chunk-64SE4X5G.js → chunk-DEBHXHJR.js} +3 -3
  168. package/dist/{chunk-EHK6KZHK.js → chunk-DNHVPZOD.js} +2 -2
  169. package/dist/{chunk-437S3G37.js → chunk-DQEMWVMT.js} +2 -2
  170. package/dist/{chunk-LZZNTPLR.js → chunk-DX3XRGLH.js} +2 -2
  171. package/dist/chunk-EA2H5LML.js +72 -0
  172. package/dist/chunk-EA2H5LML.js.map +1 -0
  173. package/dist/{chunk-IFJ23BHU.js → chunk-EEC7UJPX.js} +112 -106
  174. package/dist/chunk-EEC7UJPX.js.map +1 -0
  175. package/dist/{chunk-KSNVDPDF.js → chunk-EKBNDKDY.js} +21 -20
  176. package/dist/chunk-EKBNDKDY.js.map +1 -0
  177. package/dist/{chunk-YF6FMLBT.js → chunk-EQWEIIKQ.js} +64 -34
  178. package/dist/chunk-EQWEIIKQ.js.map +1 -0
  179. package/dist/{chunk-7MW3CVLD.js → chunk-ES36HTSC.js} +4 -4
  180. package/dist/{chunk-TN7THW5U.js → chunk-ET356KSB.js} +2 -2
  181. package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
  182. package/dist/{chunk-7LFXDGLH.js → chunk-F7GAIWFA.js} +20 -20
  183. package/dist/{chunk-IKSELOIV.js → chunk-FFPJINJE.js} +7 -7
  184. package/dist/chunk-FMLKOL2Z.js +636 -0
  185. package/dist/chunk-FMLKOL2Z.js.map +1 -0
  186. package/dist/chunk-FQC3DHH2.js +20 -0
  187. package/dist/chunk-FQC3DHH2.js.map +1 -0
  188. package/dist/{chunk-V53GJUSL.js → chunk-FUTF72MJ.js} +15 -15
  189. package/dist/chunk-GCASGYIO.js +71 -0
  190. package/dist/chunk-GCASGYIO.js.map +1 -0
  191. package/dist/{chunk-5UNWK7KU.js → chunk-GFPZS3F5.js} +8 -8
  192. package/dist/{chunk-BCDKBDSY.js → chunk-GNVZQ5JN.js} +99 -41
  193. package/dist/chunk-GNVZQ5JN.js.map +1 -0
  194. package/dist/{chunk-G6NKALRN.js → chunk-H4WG3UQZ.js} +2 -2
  195. package/dist/{chunk-HLTAPHZZ.js → chunk-HNZKVLAN.js} +2 -2
  196. package/dist/{chunk-5EZXHU36.js → chunk-HYQJQGD3.js} +2 -2
  197. package/dist/{chunk-ANADNYWK.js → chunk-IDZFBSHN.js} +8 -6
  198. package/dist/{chunk-ANADNYWK.js.map → chunk-IDZFBSHN.js.map} +1 -1
  199. package/dist/{chunk-XVLEGMJI.js → chunk-IFH6LWTO.js} +50 -8
  200. package/dist/chunk-IFH6LWTO.js.map +1 -0
  201. package/dist/{chunk-RULE4VG5.js → chunk-ILGC6JH6.js} +21 -6
  202. package/dist/chunk-ILGC6JH6.js.map +1 -0
  203. package/dist/chunk-IUM3VSHI.js +113 -0
  204. package/dist/chunk-IUM3VSHI.js.map +1 -0
  205. package/dist/{chunk-ND5M64JJ.js → chunk-IYNGIMVG.js} +101 -91
  206. package/dist/chunk-IYNGIMVG.js.map +1 -0
  207. package/dist/{chunk-TRWPCR6P.js → chunk-JECBQBEX.js} +3 -3
  208. package/dist/{chunk-HG32URJJ.js → chunk-JYIFGGEM.js} +2 -2
  209. package/dist/{chunk-VA4WSW54.js → chunk-JYIJNNN3.js} +3 -3
  210. package/dist/{chunk-L5HJQC36.js → chunk-K2TDK7GG.js} +3 -3
  211. package/dist/{chunk-MKDRQAA3.js → chunk-KAVBJSBQ.js} +4 -4
  212. package/dist/{chunk-EEARRVZ2.js → chunk-KF5EUVKQ.js} +16 -6
  213. package/dist/chunk-KF5EUVKQ.js.map +1 -0
  214. package/dist/chunk-KFZY2OFH.js +42 -0
  215. package/dist/chunk-KFZY2OFH.js.map +1 -0
  216. package/dist/{chunk-4OKLXWDZ.js → chunk-KNB7IBBU.js} +2 -2
  217. package/dist/{chunk-QLULYKWZ.js → chunk-KSXJOC4F.js} +2 -2
  218. package/dist/{chunk-OBMR4VIX.js → chunk-L2DPF4DF.js} +186 -15
  219. package/dist/chunk-L2DPF4DF.js.map +1 -0
  220. package/dist/{chunk-JI5AVXYO.js → chunk-LEPOP46W.js} +6 -6
  221. package/dist/{chunk-O7BBFJLP.js → chunk-LTAVSOZW.js} +2 -2
  222. package/dist/{chunk-E3VODCC3.js → chunk-LUDXM7MD.js} +14 -2
  223. package/dist/{chunk-E3VODCC3.js.map → chunk-LUDXM7MD.js.map} +1 -1
  224. package/dist/{chunk-2IZAGAJR.js → chunk-LULR4IUW.js} +3 -3
  225. package/dist/{chunk-NUWYOKS6.js → chunk-MC5Q3J7S.js} +398 -7
  226. package/dist/chunk-MC5Q3J7S.js.map +1 -0
  227. package/dist/{chunk-WMWVO45V.js → chunk-MC6XO7T4.js} +2 -2
  228. package/dist/chunk-MKQBXQKU.js +107 -0
  229. package/dist/chunk-MKQBXQKU.js.map +1 -0
  230. package/dist/{chunk-7PND4PUC.js → chunk-MMGGVZ4Q.js} +29 -9
  231. package/dist/{chunk-7PND4PUC.js.map → chunk-MMGGVZ4Q.js.map} +1 -1
  232. package/dist/{chunk-D6RIFG4O.js → chunk-MNB5RMAY.js} +2 -2
  233. package/dist/{chunk-67ZCJLJY.js → chunk-MYFQ3ED4.js} +8 -8
  234. package/dist/{chunk-V3UE5I5F.js → chunk-MYVPLJOO.js} +2 -2
  235. package/dist/chunk-NINSR6LX.js +83 -0
  236. package/dist/chunk-NINSR6LX.js.map +1 -0
  237. package/dist/{chunk-MTWKDOVO.js → chunk-NLE6TSLG.js} +2 -2
  238. package/dist/{chunk-DBRYEIGY.js → chunk-OJP3N7UK.js} +2 -2
  239. package/dist/{chunk-AD6AMF2N.js → chunk-OQJIB32H.js} +28 -23
  240. package/dist/chunk-OQJIB32H.js.map +1 -0
  241. package/dist/{chunk-SMX5267P.js → chunk-OZKOPQCM.js} +2 -2
  242. package/dist/{chunk-JCK7V6SN.js → chunk-P65YJEEL.js} +2 -2
  243. package/dist/{chunk-MTR7BZQN.js → chunk-PBGWYM3H.js} +3 -3
  244. package/dist/chunk-PIG4WJFQ.js +87 -0
  245. package/dist/chunk-PIG4WJFQ.js.map +1 -0
  246. package/dist/chunk-PQVCH2AE.js +76 -0
  247. package/dist/chunk-PQVCH2AE.js.map +1 -0
  248. package/dist/{chunk-AXTXN4T6.js → chunk-PWFCHOB3.js} +2 -2
  249. package/dist/{chunk-FDPZVY6D.js → chunk-QFN4U7AG.js} +2 -2
  250. package/dist/{chunk-K2ZLHESQ.js → chunk-QIEUU4UK.js} +2 -2
  251. package/dist/{chunk-AHLPZ2SF.js → chunk-QJAQNXWI.js} +44 -6
  252. package/dist/chunk-QJAQNXWI.js.map +1 -0
  253. package/dist/{chunk-3D6AFGQR.js → chunk-QVT3E4CE.js} +7 -7
  254. package/dist/{chunk-VYOFVVNK.js → chunk-R26ZMXR2.js} +24 -24
  255. package/dist/{chunk-VYOFVVNK.js.map → chunk-R26ZMXR2.js.map} +1 -1
  256. package/dist/chunk-R3DJVOSM.js +34 -0
  257. package/dist/chunk-R3DJVOSM.js.map +1 -0
  258. package/dist/{chunk-SFQ6QNL7.js → chunk-R6YJI3HE.js} +2 -1
  259. package/dist/{chunk-5CJVLG3H.js → chunk-RFDD3B7W.js} +5 -5
  260. package/dist/{chunk-JBPKEARU.js → chunk-RKNJBZ55.js} +4 -4
  261. package/dist/chunk-ROI7BK7H.js +88 -0
  262. package/dist/chunk-ROI7BK7H.js.map +1 -0
  263. package/dist/{chunk-UTRJFDP2.js → chunk-S2BBISHU.js} +4 -4
  264. package/dist/{chunk-IALLX7EE.js → chunk-S2FSBU4H.js} +3 -3
  265. package/dist/{chunk-BFPETA3S.js → chunk-SCCO46KZ.js} +3 -2
  266. package/dist/chunk-SCCO46KZ.js.map +1 -0
  267. package/dist/chunk-SICXL4MK.js +165 -0
  268. package/dist/chunk-SICXL4MK.js.map +1 -0
  269. package/dist/chunk-SK7AMF2J.js +168 -0
  270. package/dist/chunk-SK7AMF2J.js.map +1 -0
  271. package/dist/{chunk-GMSDQUCR.js → chunk-TDTXKOAJ.js} +6475 -5748
  272. package/dist/chunk-TDTXKOAJ.js.map +1 -0
  273. package/dist/{chunk-KSBEEMQF.js → chunk-TG6IHVE2.js} +151 -6
  274. package/dist/chunk-TG6IHVE2.js.map +1 -0
  275. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  276. package/dist/{chunk-PK5XBDA6.js → chunk-U3ZAVRP3.js} +2 -2
  277. package/dist/{chunk-ODPLEWB6.js → chunk-UFGFMWAD.js} +47 -17
  278. package/dist/chunk-UFGFMWAD.js.map +1 -0
  279. package/dist/{chunk-4KJLYTLS.js → chunk-V57NLO5P.js} +2 -2
  280. package/dist/{chunk-FLVL4L3L.js → chunk-VDX2J7OX.js} +2 -2
  281. package/dist/{chunk-7XGSIUP5.js → chunk-W4FBGYGK.js} +1 -1
  282. package/dist/{chunk-TXLGHDHS.js → chunk-W4XJFLAL.js} +53 -32
  283. package/dist/chunk-W4XJFLAL.js.map +1 -0
  284. package/dist/{chunk-6SXVCD7W.js → chunk-W7IGLX4G.js} +2 -2
  285. package/dist/{chunk-KQDNAXOM.js → chunk-WG5HSQ4P.js} +19 -6
  286. package/dist/chunk-WG5HSQ4P.js.map +1 -0
  287. package/dist/{chunk-LTJAMRGI.js → chunk-WL5EBRDH.js} +17 -3
  288. package/dist/chunk-WL5EBRDH.js.map +1 -0
  289. package/dist/{chunk-KAWTOYAW.js → chunk-WLZYGLJ4.js} +2 -2
  290. package/dist/{chunk-W5NKDU24.js → chunk-WON4APQY.js} +4 -4
  291. package/dist/{chunk-NKCPUHCI.js → chunk-WZFAPHIK.js} +6 -6
  292. package/dist/{chunk-KQPJLK3X.js → chunk-XL24QQ63.js} +2 -2
  293. package/dist/{chunk-X47LWMKA.js → chunk-XMMESCPD.js} +26 -1
  294. package/dist/chunk-XMMESCPD.js.map +1 -0
  295. package/dist/{chunk-4B4MUS5D.js → chunk-YROFNEG5.js} +7 -7
  296. package/dist/{chunk-WU46YPY6.js → chunk-YV32N67O.js} +1 -1
  297. package/dist/chunk-YV32N67O.js.map +1 -0
  298. package/dist/{chunk-B3F4CWQR.js → chunk-YVKF3HEW.js} +1 -1
  299. package/dist/chunk-YVKF3HEW.js.map +1 -0
  300. package/dist/{chunk-VRAD2FGO.js → chunk-Z54EM5YZ.js} +12 -12
  301. package/dist/{chunk-2VN4JAX7.js → chunk-ZOKZIR5K.js} +95 -33
  302. package/dist/chunk-ZOKZIR5K.js.map +1 -0
  303. package/dist/{cli-_Y2Bmt6A.d.ts → cli-C_pqqTCw.d.ts} +28 -12
  304. package/dist/cli.d.ts +16 -9
  305. package/dist/cli.js +145 -130
  306. package/dist/compounding/engine.d.ts +5 -2
  307. package/dist/compounding/engine.js +39 -29
  308. package/dist/compounding/preference-consolidator.d.ts +3 -1
  309. package/dist/compounding/preference-consolidator.js +1 -1
  310. package/dist/compression-optimizer.d.ts +3 -1
  311. package/dist/config-qmd.d.ts +8 -0
  312. package/dist/config-qmd.js +20 -0
  313. package/dist/config-qmd.js.map +1 -0
  314. package/dist/config.d.ts +3 -1
  315. package/dist/config.js +15 -10
  316. package/dist/connectors/codex-materialize-runner.d.ts +3 -1
  317. package/dist/connectors/codex-materialize-runner.js +39 -29
  318. package/dist/connectors/codex-materialize.d.ts +3 -1
  319. package/dist/connectors/codex-materialize.js +2 -2
  320. package/dist/connectors/index.d.ts +3 -1
  321. package/dist/connectors/index.js +44 -35
  322. package/dist/consolidation-provenance-check.d.ts +5 -2
  323. package/dist/consolidation-provenance-check.js +4 -4
  324. package/dist/consolidation-undo.d.ts +5 -2
  325. package/dist/consolidation-undo.js +3 -3
  326. package/dist/contradiction/index.d.ts +5 -2
  327. package/dist/contradiction/index.js +10 -4
  328. package/dist/{contradiction-scan-J57T5QV7.js → contradiction-scan-RJBABNRH.js} +4 -4
  329. package/dist/contradiction-scan-RJBABNRH.js.map +1 -0
  330. package/dist/conversation-index/backend.d.ts +3 -1
  331. package/dist/conversation-index/backend.js +5 -5
  332. package/dist/conversation-index/chunker.d.ts +3 -1
  333. package/dist/conversation-index/cleanup.js +2 -2
  334. package/dist/conversation-index/faiss-adapter.d.ts +3 -1
  335. package/dist/conversation-index/faiss-adapter.js +2 -2
  336. package/dist/conversation-index/indexer.d.ts +3 -1
  337. package/dist/conversation-index/indexer.js +2 -2
  338. package/dist/conversation-index/search.d.ts +3 -1
  339. package/dist/conversation-index/search.js +2 -2
  340. package/dist/cross-namespace-budget.d.ts +45 -1
  341. package/dist/cross-namespace-budget.js +5 -3
  342. package/dist/dashboard-runtime.js +2 -2
  343. package/dist/day-summary.d.ts +3 -1
  344. package/dist/day-summary.js +3 -3
  345. package/dist/delinearize.d.ts +3 -1
  346. package/dist/direct-answer-wiring.d.ts +3 -1
  347. package/dist/direct-answer.d.ts +3 -1
  348. package/dist/{dreams-ledger-6UODQOX6.js → dreams-ledger-567VKVOU.js} +4 -2
  349. package/dist/dreams-ledger-567VKVOU.js.map +1 -0
  350. package/dist/embedding-fallback.d.ts +3 -1
  351. package/dist/embedding-fallback.js +3 -3
  352. package/dist/enrichment/index.d.ts +3 -1
  353. package/dist/entity-retrieval.d.ts +5 -2
  354. package/dist/entity-retrieval.js +38 -29
  355. package/dist/entity-schema.d.ts +3 -1
  356. package/dist/explicit-capture.d.ts +13 -8
  357. package/dist/explicit-capture.js +7 -3
  358. package/dist/extraction-faithfulness.d.ts +3 -1
  359. package/dist/extraction-faithfulness.js +5 -5
  360. package/dist/extraction-judge-telemetry.d.ts +3 -1
  361. package/dist/extraction-judge-telemetry.js +2 -2
  362. package/dist/extraction-judge-training.d.ts +3 -1
  363. package/dist/extraction-judge-training.js +2 -2
  364. package/dist/extraction-judge.d.ts +3 -1
  365. package/dist/extraction-judge.js +5 -5
  366. package/dist/extraction.d.ts +3 -1
  367. package/dist/extraction.js +13 -12
  368. package/dist/faithfulness-config.js +3 -2
  369. package/dist/fallback-llm.d.ts +3 -1
  370. package/dist/fallback-llm.js +4 -4
  371. package/dist/{first-start-migration-TI67YMLG.js → first-start-migration-CSRHCJIQ.js} +2 -2
  372. package/dist/{forget-CQCLB5LB.js → forget-HRPLVB3W.js} +5 -5
  373. package/dist/graph-dashboard-diff.d.ts +3 -1
  374. package/dist/graph-dashboard-key.d.ts +3 -1
  375. package/dist/graph-dashboard-parser.d.ts +3 -1
  376. package/dist/{graph-edge-decay-FO7AM4UR.js → graph-edge-decay-Z6ENALU2.js} +3 -3
  377. package/dist/graph-edge-decay-Z6ENALU2.js.map +1 -0
  378. package/dist/graph-edge-reinforcement.d.ts +3 -1
  379. package/dist/graph-snapshot.d.ts +3 -1
  380. package/dist/graph-snapshot.js +2 -2
  381. package/dist/graph.d.ts +57 -10
  382. package/dist/graph.js +1 -1
  383. package/dist/identity-continuity.d.ts +1 -2
  384. package/dist/importance.d.ts +3 -1
  385. package/dist/importers/index.d.ts +3 -1
  386. package/dist/in-flight-reads.d.ts +3 -1
  387. package/dist/index.d.ts +101 -92
  388. package/dist/index.js +290 -242
  389. package/dist/intent.d.ts +3 -1
  390. package/dist/lcm/archive.js +2 -2
  391. package/dist/lcm/engine.d.ts +3 -1
  392. package/dist/lcm/engine.js +6 -6
  393. package/dist/lcm/index.d.ts +3 -1
  394. package/dist/lcm/index.js +13 -13
  395. package/dist/lcm/schema.js +2 -2
  396. package/dist/lcm/summarizer.js +3 -3
  397. package/dist/lcm/tools.d.ts +3 -1
  398. package/dist/lifecycle.d.ts +3 -1
  399. package/dist/live-connectors-runner.d.ts +3 -1
  400. package/dist/local-llm.d.ts +5 -2
  401. package/dist/local-llm.js +3 -3
  402. package/dist/local-model-endpoint.d.ts +3 -1
  403. package/dist/logger.d.ts +3 -1
  404. package/dist/logger.js +7 -3
  405. package/dist/maintenance/archive-observations.js +2 -2
  406. package/dist/maintenance/memory-governance.d.ts +3 -1
  407. package/dist/maintenance/memory-governance.js +38 -28
  408. package/dist/maintenance/migrate-observations.js +3 -3
  409. package/dist/maintenance/observation-ledger-utils.js +2 -2
  410. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +102 -1
  411. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +40 -28
  412. package/dist/maintenance/rebuild-memory-projection.js +41 -31
  413. package/dist/maintenance/rebuild-observations.js +3 -3
  414. package/dist/mcp-memory-inspector-app.d.ts +22 -15
  415. package/dist/memory-action-policy.d.ts +3 -1
  416. package/dist/memory-cache.d.ts +46 -2
  417. package/dist/memory-cache.js +7 -1
  418. package/dist/memory-corpus-version.js +2 -2
  419. package/dist/memory-lifecycle-ledger-utils.d.ts +25 -2
  420. package/dist/memory-lifecycle-ledger-utils.js +11 -1
  421. package/dist/memory-projection-store.d.ts +3 -1
  422. package/dist/memory-projection-store.js +2 -2
  423. package/dist/memory-provenance.d.ts +3 -1
  424. package/dist/memory-worth-outcomes.d.ts +5 -2
  425. package/dist/model-registry.js +2 -2
  426. package/dist/models-json.d.ts +3 -1
  427. package/dist/models-json.js +2 -2
  428. package/dist/namespaces/migrate.d.ts +6 -3
  429. package/dist/namespaces/migrate.js +54 -45
  430. package/dist/namespaces/principal.d.ts +27 -2
  431. package/dist/namespaces/principal.js +6 -2
  432. package/dist/namespaces/search.d.ts +16 -2
  433. package/dist/namespaces/search.js +25 -21
  434. package/dist/namespaces/storage.d.ts +24 -3
  435. package/dist/namespaces/storage.js +38 -30
  436. package/dist/native-knowledge.d.ts +3 -1
  437. package/dist/native-knowledge.js +2 -2
  438. package/dist/negative.js +2 -2
  439. package/dist/offline-sync-exclude-globs.d.ts +13 -0
  440. package/dist/offline-sync-exclude-globs.js +10 -0
  441. package/dist/offline-sync-exclude-globs.js.map +1 -0
  442. package/dist/offline-sync-impression-drain.d.ts +78 -0
  443. package/dist/offline-sync-impression-drain.js +37 -0
  444. package/dist/offline-sync-impression-drain.js.map +1 -0
  445. package/dist/offline-sync.js +4 -2
  446. package/dist/operator-toolkit.d.ts +5 -2
  447. package/dist/operator-toolkit.js +73 -58
  448. package/dist/orchestration/compression-guideline-coordinator.d.ts +5 -2
  449. package/dist/orchestration/compression-guideline-coordinator.js +3 -3
  450. package/dist/orchestration/maintenance.d.ts +121 -2
  451. package/dist/orchestration/maintenance.js +47 -34
  452. package/dist/{orchestrator-BbZ_dQSU.d.ts → orchestrator-CQJ8U7En.d.ts} +85 -79
  453. package/dist/orchestrator.d.ts +13 -8
  454. package/dist/orchestrator.js +197 -180
  455. package/dist/page-versioning.js +3 -3
  456. package/dist/patterns-cli.d.ts +3 -1
  457. package/dist/{pipeline-FRMDb1fn.d.ts → pipeline-Cn-kvYeV.d.ts} +1 -1
  458. package/dist/policy-runtime.d.ts +3 -1
  459. package/dist/prioritized-embed.d.ts +19 -0
  460. package/dist/prioritized-embed.js +8 -0
  461. package/dist/prioritized-embed.js.map +1 -0
  462. package/dist/proactive-contention.d.ts +28 -0
  463. package/dist/proactive-contention.js +8 -0
  464. package/dist/proactive-contention.js.map +1 -0
  465. package/dist/profiling.js +2 -2
  466. package/dist/provenance.d.ts +3 -1
  467. package/dist/provenance.js +3 -2
  468. package/dist/{purge-NDWV6WYD.js → purge-IRF47ZTX.js} +3 -3
  469. package/dist/{qmd-xJRrHFbA.d.ts → qmd-oh9VXz1d.d.ts} +11 -1
  470. package/dist/qmd-preflight.d.ts +5 -2
  471. package/dist/qmd-recall-cache.d.ts +3 -1
  472. package/dist/qmd-status.d.ts +57 -0
  473. package/dist/qmd-status.js +18 -0
  474. package/dist/qmd-status.js.map +1 -0
  475. package/dist/qmd.d.ts +5 -2
  476. package/dist/qmd.js +8 -4
  477. package/dist/recall-concurrency-config.d.ts +16 -0
  478. package/dist/recall-concurrency-config.js +10 -0
  479. package/dist/recall-concurrency-config.js.map +1 -0
  480. package/dist/recall-disclosure-escalation.d.ts +3 -1
  481. package/dist/recall-explain-renderer.d.ts +4 -1
  482. package/dist/recall-explain-renderer.js +3 -3
  483. package/dist/recall-memory-map.d.ts +26 -0
  484. package/dist/recall-memory-map.js +18 -0
  485. package/dist/recall-memory-map.js.map +1 -0
  486. package/dist/recall-planner-llm.d.ts +3 -1
  487. package/dist/recall-planner-llm.js +4 -4
  488. package/dist/recall-qos.js +2 -2
  489. package/dist/recall-state.d.ts +163 -2
  490. package/dist/recall-state.js +6 -3
  491. package/dist/recall-tag-filter.d.ts +3 -1
  492. package/dist/recall-timings.d.ts +11 -2
  493. package/dist/recall-timings.js +3 -1
  494. package/dist/recall-xray-cli.d.ts +3 -1
  495. package/dist/recall-xray-cli.js +4 -4
  496. package/dist/recall-xray-renderer.d.ts +3 -1
  497. package/dist/recall-xray-renderer.js +3 -3
  498. package/dist/recall-xray.d.ts +3 -1
  499. package/dist/recall-xray.js +2 -2
  500. package/dist/relevance.js +3 -3
  501. package/dist/replay/normalizers/chatgpt.d.ts +3 -1
  502. package/dist/replay/normalizers/claude.d.ts +3 -1
  503. package/dist/replay/normalizers/openclaw.d.ts +3 -1
  504. package/dist/replay/normalizers/shared.d.ts +3 -1
  505. package/dist/replay/runner.d.ts +3 -1
  506. package/dist/replay/types.d.ts +3 -1
  507. package/dist/rerank.d.ts +8 -1
  508. package/dist/rerank.js +3 -1
  509. package/dist/resolution-3K27T4VO.js +18 -0
  510. package/dist/resolution-3K27T4VO.js.map +1 -0
  511. package/dist/resolve-auth-token.d.ts +3 -1
  512. package/dist/resolve-provider-secret.js +2 -2
  513. package/dist/resume-bundles.js +19 -14
  514. package/dist/retrieval-agents.d.ts +19 -16
  515. package/dist/retrieval-agents.js +3 -3
  516. package/dist/retrieval-tiers.d.ts +3 -1
  517. package/dist/routing/engine.d.ts +3 -1
  518. package/dist/routing/store.d.ts +3 -1
  519. package/dist/routing/store.js +2 -2
  520. package/dist/salvage-envelope.d.ts +18 -0
  521. package/dist/salvage-envelope.js +15 -0
  522. package/dist/salvage-envelope.js.map +1 -0
  523. package/dist/schemas.d.ts +24 -24
  524. package/dist/scope-profiles-EpJG7yKP.d.ts +30 -0
  525. package/dist/search/document-scanner.js +3 -2
  526. package/dist/search/embed-helper.d.ts +3 -1
  527. package/dist/search/embed-helper.js +3 -3
  528. package/dist/search/factory.d.ts +3 -1
  529. package/dist/search/factory.js +19 -17
  530. package/dist/search/index.d.ts +3 -1
  531. package/dist/search/index.js +23 -21
  532. package/dist/search/lancedb-backend.d.ts +3 -1
  533. package/dist/search/lancedb-backend.js +6 -5
  534. package/dist/search/meilisearch-backend.d.ts +3 -1
  535. package/dist/search/meilisearch-backend.js +6 -5
  536. package/dist/search/noop-backend.d.ts +3 -1
  537. package/dist/search/orama-backend.d.ts +3 -1
  538. package/dist/search/orama-backend.js +6 -5
  539. package/dist/search/port.d.ts +27 -2
  540. package/dist/search/port.js +1 -1
  541. package/dist/search/remote-backend.d.ts +3 -1
  542. package/dist/search/remote-backend.js +3 -3
  543. package/dist/secure-store/index.d.ts +12 -1
  544. package/dist/secure-store/index.js +6 -3
  545. package/dist/{semantic-consolidation-fvdZRa5Z.d.ts → semantic-consolidation-DILZEQq3.d.ts} +1 -1
  546. package/dist/semantic-consolidation.d.ts +4 -2
  547. package/dist/semantic-consolidation.js +41 -32
  548. package/dist/semantic-rule-promotion.js +37 -27
  549. package/dist/semantic-rule-verifier.d.ts +3 -1
  550. package/dist/semantic-rule-verifier.js +38 -28
  551. package/dist/session-observer-bands.d.ts +3 -1
  552. package/dist/session-observer-state.d.ts +3 -1
  553. package/dist/session-observer-state.js +2 -2
  554. package/dist/session-transcript-migration.js +2 -2
  555. package/dist/shared-context/manager.d.ts +3 -1
  556. package/dist/shared-context/manager.js +3 -3
  557. package/dist/signal.d.ts +3 -1
  558. package/dist/{storage-CrvzaM9C.d.ts → storage-NIyKYD8g.d.ts} +505 -110
  559. package/dist/storage-guards.js +2 -2
  560. package/dist/storage.d.ts +6 -3
  561. package/dist/storage.js +41 -29
  562. package/dist/structured-attributes.d.ts +23 -1
  563. package/dist/structured-attributes.js +7 -1
  564. package/dist/summarizer.d.ts +3 -1
  565. package/dist/summarizer.js +11 -11
  566. package/dist/summary-snapshot.d.ts +3 -1
  567. package/dist/summary-snapshot.js +2 -2
  568. package/dist/temporal-index-batch.d.ts +1 -0
  569. package/dist/temporal-index-batch.js +10 -0
  570. package/dist/temporal-index-batch.js.map +1 -0
  571. package/dist/temporal-index-compat.d.ts +279 -1
  572. package/dist/temporal-index-compat.js +1 -1
  573. package/dist/temporal-index.d.ts +1 -225
  574. package/dist/temporal-index.js +35 -3
  575. package/dist/temporal-supersession.d.ts +5 -2
  576. package/dist/temporal-supersession.js +2 -2
  577. package/dist/temporal-timeline-recall.d.ts +3 -1
  578. package/dist/temporal-validity.d.ts +3 -1
  579. package/dist/threading.d.ts +3 -1
  580. package/dist/threading.js +2 -2
  581. package/dist/tier-migration.d.ts +5 -2
  582. package/dist/tier-routing.d.ts +3 -1
  583. package/dist/{tier-stats-KV7IWCJR.js → tier-stats-QEJSPFV2.js} +2 -2
  584. package/dist/tokens.js +3 -3
  585. package/dist/topics.d.ts +3 -1
  586. package/dist/transcript.d.ts +3 -1
  587. package/dist/transcript.js +2 -2
  588. package/dist/transfer/backup.js +3 -3
  589. package/dist/transfer/capsule-export.js +3 -3
  590. package/dist/transfer/capsule-import.js +6 -6
  591. package/dist/transfer/types.d.ts +24 -24
  592. package/dist/trust-score-stage.d.ts +75 -38
  593. package/dist/trust-score-stage.js +11 -3
  594. package/dist/trust-score.d.ts +3 -1
  595. package/dist/{types-Bl4BWDM8.d.ts → types-D_fG2ix8.d.ts} +49 -63
  596. package/dist/types-continuity.d.ts +52 -0
  597. package/dist/types-continuity.js +1 -0
  598. package/dist/types-continuity.js.map +1 -0
  599. package/dist/types.d.ts +3 -1
  600. package/dist/types.js +1 -1
  601. package/dist/utility-runtime.d.ts +3 -1
  602. package/dist/utils/serialize-mutations.d.ts +31 -2
  603. package/dist/utils/serialize-mutations.js +1 -1
  604. package/dist/verified-recall.js +39 -29
  605. package/dist/write-envelope.d.ts +282 -0
  606. package/dist/write-envelope.js +35 -0
  607. package/dist/write-envelope.js.map +1 -0
  608. package/dist/write-quarantine.d.ts +79 -0
  609. package/dist/write-quarantine.js +11 -0
  610. package/dist/write-quarantine.js.map +1 -0
  611. package/dist/write-rate-limiter.d.ts +45 -0
  612. package/dist/write-rate-limiter.js +9 -0
  613. package/dist/write-rate-limiter.js.map +1 -0
  614. package/package.json +37 -2
  615. package/src/access-admin-ops-surface.ts +17 -7
  616. package/src/access-boundary.test.ts +28 -0
  617. package/src/access-boundary.ts +31 -2
  618. package/src/access-citation.test.ts +72 -0
  619. package/src/access-citation.ts +139 -0
  620. package/src/access-errors.ts +21 -0
  621. package/src/access-fingerprint-parity.test.ts +211 -0
  622. package/src/access-http-cancellation.test.ts +59 -21
  623. package/src/access-http.test.ts +90 -0
  624. package/src/access-http.ts +79 -79
  625. package/src/access-mcp-cancellation.test.ts +16 -7
  626. package/src/access-memory-search-fanout.test.ts +220 -0
  627. package/src/access-memory-search-fanout.ts +168 -0
  628. package/src/access-observe-quarantine.test.ts +120 -0
  629. package/src/access-observe-write-surface.ts +130 -11
  630. package/src/access-operations-batch.ts +2 -0
  631. package/src/access-recall-concurrency.ts +773 -0
  632. package/src/access-recall-response.ts +307 -0
  633. package/src/access-recall-surface.ts +100 -252
  634. package/src/access-service-coding-write.test.ts +22 -4
  635. package/src/access-service-health.test.ts +49 -0
  636. package/src/access-service-namespace.test.ts +486 -8
  637. package/src/access-service-observe-scope.test.ts +4 -0
  638. package/src/access-service-recall-concurrency.test.ts +1990 -0
  639. package/src/access-service.ts +182 -175
  640. package/src/access-surface-catalog.ts +1 -0
  641. package/src/access-token-capabilities.ts +16 -9
  642. package/src/active-recall.test.ts +35 -0
  643. package/src/active-recall.ts +7 -0
  644. package/src/bounded-jsonl-state.ts +93 -0
  645. package/src/buffer-session.test.ts +422 -5
  646. package/src/buffer-surprise-trigger.test.ts +41 -0
  647. package/src/buffer.ts +218 -3
  648. package/src/capabilities-cluster-b.test.ts +1 -0
  649. package/src/capabilities.ts +5 -6
  650. package/src/cli.ts +21 -22
  651. package/src/coding/architecture-surfaces.test.ts +6 -3
  652. package/src/coding/architecture-surfaces.ts +36 -25
  653. package/src/coding/decision-surfaces.ts +42 -34
  654. package/src/compounding/engine.test.ts +5 -1
  655. package/src/compounding/engine.ts +7 -7
  656. package/src/config-qmd.ts +89 -0
  657. package/src/config.test.ts +136 -0
  658. package/src/config.ts +122 -118
  659. package/src/connector-provenance-lifecycle.test.ts +4 -4
  660. package/src/connectors/coerce.test.ts +131 -0
  661. package/src/connectors/coerce.ts +80 -7
  662. package/src/contradiction/contradiction.test.ts +10 -6
  663. package/src/contradiction/resolution.ts +17 -4
  664. package/src/correction/correction-access-wiring.ts +62 -18
  665. package/src/cross-namespace-budget.test.ts +35 -0
  666. package/src/cross-namespace-budget.ts +86 -19
  667. package/src/explicit-capture.ts +54 -17
  668. package/src/extraction.ts +2 -3
  669. package/src/faithfulness-graph-guard.test.ts +16 -69
  670. package/src/graph-recall.test.ts +31 -0
  671. package/src/graph.test.ts +137 -1
  672. package/src/graph.ts +274 -17
  673. package/src/index.ts +22 -2
  674. package/src/local-llm.ts +4 -6
  675. package/src/logger.ts +16 -0
  676. package/src/maintenance/dreams-ledger.ts +100 -49
  677. package/src/maintenance/rebuild-memory-lifecycle-ledger-cli.ts +77 -0
  678. package/src/maintenance/rebuild-memory-lifecycle-ledger.ts +373 -9
  679. package/src/memory-cache.ts +70 -0
  680. package/src/memory-lifecycle-ledger-utils.ts +51 -5
  681. package/src/namespaces/principal.test.ts +37 -1
  682. package/src/namespaces/principal.ts +48 -0
  683. package/src/namespaces/search.test.ts +79 -5
  684. package/src/namespaces/search.ts +59 -6
  685. package/src/namespaces/storage.ts +45 -1
  686. package/src/offline-sync-exclude-globs.ts +58 -0
  687. package/src/offline-sync-impression-drain.test.ts +316 -0
  688. package/src/offline-sync-impression-drain.ts +260 -0
  689. package/src/offline-sync.test.ts +32 -5
  690. package/src/offline-sync.ts +1 -14
  691. package/src/operator-toolkit.ts +1 -1
  692. package/src/orchestration/batch-deindex-flush.test.ts +146 -0
  693. package/src/orchestration/consolidation-run.ts +96 -85
  694. package/src/orchestration/extraction-envelope.ts +94 -0
  695. package/src/orchestration/extraction-persist-promotion.ts +134 -0
  696. package/src/orchestration/extraction-persist.ts +325 -260
  697. package/src/orchestration/extraction-run.test.ts +1 -1
  698. package/src/orchestration/extraction-run.ts +2 -2
  699. package/src/orchestration/graph-recall-coordinator.ts +18 -7
  700. package/src/orchestration/lifecycle-policy-coordinator.ts +63 -48
  701. package/src/orchestration/maintenance.test.ts +2103 -3
  702. package/src/orchestration/maintenance.ts +581 -2
  703. package/src/orchestration/namespace-read-fanout.ts +14 -8
  704. package/src/orchestration/orchestrator-helpers.ts +8 -1
  705. package/src/orchestration/orchestrator-init.ts +22 -6
  706. package/src/orchestration/orchestrator-namespace-scope.ts +71 -0
  707. package/src/orchestration/persistence-index.ts +64 -9
  708. package/src/orchestration/qmd-result-resolver.ts +27 -0
  709. package/src/orchestration/recall-entry.ts +34 -19
  710. package/src/orchestration/recall-internal.ts +207 -79
  711. package/src/orchestration/recall-rerank-coordinator.ts +229 -82
  712. package/src/orchestration/recall-result-formatter.ts +76 -20
  713. package/src/orchestration/recall-search-pipeline.test.ts +70 -0
  714. package/src/orchestration/recall-search-pipeline.ts +102 -129
  715. package/src/orchestration/recall-section-coordinator.ts +315 -85
  716. package/src/orchestration/semantic-consolidation-coordinator.ts +69 -37
  717. package/src/orchestration/session-context.ts +21 -0
  718. package/src/orchestration/workspace-ops.test.ts +348 -0
  719. package/src/orchestration/workspace-ops.ts +172 -34
  720. package/src/orchestrator-chunked-hash-durability.test.ts +126 -0
  721. package/src/orchestrator-connector-dedup.test.ts +1061 -40
  722. package/src/orchestrator-flush.test.ts +155 -39
  723. package/src/orchestrator-nonchunked-hash-durability.test.ts +121 -0
  724. package/src/orchestrator-source-attribution.test.ts +9 -9
  725. package/src/orchestrator.ts +166 -150
  726. package/src/prioritized-embed.ts +123 -0
  727. package/src/proactive-contention.test.ts +80 -0
  728. package/src/proactive-contention.ts +39 -0
  729. package/src/procedural/procedure-miner.test.ts +19 -14
  730. package/src/procedural/procedure-miner.ts +44 -13
  731. package/src/qmd-client.test.ts +111 -1
  732. package/src/qmd-status.ts +186 -0
  733. package/src/qmd.test.ts +22 -0
  734. package/src/qmd.ts +60 -48
  735. package/src/recall-budget-config.test.ts +30 -0
  736. package/src/recall-cold-deadline.test.ts +149 -0
  737. package/src/recall-concurrency-config.ts +28 -0
  738. package/src/recall-memory-map.ts +74 -0
  739. package/src/recall-rerank-coordinator.test.ts +508 -0
  740. package/src/recall-state.test.ts +825 -1
  741. package/src/recall-state.ts +406 -7
  742. package/src/recall-timings-access.test.ts +41 -0
  743. package/src/recall-timings.ts +16 -0
  744. package/src/relay/mission-access.test.ts +5 -5
  745. package/src/rerank.ts +22 -0
  746. package/src/retrieval-agents.test.ts +79 -0
  747. package/src/retrieval-agents.ts +71 -19
  748. package/src/salvage-envelope.ts +28 -0
  749. package/src/scopes/scope-plan.test.ts +42 -0
  750. package/src/scopes/scope-plan.ts +45 -0
  751. package/src/search/port.ts +24 -0
  752. package/src/secure-store/index.ts +1 -0
  753. package/src/secure-store/secure-fs.ts +48 -0
  754. package/src/secure-store/secure-store.test.ts +40 -0
  755. package/src/semantic-rule-promotion.ts +13 -4
  756. package/src/storage/content-hash-index.ts +655 -0
  757. package/src/storage/entity-timeline.ts +473 -0
  758. package/src/storage/memory-lifecycle-ledger-access.ts +603 -0
  759. package/src/storage/secure-line-reader.test.ts +197 -0
  760. package/src/storage/secure-line-reader.ts +181 -3
  761. package/src/storage-append-header-sniff.test.ts +195 -0
  762. package/src/storage-behavior-signals-cache.test.ts +237 -0
  763. package/src/storage-contract/cache-coherence.test.ts +96 -1
  764. package/src/storage-contract/content-hash.test.ts +47 -2
  765. package/src/storage-fact-hash-index-defer.test.ts +1200 -0
  766. package/src/storage-memory-lifecycle-ledger.test.ts +1146 -3
  767. package/src/storage.ts +942 -903
  768. package/src/structured-attributes.ts +52 -0
  769. package/src/temporal-index-batch.ts +112 -0
  770. package/src/temporal-index.test.ts +193 -0
  771. package/src/temporal-index.ts +49 -53
  772. package/src/testing/lifecycle-matrix.test.ts +212 -0
  773. package/src/testing/lifecycle-matrix.ts +271 -0
  774. package/src/testing/orchestrator-lite.ts +236 -0
  775. package/src/testing/subjects/dreams-ledger.test.ts +67 -0
  776. package/src/testing/subjects/extraction-lifecycle.test.ts +442 -0
  777. package/src/testing/subjects/lifecycle-ledger.test.ts +93 -0
  778. package/src/testing/subjects/recall-budget.test.ts +461 -0
  779. package/src/testing/subjects/serialized-write-chain.test.ts +224 -0
  780. package/src/trust-score-stage.test.ts +154 -0
  781. package/src/trust-score-stage.ts +216 -53
  782. package/src/types-continuity.ts +57 -0
  783. package/src/types.ts +66 -77
  784. package/src/utils/path-containment.test.ts +75 -0
  785. package/src/utils/path-containment.ts +76 -0
  786. package/src/utils/serialize-mutations.test.ts +122 -0
  787. package/src/utils/serialize-mutations.ts +68 -3
  788. package/src/wearables/memory-gen.test.ts +31 -9
  789. package/src/wearables/memory-gen.ts +95 -55
  790. package/src/wearables/pipeline.test.ts +10 -7
  791. package/src/wearables/service.test.ts +6 -8
  792. package/src/wearables/service.ts +2 -2
  793. package/src/write-envelope.extension.test.ts +111 -0
  794. package/src/write-envelope.test.ts +683 -0
  795. package/src/write-envelope.ts +902 -0
  796. package/src/write-quarantine.test.ts +193 -0
  797. package/src/write-quarantine.ts +241 -0
  798. package/src/write-rate-limiter.test.ts +105 -0
  799. package/src/write-rate-limiter.ts +135 -0
  800. package/src/write-sealed-parity.test.ts +204 -0
  801. package/dist/chunk-2VN4JAX7.js.map +0 -1
  802. package/dist/chunk-37CTGERM.js.map +0 -1
  803. package/dist/chunk-7ICYQUOL.js.map +0 -1
  804. package/dist/chunk-AD6AMF2N.js.map +0 -1
  805. package/dist/chunk-AHLPZ2SF.js.map +0 -1
  806. package/dist/chunk-ASKEM4AR.js.map +0 -1
  807. package/dist/chunk-B3F4CWQR.js.map +0 -1
  808. package/dist/chunk-BCDKBDSY.js.map +0 -1
  809. package/dist/chunk-BFPETA3S.js.map +0 -1
  810. package/dist/chunk-BFVEEB7W.js.map +0 -1
  811. package/dist/chunk-E5BK6CGV.js +0 -335
  812. package/dist/chunk-E5BK6CGV.js.map +0 -1
  813. package/dist/chunk-EEARRVZ2.js.map +0 -1
  814. package/dist/chunk-F7AU34FC.js.map +0 -1
  815. package/dist/chunk-FBNWOMCE.js.map +0 -1
  816. package/dist/chunk-FTYDWKO6.js.map +0 -1
  817. package/dist/chunk-GMSDQUCR.js.map +0 -1
  818. package/dist/chunk-GWTFLF2P.js.map +0 -1
  819. package/dist/chunk-IFJ23BHU.js.map +0 -1
  820. package/dist/chunk-IKQTFQMI.js.map +0 -1
  821. package/dist/chunk-J2HSAU72.js.map +0 -1
  822. package/dist/chunk-JMBVCAR4.js.map +0 -1
  823. package/dist/chunk-KQDNAXOM.js.map +0 -1
  824. package/dist/chunk-KSBEEMQF.js.map +0 -1
  825. package/dist/chunk-KSNVDPDF.js.map +0 -1
  826. package/dist/chunk-LC7OODWZ.js.map +0 -1
  827. package/dist/chunk-LTJAMRGI.js.map +0 -1
  828. package/dist/chunk-ND5M64JJ.js.map +0 -1
  829. package/dist/chunk-NUWYOKS6.js.map +0 -1
  830. package/dist/chunk-NWTGD4AN.js.map +0 -1
  831. package/dist/chunk-OBMR4VIX.js.map +0 -1
  832. package/dist/chunk-ODPLEWB6.js.map +0 -1
  833. package/dist/chunk-PHK3HARR.js +0 -32
  834. package/dist/chunk-PHK3HARR.js.map +0 -1
  835. package/dist/chunk-RANHFI3P.js +0 -8
  836. package/dist/chunk-RANHFI3P.js.map +0 -1
  837. package/dist/chunk-RBQLJSJ7.js.map +0 -1
  838. package/dist/chunk-RULE4VG5.js.map +0 -1
  839. package/dist/chunk-SVOZFLIQ.js +0 -16
  840. package/dist/chunk-SVOZFLIQ.js.map +0 -1
  841. package/dist/chunk-TXLGHDHS.js.map +0 -1
  842. package/dist/chunk-UN3CH3CO.js +0 -118
  843. package/dist/chunk-UN3CH3CO.js.map +0 -1
  844. package/dist/chunk-VSMRDBFT.js +0 -17
  845. package/dist/chunk-VSMRDBFT.js.map +0 -1
  846. package/dist/chunk-WU46YPY6.js.map +0 -1
  847. package/dist/chunk-X47LWMKA.js.map +0 -1
  848. package/dist/chunk-X64YLC24.js.map +0 -1
  849. package/dist/chunk-XVLEGMJI.js.map +0 -1
  850. package/dist/chunk-YF6FMLBT.js.map +0 -1
  851. package/dist/resolution-VH4NGENZ.js +0 -12
  852. /package/dist/{capsule-crypto-CZJSLEFG.js.map → access-citation.js.map} +0 -0
  853. /package/dist/{contradiction-scan-J57T5QV7.js.map → access-memory-search-fanout.js.map} +0 -0
  854. /package/dist/{dreams-ledger-6UODQOX6.js.map → access-recall-concurrency.js.map} +0 -0
  855. /package/dist/{graph-edge-decay-FO7AM4UR.js.map → access-recall-response.js.map} +0 -0
  856. /package/dist/{resolution-VH4NGENZ.js.map → bounded-jsonl-state.js.map} +0 -0
  857. /package/dist/{capsule-merge-Z2HUO6IK.js.map → capsule-merge-5KKJQBWQ.js.map} +0 -0
  858. /package/dist/{chunk-A3GOMRJG.js.map → chunk-23L3IXFD.js.map} +0 -0
  859. /package/dist/{chunk-MRHFJV44.js.map → chunk-2DQ2XREU.js.map} +0 -0
  860. /package/dist/{chunk-L2B3EE7B.js.map → chunk-2QMKMVHH.js.map} +0 -0
  861. /package/dist/{chunk-6CALL5VN.js.map → chunk-2UFO7X4Q.js.map} +0 -0
  862. /package/dist/{chunk-2MR3MFQB.js.map → chunk-2VEOKUPP.js.map} +0 -0
  863. /package/dist/{chunk-RHOZ5LLO.js.map → chunk-347WD2LE.js.map} +0 -0
  864. /package/dist/{chunk-5S7Z5SHA.js.map → chunk-34RC5RT7.js.map} +0 -0
  865. /package/dist/{chunk-KGWXHWAH.js.map → chunk-3QAH2S33.js.map} +0 -0
  866. /package/dist/{chunk-ZIDSD6VC.js.map → chunk-3Y224NYC.js.map} +0 -0
  867. /package/dist/{chunk-VFSP73LP.js.map → chunk-45GF7Y3V.js.map} +0 -0
  868. /package/dist/{chunk-OEHCMALU.js.map → chunk-5I4M26Q7.js.map} +0 -0
  869. /package/dist/{chunk-2E6G7FCE.js.map → chunk-5Q7EVV4X.js.map} +0 -0
  870. /package/dist/{chunk-VZ5OJE4X.js.map → chunk-5VQJBH2G.js.map} +0 -0
  871. /package/dist/{chunk-PUBTHW5O.js.map → chunk-6DRPPQEJ.js.map} +0 -0
  872. /package/dist/{chunk-4LEF6XWJ.js.map → chunk-6O22TZSB.js.map} +0 -0
  873. /package/dist/{chunk-ZQ7UBUZ6.js.map → chunk-6QYST5XN.js.map} +0 -0
  874. /package/dist/{chunk-W4PGTAS2.js.map → chunk-6WAFYNVT.js.map} +0 -0
  875. /package/dist/{chunk-R5VAVVHP.js.map → chunk-72A4L5JJ.js.map} +0 -0
  876. /package/dist/{chunk-3FAMU5TX.js.map → chunk-A6USBZTO.js.map} +0 -0
  877. /package/dist/{chunk-TXVD7PLT.js.map → chunk-A72SWTWW.js.map} +0 -0
  878. /package/dist/{chunk-FC77VUX5.js.map → chunk-A7Q43EUZ.js.map} +0 -0
  879. /package/dist/{chunk-UJBESW6X.js.map → chunk-AE7WMV4V.js.map} +0 -0
  880. /package/dist/{chunk-OKUEZOGW.js.map → chunk-AITCS2RC.js.map} +0 -0
  881. /package/dist/{chunk-OC35KQIN.js.map → chunk-AJ7QCSIS.js.map} +0 -0
  882. /package/dist/{chunk-FNMFJWBY.js.map → chunk-ANEUPF6O.js.map} +0 -0
  883. /package/dist/{chunk-2A3OXAP2.js.map → chunk-B7RWBZXW.js.map} +0 -0
  884. /package/dist/{chunk-N3JDIRBW.js.map → chunk-BLAKS3CP.js.map} +0 -0
  885. /package/dist/{chunk-M7VGG3ID.js.map → chunk-BV5WMSIJ.js.map} +0 -0
  886. /package/dist/{chunk-2BFLDH5F.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  887. /package/dist/{chunk-UXKMMNJD.js.map → chunk-C23BYTJV.js.map} +0 -0
  888. /package/dist/{chunk-JZHHREBL.js.map → chunk-C3AKM55W.js.map} +0 -0
  889. /package/dist/{chunk-RP7YXA67.js.map → chunk-C5JF6EZ7.js.map} +0 -0
  890. /package/dist/{chunk-DDGV7NAX.js.map → chunk-CQMEM5CC.js.map} +0 -0
  891. /package/dist/{chunk-A7B4RMQG.js.map → chunk-CXZQOVIE.js.map} +0 -0
  892. /package/dist/{chunk-7N2RUBAP.js.map → chunk-DDA47TES.js.map} +0 -0
  893. /package/dist/{chunk-64SE4X5G.js.map → chunk-DEBHXHJR.js.map} +0 -0
  894. /package/dist/{chunk-EHK6KZHK.js.map → chunk-DNHVPZOD.js.map} +0 -0
  895. /package/dist/{chunk-437S3G37.js.map → chunk-DQEMWVMT.js.map} +0 -0
  896. /package/dist/{chunk-LZZNTPLR.js.map → chunk-DX3XRGLH.js.map} +0 -0
  897. /package/dist/{chunk-7MW3CVLD.js.map → chunk-ES36HTSC.js.map} +0 -0
  898. /package/dist/{chunk-TN7THW5U.js.map → chunk-ET356KSB.js.map} +0 -0
  899. /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
  900. /package/dist/{chunk-7LFXDGLH.js.map → chunk-F7GAIWFA.js.map} +0 -0
  901. /package/dist/{chunk-IKSELOIV.js.map → chunk-FFPJINJE.js.map} +0 -0
  902. /package/dist/{chunk-V53GJUSL.js.map → chunk-FUTF72MJ.js.map} +0 -0
  903. /package/dist/{chunk-5UNWK7KU.js.map → chunk-GFPZS3F5.js.map} +0 -0
  904. /package/dist/{chunk-G6NKALRN.js.map → chunk-H4WG3UQZ.js.map} +0 -0
  905. /package/dist/{chunk-HLTAPHZZ.js.map → chunk-HNZKVLAN.js.map} +0 -0
  906. /package/dist/{chunk-5EZXHU36.js.map → chunk-HYQJQGD3.js.map} +0 -0
  907. /package/dist/{chunk-TRWPCR6P.js.map → chunk-JECBQBEX.js.map} +0 -0
  908. /package/dist/{chunk-HG32URJJ.js.map → chunk-JYIFGGEM.js.map} +0 -0
  909. /package/dist/{chunk-VA4WSW54.js.map → chunk-JYIJNNN3.js.map} +0 -0
  910. /package/dist/{chunk-L5HJQC36.js.map → chunk-K2TDK7GG.js.map} +0 -0
  911. /package/dist/{chunk-MKDRQAA3.js.map → chunk-KAVBJSBQ.js.map} +0 -0
  912. /package/dist/{chunk-4OKLXWDZ.js.map → chunk-KNB7IBBU.js.map} +0 -0
  913. /package/dist/{chunk-QLULYKWZ.js.map → chunk-KSXJOC4F.js.map} +0 -0
  914. /package/dist/{chunk-JI5AVXYO.js.map → chunk-LEPOP46W.js.map} +0 -0
  915. /package/dist/{chunk-O7BBFJLP.js.map → chunk-LTAVSOZW.js.map} +0 -0
  916. /package/dist/{chunk-2IZAGAJR.js.map → chunk-LULR4IUW.js.map} +0 -0
  917. /package/dist/{chunk-WMWVO45V.js.map → chunk-MC6XO7T4.js.map} +0 -0
  918. /package/dist/{chunk-D6RIFG4O.js.map → chunk-MNB5RMAY.js.map} +0 -0
  919. /package/dist/{chunk-67ZCJLJY.js.map → chunk-MYFQ3ED4.js.map} +0 -0
  920. /package/dist/{chunk-V3UE5I5F.js.map → chunk-MYVPLJOO.js.map} +0 -0
  921. /package/dist/{chunk-MTWKDOVO.js.map → chunk-NLE6TSLG.js.map} +0 -0
  922. /package/dist/{chunk-DBRYEIGY.js.map → chunk-OJP3N7UK.js.map} +0 -0
  923. /package/dist/{chunk-SMX5267P.js.map → chunk-OZKOPQCM.js.map} +0 -0
  924. /package/dist/{chunk-JCK7V6SN.js.map → chunk-P65YJEEL.js.map} +0 -0
  925. /package/dist/{chunk-MTR7BZQN.js.map → chunk-PBGWYM3H.js.map} +0 -0
  926. /package/dist/{chunk-AXTXN4T6.js.map → chunk-PWFCHOB3.js.map} +0 -0
  927. /package/dist/{chunk-FDPZVY6D.js.map → chunk-QFN4U7AG.js.map} +0 -0
  928. /package/dist/{chunk-K2ZLHESQ.js.map → chunk-QIEUU4UK.js.map} +0 -0
  929. /package/dist/{chunk-3D6AFGQR.js.map → chunk-QVT3E4CE.js.map} +0 -0
  930. /package/dist/{chunk-SFQ6QNL7.js.map → chunk-R6YJI3HE.js.map} +0 -0
  931. /package/dist/{chunk-5CJVLG3H.js.map → chunk-RFDD3B7W.js.map} +0 -0
  932. /package/dist/{chunk-JBPKEARU.js.map → chunk-RKNJBZ55.js.map} +0 -0
  933. /package/dist/{chunk-UTRJFDP2.js.map → chunk-S2BBISHU.js.map} +0 -0
  934. /package/dist/{chunk-IALLX7EE.js.map → chunk-S2FSBU4H.js.map} +0 -0
  935. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  936. /package/dist/{chunk-PK5XBDA6.js.map → chunk-U3ZAVRP3.js.map} +0 -0
  937. /package/dist/{chunk-4KJLYTLS.js.map → chunk-V57NLO5P.js.map} +0 -0
  938. /package/dist/{chunk-FLVL4L3L.js.map → chunk-VDX2J7OX.js.map} +0 -0
  939. /package/dist/{chunk-7XGSIUP5.js.map → chunk-W4FBGYGK.js.map} +0 -0
  940. /package/dist/{chunk-6SXVCD7W.js.map → chunk-W7IGLX4G.js.map} +0 -0
  941. /package/dist/{chunk-KAWTOYAW.js.map → chunk-WLZYGLJ4.js.map} +0 -0
  942. /package/dist/{chunk-W5NKDU24.js.map → chunk-WON4APQY.js.map} +0 -0
  943. /package/dist/{chunk-NKCPUHCI.js.map → chunk-WZFAPHIK.js.map} +0 -0
  944. /package/dist/{chunk-KQPJLK3X.js.map → chunk-XL24QQ63.js.map} +0 -0
  945. /package/dist/{chunk-4B4MUS5D.js.map → chunk-YROFNEG5.js.map} +0 -0
  946. /package/dist/{chunk-VRAD2FGO.js.map → chunk-Z54EM5YZ.js.map} +0 -0
  947. /package/dist/{first-start-migration-TI67YMLG.js.map → first-start-migration-CSRHCJIQ.js.map} +0 -0
  948. /package/dist/{forget-CQCLB5LB.js.map → forget-HRPLVB3W.js.map} +0 -0
  949. /package/dist/{purge-NDWV6WYD.js.map → purge-IRF47ZTX.js.map} +0 -0
  950. /package/dist/{tier-stats-KV7IWCJR.js.map → tier-stats-QEJSPFV2.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/orchestration/maintenance.ts"],"sourcesContent":["/**\n * Maintenance scheduler — extracted from the orchestrator (issue #1526 PR1).\n *\n * Owns the WHEN of memory maintenance:\n * - cron auto-registration (writes jobs.json entries the OpenClaw cron\n * daemon picks up)\n * - debounced + singleflight QMD index maintenance (re-index + embed\n * after writes)\n * - consolidation scheduling trigger (count + interval gated)\n *\n * Does NOT own the WHAT — the actual job runners (runSemanticConsolidation,\n * runPatternReinforcement, runDeepSleepGovernanceNow, runConsolidation)\n * remain on the orchestrator because they need the full LLM + extraction\n * dependency surface. The scheduler invokes consolidation through a\n * callback so the orchestrator stays the source of truth for that work.\n *\n * Behavior-preserving move from orchestrator.ts. No logic changes — the\n * orchestrator keeps thin delegating methods so existing tests that stub\n * `orchestrator.requestQmdMaintenance` etc. continue to work.\n */\n\nimport { resolveNamespaceCapabilities,\n resolveQmdCapabilities,resolveConsolidationCapabilities, resolveRecallAuxiliaryCapabilities } from \"../capabilities.js\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { PluginConfig } from \"../types.js\";\nimport type { SearchBackend } from \"../search/port.js\";\nimport {\n NamespaceSearchRouter,\n type NamespaceUpdateResult,\n} from \"../namespaces/search.js\";\nimport type { NamespaceCatalog } from \"../namespaces/catalog.js\";\nimport {\n planNamespaceMaintenance,\n runNamespaceMaintenanceBatchPlan,\n type NamespaceMaintenancePlan,\n type NamespaceMaintenanceSkipReason,\n} from \"../maintenance/namespace-planner.js\";\nimport {\n ensureContradictionScanCron,\n ensureDaySummaryCron,\n ensureGraphEdgeDecayCron,\n ensureNightlyGovernanceCron,\n ensurePatternReinforcementCron,\n ensureProceduralMiningCron,\n graphEdgeDecayCadenceToCronExpr,\n} from \"../maintenance/memory-governance-cron.js\";\nimport { resolveHomeDir } from \"../runtime/env.js\";\nimport { log } from \"../logger.js\";\n\n/** Reason a QMD maintenance pass was skipped, used for status recording. */\nfunction qmdMaintenanceSkipReasonForError(\n error: unknown,\n): NamespaceMaintenanceSkipReason | null {\n const message = error instanceof Error ? error.message : String(error);\n return /^QMD (?:update|embed) skipped by .*min-interval gate$/.test(message)\n ? \"throttled\"\n : null;\n}\n\n/** Dependencies injected by the orchestrator. All stable references. */\nexport interface MaintenanceSchedulerDeps {\n config: PluginConfig;\n /** Live accessor — the orchestrator can reassign its qmd backend after\n * construction (e.g. swap to NoopSearchBackend when the collection is\n * missing), and the scheduler must always observe the current backend. */\n getQmd: () => SearchBackend;\n namespaceSearchRouter: NamespaceSearchRouter;\n namespaceCatalog: NamespaceCatalog;\n}\n\n/**\n * Schedules and debounces memory maintenance work. Owns the cadence +\n * singleflight state that previously lived as private orchestrator fields.\n *\n * The orchestrator constructs one instance in its constructor and delegates\n * the public scheduling entrypoints to it. Job execution stays on the\n * orchestrator (LLM-heavy) and is invoked through callbacks.\n */\nexport class MaintenanceScheduler {\n // ── Consolidation scheduling state ──\n private nonZeroExtractionsSinceConsolidation = 0;\n private lastConsolidationRunAtMs = 0;\n private consolidationInFlight = false;\n\n // ── QMD maintenance scheduling state ──\n private qmdMaintenanceTimer: NodeJS.Timeout | null = null;\n private qmdMaintenancePending = false;\n private qmdMaintenanceInFlight = false;\n private lastQmdEmbedAtMs = 0;\n private lastQmdEmbedAtMsByNamespace = new Map<string, number>();\n\n constructor(private readonly deps: MaintenanceSchedulerDeps) {}\n\n // ───────────────────────────────────────────────────────────────────────\n // Cron auto-registration\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Register every cron job the daemon should run, gated by its config flag.\n * Each registration is independent and non-fatal — a failure in one does\n * not block the others (mirrors the orchestrator's prior sequential try/\n * catch behavior exactly).\n *\n * Returns when all eligible registrations have completed so callers that\n * `await deferredReady` can rely on jobs.json being current.\n */\n async autoRegisterCrons(_signal: AbortSignal): Promise<void> {\n if (resolveRecallAuxiliaryCapabilities(this.deps.config).daySummary) {\n try {\n await this.autoRegisterDaySummaryCron();\n } catch (err) {\n log.debug(`day-summary cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.nightlyGovernanceCronAutoRegister) {\n try {\n await this.autoRegisterNightlyGovernanceCron();\n } catch (err) {\n log.debug(`nightly governance cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.procedural?.proceduralMiningCronAutoRegister) {\n try {\n await this.autoRegisterProceduralMiningCron();\n } catch (err) {\n log.debug(`procedural mining cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.contradictionScan?.enabled) {\n try {\n await this.autoRegisterContradictionScanCron();\n } catch (err) {\n log.debug(`contradiction scan cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (resolveConsolidationCapabilities(this.deps.config).patternReinforcement) {\n try {\n await this.autoRegisterPatternReinforcementCron();\n } catch (err) {\n log.debug(`pattern reinforcement cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (resolveConsolidationCapabilities(this.deps.config).graphEdgeDecay) {\n try {\n await this.autoRegisterGraphEdgeDecayCron();\n } catch (err) {\n log.debug(`graph edge decay cron auto-register failed (non-fatal): ${err}`);\n }\n }\n }\n\n async autoRegisterDaySummaryCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"day-summary cron: jobs.json not found, skipping auto-register\");\n return;\n }\n\n // Resolve an OpenClaw cron-routing model only in gateway mode. In plugin\n // mode, summaryModel is a direct-client model id for Remnic's own LLM\n // calls and may be unroutable as an OpenClaw agentTurn model.\n const rawSummaryModel = this.deps.config.summaryModel;\n const taskPrimary = this.deps.config.taskModelChain?.primary;\n const isGateway = this.deps.config.modelSource === \"gateway\";\n const model = isGateway ? (rawSummaryModel || taskPrimary || undefined) : undefined;\n // Attach task-chain fallbacks only when the model matches the task-chain\n // primary. If summaryModel is a distinct override, its fallbacks would\n // be unrelated to the task chain. Also append gateway default models as\n // tail fallbacks (de-duped) so a task-chain outage doesn't stop the cron\n // before reaching the gateway default chain. Mirrors hourly cron pattern.\n const fallbacks: string[] = [];\n if (model && taskPrimary && model === taskPrimary) {\n const seen = new Set<string>(model ? [model] : []);\n const addUnique = (value: string | undefined) => {\n if (typeof value !== \"string\") return;\n const trimmed = value.trim();\n if (trimmed.length > 0 && !seen.has(trimmed)) {\n seen.add(trimmed);\n fallbacks.push(trimmed);\n }\n };\n for (const fb of this.deps.config.taskModelChain?.fallbacks ?? []) addUnique(fb);\n const gwDefaults = this.deps.config.gatewayConfig?.agents?.defaults?.model;\n addUnique(gwDefaults?.primary);\n if (Array.isArray(gwDefaults?.fallbacks)) {\n for (const fb of gwDefaults.fallbacks) addUnique(fb);\n }\n }\n\n const timezone =\n this.deps.config.daySummaryTimezone ||\n Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n const result = await ensureDaySummaryCron(jobsPath, {\n timezone,\n ...(model ? { model } : {}),\n ...(fallbacks.length > 0 ? { fallbacks } : {}),\n });\n if (result.created) {\n log.info(\n `day-summary cron auto-registered (${result.jobId}, 23:47 ${timezone}${model ? `, model: ${model}` : \"\"})`,\n );\n } else if (result.updated) {\n log.info(\n `day-summary cron reconciled (${result.jobId}, timezone: ${timezone}${model ? `, model: ${model}` : \"\"})`,\n );\n } else {\n log.debug(\"day-summary cron already up to date\");\n }\n } catch (err) {\n log.debug(`day-summary cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterNightlyGovernanceCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"nightly governance cron: jobs.json not found, skipping auto-register\");\n return;\n }\n\n const created = await ensureNightlyGovernanceCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(\n `nightly governance cron auto-registered (${created.jobId}, 02:23 ${Intl.DateTimeFormat().resolvedOptions().timeZone})`,\n );\n } else {\n log.debug(\"nightly governance cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`nightly governance cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterProceduralMiningCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"procedural mining cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensureProceduralMiningCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`procedural mining cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"procedural mining cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`procedural mining cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterContradictionScanCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"contradiction scan cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensureContradictionScanCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`contradiction scan cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"contradiction scan cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`contradiction scan cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterPatternReinforcementCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"pattern reinforcement cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensurePatternReinforcementCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`pattern reinforcement cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"pattern reinforcement cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`pattern reinforcement cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterGraphEdgeDecayCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"graph edge decay cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const scheduleExpr = graphEdgeDecayCadenceToCronExpr(\n this.deps.config.graphEdgeDecayCadenceMs,\n );\n const created = await ensureGraphEdgeDecayCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n scheduleExpr,\n });\n if (created.created) {\n log.info(`graph edge decay cron auto-registered (${created.jobId}, ${scheduleExpr})`);\n } else {\n log.debug(\"graph edge decay cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`graph edge decay cron auto-register error: ${err}`);\n }\n }\n\n // ───────────────────────────────────────────────────────────────────────\n // Consolidation scheduling\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Maybe trigger a background consolidation pass after an extraction.\n * Counted + interval gated so a burst of extractions does not fan into a\n * burst of consolidation passes. The consolidation runner itself is\n * passed in as a callback because it lives on the orchestrator (LLM +\n * storage dependency surface) and is not owned by this module.\n */\n maybeScheduleConsolidation(\n nonZeroExtraction: boolean,\n runConsolidation: () => Promise<unknown>,\n ): void {\n if (nonZeroExtraction) this.nonZeroExtractionsSinceConsolidation += 1;\n if (\n this.deps.config.consolidationRequireNonZeroExtraction &&\n !nonZeroExtraction\n ) {\n return;\n }\n if (\n this.nonZeroExtractionsSinceConsolidation <\n this.deps.config.consolidateEveryN\n ) {\n return;\n }\n\n const now = Date.now();\n if (\n now - this.lastConsolidationRunAtMs <\n this.deps.config.consolidationMinIntervalMs\n ) {\n return;\n }\n if (this.consolidationInFlight) return;\n\n this.consolidationInFlight = true;\n this.lastConsolidationRunAtMs = now;\n this.nonZeroExtractionsSinceConsolidation = 0;\n runConsolidation()\n .catch((err) => log.error(\"background consolidation failed\", err))\n .finally(() => {\n this.consolidationInFlight = false;\n });\n }\n\n /** Whether a background consolidation pass is currently running. Exposed so\n * the orchestrator's waitForConsolidationIdle can poll idle state without\n * owning the cadence state (issue #1526 PR1). */\n isConsolidationInFlight(): boolean {\n return this.consolidationInFlight;\n }\n\n /** Whether a debounced QMD maintenance pass is armed and waiting for the\n * debounce timer. Exposed so drain/teardown diagnostics (e.g. the bench\n * adapter) can observe scheduler idle state after the #1526 PR1 extraction\n * moved this flag off the orchestrator. */\n isQmdMaintenancePending(): boolean {\n return this.qmdMaintenancePending;\n }\n\n /** Whether a QMD maintenance pass is currently running (singleflight guard).\n * Exposed for drain/teardown diagnostics (see isQmdMaintenancePending). */\n isQmdMaintenanceInFlight(): boolean {\n return this.qmdMaintenanceInFlight;\n }\n // ───────────────────────────────────────────────────────────────────────\n // QMD maintenance scheduling (debounced + singleflight)\n // ───────────────────────────────────────────────────────────────────────\n\n /** Internal: queue a debounced QMD maintenance pass. */\n private requestQmdMaintenance(): void {\n if (!this.deps.getQmd().isAvailable()) return;\n if (!resolveQmdCapabilities(this.deps.config).qmdMaintenance) return;\n\n this.qmdMaintenancePending = true;\n if (this.qmdMaintenanceTimer) return;\n\n this.qmdMaintenanceTimer = setTimeout(() => {\n this.qmdMaintenanceTimer = null;\n this.runQmdMaintenance().catch((err) =>\n log.debug(`background qmd maintenance failed: ${err}`),\n );\n }, this.deps.config.qmdMaintenanceDebounceMs);\n }\n\n /**\n * Public entrypoint for tool-driven QMD maintenance requests.\n * Routes through existing debounced/singleflight maintenance controls.\n */\n requestQmdMaintenanceForTool(reason: string): void {\n try {\n this.requestQmdMaintenance();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log.warn(`qmd maintenance request failed (${reason}): ${msg}`);\n }\n }\n\n /** Internal: run a single QMD maintenance pass under singleflight guard. */\n async runQmdMaintenance(): Promise<void> {\n if (this.qmdMaintenanceInFlight) return;\n if (!this.qmdMaintenancePending) return;\n this.qmdMaintenanceInFlight = true;\n this.qmdMaintenancePending = false;\n\n try {\n if (resolveNamespaceCapabilities(this.deps.config).namespaces) {\n // Include cataloged dynamic namespaces, not just the configured set\n // (NGnei), but run through the namespace-aware maintenance planner so\n // each namespace is budgeted, lock-protected, and status-recorded\n // independently (issue #1500).\n const plan = await this.namespaceMaintenancePlan(\"qmd\");\n const now = Date.now();\n const lastEmbedAtByNamespace = this.lastQmdEmbedAtMsByNamespace;\n const dueEmbedNamespaces = (namespaces: string[]): string[] => {\n if (!resolveQmdCapabilities(this.deps.config).qmdAutoEmbed) return [];\n return namespaces.filter(\n (namespace) =>\n now - (lastEmbedAtByNamespace.get(namespace) ?? 0) >=\n this.deps.config.qmdEmbedMinIntervalMs,\n );\n };\n const markEmbedded = (namespaces: string[]): void => {\n if (namespaces.length === 0) return;\n for (const namespace of namespaces) {\n lastEmbedAtByNamespace.set(namespace, now);\n }\n this.lastQmdEmbedAtMs = now;\n };\n await runNamespaceMaintenanceBatchPlan(\n this.deps.config,\n plan,\n async (candidates) => {\n const namespaces = candidates.map((candidate) => candidate.namespace);\n const embedNamespaces = dueEmbedNamespaces(namespaces);\n let result: NamespaceUpdateResult;\n try {\n result = await this.deps.namespaceSearchRouter.updateNamespacesDetailed(\n namespaces,\n undefined,\n { strict: true },\n );\n } catch (error) {\n if (\n embedNamespaces.length > 0 &&\n qmdMaintenanceSkipReasonForError(error) === \"throttled\"\n ) {\n await this.deps.namespaceSearchRouter.embedNamespaces(embedNamespaces, {\n strict: true,\n });\n markEmbedded(embedNamespaces);\n }\n throw error;\n }\n if (result.backendCount <= 0) {\n throw new Error(\"no eligible QMD backend for selected namespaces\");\n }\n if (result.eligibleNamespaces.length !== namespaces.length) {\n const eligible = new Set(result.eligibleNamespaces);\n const missing = namespaces.filter(\n (namespace) => !eligible.has(namespace),\n );\n throw new Error(\n `QMD backend ineligible for selected namespaces (${missing.length})`,\n );\n }\n if (embedNamespaces.length > 0) {\n await this.deps.namespaceSearchRouter.embedNamespaces(embedNamespaces, {\n strict: true,\n });\n markEmbedded(embedNamespaces);\n }\n return { itemCount: result.backendCount };\n },\n this.deps.namespaceCatalog,\n {\n skipReasonForError: qmdMaintenanceSkipReasonForError,\n },\n );\n } else {\n await this.deps.getQmd().update();\n const now = Date.now();\n if (\n resolveQmdCapabilities(this.deps.config).qmdAutoEmbed &&\n now - this.lastQmdEmbedAtMs >= this.deps.config.qmdEmbedMinIntervalMs\n ) {\n await this.deps.getQmd().embed();\n this.lastQmdEmbedAtMs = now;\n }\n }\n } finally {\n this.qmdMaintenanceInFlight = false;\n if (this.qmdMaintenancePending) {\n this.requestQmdMaintenance();\n }\n }\n }\n\n /** Build the namespace-aware maintenance plan for one job. */\n private async namespaceMaintenancePlan(\n jobName: string,\n ): Promise<NamespaceMaintenancePlan> {\n return planNamespaceMaintenance(this.deps.config, {\n jobName,\n catalog: this.deps.namespaceCatalog,\n });\n }\n\n // ───────────────────────────────────────────────────────────────────────\n // Lifecycle\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Clear any pending debounce timer. Called from the orchestrator's\n * destroy() so a late tick does not fire on a torn-down instance.\n */\n dispose(): void {\n if (this.qmdMaintenanceTimer) {\n clearTimeout(this.qmdMaintenanceTimer);\n this.qmdMaintenanceTimer = null;\n }\n this.qmdMaintenancePending = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AA4B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C,WAAK,sBAAsB;AAAA,IAC7B;AACA,SAAK,wBAAwB;AAAA,EAC/B;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport { launchProcessSync } from \"./runtime/child-process.js\";\nimport { mergeEnv, readEnvVar } from \"./runtime/env.js\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\n\n/** Trim trailing slash characters without backtracking regex. */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s[end - 1] === \"/\") end--;\n return s.substring(0, end);\n}\n\nfunction stripTrailingV1Path(s: string): string {\n return s.endsWith(\"/v1\") ? s.slice(0, -3) : s;\n}\n\nfunction explicitPortFromUrl(s: string): number | null {\n try {\n const parsed = new URL(s);\n if (!parsed.port) return null;\n const port = Number(parsed.port);\n return Number.isInteger(port) ? port : null;\n } catch {\n return null;\n }\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isLlamaCppPropsResponse(value: unknown): boolean {\n return (\n isObjectRecord(value) &&\n isObjectRecord(value.default_generation_settings) &&\n typeof value.total_slots === \"number\" &&\n (\n typeof value.model_path === \"string\" ||\n typeof value.chat_template === \"string\" ||\n typeof value.build_info === \"string\"\n )\n );\n}\n\nfunction isLlamaCppModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n if (entry.owned_by === \"llamacpp\") return true;\n if (typeof entry.id === \"string\" && entry.id.endsWith(\".gguf\")) return true;\n const meta = entry.meta;\n return (\n isObjectRecord(meta) &&\n (\"n_ctx_train\" in meta || \"n_params\" in meta || \"vocab_type\" in meta)\n );\n });\n}\n\nfunction isLmStudioApiV1ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.models)) {\n return false;\n }\n return value.models.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.key === \"string\" &&\n typeof entry.display_name === \"string\" &&\n (\n typeof entry.format === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n Array.isArray(entry.loaded_instances)\n )\n );\n });\n}\n\nfunction isLmStudioApiV0ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.id === \"string\" &&\n typeof entry.publisher === \"string\" &&\n (\n typeof entry.compatibility_type === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n typeof entry.state === \"string\"\n )\n );\n });\n}\n\nfunction isLmStudioNativeModelsResponse(value: unknown): boolean {\n return isLmStudioApiV1ModelsResponse(value) || isLmStudioApiV0ModelsResponse(value);\n}\n\n/**\n * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)\n *\n * Based on openclaw-tactician's provider detection patterns for consistency.\n * Provides privacy-preserving, cost-effective LLM operations with\n * graceful fallback to cloud providers when local LLM is unavailable.\n */\nexport type LocalLlmType = \"lmstudio\" | \"ollama\" | \"mlx\" | \"vllm\" | \"llamacpp\" | \"generic\";\n\n/**\n * Backends known to honor `chat_template_kwargs: { enable_thinking: false }`\n * on OpenAI-compatible `/v1/chat/completions`. LM Studio, vLLM, and\n * llama.cpp forward this field to the jinja chat template, where thinking-capable\n * models (Qwen 3.5, Gemma 4, DeepSeek) suppress reasoning tokens.\n *\n * Strict OpenAI-compatible backends (standard OpenAI, Azure OpenAI, some\n * proxies) reject unknown request fields with 400 — which trips the\n * `localLlm400*` cooldown path. `LocalLlmClient` therefore only injects\n * the kwarg when the detected backend is in this set; unknown / `generic`\n * / `ollama` / `mlx` fail open (no injection, no 400 risk). Issue #548.\n */\nconst THINKING_COMPATIBLE_BACKENDS: ReadonlySet<LocalLlmType> = new Set([\n \"lmstudio\",\n \"vllm\",\n \"llamacpp\",\n]);\n\nconst THINKING_SUPPRESSED_OPERATIONS: ReadonlySet<string> = new Set([\n \"extraction\",\n \"extraction-judge\",\n \"extraction-faithfulness\",\n \"contradiction-judge\",\n \"contradiction_verification\",\n \"link_suggestion\",\n \"memory_summarization\",\n \"proactive_extraction\",\n \"lcm-summarize\",\n \"day_summary\",\n \"hourly_summary\",\n \"hourly_summary_extended\",\n]);\n\ninterface LocalServerConfig {\n type: LocalLlmType;\n defaultPort: number;\n healthEndpoint: string;\n modelsEndpoint: string;\n detectFn: (response: unknown) => boolean;\n}\n\nconst LOCAL_SERVERS: LocalServerConfig[] = [\n {\n type: \"ollama\",\n defaultPort: 11434,\n healthEndpoint: \"/\",\n modelsEndpoint: \"/api/tags\",\n detectFn: (resp) => typeof resp === \"string\" && resp.includes(\"Ollama\"),\n },\n {\n type: \"llamacpp\",\n defaultPort: 8080,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && resp.status === \"ok\",\n },\n {\n type: \"mlx\",\n defaultPort: 8080,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && Array.isArray(resp.data),\n },\n {\n type: \"lmstudio\",\n defaultPort: 1234,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && Array.isArray(resp.data),\n },\n {\n type: \"vllm\",\n defaultPort: 8000,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => resp === \"\" || (isObjectRecord(resp) && !(\"status\" in resp)),\n },\n];\n\nfunction orderedLocalServers(configuredBaseUrl: string): LocalServerConfig[] {\n const configuredPort = explicitPortFromUrl(configuredBaseUrl);\n if (configuredPort === null) return LOCAL_SERVERS;\n const matching = LOCAL_SERVERS.filter(\n (serverConfig) => serverConfig.defaultPort === configuredPort,\n );\n if (matching.length === 0) return LOCAL_SERVERS;\n const matchingTypes = new Set(matching.map((serverConfig) => serverConfig.type));\n return [\n ...matching,\n ...LOCAL_SERVERS.filter((serverConfig) => !matchingTypes.has(serverConfig.type)),\n ];\n}\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\ninterface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string };\n timeoutMs?: number;\n operation?: string;\n forceDisableThinking?: boolean;\n priority?: LocalLlmRequestPriority;\n}\n\ninterface LocalLlmQueuedRequest {\n messages: Array<{ role: string; content: string }>;\n options: LocalLlmChatCompletionOptions;\n priority: LocalLlmRequestPriority;\n enqueuedAtMs: number;\n resolve: (value: LocalLlmChatCompletionResult | null) => void;\n}\n\ninterface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\n\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\ntype LocalLlmBackendState = {\n untilMs: number;\n reason: string;\n};\nexport class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private detectedType: LocalLlmType | null = null;\n private cachedModelInfo: LocalModelInfo | null = null;\n private cachedLmsContext: number | null = null;\n private lastLmsCheck: number = 0;\n private consecutive400s: number = 0;\n private cooldownUntilMs: number = 0;\n private modelRegistry?: ModelRegistry;\n private _disableThinking: boolean = false;\n private readonly requestQueues: Record<LocalLlmRequestPriority, LocalLlmQueuedRequest[]> = {\n \"recall-critical\": [],\n background: [],\n };\n private readonly queueProcessing = new Set<LocalLlmRequestPriority>();\n private queueDrainScheduled: boolean = false;\n private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute\n private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n }\n\n /**\n * Request thinking/reasoning suppression on the next chat completion.\n *\n * When `true`, the client will inject\n * `chat_template_kwargs: { enable_thinking: false }` into the request\n * body — **but only when the detected backend is known to support it**\n * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict\n * OpenAI-compat backends reject unknown fields with 400; on those the\n * client fails open (thinking runs normally). This is the safe\n * default for Remnic extraction-style operations: measurable latency\n * win on thinking-capable backends, zero risk on others. Consolidation\n * operations keep thinking enabled unless explicitly added to\n * `THINKING_SUPPRESSED_OPERATIONS`. Issues #548 and #979.\n */\n set disableThinking(value: boolean) {\n this._disableThinking = value;\n }\n\n private resolveHomeDir(): string {\n return this.config.localLlmHomeDir || readEnvVar(\"HOME\") || os.homedir();\n }\n\n private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {\n const headers: Record<string, string> = {\n ...base,\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return headers;\n }\n\n private isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n }\n\n /**\n * Set the ModelRegistry for caching detected capabilities\n */\n setModelRegistry(registry: ModelRegistry): void {\n this.modelRegistry = registry;\n }\n\n /**\n * Get the detected server type (null if not detected)\n */\n getDetectedType(): LocalLlmType | null {\n return this.detectedType;\n }\n\n private getBackendKey(): string {\n return trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n ).replace(/\\/v1$/, \"\");\n }\n\n private getGlobalBackendState(): Map<string, LocalLlmBackendState> {\n const globalAny = globalThis as typeof globalThis & {\n [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendState>;\n };\n if (!globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE]) {\n globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = new Map();\n }\n return globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];\n }\n\n private getTrippedBackendState(now: number): LocalLlmBackendState | null {\n const state = this.getGlobalBackendState().get(this.getBackendKey()) ?? null;\n if (!state) return null;\n if (state.untilMs <= now) {\n this.getGlobalBackendState().delete(this.getBackendKey());\n this.lastHealthCheck = 0;\n return null;\n }\n return state;\n }\n\n private markBackendUnavailable(reason: string, durationMs: number): void {\n const normalizedReason = this.normalizeBackendTripReason(reason);\n if (durationMs > 0) {\n const untilMs = Date.now() + durationMs;\n this.getGlobalBackendState().set(this.getBackendKey(), { untilMs, reason: normalizedReason });\n } else {\n this.getGlobalBackendState().delete(this.getBackendKey());\n }\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.warn(\n `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizedReason}`,\n );\n }\n\n private extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n }\n\n private extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = this.extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return this.extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n }\n\n private normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n }\n\n /**\n * Fetch with timeout for health checks\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n ): Promise<{ ok: boolean; data: unknown; status: number | null }> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n });\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { ok: false, data: null, status: response.status };\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return { ok: true, data: await response.json(), status: response.status };\n } else {\n return { ok: true, data: await response.text(), status: response.status };\n }\n } catch (err) {\n clearTimeout(timeout);\n return { ok: false, data: null, status: null };\n }\n }\n\n private async probeLmStudioNativeModels(\n probeBaseUrl: string,\n ): Promise<{ matched: boolean; unauthorized: boolean }> {\n let unauthorized = false;\n for (const endpoint of [\"/api/v1/models\", \"/api/v0/models\"]) {\n const probe = await this.fetchWithTimeout(`${probeBaseUrl}${endpoint}`);\n if (probe.ok && isLmStudioNativeModelsResponse(probe.data)) {\n return { matched: true, unauthorized };\n }\n if (probe.status === 401 || probe.status === 403) {\n unauthorized = true;\n }\n }\n return { matched: false, unauthorized };\n }\n\n /**\n * Check if local LLM is available\n * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)\n */\n async checkAvailability(): Promise<boolean> {\n // Cache health check results for 1 minute\n const now = Date.now();\n const trippedState = this.getTrippedBackendState(now);\n if (trippedState) {\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.info(\n `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason})`,\n );\n return false;\n }\n if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {\n return this.isAvailable;\n }\n\n // Normalize URL - replace localhost with 127.0.0.1, remove trailing slashes.\n // Probe server-native endpoints from the server root even when users configure\n // the OpenAI-compatible `/v1` base URL for chat completions.\n const configuredBaseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const probeBaseUrl = stripTrailingV1Path(configuredBaseUrl);\n let sawUnauthorizedProbe = false;\n\n // Try to detect which server type is running\n for (const serverConfig of orderedLocalServers(configuredBaseUrl)) {\n const healthUrl = `${probeBaseUrl}${serverConfig.healthEndpoint}`;\n log.debug(`checking ${serverConfig.type} at ${healthUrl}`);\n\n const result = await this.fetchWithTimeout(healthUrl);\n if (result.ok && serverConfig.detectFn(result.data)) {\n if (serverConfig.type === \"mlx\") {\n const lmStudioProbe = await this.probeLmStudioNativeModels(probeBaseUrl);\n if (lmStudioProbe.unauthorized) {\n sawUnauthorizedProbe = true;\n }\n if (lmStudioProbe.matched) {\n this.isAvailable = true;\n this.detectedType = \"lmstudio\";\n this.lastHealthCheck = now;\n log.info(`detected lmstudio at ${configuredBaseUrl}`);\n return true;\n }\n }\n if (serverConfig.type === \"llamacpp\") {\n let sawLlamaCppSignal = false;\n const propsProbe = await this.fetchWithTimeout(`${probeBaseUrl}/props`);\n if (propsProbe.ok && isLlamaCppPropsResponse(propsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (propsProbe.status === 401 || propsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n }\n\n const modelsUrl = `${probeBaseUrl}${serverConfig.modelsEndpoint}`;\n const modelsProbe = await this.fetchWithTimeout(modelsUrl);\n if (modelsProbe.ok && isLlamaCppModelsResponse(modelsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (modelsProbe.status === 401 || modelsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n continue;\n }\n\n const authConfigured =\n Boolean(this.config.localLlmApiKey) &&\n this.config.localLlmAuthHeader !== false;\n if (!sawLlamaCppSignal || (authConfigured && !modelsProbe.ok)) {\n continue;\n }\n }\n this.isAvailable = true;\n this.detectedType = serverConfig.type;\n this.lastHealthCheck = now;\n log.info(`detected ${serverConfig.type} at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n }\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${probeBaseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl);\n if (result.ok) {\n this.isAvailable = true;\n this.detectedType = \"generic\";\n this.lastHealthCheck = now;\n log.info(`detected generic OpenAI-compatible server at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n } catch {\n // Fall through to unavailable\n }\n\n this.isAvailable = false;\n this.detectedType = null;\n this.lastHealthCheck = now;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${configuredBaseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.debug(\"local LLM not available at\", configuredBaseUrl);\n return false;\n }\n\n /**\n * Try to get context window from LM Studio settings.json as fallback.\n * This reads the defaultContextLength setting which is what LM Studio uses\n * when loading models without explicit context configuration.\n */\n private getContextFromLmStudioSettings(): number | null {\n try {\n const homeDir = this.resolveHomeDir();\n const settingsPath = `${homeDir}/.cache/lm-studio/settings.json`;\n\n if (!fs.existsSync(settingsPath)) {\n log.debug(`LM Studio settings: file not found at ${settingsPath}`);\n return null;\n }\n\n const content = fs.readFileSync(settingsPath, \"utf-8\");\n const settings = JSON.parse(content) as {\n defaultContextLength?: {\n type?: string;\n value?: number;\n };\n };\n\n if (settings.defaultContextLength?.value) {\n const contextWindow = settings.defaultContextLength.value;\n log.debug(`LM Studio settings: found default context length: ${contextWindow}`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LM Studio settings: failed to read - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Try to get context window from LMS CLI (LM Studio specific).\n * Uses --json flag for reliable parsing.\n * Returns null if LMS CLI is not available or model not found.\n */\n private getContextFromLmsCli(modelId: string): number | null {\n try {\n // Check if lms CLI exists in common locations.\n // HOME may be absent in launchd environments, so prefer the resolved helper.\n const homeDir = this.resolveHomeDir();\n const lmsPaths = [\n this.config.localLmsCliPath || \"\",\n `${homeDir}/.cache/lm-studio/bin/lms`,\n \"/usr/local/bin/lms\",\n \"/opt/homebrew/bin/lms\",\n ];\n\n const lmsPath = lmsPaths.find((p) => p.length > 0 && fs.existsSync(p));\n if (!lmsPath) {\n log.debug(`LMS CLI: not found in standard locations (checked: ${lmsPaths.join(\", \")})`);\n return null;\n }\n\n // Run lms ps --json to get loaded models with context\n // Use spawnSync with shell and explicit PATH to ensure lms can find its dependencies\n log.debug(`LMS CLI: running: ${lmsPath} ps --json`);\n const existingPath = readEnvVar(\"PATH\") || \"\";\n const result = launchProcessSync(lmsPath, [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false, // Don't use shell for JSON output - more reliable\n env: mergeEnv({\n PATH: `${this.config.localLmsBinDir || `${homeDir}/.cache/lm-studio/bin`}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${existingPath}`,\n HOME: homeDir,\n }),\n });\n\n if (result.error) {\n log.debug(`LMS CLI: spawn error - ${result.error.message}`);\n return null;\n }\n\n if (result.stderr && result.stderr.trim()) {\n log.debug(`LMS CLI: stderr - ${result.stderr.slice(0, 200)}`);\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n log.debug(\"LMS CLI: empty output - LM Studio may not be running or no models loaded\");\n return null;\n }\n\n // Parse JSON output\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch (parseErr) {\n log.debug(`LMS CLI: JSON parse error - ${parseErr}`);\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n log.debug(\"LMS CLI: no models loaded\");\n return null;\n }\n\n // Find the model matching our configured model ID\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model) {\n log.debug(`LMS CLI: model \"${modelId}\" not found in loaded models: ${models.map(m => m.identifier).join(\", \")}`);\n return null;\n }\n\n // Use contextLength (actual configured) or fall back to maxContextLength (model max)\n const contextWindow = model.contextLength || model.maxContextLength;\n\n if (contextWindow) {\n log.info(`LMS CLI detected context window: ${contextWindow} for ${modelId} (max: ${model.maxContextLength})`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n // LMS CLI not available or failed\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LMS CLI: failed - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Get full model info from LMS CLI including context length and max context length.\n * Returns null if LMS CLI is unavailable or model not found.\n */\n private getLmsModelInfo(modelId: string): { contextLength: number; maxContextLength: number; identifier: string } | null {\n try {\n const result = launchProcessSync(\"lms\", [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false,\n });\n\n if (result.error) {\n return null;\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n return null;\n }\n\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch {\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n return null;\n }\n\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model || !model.contextLength) {\n return null;\n }\n\n return {\n contextLength: model.contextLength,\n maxContextLength: model.maxContextLength || model.contextLength,\n identifier: model.identifier || modelId,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Get context window for the configured model, using cache if available.\n * This method caches the result to avoid repeated LMS CLI calls.\n * Order: ModelRegistry (persistent) -> memory cache -> LMS CLI -> settings.json\n */\n getCachedContextWindow(modelId: string): number | null {\n const now = Date.now();\n\n // 1. Check ModelRegistry for persisted context window\n if (this.modelRegistry) {\n const caps = this.modelRegistry.getCapabilities(modelId);\n if (caps.source === \"lmstudio\" && caps.contextWindow) {\n log.debug(`ModelRegistry: using persisted LM Studio context: ${caps.contextWindow}`);\n // Also update memory cache\n this.cachedLmsContext = caps.contextWindow;\n this.lastLmsCheck = now;\n return caps.contextWindow;\n }\n }\n\n // 2. Return in-memory cached value if still valid\n if (this.cachedLmsContext && now - this.lastLmsCheck < LocalLlmClient.LMS_CACHE_INTERVAL_MS) {\n log.debug(`LMS CLI: returning in-memory cached context: ${this.cachedLmsContext}`);\n return this.cachedLmsContext;\n }\n\n // 3. Try LMS CLI (authoritative source)\n const lmsInfo = this.getLmsModelInfo(modelId);\n if (lmsInfo?.contextLength) {\n this.cachedLmsContext = lmsInfo.contextLength;\n this.lastLmsCheck = now;\n // Calculate appropriate output tokens based on context size\n // Use 12.5% of context window, capped at 16K (generous but safe)\n const calculatedOutputTokens = Math.min(Math.floor(lmsInfo.contextLength / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096); // Minimum 4K\n // Persist to ModelRegistry with detected capabilities\n if (this.modelRegistry) {\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: lmsInfo.maxContextLength || lmsInfo.contextLength,\n contextWindow: lmsInfo.contextLength,\n supportsExtendedContext: (lmsInfo.maxContextLength || lmsInfo.contextLength) > 65536,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n log.info(`LMS CLI: Stored capabilities for ${modelId}: ${lmsInfo.contextLength} context, ${outputTokens} output tokens`);\n }\n return lmsInfo.contextLength;\n }\n\n // Legacy: Try LMS CLI context only (fallback)\n const legacyContext = this.getContextFromLmsCli(modelId);\n if (legacyContext) {\n this.cachedLmsContext = legacyContext;\n this.lastLmsCheck = now;\n // Persist to ModelRegistry with calculated output tokens\n if (this.modelRegistry) {\n const calculatedOutputTokens = Math.min(Math.floor(legacyContext / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096);\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: legacyContext,\n contextWindow: legacyContext,\n supportsExtendedContext: false,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n }\n return legacyContext;\n }\n\n // 4. Fall back to LM Studio settings.json\n const settingsContext = this.getContextFromLmStudioSettings();\n if (settingsContext) {\n log.info(`LM Studio settings: using default context: ${settingsContext}`);\n this.cachedLmsContext = settingsContext;\n this.lastLmsCheck = now;\n return settingsContext;\n }\n\n return null;\n }\n\n /**\n * Clear the LMS context cache. Call this when the model changes.\n */\n clearContextCache(): void {\n this.cachedLmsContext = null;\n this.lastLmsCheck = 0;\n log.debug(\"LMS CLI: context cache cleared\");\n }\n\n private remainingCooldownMs(now: number = Date.now()): number {\n return Math.max(0, this.cooldownUntilMs - now);\n }\n\n private scheduleQueueDrain(): void {\n if (this.queueDrainScheduled) return;\n this.queueDrainScheduled = true;\n\n queueMicrotask(() => {\n this.queueDrainScheduled = false;\n this.startAvailableQueuedRequests();\n });\n }\n\n private hasQueuedRequests(): boolean {\n return (\n this.requestQueues[\"recall-critical\"].length > 0 ||\n this.requestQueues.background.length > 0\n );\n }\n\n private dequeueQueuedRequest(priority: LocalLlmRequestPriority): LocalLlmQueuedRequest | null {\n const next = this.requestQueues[priority].shift();\n return next ?? null;\n }\n\n private failOpenQueuedRequestsForCooldown(): number {\n let dropped = 0;\n for (const priority of [\"recall-critical\", \"background\"] as const) {\n while (this.requestQueues[priority].length > 0) {\n const queued = this.requestQueues[priority].shift();\n queued?.resolve(null);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n private startAvailableQueuedRequests(): void {\n if (!this.queueProcessing.has(\"recall-critical\")) {\n const nextCritical = this.dequeueQueuedRequest(\"recall-critical\");\n if (nextCritical) {\n this.queueProcessing.add(\"recall-critical\");\n void this.runQueuedRequest(nextCritical);\n }\n }\n\n if (!this.queueProcessing.has(\"background\")) {\n const nextBackground = this.dequeueQueuedRequest(\"background\");\n if (nextBackground) {\n this.queueProcessing.add(\"background\");\n void this.runQueuedRequest(nextBackground);\n }\n }\n }\n\n private async runQueuedRequest(next: LocalLlmQueuedRequest): Promise<void> {\n try {\n const remainingCooldownMs = this.remainingCooldownMs();\n if (remainingCooldownMs > 0) {\n const additionalDropped = this.failOpenQueuedRequestsForCooldown();\n log.warn(\n `local LLM: cooldown active (${remainingCooldownMs}ms remaining), dropping ${additionalDropped + 1} queued request(s) fail-open`,\n );\n next.resolve(null);\n return;\n }\n\n let result: LocalLlmChatCompletionResult | null = null;\n try {\n result = await this.runChatCompletionRequest(next.messages, next.options, {\n priority: next.priority,\n enqueuedAtMs: next.enqueuedAtMs,\n });\n } catch (err) {\n log.warn(`local LLM queue drain failed open: ${err instanceof Error ? err.message : String(err)}`);\n }\n next.resolve(result);\n } finally {\n this.queueProcessing.delete(next.priority);\n if (this.hasQueuedRequests()) {\n this.scheduleQueueDrain();\n }\n }\n }\n\n private async runChatCompletionRequest(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions,\n queueMeta?: { priority: LocalLlmRequestPriority; enqueuedAtMs: number },\n ): Promise<LocalLlmChatCompletionResult | null> {\n log.debug(\n `local LLM chatCompletion: localLlmEnabled=${resolveLocalLlmCapabilities(this.config).localLlm}, model=${this.config.localLlmModel}`,\n );\n\n const operation = options.operation ?? \"unspecified\";\n const startedAtMs = Date.now();\n if (queueMeta) {\n log.debug(\n `local LLM queue start: priority=${queueMeta.priority} waitMs=${startedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n\n try {\n const isAvailable = await this.checkAvailability();\n if (!isAvailable) {\n log.debug(\n `local LLM: checkAvailability returned false for ${this.config.localLlmUrl}`,\n );\n return null;\n }\n\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const requestBody: Record<string, unknown> = {\n model: this.config.localLlmModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n };\n\n // Skip response_format for local LLMs - they don't support json_object type\n // The prompts already instruct the model to output JSON\n // Only send if it's json_schema type which some local LLMs support\n if (options.responseFormat?.type === \"json_schema\") {\n requestBody.response_format = options.responseFormat;\n }\n\n // Suppress thinking/reasoning for operations that benefit from terse,\n // structured output. Thinking-capable models (Qwen 3.5, Gemma 4,\n // DeepSeek) default to thinking-on via their chat template; sending\n // `chat_template_kwargs: { enable_thinking: false }` tells the template\n // to skip reasoning tokens. Consolidation operations on the main client\n // intentionally keep thinking enabled so entity resolution and\n // deduplication can use the model's reasoning path. Fast-tier callers can\n // still force suppression per request to preserve their low-latency\n // contract.\n //\n // Gate the injection on detected backend support (issue #548,\n // Codex P1 on PR #550): `chat_template_kwargs` is an LM Studio /\n // vLLM / llama.cpp extension, not part of standard OpenAI chat\n // completions. Strict OpenAI-compatible backends reject\n // unknown fields with 400, which trips the 400-cooldown path and\n // can effectively disable local extraction. Fail open when the\n // backend hasn't been positively identified as thinking-capable.\n const shouldSuppressThinking =\n options.forceDisableThinking === true ||\n (this._disableThinking &&\n THINKING_SUPPRESSED_OPERATIONS.has(operation));\n if (\n shouldSuppressThinking &&\n this.detectedType !== null &&\n THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)\n ) {\n requestBody.chat_template_kwargs = { enable_thinking: false };\n } else if (shouldSuppressThinking && this.detectedType === \"ollama\") {\n // Ollama's /v1 endpoint silently drops `chat_template_kwargs` AND\n // `enable_thinking` — the ONLY field it maps to think-off is\n // `reasoning_effort` (\"none\" → ThinkValue{false} in openai.go;\n // verified against Ollama 0.32.0 source and live probes,\n // issue #1996). Without this, thinking-capable models (Gemma 4,\n // Qwen 3.5+) burn 1,700-2,000 reasoning tokens per extraction on\n // Ollama, exceed the client timeout, and retry forever. The effort\n // is configurable via `localLlmReasoningEffort` (default \"none\");\n // an empty value disables injection (pre-#1996 behavior).\n const effort = this.config.localLlmReasoningEffort;\n if (effort) {\n requestBody.reasoning_effort = effort;\n }\n }\n\n // Normalize URL (use 127.0.0.1 instead of localhost)\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const chatUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/chat/completions`\n : `${baseUrl}/v1/chat/completions`;\n\n const requestBodyJson = JSON.stringify(requestBody);\n log.debug(\n `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,\n );\n // Avoid logging request bodies by default (can contain sensitive user content).\n log.debug(`local LLM: request body length=${requestBodyJson.length}`);\n\n // Write request body to file for debugging\n if (this.config.debug) {\n try {\n const { writeFileSync } = await import(\"node:fs\");\n writeFileSync(\"/tmp/engram-last-request.json\", requestBodyJson);\n } catch {\n /* ignore */\n }\n }\n\n const effectiveTimeoutMs =\n typeof options.timeoutMs === \"number\"\n ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)\n : this.config.localLlmTimeoutMs;\n const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);\n let response: Response | null = null;\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const attemptAbort = new AbortController();\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n try {\n response = await fetch(chatUrl, {\n method: \"POST\",\n headers: this.buildRequestHeaders({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify(requestBody),\n signal: attemptAbort.signal,\n });\n } catch (err) {\n if (!this.isAbortError(err)) throw err;\n lastAbortError = err instanceof Error ? err : new Error(String(err));\n if (attempt < maxAttempts) {\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request aborted: op=${operation} attempt=${attempt}/${maxAttempts} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel}; retrying after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n break;\n } finally {\n clearTimeout(attemptTimeout);\n }\n\n if (response.ok) break;\n if (response.status >= 500 && attempt < maxAttempts) {\n try {\n const errorText = await response.clone().text();\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n } catch (e) {\n log.debug(`local LLM failed to inspect retryable error body: ${e}`);\n }\n }\n if (response.status < 500 || attempt >= maxAttempts) break;\n\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request got ${response.status}; retrying (attempt ${attempt + 1}/${maxAttempts}) after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\n );\n\n if (!response) {\n if (lastAbortError) {\n log.warn(\n `local LLM request aborted after ${maxAttempts} attempt(s): op=${operation} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel} promptChars=${promptChars} durationMs=${Date.now() - startedAtMs}`,\n );\n } else {\n log.warn(\n `local LLM request failed: no response object (op=${operation} model=${this.config.localLlmModel} durationMs=${Date.now() - startedAtMs})`,\n );\n }\n return null;\n }\n\n if (!response.ok) {\n let reason = \"\";\n let errorText = \"\";\n try {\n errorText = await response.text();\n // Try to extract a stable error message without logging content.\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n // Keep a short preview in debug only.\n log.debug(`local LLM error body: ${errorText.slice(0, 500)}`);\n }\n } catch (e) {\n log.debug(`local LLM failed to read error body: ${e}`);\n }\n log.warn(\n `local LLM request failed: ${response.status} ${response.statusText}${reason} ` +\n `(op=${operation}, model=${this.config.localLlmModel}, url=${chatUrl}, promptChars=${promptChars}, maxTokens=${requestBody.max_tokens as number})`,\n );\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReason(reason) ??\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n if (response.status === 400) {\n this.consecutive400s += 1;\n if (this.consecutive400s >= this.config.localLlm400TripThreshold) {\n this.cooldownUntilMs = Date.now() + this.config.localLlm400CooldownMs;\n log.warn(\n `local LLM: entering cooldown for ${this.config.localLlm400CooldownMs}ms ` +\n `after ${this.consecutive400s} consecutive 400 responses`,\n );\n this.consecutive400s = 0;\n }\n } else {\n this.consecutive400s = 0;\n }\n return null;\n }\n this.consecutive400s = 0;\n\n const data = (await response.json()) as {\n choices?: Array<{\n message?: { content?: string; reasoning_content?: string };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n log.debug(\n `local LLM response: choices=${data.choices?.length}, usage=${JSON.stringify(data.usage)}`,\n );\n\n // Thinking models (e.g. Qwen 3.5) may put their response in\n // `reasoning_content` and leave `content` empty. Fall back to\n // reasoning_content so engram still gets a usable result.\n const msg = data.choices?.[0]?.message;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content. choices=${JSON.stringify(data.choices)?.slice(0, 200)}`);\n return null;\n }\n\n // Estimate tokens if not provided by local LLM\n const usage = data.usage\n ? {\n promptTokens: data.usage.prompt_tokens ?? 0,\n completionTokens: data.usage.completion_tokens ?? 0,\n totalTokens: data.usage.total_tokens ?? 0,\n }\n : this.estimateTokens(messages, content);\n\n const durationMs = Date.now() - startedAtMs;\n if (resolvePipelineProcessingCapabilities(this.config).slowLog && durationMs >= this.config.slowLogThresholdMs) {\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const op = options.operation ? ` op=${options.operation}` : \"\";\n log.warn(\n `SLOW local LLM:${op} durationMs=${durationMs} model=${this.config.localLlmModel} url=${chatUrl} promptChars=${promptChars} outputTokens=${usage.completionTokens} totalTokens=${usage.totalTokens}`,\n );\n }\n\n log.debug(\"local LLM: request succeeded, tokens:\", usage.totalTokens);\n return { content, usage };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const durationMs = Date.now() - startedAtMs;\n if (this.isAbortError(err)) {\n log.warn(\n `local LLM request aborted: op=${operation} timeoutMs=${options.timeoutMs ?? this.config.localLlmTimeoutMs} model=${this.config.localLlmModel} durationMs=${durationMs} error=${errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = this.extractNonRecoverableBackendReason(errMsg);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n }\n return null;\n } finally {\n if (queueMeta) {\n const finishedAtMs = Date.now();\n const waitMs = startedAtMs - queueMeta.enqueuedAtMs;\n log.debug(\n `local LLM queue finish: priority=${queueMeta.priority} waitMs=${waitMs} runMs=${finishedAtMs - startedAtMs} totalMs=${finishedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n }\n }\n\n /**\n * Query the local LLM server for loaded model information.\n * Returns null if unavailable or if the model is not found.\n */\n async getLoadedModelInfo(): Promise<LocalModelInfo | null> {\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n\n // Handle URL construction - localLlmUrl may already include /v1\n const modelsUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/models`\n : `${baseUrl}/v1/models`;\n log.debug(`Fetching model info from ${modelsUrl}`);\n\n try {\n const result = await this.fetchWithTimeout(modelsUrl, 3000);\n if (!result.ok) {\n if (result.status === 401 || result.status === 403) {\n log.warn(\n `Local LLM: unauthorized while fetching models from ${modelsUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.warn(`Local LLM: Failed to fetch models from ${modelsUrl} - server returned error`);\n return null;\n }\n if (!result.data) {\n log.warn(`Local LLM: No data returned from ${modelsUrl}`);\n return null;\n }\n\n const data = result.data as {\n data?: Array<{\n id?: string;\n object?: string;\n owned_by?: string;\n // LM Studio specific fields\n max_context_length?: number;\n max_tokens?: number;\n // Ollama specific\n name?: string;\n details?: {\n parameter_size?: string;\n family?: string;\n };\n }>;\n };\n\n if (!Array.isArray(data.data) || data.data.length === 0) {\n log.warn(\"Local LLM returned no models\");\n return null;\n }\n\n // Verbose model listings are noisy on every gateway restart. Keep it debug-only.\n const modelIds = data.data.map((m) => m.id).filter(Boolean);\n log.debug(\n `Local LLM: Found ${modelIds.length} model(s). First 10: ${modelIds.slice(0, 10).join(\", \")}`,\n );\n\n // Find the model matching our configured model ID\n const configuredModel = this.config.localLlmModel;\n let model = data.data.find((m) => m.id === configuredModel);\n\n // If not found by exact match, try partial match (handle suffixes like @4bit)\n if (!model) {\n model = data.data.find((m) =>\n configuredModel.includes(m.id || \"\") ||\n (m.id || \"\").includes(configuredModel.replace(/@\\d+bit$/, \"\"))\n );\n }\n\n // If still not found, use the first loaded model and warn\n if (!model) {\n model = data.data[0];\n const availablePreview = data.data\n .map((m) => m.id)\n .filter(Boolean)\n .slice(0, 10)\n .join(\", \");\n log.warn(\n `Configured model \"${configuredModel}\" not found in local LLM. ` +\n `Using \"${model.id}\" instead. Available (first 10): ${availablePreview}`\n );\n }\n\n // Extract context window - try multiple field names\n let contextWindow = model.max_context_length || model.max_tokens;\n\n // If API doesn't report context window, try LMS CLI (LM Studio specific)\n if (!contextWindow) {\n log.info(\"Local LLM: API did not report context window, trying LMS CLI...\");\n const lmsContext = this.getCachedContextWindow(model.id || \"\");\n if (lmsContext) {\n contextWindow = lmsContext;\n }\n }\n\n this.cachedModelInfo = {\n id: model.id || \"unknown\",\n contextWindow: contextWindow,\n maxTokens: model.max_tokens,\n };\n\n log.info(\n `Local LLM model detected: ${this.cachedModelInfo.id}, ` +\n `context window: ${contextWindow?.toLocaleString() || \"unknown (may use default)\"}`\n );\n\n return this.cachedModelInfo;\n } catch (err) {\n log.warn(`Failed to fetch model info: ${err}`);\n return null;\n }\n }\n\n /**\n * Check if the configured model is available and get its actual context window.\n * Warns if there's a mismatch between expected and actual context.\n */\n async validateModelConfig(expectedContextWindow?: number): Promise<{\n available: boolean;\n actualContextWindow?: number;\n warnings: string[];\n }> {\n const warnings: string[] = [];\n\n const modelInfo = await this.getLoadedModelInfo();\n if (!modelInfo) {\n return { available: false, warnings: [\"Could not query local LLM for model info\"] };\n }\n\n // If we have expected context and the server reports one, check for mismatch\n if (expectedContextWindow && modelInfo.contextWindow) {\n if (modelInfo.contextWindow < expectedContextWindow) {\n warnings.push(\n `Context window mismatch: Model ${modelInfo.id} supports ${modelInfo.contextWindow.toLocaleString()} tokens, ` +\n `but engram is configured for ${expectedContextWindow.toLocaleString()}. ` +\n `Set localLlmMaxContext: ${modelInfo.contextWindow} in config to avoid errors.`\n );\n }\n }\n\n // Warn if server doesn't report context window (common with some local LLM setups)\n if (!modelInfo.contextWindow) {\n warnings.push(\n `Local LLM server did not report context window for ${modelInfo.id}. ` +\n `If you get \"context length exceeded\" errors, set localLlmMaxContext in config.`\n );\n }\n\n return {\n available: true,\n actualContextWindow: modelInfo.contextWindow,\n warnings,\n };\n }\n\n /**\n * Make a chat completion request to local LLM\n */\n async chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions = {},\n ): Promise<LocalLlmChatCompletionResult | null> {\n if (!resolveLocalLlmCapabilities(this.config).localLlm) {\n log.debug(\"local LLM: disabled, returning null\");\n return null;\n }\n\n const remainingMs = this.remainingCooldownMs();\n if (remainingMs > 0) {\n log.debug(`local LLM: cooldown active (${remainingMs}ms remaining), skipping request`);\n return null;\n }\n if (options.priority) {\n const priority = options.priority;\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n this.requestQueues[priority].push({\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve,\n });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n\n /**\n * Estimate tokens when local LLM doesn't return usage stats\n * Rough estimate: 1 token ≈ 4 characters\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n const promptTokens = Math.ceil(promptChars / 4);\n const completionTokens = Math.ceil(response.length / 4);\n\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n }\n\n /**\n * Try local LLM first, fallback to cloud provider if configured\n */\n async withFallback<T>(\n localOperation: () => Promise<T | null>,\n fallbackOperation: () => Promise<T>,\n operationName: string\n ): Promise<T> {\n // Try local LLM first if enabled\n if (resolveLocalLlmCapabilities(this.config).localLlm) {\n const localResult = await localOperation();\n if (localResult !== null) {\n log.debug(`${operationName}: used local LLM`);\n return localResult;\n }\n\n // Local failed or unavailable\n if (this.config.localLlmFallback) {\n log.info(`${operationName}: local LLM unavailable, falling back to cloud`);\n } else {\n throw new Error(`${operationName}: local LLM unavailable and fallback disabled`);\n }\n }\n\n // Use fallback (cloud provider)\n return fallbackOperation();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,OAAO,QAAQ;AACf,OAAO,QAAQ;AAQf,SAAS,oBAAoB,GAAmB;AAC9C,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,MAAM,CAAC,MAAM,IAAK;AACtC,SAAO,EAAE,UAAU,GAAG,GAAG;AAC3B;AAEA,SAAS,oBAAoB,GAAmB;AAC9C,SAAO,EAAE,SAAS,KAAK,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI;AAC9C;AAEA,SAAS,oBAAoB,GAA0B;AACrD,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,CAAC;AACxB,QAAI,CAAC,OAAO,KAAM,QAAO;AACzB,UAAM,OAAO,OAAO,OAAO,IAAI;AAC/B,WAAO,OAAO,UAAU,IAAI,IAAI,OAAO;AAAA,EACzC,QAAQ;A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,mBACA,eACY;AAEZ,QAAI,4BAA4B,KAAK,MAAM,EAAE,UAAU;AACrD,YAAM,cAAc,MAAM,eAAe;AACzC,UAAI,gBAAgB,MAAM;AACxB,YAAI,MAAM,GAAG,aAAa,kBAAkB;AAC5C,eAAO;AAAA,MACT;AAGA,UAAI,KAAK,OAAO,kBAAkB;AAChC,YAAI,KAAK,GAAG,aAAa,gDAAgD;AAAA,MAC3E,OAAO;AACL,cAAM,IAAI,MAAM,GAAG,aAAa,+CAA+C;AAAA,MACjF;AAAA,IACF;AAGA,WAAO,kBAAkB;AAAA,EAC3B;AACF;","names":["backoffMs","promptChars"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/graph.ts"],"sourcesContent":["/**\n * Multi-Graph Memory (MAGMA/SYNAPSE-inspired, v8.2)\n *\n * Maintains three typed edge graphs:\n * entity.jsonl — memories sharing a named entity (entityRef)\n * time.jsonl — consecutive memories in the same thread/session\n * causal.jsonl — memories linked by causal language heuristics\n *\n * Stored under `<memoryDir>/state/graphs/`.\n * All writes are fail-open: errors are caught/logged, never thrown.\n */\n\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { readEdgeConfidence } from \"./graph-edge-reinforcement.js\";\nimport { emitGraphEvent } from \"./graph-events.js\";\nimport type { GraphConstructionCapabilitySet } from \"./capabilities.js\";\n\nexport type GraphType = \"entity\" | \"time\" | \"causal\";\n\nexport interface GraphEdge {\n from: string; // relative memory path (e.g. \"facts/2026-02-22/abc.md\")\n to: string; // relative memory path\n type: GraphType;\n weight: number; // 1.0 default, decay applied during traversal\n label: string; // entity name, threadId, or matched causal phrase\n ts: string; // ISO timestamp of edge creation\n\n // Issue #681 — edge confidence + reinforcement (PR 1/3: schema + primitive only).\n // Both fields are optional so existing edges without confidence still validate.\n // Treat a missing `confidence` as 1.0 (legacy behavior) at read sites.\n // PR 2/3 wires the maintenance decay job; PR 3/3 weights PageRank traversal by confidence.\n confidence?: number; // [0, 1]; missing = 1.0\n lastReinforcedAt?: string; // ISO timestamp of most recent reinforcement\n}\n\nexport interface GraphConfig {\n multiGraphMemoryEnabled: boolean;\n entityGraphEnabled: boolean;\n timeGraphEnabled: boolean;\n causalGraphEnabled: boolean;\n maxGraphTraversalSteps: number;\n graphActivationDecay: number;\n maxEntityGraphEdgesPerMemory: number;\n graphLateralInhibitionEnabled: boolean;\n graphLateralInhibitionBeta: number;\n graphLateralInhibitionTopM: number;\n /**\n * Issue #681 PR 3/3 — minimum edge confidence required for traversal.\n * Edges with confidence below this floor are pruned. Legacy edges\n * (no `confidence` field) are treated as 1.0 and always pass.\n * Range `[0, 1]`. Default 0.2.\n */\n graphTraversalConfidenceFloor: number;\n /**\n * Issue #681 PR 3/3 — number of PageRank-style refinement iterations\n * applied on top of BFS activation. Set to 0 to disable refinement\n * and return raw BFS scores. Default 8.\n */\n graphTraversalPageRankIterations: number;\n}\n\n/** Default minimum edge confidence required for traversal (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR = 0.2;\n/** Default PageRank-style refinement iteration count (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_PAGERANK_ITERATIONS = 8;\n\n// Causal signal phrases — order matters (most specific first)\nexport const CAUSAL_PHRASES = [\"as a result\", \"led to\", \"because of\", \"therefore\", \"caused\", \"because\"];\n\nexport function graphsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"graphs\");\n}\n\nexport function graphFilePath(memoryDir: string, type: GraphType): string {\n return path.join(graphsDir(memoryDir), `${type}.jsonl`);\n}\n\nexport async function ensureGraphsDir(memoryDir: string): Promise<void> {\n await mkdir(graphsDir(memoryDir), { recursive: true });\n}\n\n// ---------------------------------------------------------------------------\n// Per-graph-file write lock (gotcha #40 promise-chain pattern).\n//\n// Both the append path (`appendEdge`) and the rewrite path used by the\n// decay maintenance job must serialize on the same lock keyed by the\n// JSONL file path. Without this, an extraction can append a new edge\n// between the decay job's read-snapshot and rewrite, silently dropping\n// the appended edge during active traffic (issue #729 / Codex P1).\n// ---------------------------------------------------------------------------\nconst graphWriteLocks = new Map<string, Promise<void>>();\n\n/**\n * Run `fn` while holding the write lock for the given graph JSONL file.\n *\n * The lock is keyed by absolute file path so concurrent writes to\n * different graph types proceed independently. The chain recovers from\n * rejection (gotcha #40) so a single I/O failure does not poison all\n * future writers, but the original error is still surfaced to the\n * caller of `withGraphWriteLock`.\n */\nexport function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n const prev = graphWriteLocks.get(filePath) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n graphWriteLocks.set(\n filePath,\n next.then(\n () => undefined,\n () => undefined\n )\n );\n return next;\n}\n\nexport async function appendEdge(memoryDir: string, edge: GraphEdge): Promise<void> {\n await ensureGraphsDir(memoryDir);\n const filePath = graphFilePath(memoryDir, edge.type);\n const line = `${JSON.stringify(edge)}\\n`;\n await withGraphWriteLock(filePath, async () => {\n await appendFile(filePath, line, \"utf8\");\n });\n // Emit edge-added event for SSE subscribers (issue #691 PR 5/5).\n // Fail-open: emitGraphEvent catches listener errors so a bad SSE client\n // can never surface into the extraction pipeline.\n emitGraphEvent(memoryDir, \"edge-added\", {\n source: edge.from,\n target: edge.to,\n kind: edge.type,\n weight: edge.weight,\n label: edge.label,\n confidence: typeof edge.confidence === \"number\" ? edge.confidence : 1.0,\n });\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\nfunction parseEdgesJsonl(raw: string, expectedType: GraphType): GraphEdge[] {\n const edges: GraphEdge[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (isValidGraphEdge(parsed, expectedType)) {\n edges.push(parsed);\n }\n } catch {\n // skip corrupt lines — fail-open for partial JSONL recovery\n }\n }\n return edges;\n}\n\n/**\n * Read all edges of a given type from the JSONL file.\n * Returns [] if the file doesn't exist or any read error occurs (fail-open).\n *\n * Production traversal callers (recall/PageRank) depend on this fail-open\n * posture so a temporarily missing or unreadable graph file never blocks\n * a recall. Maintenance jobs that need to distinguish ENOENT from real\n * I/O failures must use {@link readEdgesStrict} instead.\n */\nexport async function readEdges(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch {\n return [];\n }\n}\n\n/**\n * Same as {@link readEdges} but only swallows `ENOENT`; all other read\n * errors (`EACCES`, `EIO`, …) are propagated. Used by the graph-edge\n * decay maintenance job so I/O outages surface as a failed run instead\n * of being silently reported as \"no edges to decay\" (issue #729 /\n * Codex P1, line 120).\n */\nexport async function readEdgesStrict(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Read edges from all enabled graph types.\n */\nexport async function readAllEdges(\n memoryDir: string,\n graphCaps: Pick<GraphConstructionCapabilitySet, \"entityGraph\" | \"timeGraph\" | \"causalGraph\">,\n): Promise<GraphEdge[]> {\n const parts: GraphEdge[][] = await Promise.all([\n graphCaps.entityGraph ? readEdges(memoryDir, \"entity\") : Promise.resolve([]),\n graphCaps.timeGraph ? readEdges(memoryDir, \"time\") : Promise.resolve([]),\n graphCaps.causalGraph ? readEdges(memoryDir, \"causal\") : Promise.resolve([]),\n ]);\n return parts.flat();\n}\n\nexport interface GraphHealthFileStats {\n type: GraphType;\n filePath: string;\n exists: boolean;\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n}\n\nexport interface GraphHealthReport {\n generatedAt: string;\n enabledTypes: GraphType[];\n totals: {\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n };\n files: GraphHealthFileStats[];\n repairGuidance?: string[];\n}\n\nfunction isValidGraphEdge(raw: unknown, expectedType: GraphType): raw is GraphEdge {\n if (!raw || typeof raw !== \"object\") return false;\n const edge = raw as Record<string, unknown>;\n return (\n edge.type === expectedType &&\n typeof edge.from === \"string\" &&\n edge.from.length > 0 &&\n typeof edge.to === \"string\" &&\n edge.to.length > 0 &&\n typeof edge.weight === \"number\" &&\n Number.isFinite(edge.weight) &&\n typeof edge.label === \"string\" &&\n typeof edge.ts === \"string\"\n );\n}\n\nexport async function analyzeGraphHealth(\n memoryDir: string,\n options?: {\n entityGraphEnabled?: boolean;\n timeGraphEnabled?: boolean;\n causalGraphEnabled?: boolean;\n includeRepairGuidance?: boolean;\n }\n): Promise<GraphHealthReport> {\n const enabledTypes: GraphType[] = [];\n if (options?.entityGraphEnabled !== false) enabledTypes.push(\"entity\");\n if (options?.timeGraphEnabled !== false) enabledTypes.push(\"time\");\n if (options?.causalGraphEnabled !== false) enabledTypes.push(\"causal\");\n\n const files: GraphHealthFileStats[] = [];\n const globalNodes = new Set<string>();\n\n for (const type of enabledTypes) {\n const filePath = graphFilePath(memoryDir, type);\n let exists = true;\n let totalLines = 0;\n let validEdges = 0;\n let corruptLines = 0;\n const nodes = new Set<string>();\n\n try {\n const raw = await readFile(filePath, \"utf8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n totalLines += 1;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!isValidGraphEdge(parsed, type)) {\n corruptLines += 1;\n continue;\n }\n validEdges += 1;\n nodes.add(parsed.from);\n nodes.add(parsed.to);\n globalNodes.add(parsed.from);\n globalNodes.add(parsed.to);\n } catch {\n corruptLines += 1;\n }\n }\n } catch {\n exists = false;\n }\n\n files.push({\n type,\n filePath,\n exists,\n totalLines,\n validEdges,\n corruptLines,\n uniqueNodes: nodes.size,\n });\n }\n\n const totals = files.reduce(\n (acc, item) => {\n acc.totalLines += item.totalLines;\n acc.validEdges += item.validEdges;\n acc.corruptLines += item.corruptLines;\n return acc;\n },\n {\n totalLines: 0,\n validEdges: 0,\n corruptLines: 0,\n uniqueNodes: globalNodes.size,\n }\n );\n totals.uniqueNodes = globalNodes.size;\n\n const report: GraphHealthReport = {\n generatedAt: new Date().toISOString(),\n enabledTypes,\n totals,\n files,\n };\n\n if (options?.includeRepairGuidance === true) {\n const guidance: string[] = [];\n if (totals.corruptLines > 0) {\n guidance.push(\n \"Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs.\"\n );\n }\n if (totals.validEdges === 0) {\n guidance.push(\n \"No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files.\"\n );\n }\n if (guidance.length > 0) report.repairGuidance = guidance;\n }\n\n return report;\n}\n\n/**\n * Detect causal signal phrases in text. Returns the first matched phrase, or null.\n */\nexport function detectCausalPhrase(text: string): string | null {\n const lower = text.toLowerCase();\n for (const phrase of CAUSAL_PHRASES) {\n if (lower.includes(phrase)) return phrase;\n }\n return null;\n}\n\n/**\n * GraphIndex — builds and updates the three memory graphs.\n *\n * Usage (orchestrator):\n * this.graphIndex = new GraphIndex(config.memoryDir, config);\n *\n * // After each memory write:\n * await this.graphIndex.onMemoryWritten(memoryPath, frontmatter, threadId, recentInThread);\n */\nexport class GraphIndex {\n private readonly memoryDir: string;\n private readonly cfg: GraphConfig;\n\n // Cache for readAllEdges() result. With 30k+ entity edges (6 MB JSONL) the\n // file read + JSON parse takes 2-4 s per call. This instance-level cache\n // eliminates that overhead on every spreadingActivation() call; it is\n // invalidated (set to null) in onMemoryWritten() so new edges appear promptly.\n private edgeCache: { allEdges: GraphEdge[]; loadedAt: number } | null = null;\n private static readonly EDGE_CACHE_TTL_MS = 300_000; // 5 minutes\n\n constructor(memoryDir: string, cfg: GraphConfig) {\n this.memoryDir = memoryDir;\n this.cfg = cfg;\n }\n\n /** Clear the edge cache so the next spreadingActivation() re-reads from disk.\n * Call after any code path that appends edges outside of onMemoryWritten(). */\n invalidateEdgeCache(): void {\n this.edgeCache = null;\n }\n\n private async loadEdgesCached(): Promise<GraphEdge[]> {\n if (this.edgeCache && Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS) {\n return this.edgeCache.allEdges;\n }\n const allEdges = await readAllEdges(this.memoryDir, {\n entityGraph: this.cfg.entityGraphEnabled,\n timeGraph: this.cfg.timeGraphEnabled,\n causalGraph: this.cfg.causalGraphEnabled,\n });\n this.edgeCache = { allEdges, loadedAt: Date.now() };\n return allEdges;\n }\n\n /**\n * Called after a memory is written to disk.\n *\n * @param memoryPath - relative path from memoryDir (e.g. \"facts/2026-02-22/abc.md\")\n * @param entityRef - entityRef frontmatter field (if any)\n * @param content - full memory text (for causal detection)\n * @param created - ISO timestamp of this memory\n * @param threadId - current thread ID (for time graph)\n * @param recentInThread - paths of the N most-recent memories in this thread (for time graph)\n * @param entitySiblings - paths of other memories that share the same entityRef (for entity graph)\n */\n async onMemoryWritten(opts: {\n memoryPath: string;\n entityRef?: string;\n content: string;\n created: string;\n threadId?: string;\n recentInThread?: string[];\n entitySiblings?: string[];\n causalPredecessor?: string;\n /**\n * Optional frozen gate overrides (from GraphConstructionCapabilitySet).\n * When provided, these take precedence over `this.cfg` so the caller's\n * operation-scoped snapshot is the single source of truth (#1566).\n */\n graphCapsOverride?: {\n entityGraph: boolean;\n timeGraph: boolean;\n causalGraph: boolean;\n multiGraphMemory: boolean;\n };\n }): Promise<void> {\n const g = opts.graphCapsOverride;\n const multiGraphOn = g ? g.multiGraphMemory : this.cfg.multiGraphMemoryEnabled;\n if (!multiGraphOn) return;\n const entityOn = g ? g.entityGraph : this.cfg.entityGraphEnabled;\n const timeOn = g ? g.timeGraph : this.cfg.timeGraphEnabled;\n const causalOn = g ? g.causalGraph : this.cfg.causalGraphEnabled;\n const ts = new Date().toISOString();\n\n try {\n // Entity graph\n if (entityOn && opts.entityRef && opts.entitySiblings?.length) {\n const siblings = opts.entitySiblings.slice(0, this.cfg.maxEntityGraphEdgesPerMemory);\n for (const sibling of siblings) {\n await appendEdge(this.memoryDir, {\n from: opts.memoryPath,\n to: sibling,\n type: \"entity\",\n weight: 1.0,\n label: opts.entityRef,\n ts,\n });\n }\n }\n\n // Time graph — link to most recent memory in same thread\n if (timeOn && opts.threadId && opts.recentInThread?.length) {\n const predecessor = opts.recentInThread[opts.recentInThread.length - 1];\n if (predecessor && predecessor !== opts.memoryPath) {\n await appendEdge(this.memoryDir, {\n from: predecessor,\n to: opts.memoryPath,\n type: \"time\",\n weight: 1.0,\n label: opts.threadId,\n ts,\n });\n }\n }\n\n // Causal graph\n if (causalOn && opts.causalPredecessor) {\n const phrase = detectCausalPhrase(opts.content);\n if (phrase) {\n await appendEdge(this.memoryDir, {\n from: opts.causalPredecessor,\n to: opts.memoryPath,\n type: \"causal\",\n weight: 1.0,\n label: phrase,\n ts,\n });\n }\n }\n } catch (err) {\n // Fail-open: graph write errors must never surface to caller\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] onMemoryWritten error: ${err}`);\n } finally {\n // Invalidate edge cache so spreadingActivation() picks up new edges.\n // In `finally` so the cache is cleared even on partial write failure.\n this.edgeCache = null;\n }\n }\n\n /**\n * Spreading activation BFS (SYNAPSE-inspired).\n *\n * Starting from `seeds`, traverse the combined graph for up to `maxSteps` hops.\n * Each candidate gets an activation score = edge.weight × edgeConfidence × decay^hop.\n *\n * Issue #681 PR 3/3 — confidence-aware traversal:\n * - Each edge's `weight` is multiplied by its `confidence` (legacy edges\n * missing `confidence` are treated as 1.0, preserving prior behavior).\n * - Edges with `confidence < graphTraversalConfidenceFloor` are pruned and\n * contribute neither activation nor downstream neighbors.\n * - When `graphTraversalPageRankIterations > 0`, an additional PageRank-\n * style refinement pass redistributes activation along confidence-weighted\n * edges, sharpening the ranking among multi-hop candidates.\n * - Per-result provenance includes the highest-confidence edge that landed\n * on each candidate, so the X-ray surface can attribute pruning and\n * ranking decisions back to specific edges.\n *\n * @param seeds - initial memory paths to expand from (e.g. QMD top results)\n * @param maxSteps - max BFS hops (from config: maxGraphTraversalSteps)\n * @returns Array of {path, score, edgeConfidence, ...} sorted descending, not including seed paths\n */\n async spreadingActivation(\n seeds: string[],\n maxSteps?: number,\n opts?: {\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` and includes low-confidence\n * edges in traversal. Equivalent to forcing the floor to `0`.\n * Default `false` (floor from config is applied).\n */\n includeLowConfidence?: boolean;\n /** Absolute deadline in ms-since-epoch for post-retrieval assembly. */\n deadlineAtMs?: number;\n }\n ): Promise<\n Array<{\n path: string;\n score: number;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Confidence of the edge that produced this candidate's recorded\n * provenance (the strongest edge along the chosen entry path).\n * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.\n */\n edgeConfidence: number;\n }>\n > {\n if (!this.cfg.multiGraphMemoryEnabled) return [];\n const steps = maxSteps ?? this.cfg.maxGraphTraversalSteps;\n const decay = this.cfg.graphActivationDecay;\n // When `includeLowConfidence` is set, use floor=0 so all edges\n // participate in traversal regardless of their decay state.\n // Otherwise clamp the configured floor into [0, 1] so misconfiguration\n // cannot (a) admit edges with negative confidence or (b) reject every\n // edge.\n const floor =\n opts?.includeLowConfidence === true ? 0 : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);\n const iterations = clampPageRankIterations(this.cfg.graphTraversalPageRankIterations);\n const deadlineAtMs = opts?.deadlineAtMs;\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n try {\n if (deadlineExpired()) return [];\n const allEdges = await this.loadEdgesCached();\n if (deadlineExpired()) return [];\n\n // Build adjacency index: from → edges, to → edges (bidirectional for entity/time, directional for causal).\n // Edges below the confidence floor are pruned at index time so neither\n // direct activation nor downstream BFS expansion can re-introduce them.\n const adj = new Map<string, GraphEdge[]>();\n for (let i = 0; i < allEdges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return [];\n const edge = allEdges[i];\n const conf = readEdgeConfidence(edge);\n if (conf < floor) continue;\n if (!adj.has(edge.from)) adj.set(edge.from, []);\n adj.get(edge.from)!.push(edge);\n // Entity and time edges are bidirectional\n if (edge.type !== \"causal\") {\n if (!adj.has(edge.to)) adj.set(edge.to, []);\n adj.get(edge.to)!.push({ ...edge, from: edge.to, to: edge.from });\n }\n }\n\n const seedSet = new Set(seeds);\n const scores = new Map<string, number>(); // candidate path → accumulated activation score\n const provenance = new Map<\n string,\n {\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n edgeConfidence: number;\n }\n >();\n let frontier = new Map<string, { node: string; seed: string; activation: number }>();\n const reachedBySeed = new Map<string, Set<string>>();\n for (const seed of seeds) {\n frontier.set(`${seed}\\0${seed}`, { node: seed, seed, activation: 1 });\n reachedBySeed.set(seed, new Set([seed]));\n }\n const finalizeScores = () =>\n Array.from(scores.entries())\n .map(([p, score]) => ({\n path: p,\n score,\n seed: provenance.get(p)?.seed ?? \"\",\n hopDepth: provenance.get(p)?.hopDepth ?? 0,\n decayedWeight: provenance.get(p)?.decayedWeight ?? 0,\n graphType: provenance.get(p)?.graphType ?? \"entity\",\n edgeConfidence: provenance.get(p)?.edgeConfidence ?? 1,\n }))\n .sort((a, b) => b.score - a.score);\n\n for (let hop = 0; hop < steps && frontier.size > 0; hop++) {\n if (deadlineExpired()) return finalizeScores();\n const nextFrontier = new Map<string, { node: string; seed: string; activation: number }>();\n\n for (const { node, seed: sourceSeed, activation } of frontier.values()) {\n const edges = adj.get(node) ?? [];\n for (let i = 0; i < edges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return finalizeScores();\n const edge = edges[i];\n const neighbor = edge.to === node ? edge.from : edge.to;\n const conf = readEdgeConfidence(edge);\n // Defense in depth: the adjacency build already drops sub-floor\n // edges, but if a synthesized reverse edge ever bypassed that\n // path, this guard keeps spreading activation honest.\n if (conf < floor) continue;\n const score = activation * edge.weight * conf * decay;\n const reachedForSeed = reachedBySeed.get(sourceSeed);\n if (reachedForSeed?.has(neighbor)) {\n continue;\n }\n\n if (!seedSet.has(neighbor)) {\n const existing = scores.get(neighbor) ?? 0;\n scores.set(neighbor, existing + score);\n\n const prev = provenance.get(neighbor);\n if (!prev || hop + 1 < prev.hopDepth || (hop + 1 === prev.hopDepth && score > prev.decayedWeight)) {\n provenance.set(neighbor, {\n seed: sourceSeed,\n hopDepth: hop + 1,\n decayedWeight: score,\n graphType: edge.type,\n edgeConfidence: conf,\n });\n }\n\n if (hop + 1 < steps) {\n const frontierKey = `${sourceSeed}\\0${neighbor}`;\n const existingFrontier = nextFrontier.get(frontierKey);\n if (existingFrontier) {\n existingFrontier.activation += score;\n } else {\n nextFrontier.set(frontierKey, {\n node: neighbor,\n seed: sourceSeed,\n activation: score,\n });\n }\n }\n }\n }\n }\n\n for (const { node, seed } of nextFrontier.values()) {\n reachedBySeed.get(seed)?.add(node);\n }\n frontier = nextFrontier;\n }\n\n // Issue #681 PR 3/3 — optional PageRank-style refinement.\n // Redistributes a node's accumulated activation along its outgoing\n // edges, weighted by edge confidence. Damping is fixed at the\n // canonical 0.85 so the ranking stays comparable across queries;\n // the `iterations` knob bounds compute, not behavior shape.\n if (!deadlineExpired() && iterations > 0 && scores.size > 1) {\n applyPageRankRefinement(scores, adj, {\n iterations,\n floor,\n damping: 0.85,\n deadlineAtMs,\n });\n }\n\n // Apply lateral inhibition if enabled (Synapse-inspired competitive suppression)\n if (deadlineExpired()) return finalizeScores();\n if (this.cfg.graphLateralInhibitionEnabled && scores.size > 1) {\n const inhibited = applyLateralInhibition(scores, {\n beta: this.cfg.graphLateralInhibitionBeta,\n topM: this.cfg.graphLateralInhibitionTopM,\n });\n for (const [k, v] of inhibited) {\n scores.set(k, v);\n }\n }\n\n return finalizeScores();\n } catch (err) {\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] spreadingActivation error: ${err}`);\n return [];\n }\n }\n}\n\n/**\n * Clamp `graphTraversalConfidenceFloor` into the legal range `[0, 1]`.\n * Non-finite or non-numeric values fall back to the documented default\n * so misconfiguration cannot silently disable the floor or reject every edge.\n *\n * Exported for tests; call sites in `spreadingActivation` use it to make\n * the contract explicit at every boundary.\n */\nexport function clampConfidenceFloor(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n return DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR;\n }\n if (raw < 0) return 0;\n if (raw > 1) return 1;\n return raw;\n}\n\n/**\n * Clamp `graphTraversalPageRankIterations` into a non-negative integer.\n * Negative or non-finite values fall back to 0 (disable refinement) so\n * misconfiguration cannot stall recall in an unbounded loop.\n */\nexport function clampPageRankIterations(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) return 0;\n if (raw <= 0) return 0;\n return Math.floor(raw);\n}\n\n/**\n * PageRank-style refinement on top of the BFS activation map.\n *\n * Each iteration redistributes a fraction of every node's score along\n * its outgoing edges, scaled by edge confidence. Confidence below\n * `floor` is filtered out before redistribution, mirroring the BFS\n * pruning rule. Mutates `scores` in place.\n *\n * Exported for tests; in production, call sites pass the same adjacency\n * map already used by BFS so behavior stays consistent.\n */\nexport function applyPageRankRefinement(\n scores: Map<string, number>,\n adj: Map<string, GraphEdge[]>,\n opts: { iterations: number; floor: number; damping: number; deadlineAtMs?: number }\n): void {\n const { iterations, floor, damping, deadlineAtMs } = opts;\n if (iterations <= 0 || scores.size === 0) return;\n const safeDamping = Math.min(1, Math.max(0, damping));\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n // Pre-compute confidence-weighted out-edge totals for normalization.\n // Done once per refinement, not per iteration, since adjacency is\n // immutable inside the loop.\n //\n // Codex P1 (#735): the denominator MUST be computed over the same\n // eligible-neighbor set the iteration redistributes into — i.e.\n // edges whose neighbor is in `scores`. Counting edges-to-seeds (or\n // edges-to-unseen-nodes) in the denominator while dropping their\n // flow during iteration leaks `safeDamping × score` every pass and\n // collapses leaf candidates' scores instead of just re-ranking them.\n const eligible = (edge: GraphEdge, fromNode: string): boolean => {\n if (readEdgeConfidence(edge) < floor) return false;\n const neighbor = edge.to === fromNode ? edge.from : edge.to;\n return scores.has(neighbor);\n };\n const outboundTotal = new Map<string, number>();\n for (const [node, edges] of adj.entries()) {\n if (deadlineExpired()) return;\n if (!scores.has(node)) continue; // only candidate nodes redistribute\n let sum = 0;\n for (const edge of edges) {\n if (!eligible(edge, node)) continue;\n sum += readEdgeConfidence(edge) * edge.weight;\n }\n if (sum > 0) outboundTotal.set(node, sum);\n }\n\n for (let i = 0; i < iterations; i += 1) {\n if (deadlineExpired()) return;\n const next = new Map<string, number>();\n // Teleport / damping floor: every node retains `(1 - damping) * score`\n // of its current activation so dangling nodes do not bleed to zero.\n for (const [node, score] of scores) {\n next.set(node, (1 - safeDamping) * score);\n }\n for (const [node, score] of scores) {\n const outEdges = adj.get(node);\n const total = outboundTotal.get(node);\n // Dangling-node fallback: when a candidate has zero eligible\n // outflow (no in-scores neighbors above the floor), the\n // `safeDamping × score` portion would otherwise evaporate. Keep\n // it on `node` so total mass is conserved and the score reflects\n // the candidate's standing rather than its in-degree topology.\n if (!outEdges || outEdges.length === 0 || !total || total <= 0) {\n next.set(node, (next.get(node) ?? 0) + safeDamping * score);\n continue;\n }\n for (let edgeIndex = 0; edgeIndex < outEdges.length; edgeIndex += 1) {\n if ((edgeIndex & 1023) === 0 && deadlineExpired()) return;\n const edge = outEdges[edgeIndex];\n if (!eligible(edge, node)) continue;\n const conf = readEdgeConfidence(edge);\n const neighbor = edge.to === node ? edge.from : edge.to;\n const flow = safeDamping * score * ((conf * edge.weight) / total);\n next.set(neighbor, (next.get(neighbor) ?? 0) + flow);\n }\n }\n for (const [node, score] of next) {\n scores.set(node, score);\n }\n }\n}\n\n/**\n * Lateral inhibition (Synapse-inspired).\n *\n * For each node, the top-M higher-activation competitors exert inhibition\n * proportional to their activation difference. Output is clamped to [0, ∞).\n *\n * No sigmoid is applied here — downstream `normalizeGraphActivationScore`\n * already applies x/(1+x) soft squash, so adding a sigmoid would double-\n * normalize and cap graph influence at ~50%.\n *\n * Formula: u_hat_i = max(0, u_i - beta * sum_{k in top-M where u_k > u_i}(u_k - u_i))\n *\n * When beta=0 or topM=0, returns original scores unchanged (no-op).\n */\nexport function applyLateralInhibition(\n scores: Map<string, number>,\n opts: { beta: number; topM: number }\n): Map<string, number> {\n const { beta, topM } = opts;\n if (beta === 0 || topM === 0) return new Map(scores);\n\n const sorted = Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);\n const topCompetitors = sorted.slice(0, topM);\n\n const result = new Map<string, number>();\n for (const [node, u] of scores) {\n let inhibition = 0;\n for (const [, uK] of topCompetitors) {\n if (uK > u) {\n inhibition += uK - u;\n }\n }\n result.set(node, Math.max(0, u - beta * inhibition));\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;AAYA,SAAS,YAAY,OAAO,gBAAgB;AAC5C,YAAY,UAAU;AAmDf,IAAM,2CAA2C;AAEjD,IAAM,8CAA8C;AAGpD,IAAM,iBAAiB,CAAC,eAAe,UAAU,cAAc,aAAa,UAAU,SAAS;AAE/F,SAAS,UAAU,WAA2B;AACnD,SAAY,UAAK,WAAW,SAAS,QAAQ;AAC/C;AAEO,SAAS,cAAc,WAAmB,MAAyB;AACxE,SAAY,UAAK,UAAU,SAAS,GAAG,GAAG,IAAI,QAAQ;AACxD;AAEA,eAAsB,gBAAgB,WAAkC;AACtE,QAAM,MAAM,UAAU,SAAS,GAAG,EAAE,WAAW,KAAK,CAAC;AACvD;AAWA,IAAM,kBAAkB,oBAAI,IAA2B;AAWhD,SAAS,mBAAsB,UAAkB,IAAkC;AACxF,QAAM,OAAO,gBAAgB,IAAI,QAAQ,KAAK,QAAQ,QAAQ;AAC9D,QAAM,OAAO,KAAK,KAAK,IAAI,EAA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C,cAAM,WAAW,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK;AACrD,cAAM,OAAO,cAAc,SAAU,OAAO,KAAK,SAAU;AAC3D,aAAK,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,KAAK,IAAI;AAAA,MACrD;AAAA,IACF;AACA,eAAW,CAAC,MAAM,KAAK,KAAK,MAAM;AAChC,aAAO,IAAI,MAAM,KAAK;AAAA,IACxB;AAAA,EACF;AACF;AAgBO,SAAS,uBACd,QACA,MACqB;AACrB,QAAM,EAAE,MAAM,KAAK,IAAI;AACvB,MAAI,SAAS,KAAK,SAAS,EAAG,QAAO,IAAI,IAAI,MAAM;AAEnD,QAAM,SAAS,MAAM,KAAK,OAAO,QAAQ,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AACtE,QAAM,iBAAiB,OAAO,MAAM,GAAG,IAAI;AAE3C,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,CAAC,MAAM,CAAC,KAAK,QAAQ;AAC9B,QAAI,aAAa;AACjB,eAAW,CAAC,EAAE,EAAE,KAAK,gBAAgB;AACnC,UAAI,KAAK,GAAG;AACV,sBAAc,KAAK;AAAA,MACrB;AAAA,IACF;AACA,WAAO,IAAI,MAAM,KAAK,IAAI,GAAG,IAAI,OAAO,UAAU,CAAC;AAAA,EACrD;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cross-namespace-budget.ts"],"sourcesContent":["/**\n * Per-principal cross-namespace query-budget limiter (issue #565 PR 4/5).\n *\n * Detects and throttles bursts of recall-type operations that a principal\n * issues against namespaces *other than their own*. Thresholds come from the\n * memory-extraction threat model (`docs/security/memory-extraction-threat-model.md`\n * §6.2) and the ADAM baseline report (`docs/security/adam-baseline-2026-04.md`):\n * a T2-class same-namespace attacker plateaus at 61 queries in the published\n * baseline, so the default window is set well below that to force any\n * adaptive loop to noticeably slow down.\n *\n * Shape:\n * - Pure, in-process, per-principal sliding window. No persistence.\n * - Only cross-namespace reads count: a principal hitting only their own\n * namespace is never throttled.\n * - The limiter is behind the `recallCrossNamespaceBudgetEnabled` feature\n * flag (defaults to `false`) and is a no-op when disabled. This mirrors\n * the canonical \"new filter/transform needs an enabled check\" pattern\n * (see CLAUDE.md gotcha #30).\n *\n * The module has no side effects beyond incrementing its own counters, and\n * it does NOT take a clock dependency — callers pass the current epoch ms\n * (or let the default `Date.now()` do it) so tests can step time\n * deterministically.\n */\n\nexport interface CrossNamespaceBudgetConfig {\n /** Feature flag. Defaults to false — a disabled limiter is always allow. */\n enabled?: boolean;\n /**\n * Rolling window size in milliseconds. Counts decay out of the window\n * as the clock advances. Default: 60_000 (1 minute).\n */\n windowMs?: number;\n /**\n * Soft cap. Once a principal has `softLimit` cross-namespace reads in the\n * window, the limiter *records* a warning on the decision but still\n * allows the call. Used by PR 5's anomaly detector to surface flags\n * without blocking. Default: 10.\n */\n softLimit?: number;\n /**\n * Hard cap. Once `hardLimit` is reached, the limiter denies the call.\n * Default: 30 — picked to be well below the T2 baseline of ~60 queries\n * at half-plateau, so an ADAM-style adaptive loop is throttled before it\n * meaningfully leaks.\n */\n hardLimit?: number;\n}\n\nexport const DEFAULT_CROSS_NAMESPACE_BUDGET: Required<CrossNamespaceBudgetConfig> =\n Object.freeze({\n enabled: false,\n windowMs: 60_000,\n softLimit: 10,\n hardLimit: 30,\n });\n\n/**\n * Why a call was denied / warned. Stable strings so callers can key log\n * lines and metrics on them.\n */\nexport type BudgetDecisionReason =\n | \"allowed-same-namespace\"\n | \"allowed-no-limit\"\n | \"allowed-under-soft\"\n | \"warn-over-soft\"\n | \"deny-over-hard\";\n\nexport interface BudgetDecision {\n allowed: boolean;\n reason: BudgetDecisionReason;\n /** Cross-namespace reads by this principal currently in the window. */\n count: number;\n /** Active config snapshot at decision time. */\n limit: {\n softLimit: number;\n hardLimit: number;\n windowMs: number;\n };\n}\n\ninterface PrincipalBucket {\n /** Epoch-ms timestamps of cross-namespace reads in the active window. */\n timestamps: number[];\n}\n\n/**\n * Normalize the provided config against the defaults and reject clearly\n * invalid shapes (non-positive windows, inverted limits). Never throws —\n * returns a safe effective config the limiter can use.\n */\nfunction effectiveConfig(\n raw: CrossNamespaceBudgetConfig | undefined,\n): Required<CrossNamespaceBudgetConfig> {\n const base = { ...DEFAULT_CROSS_NAMESPACE_BUDGET };\n if (!raw) return base;\n const out = { ...base };\n if (typeof raw.enabled === \"boolean\") out.enabled = raw.enabled;\n if (\n typeof raw.windowMs === \"number\" &&\n Number.isFinite(raw.windowMs) &&\n raw.windowMs > 0\n ) {\n out.windowMs = raw.windowMs;\n }\n if (\n typeof raw.softLimit === \"number\" &&\n Number.isFinite(raw.softLimit) &&\n raw.softLimit >= 0\n ) {\n out.softLimit = Math.floor(raw.softLimit);\n }\n if (\n typeof raw.hardLimit === \"number\" &&\n Number.isFinite(raw.hardLimit) &&\n raw.hardLimit >= 1\n ) {\n // Floor the value, then defensively require the floored result is\n // still >= 1. `raw.hardLimit = 0.5` previously passed the `> 0`\n // gate and floored to 0, turning a minor misconfiguration into a\n // full denial of cross-namespace reads. Now we fall back to the\n // default instead.\n const floored = Math.floor(raw.hardLimit);\n if (floored >= 1) out.hardLimit = floored;\n }\n if (out.softLimit > out.hardLimit) {\n // Inverted limits -> treat soft = hard so we never warn past the deny\n // threshold. Defensive, should never happen with well-formed config.\n out.softLimit = out.hardLimit;\n }\n return out;\n}\n\nfunction normalizeClock(now: number | undefined): number {\n if (now === undefined) return Date.now();\n if (Number.isFinite(now)) return Math.floor(now);\n return 0;\n}\n\n/**\n * In-process cross-namespace budget limiter. Instantiate once per\n * orchestrator / access-service.\n *\n * Threadsafe-by-construction: Node.js is single-threaded per process for\n * application code, and the limiter never awaits between read-modify-write\n * operations on its internal state.\n */\nexport class CrossNamespaceBudget {\n private readonly config: Required<CrossNamespaceBudgetConfig>;\n private readonly buckets = new Map<string, PrincipalBucket>();\n\n constructor(config?: CrossNamespaceBudgetConfig) {\n this.config = effectiveConfig(config);\n }\n\n /** Exposed for tests / audit surfaces. Never mutate the returned value. */\n getConfig(): Required<CrossNamespaceBudgetConfig> {\n return this.config;\n }\n\n /**\n * Check whether `principal` is allowed to issue another cross-namespace\n * read. Call site is expected to compare `principalNamespace` against\n * `queryNamespace` and only pass through reads where they differ — the\n * limiter treats every call as a cross-namespace event.\n *\n * @param principal Stable identifier for the calling principal (token\n * subject, session principal, etc.). Must be non-empty.\n * @param now Epoch-ms clock read. Defaults to `Date.now()`; tests pass a\n * fixed value to step time deterministically.\n */\n record(principal: string, now?: number): BudgetDecision {\n const normalizedNow = normalizeClock(now);\n const { enabled, windowMs, softLimit, hardLimit } = this.config;\n const limit = { softLimit, hardLimit, windowMs };\n\n if (!enabled) {\n return {\n allowed: true,\n reason: \"allowed-no-limit\",\n count: 0,\n limit,\n };\n }\n\n if (typeof principal !== \"string\" || principal.length === 0) {\n // A missing principal means \"we can't attribute this call\". Rather\n // than fail open, treat it as a cross-namespace event against a\n // shared bucket — denial-of-service risk is bounded because the\n // bucket is scoped per-process.\n principal = \"__anonymous__\";\n }\n\n const bucket = this.buckets.get(principal) ?? { timestamps: [] };\n const cutoff = normalizedNow - windowMs;\n // Drop timestamps that slid out of the window.\n while (bucket.timestamps.length > 0 && bucket.timestamps[0]! < cutoff) {\n bucket.timestamps.shift();\n }\n\n // Count the current call against the window BEFORE deciding — a call\n // that crosses the deny threshold should itself be denied, not the\n // next one. This is what the threat model calls \"fail at the Nth,\n // not the (N+1)th\".\n bucket.timestamps.push(normalizedNow);\n this.buckets.set(principal, bucket);\n const count = bucket.timestamps.length;\n\n if (count >= hardLimit) {\n // Denied: roll back the timestamp we just added so a repeated denied\n // call does not push the bucket further into the future. This keeps\n // the limiter stateless with respect to denied attempts.\n bucket.timestamps.pop();\n // Evict empty buckets (e.g. the first record after a long idle\n // rolled the only timestamp out, then got denied and rolled back).\n // Prevents unbounded map growth across many transient principals.\n if (bucket.timestamps.length === 0) {\n this.buckets.delete(principal);\n }\n return {\n allowed: false,\n reason: \"deny-over-hard\",\n count: bucket.timestamps.length,\n limit,\n };\n }\n\n if (count > softLimit) {\n return {\n allowed: true,\n reason: \"warn-over-soft\",\n count,\n limit,\n };\n }\n\n return {\n allowed: true,\n reason: \"allowed-under-soft\",\n count,\n limit,\n };\n }\n\n /**\n * Read-only peek at whether a call would be allowed, WITHOUT recording a\n * timestamp. Useful when the caller must inspect multiple namespaces before\n * deciding to record a single event. The returned `count` reflects the\n * current window state at call time.\n */\n peek(args: {\n principal: string;\n principalNamespace: string;\n queryNamespace: string;\n now?: number;\n }): BudgetDecision {\n const pn = args.principalNamespace;\n const qn = args.queryNamespace;\n const bothPresent =\n typeof pn === \"string\" && pn.length > 0 &&\n typeof qn === \"string\" && qn.length > 0;\n if (bothPresent && pn === qn) {\n return {\n allowed: true,\n reason: \"allowed-same-namespace\",\n count: 0,\n limit: {\n softLimit: this.config.softLimit,\n hardLimit: this.config.hardLimit,\n windowMs: this.config.windowMs,\n },\n };\n }\n // Cross-namespace: simulate what record() would do without the push.\n const { enabled, windowMs, softLimit, hardLimit } = this.config;\n const limit = { softLimit, hardLimit, windowMs };\n if (!enabled) {\n return { allowed: true, reason: \"allowed-no-limit\", count: 0, limit };\n }\n let principal = args.principal;\n if (typeof principal !== \"string\" || principal.length === 0) {\n principal = \"__anonymous__\";\n }\n const now = normalizeClock(args.now);\n const bucket = this.buckets.get(principal) ?? { timestamps: [] };\n const cutoff = now - windowMs;\n let liveCount = 0;\n for (const ts of bucket.timestamps) {\n if (ts >= cutoff) liveCount++;\n }\n const projected = liveCount + 1; // +1 for the current call\n if (projected >= hardLimit) {\n return { allowed: false, reason: \"deny-over-hard\", count: liveCount, limit };\n }\n if (projected > softLimit) {\n return { allowed: true, reason: \"warn-over-soft\", count: projected, limit };\n }\n return { allowed: true, reason: \"allowed-under-soft\", count: projected, limit };\n }\n\n /**\n * Convenience guard that also skips the limiter when `principalNamespace`\n * equals `queryNamespace` (same-namespace is never cross-namespace).\n * Returns an `allowed-same-namespace` decision in that case.\n */\n check(args: {\n principal: string;\n principalNamespace: string;\n queryNamespace: string;\n now?: number;\n }): BudgetDecision {\n // Same-namespace short-circuit requires BOTH namespaces to be\n // non-empty strings. Two empty/undefined namespaces at runtime\n // would otherwise compare equal and fail-open — a critical bypass\n // in a security-critical module. Force the limiter to engage when\n // either side is missing so we never silently skip enforcement.\n const pn = args.principalNamespace;\n const qn = args.queryNamespace;\n const bothPresent =\n typeof pn === \"string\" && pn.length > 0 &&\n typeof qn === \"string\" && qn.length > 0;\n if (bothPresent && pn === qn) {\n return {\n allowed: true,\n reason: \"allowed-same-namespace\",\n count: 0,\n limit: {\n softLimit: this.config.softLimit,\n hardLimit: this.config.hardLimit,\n windowMs: this.config.windowMs,\n },\n };\n }\n return this.record(args.principal, args.now);\n }\n\n /**\n * Clear all state. Intended for tests and for the orchestrator's\n * lifecycle `before_reset` hook.\n */\n reset(): void {\n this.buckets.clear();\n }\n\n /**\n * Evict buckets whose entire timestamp list has slid out of the\n * active window by `now`. Intended to be called periodically by a\n * long-lived host process (e.g. from a maintenance cron) that sees\n * many transient principals. Safe to call at any time; returns the\n * number of buckets evicted.\n */\n gc(now?: number): number {\n const normalizedNow = normalizeClock(now);\n const cutoff = normalizedNow - this.config.windowMs;\n let evicted = 0;\n for (const [principal, bucket] of this.buckets.entries()) {\n while (bucket.timestamps.length > 0 && bucket.timestamps[0]! < cutoff) {\n bucket.timestamps.shift();\n }\n if (bucket.timestamps.length === 0) {\n this.buckets.delete(principal);\n evicted++;\n }\n }\n return evicted;\n }\n\n /** For tests: current number of live buckets. */\n bucketCount(): number {\n return this.buckets.size;\n }\n}\n"],"mappings":";AAkDO,IAAM,iCACX,OAAO,OAAO;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,WAAW;AAAA,EACX,WAAW;AACb,CAAC;AAoCH,SAAS,gBACP,KACsC;AACtC,QAAM,OAAO,EAAE,GAAG,+BAA+B;AACjD,MAAI,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W,KAAK,OAAO;AAAA,UACvB,WAAW,KAAK,OAAO;AAAA,UACvB,UAAU,KAAK,OAAO;AAAA,QACxB;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO,KAAK,WAAW,KAAK,GAAG;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAc;AACZ,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,GAAG,KAAsB;AACvB,UAAM,gBAAgB,eAAe,GAAG;AACxC,UAAM,SAAS,gBAAgB,KAAK,OAAO;AAC3C,QAAI,UAAU;AACd,eAAW,CAAC,WAAW,MAAM,KAAK,KAAK,QAAQ,QAAQ,GAAG;AACxD,aAAO,OAAO,WAAW,SAAS,KAAK,OAAO,WAAW,CAAC,IAAK,QAAQ;AACrE,eAAO,WAAW,MAAM;AAAA,MAC1B;AACA,UAAI,OAAO,WAAW,WAAW,GAAG;AAClC,aAAK,QAAQ,OAAO,SAAS;AAC7B;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,cAAsB;AACpB,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;","names":[]}
@@ -1,32 +0,0 @@
1
- // src/connectors/coerce.ts
2
- function coerceBool(value) {
3
- if (typeof value === "boolean") return value;
4
- if (typeof value === "string") {
5
- const v = value.trim().toLowerCase();
6
- if (["false", "0", "no", "off"].includes(v)) return false;
7
- if (["true", "1", "yes", "on"].includes(v)) return true;
8
- }
9
- return void 0;
10
- }
11
- function coerceInstallExtension(value) {
12
- return coerceBool(value);
13
- }
14
- function coerceNumber(value) {
15
- if (typeof value === "number") {
16
- return Number.isFinite(value) ? value : void 0;
17
- }
18
- if (typeof value === "string") {
19
- const trimmed = value.trim();
20
- if (trimmed.length === 0) return void 0;
21
- const n = Number(trimmed);
22
- return Number.isFinite(n) ? n : void 0;
23
- }
24
- return void 0;
25
- }
26
-
27
- export {
28
- coerceBool,
29
- coerceInstallExtension,
30
- coerceNumber
31
- };
32
- //# sourceMappingURL=chunk-PHK3HARR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/connectors/coerce.ts"],"sourcesContent":["/**\n * Shared boolean coercion helpers.\n *\n * Extracted from connectors/index.ts so that both config.ts and\n * connectors/index.ts can import them without creating a circular dependency.\n */\n\n/**\n * Generic boolean coercion: converts string representations of booleans\n * (e.g. from CLI `--config someFlag=false`) to proper boolean values.\n * Accepts the same truthy/falsy strings that common shells and env vars use.\n *\n * Returns `undefined` when the value is neither a boolean nor a recognised\n * string, so callers can fall back to a default.\n *\n * CLAUDE.md gotcha #36: String \"false\" is truthy in JavaScript.\n * CLAUDE.md gotcha #28: Coerce CLI values to expected types at input boundaries.\n */\nexport function coerceBool(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const v = value.trim().toLowerCase();\n if ([\"false\", \"0\", \"no\", \"off\"].includes(v)) return false;\n if ([\"true\", \"1\", \"yes\", \"on\"].includes(v)) return true;\n }\n return undefined;\n}\n\n/**\n * Coerce the `installExtension` config value from a string (e.g. from CLI\n * `--config installExtension=false`) to a proper boolean.\n *\n * Delegates to the generic `coerceBool` helper. Kept for backward compatibility.\n */\nexport function coerceInstallExtension(value: unknown): boolean | undefined {\n return coerceBool(value);\n}\n\n/**\n * Generic numeric coercion: accepts a finite number or a string that\n * parses cleanly to one. Returns `undefined` otherwise so callers can\n * fall back to a default.\n *\n * Rules:\n * - number: returned as-is only if finite (NaN / ±Infinity → undefined).\n * - string: trimmed, parsed with `Number()`. Returns `undefined` on\n * empty, NaN, or Infinity.\n *\n * CLAUDE.md gotcha #28: Coerce CLI values to expected types at input boundaries.\n */\nexport function coerceNumber(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n const n = Number(trimmed);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n}\n"],"mappings":";AAkBO,SAAS,WAAW,OAAqC;AAC9D,MAAI,OAAO,UAAU,UAAW,QAAO;AACvC,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,QAAI,CAAC,SAAS,KAAK,MAAM,KAAK,EAAE,SAAS,CAAC,EAAG,QAAO;AACpD,QAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,EAAE,SAAS,CAAC,EAAG,QAAO;AAAA,EACrD;AACA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAqC;AAC1E,SAAO,WAAW,KAAK;AACzB;AAcO,SAAS,aAAa,OAAoC;AAC/D,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,EAC1C;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,QAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,UAAM,IAAI,OAAO,OAAO;AACxB,WAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAAA,EAClC;AACA,SAAO;AACT;","names":[]}
@@ -1,8 +0,0 @@
1
- // src/access-errors.ts
2
- var EngramAccessForbiddenError = class extends Error {
3
- };
4
-
5
- export {
6
- EngramAccessForbiddenError
7
- };
8
- //# sourceMappingURL=chunk-RANHFI3P.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/access-errors.ts"],"sourcesContent":["/** Authenticated caller lacks the required authorization (HTTP 403). */\nexport class EngramAccessForbiddenError extends Error {}\n"],"mappings":";AACO,IAAM,6BAAN,cAAyC,MAAM;AAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n // Pass the hot-memories cache gate explicitly (issue #1902, Codex P2): a\n // per-namespace child root is never registered in the per-dir default map,\n // so without this it would fall back to the process-wide default and ignore\n // THIS daemon's hotMemoriesCacheEnabled config. Threading it from config\n // keeps every namespace storage aligned with its owning orchestrator.\n const sm = new StorageManager(\n root,\n this.config.entitySchemas,\n this.config.hotMemoriesCacheEnabled,\n );\n // Register this child root's gate AND TTL in the per-dir maps (issue #1902,\n // Codex P2). The constructor override above fixes the child's own gate, but\n // its TTL is resolved via the per-dir map (hotCacheTtlMs); an unregistered\n // child root would fall back to the last process-wide TTL and could inherit\n // another daemon's value. Registering keyed by root keeps both per-dir.\n StorageManager.setHotMemoriesCacheDefault(\n root,\n this.config.hotMemoriesCacheEnabled,\n this.config.hotMemoriesCacheTtlMs,\n );\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n this.cache.set(ns, sm);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n // Issue #1903: pure state-file writes only touch the catalog when explicitly\n // opted in. Router-created storages (storageFor) and the legacy default\n // storage both flow through here, so this is the single wiring point.\n sm.touchStateWrites = this.config.namespacesCatalogTouchStateWrites === true;\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n // Flush any coalesced (buffered) touches first so their appends join the\n // pending set below — otherwise this could resolve while a buffered touch's\n // lastWriteAt is still unwritten on disk (#1903, Cursor). No-op when\n // coalescing is disabled (window 0) or the catalog is inert.\n await this.catalog?.flushPendingTouches().catch(() => undefined);\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.size > 0) {\n await Promise.allSettled([...this.pendingResolveHooks]);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,eAAe;AASvC,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,iBAAiB,GAA6B;AAC3D,MAAI;AACF,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,QAAI,MAAM,eAAe,EAAG,QAAO;AACnC,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,SAAS,UAAU;AAC5B,YAAM,YAAY,KAAK,KAAK,GAAG,MAAM,IAAI;AACzC,UAAI,MAAM,eAAe,KAAK,MAAM,OAAO,EAAG,QAAO;AACrD,UAAI,MAAM,YAAY,KAAM,MAAM,iBAAiB,SAAS,EAAI,QAAO;AAAA,IACzE;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,WAAmB,SAAyB;AAIvE,MACE,QAAQ,WAAW,KACnB,QAAQ,SAAS,GAAG,KACpB,QAAQ,SAAS,IAAI,KACrB,QAAQ,SAAS,IAAI,KACrB,KAAK,WAAW,OAAO,GACvB;AACA,UAAM,IAAI,MAAM,kCAAkC,OAAO,EAAE;AAAA,EAC7D;AACA,SAAO,KAAK,KAAK,WAAW,cAAc,OAAO;AACnD;AAEA,IAAM,oCAAoC;AAAA,EACxC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,oCAAoC,CAAC,OAAO;AAElD,eAAe,iBACb,SACA,UAA6C,CAAC,GAC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AAAA;AAAA;AAAA,EAaA,MAAM,0BAAyC;AAC7C,WAAO,KAAK,oBAAoB,OAAO,GAAG;AACxC,YAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,mBAAmB,CAAC;AAAA,IACxD;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/memory-lifecycle-ledger-utils.ts"],"sourcesContent":["import path from \"node:path\";\nimport type {\n MemoryFile,\n MemoryLifecycleEvent,\n MemoryLifecycleEventType,\n MemoryLifecycleStateSummary,\n MemoryFrontmatter,\n MemoryStatus,\n} from \"./types.js\";\n\nexport const MEMORY_LIFECYCLE_RULE_VERSION = \"memory-lifecycle-ledger.v1\";\n\nexport const MEMORY_LIFECYCLE_EVENT_SORT_ORDER: Record<MemoryLifecycleEventType, number> = {\n created: 0,\n updated: 1,\n promoted: 2,\n explicit_capture_accepted: 3,\n explicit_capture_queued: 4,\n imported: 5,\n merged: 6,\n restored: 7,\n superseded: 8,\n rejected: 9,\n archived: 10,\n};\n\nexport function toMemoryPathRel(baseDir: string, filePath: string): string {\n if (!baseDir) return filePath.split(path.sep).join(\"/\");\n return path.relative(baseDir, filePath).split(path.sep).join(\"/\");\n}\n\nexport function isArchivedMemoryPath(pathRel: string): boolean {\n return pathRel === \"archive\" || pathRel.startsWith(\"archive/\");\n}\n\nexport function inferMemoryStatus(\n frontmatter: MemoryFrontmatter,\n pathRel: string,\n fallbackStatus: MemoryStatus = \"active\",\n): MemoryStatus {\n if (frontmatter.status && frontmatter.status !== \"active\") return frontmatter.status;\n if (frontmatter.archivedAt) return \"archived\";\n if (isArchivedMemoryPath(pathRel)) return \"archived\";\n if (frontmatter.status) return frontmatter.status;\n return fallbackStatus;\n}\n\nexport function isActiveMemoryStatus(status: MemoryStatus | string | undefined): boolean {\n return status === undefined || status === \"active\";\n}\n\nexport function summarizeMemoryLifecycleState(memory: MemoryFile): MemoryLifecycleStateSummary {\n return {\n category: memory.frontmatter.category,\n path: memory.path,\n status: memory.frontmatter.status ?? \"active\",\n lifecycleState: memory.frontmatter.lifecycleState,\n };\n}\n\nexport function makeRebuiltMemoryLifecycleEvent(\n memory: MemoryFile,\n eventType: MemoryLifecycleEventType,\n timestamp: string,\n): MemoryLifecycleEvent {\n return {\n eventId: `rebuild-${memory.frontmatter.id}-${eventType}-${timestamp}`,\n memoryId: memory.frontmatter.id,\n eventType,\n timestamp,\n actor: \"maintenance.rebuildMemoryLifecycleLedger\",\n ruleVersion: MEMORY_LIFECYCLE_RULE_VERSION,\n after: summarizeMemoryLifecycleState(memory),\n relatedMemoryIds: [\n ...(memory.frontmatter.supersededBy ? [memory.frontmatter.supersededBy] : []),\n ...(memory.frontmatter.supersedes ? [memory.frontmatter.supersedes] : []),\n ...((memory.frontmatter.lineage ?? []).filter(Boolean)),\n ],\n };\n}\n\nexport function buildLifecycleEventsForMemory(memory: MemoryFile): MemoryLifecycleEvent[] {\n const events: MemoryLifecycleEvent[] = [];\n const created = memory.frontmatter.created;\n const updated = memory.frontmatter.updated;\n const archivedAt = memory.frontmatter.archivedAt;\n const supersededAt = memory.frontmatter.supersededAt;\n const effectiveArchivedAt =\n archivedAt ?? (memory.frontmatter.status === \"archived\" && updated ? updated : undefined);\n\n events.push(makeRebuiltMemoryLifecycleEvent(memory, \"created\", created));\n if (\n updated &&\n updated !== created &&\n updated !== effectiveArchivedAt &&\n updated !== supersededAt\n ) {\n events.push(makeRebuiltMemoryLifecycleEvent(memory, \"updated\", updated));\n }\n if (supersededAt) {\n events.push(makeRebuiltMemoryLifecycleEvent(memory, \"superseded\", supersededAt));\n }\n if (effectiveArchivedAt) {\n events.push(makeRebuiltMemoryLifecycleEvent(memory, \"archived\", effectiveArchivedAt));\n }\n\n return events;\n}\n\nexport function sortMemoryLifecycleEvents(events: MemoryLifecycleEvent[]): MemoryLifecycleEvent[] {\n return [...events].sort((a, b) => {\n if (a.memoryId !== b.memoryId) return a.memoryId.localeCompare(b.memoryId);\n if (a.timestamp !== b.timestamp) return a.timestam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