@remnic/core 9.7.15 → 9.9.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 (929) hide show
  1. package/dist/access-admin-ops-surface.d.ts +13 -6
  2. package/dist/access-admin-ops-surface.js +85 -71
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-boundary.d.ts +35 -17
  5. package/dist/access-boundary.js +86 -74
  6. package/dist/access-citation.d.ts +28 -0
  7. package/dist/access-citation.js +9 -0
  8. package/dist/access-cli.js +194 -178
  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 +100 -87
  14. package/dist/access-identity-continuity-surface.d.ts +13 -8
  15. package/dist/access-identity-continuity-surface.js +85 -71
  16. package/dist/access-lcm-surface.d.ts +16 -9
  17. package/dist/access-lcm-surface.js +85 -71
  18. package/dist/access-mcp.d.ts +23 -16
  19. package/dist/access-mcp.js +96 -84
  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 +85 -71
  24. package/dist/access-operations-batch.js +92 -80
  25. package/dist/access-operations.d.ts +29 -22
  26. package/dist/access-operations.js +94 -82
  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 +85 -71
  33. package/dist/access-schema.d.ts +98 -98
  34. package/dist/access-schema.js +8 -6
  35. package/dist/{access-service-DpcYZ9Nl.d.ts → access-service-DbZ1G3zV.d.ts} +29 -36
  36. package/dist/access-service.d.ts +13 -6
  37. package/dist/access-service.js +89 -72
  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 +34 -24
  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/{catalog-C9444P10.d.ts → catalog-BWqHb5HT.d.ts} +1 -1
  73. package/dist/causal-behavior.d.ts +3 -1
  74. package/dist/causal-behavior.js +6 -6
  75. package/dist/causal-chain.js +4 -4
  76. package/dist/causal-consolidation.d.ts +3 -1
  77. package/dist/causal-consolidation.js +43 -34
  78. package/dist/causal-consolidation.js.map +1 -1
  79. package/dist/causal-retrieval.js +6 -6
  80. package/dist/causal-trajectory-graph.d.ts +3 -1
  81. package/dist/causal-trajectory-graph.js +1 -1
  82. package/dist/causal-trajectory.js +1 -1
  83. package/dist/{chunk-A3GOMRJG.js → chunk-23L3IXFD.js} +2 -2
  84. package/dist/chunk-2CGLBUW3.js +15 -0
  85. package/dist/chunk-2CGLBUW3.js.map +1 -0
  86. package/dist/{chunk-MRHFJV44.js → chunk-2DQ2XREU.js} +2 -2
  87. package/dist/{chunk-L2B3EE7B.js → chunk-2QMKMVHH.js} +2 -2
  88. package/dist/{chunk-VJVNLNDQ.js → chunk-2UFO7X4Q.js} +7 -7
  89. package/dist/{chunk-2MR3MFQB.js → chunk-2VEOKUPP.js} +3 -3
  90. package/dist/chunk-2Z24E5W2.js +22 -0
  91. package/dist/chunk-2Z24E5W2.js.map +1 -0
  92. package/dist/{chunk-RHOZ5LLO.js → chunk-347WD2LE.js} +2 -2
  93. package/dist/{chunk-HDTQVNWD.js → chunk-3QAH2S33.js} +3 -3
  94. package/dist/{chunk-37CTGERM.js → chunk-3WCASNQZ.js} +12 -1
  95. package/dist/chunk-3WCASNQZ.js.map +1 -0
  96. package/dist/{chunk-LRNMRXJO.js → chunk-3Y224NYC.js} +3 -3
  97. package/dist/{chunk-3IY64MV6.js → chunk-44XZ75OQ.js} +44 -10
  98. package/dist/chunk-44XZ75OQ.js.map +1 -0
  99. package/dist/{chunk-VFSP73LP.js → chunk-45GF7Y3V.js} +2 -2
  100. package/dist/{chunk-K7LOWSLU.js → chunk-4BJQODZF.js} +2479 -1520
  101. package/dist/chunk-4BJQODZF.js.map +1 -0
  102. package/dist/{chunk-JREB6UFH.js → chunk-57OWKFUQ.js} +17 -6
  103. package/dist/chunk-57OWKFUQ.js.map +1 -0
  104. package/dist/{chunk-OEHCMALU.js → chunk-5I4M26Q7.js} +5 -5
  105. package/dist/{chunk-2AZXIZEN.js → chunk-5Q7EVV4X.js} +6 -6
  106. package/dist/{chunk-LC7OODWZ.js → chunk-5SB7SC2G.js} +80 -49
  107. package/dist/chunk-5SB7SC2G.js.map +1 -0
  108. package/dist/{chunk-PUBTHW5O.js → chunk-6DRPPQEJ.js} +2 -2
  109. package/dist/{chunk-NWTGD4AN.js → chunk-6KIQT7RG.js} +10 -9
  110. package/dist/chunk-6KIQT7RG.js.map +1 -0
  111. package/dist/{chunk-FDCTQWLW.js → chunk-6O22TZSB.js} +3 -3
  112. package/dist/{chunk-ZQ7UBUZ6.js → chunk-6QYST5XN.js} +6 -6
  113. package/dist/{chunk-W4PGTAS2.js → chunk-6WAFYNVT.js} +3 -3
  114. package/dist/chunk-6ZMAMSHS.js +20 -0
  115. package/dist/chunk-6ZMAMSHS.js.map +1 -0
  116. package/dist/{chunk-R5VAVVHP.js → chunk-72A4L5JJ.js} +2 -2
  117. package/dist/{chunk-X64YLC24.js → chunk-72VAXGEI.js} +5 -13
  118. package/dist/chunk-72VAXGEI.js.map +1 -0
  119. package/dist/{chunk-IKQTFQMI.js → chunk-755Q3DGF.js} +22 -3
  120. package/dist/chunk-755Q3DGF.js.map +1 -0
  121. package/dist/{chunk-D7FOKIY5.js → chunk-7AMFUATK.js} +12 -9
  122. package/dist/{chunk-D7FOKIY5.js.map → chunk-7AMFUATK.js.map} +1 -1
  123. package/dist/{chunk-BFVEEB7W.js → chunk-7ON2JW73.js} +57 -22
  124. package/dist/chunk-7ON2JW73.js.map +1 -0
  125. package/dist/chunk-7RNBVZZO.js +270 -0
  126. package/dist/chunk-7RNBVZZO.js.map +1 -0
  127. package/dist/{chunk-3FAMU5TX.js → chunk-A6USBZTO.js} +2 -2
  128. package/dist/{chunk-ZHIVCODT.js → chunk-A72SWTWW.js} +7 -7
  129. package/dist/{chunk-FC77VUX5.js → chunk-A7Q43EUZ.js} +2 -2
  130. package/dist/{chunk-UJBESW6X.js → chunk-AE7WMV4V.js} +7 -7
  131. package/dist/{chunk-J2HSAU72.js → chunk-AIK5W3IW.js} +29 -1
  132. package/dist/chunk-AIK5W3IW.js.map +1 -0
  133. package/dist/{chunk-A5UXZRRM.js → chunk-AJ7QCSIS.js} +2 -2
  134. package/dist/{chunk-FNMFJWBY.js → chunk-ANEUPF6O.js} +5 -5
  135. package/dist/chunk-AREGMX2J.js +50 -0
  136. package/dist/chunk-AREGMX2J.js.map +1 -0
  137. package/dist/chunk-AVPXXV6J.js +448 -0
  138. package/dist/chunk-AVPXXV6J.js.map +1 -0
  139. package/dist/{chunk-2A3OXAP2.js → chunk-B7RWBZXW.js} +2 -2
  140. package/dist/{chunk-QKQYXZVS.js → chunk-BI2OJF6J.js} +1819 -1481
  141. package/dist/chunk-BI2OJF6J.js.map +1 -0
  142. package/dist/{chunk-GWTFLF2P.js → chunk-BJMBJZ2Y.js} +59 -59
  143. package/dist/chunk-BJMBJZ2Y.js.map +1 -0
  144. package/dist/{chunk-74F5STS4.js → chunk-BLAKS3CP.js} +4 -4
  145. package/dist/{chunk-M7VGG3ID.js → chunk-BV5WMSIJ.js} +9 -9
  146. package/dist/{chunk-2BFLDH5F.js → chunk-BXLOS5AJ.js} +2 -2
  147. package/dist/{chunk-UXKMMNJD.js → chunk-C23BYTJV.js} +6 -6
  148. package/dist/{chunk-JZHHREBL.js → chunk-C3AKM55W.js} +2 -2
  149. package/dist/{chunk-RP7YXA67.js → chunk-C5JF6EZ7.js} +2 -2
  150. package/dist/{chunk-T7Y5KPLN.js → chunk-C6XBRYVD.js} +16 -15
  151. package/dist/chunk-C6XBRYVD.js.map +1 -0
  152. package/dist/{chunk-FTYDWKO6.js → chunk-CEN6DW6X.js} +12 -2
  153. package/dist/chunk-CEN6DW6X.js.map +1 -0
  154. package/dist/chunk-CGASUJVP.js +421 -0
  155. package/dist/chunk-CGASUJVP.js.map +1 -0
  156. package/dist/{chunk-EHCONI6E.js → chunk-CQMEM5CC.js} +2 -2
  157. package/dist/{chunk-PBNZVPFS.js → chunk-CXZQOVIE.js} +12 -12
  158. package/dist/chunk-D3V3UMET.js +44 -0
  159. package/dist/chunk-D3V3UMET.js.map +1 -0
  160. package/dist/{chunk-7N2RUBAP.js → chunk-DDA47TES.js} +2 -2
  161. package/dist/{chunk-64SE4X5G.js → chunk-DEBHXHJR.js} +3 -3
  162. package/dist/{chunk-EHK6KZHK.js → chunk-DNHVPZOD.js} +2 -2
  163. package/dist/{chunk-437S3G37.js → chunk-DQEMWVMT.js} +2 -2
  164. package/dist/{chunk-LZZNTPLR.js → chunk-DX3XRGLH.js} +2 -2
  165. package/dist/chunk-EA2H5LML.js +72 -0
  166. package/dist/chunk-EA2H5LML.js.map +1 -0
  167. package/dist/{chunk-INELTPRG.js → chunk-EEC7UJPX.js} +103 -106
  168. package/dist/chunk-EEC7UJPX.js.map +1 -0
  169. package/dist/{chunk-KSNVDPDF.js → chunk-EKBNDKDY.js} +21 -20
  170. package/dist/chunk-EKBNDKDY.js.map +1 -0
  171. package/dist/{chunk-YF6FMLBT.js → chunk-EQWEIIKQ.js} +64 -34
  172. package/dist/chunk-EQWEIIKQ.js.map +1 -0
  173. package/dist/{chunk-DZKHSDOM.js → chunk-ES36HTSC.js} +4 -4
  174. package/dist/{chunk-TN7THW5U.js → chunk-ET356KSB.js} +2 -2
  175. package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
  176. package/dist/{chunk-DMSDUGDM.js → chunk-F7GAIWFA.js} +20 -20
  177. package/dist/{chunk-G6XXLKC5.js → chunk-FFPJINJE.js} +6 -6
  178. package/dist/chunk-FMLKOL2Z.js +636 -0
  179. package/dist/chunk-FMLKOL2Z.js.map +1 -0
  180. package/dist/chunk-FQC3DHH2.js +20 -0
  181. package/dist/chunk-FQC3DHH2.js.map +1 -0
  182. package/dist/{chunk-G4CN3ZXL.js → chunk-FUTF72MJ.js} +15 -15
  183. package/dist/chunk-GCASGYIO.js +71 -0
  184. package/dist/chunk-GCASGYIO.js.map +1 -0
  185. package/dist/{chunk-HF77M34J.js → chunk-GFPZS3F5.js} +8 -8
  186. package/dist/{chunk-BCDKBDSY.js → chunk-GNVZQ5JN.js} +99 -41
  187. package/dist/chunk-GNVZQ5JN.js.map +1 -0
  188. package/dist/{chunk-G6NKALRN.js → chunk-H4WG3UQZ.js} +2 -2
  189. package/dist/{chunk-UDQUSU27.js → chunk-HNZKVLAN.js} +2 -2
  190. package/dist/{chunk-5EZXHU36.js → chunk-HYQJQGD3.js} +2 -2
  191. package/dist/{chunk-PLQE6MJA.js → chunk-IFH6LWTO.js} +50 -8
  192. package/dist/chunk-IFH6LWTO.js.map +1 -0
  193. package/dist/{chunk-RULE4VG5.js → chunk-ILGC6JH6.js} +21 -6
  194. package/dist/chunk-ILGC6JH6.js.map +1 -0
  195. package/dist/chunk-IUM3VSHI.js +113 -0
  196. package/dist/chunk-IUM3VSHI.js.map +1 -0
  197. package/dist/{chunk-TRWPCR6P.js → chunk-JECBQBEX.js} +3 -3
  198. package/dist/{chunk-E6CBU7XP.js → chunk-JYIFGGEM.js} +2 -2
  199. package/dist/{chunk-VA4WSW54.js → chunk-JYIJNNN3.js} +3 -3
  200. package/dist/{chunk-L5HJQC36.js → chunk-K2TDK7GG.js} +3 -3
  201. package/dist/{chunk-KDXVOFYY.js → chunk-KAVBJSBQ.js} +4 -4
  202. package/dist/{chunk-BS4SGLWV.js → chunk-KF5EUVKQ.js} +16 -6
  203. package/dist/chunk-KF5EUVKQ.js.map +1 -0
  204. package/dist/chunk-KFZY2OFH.js +42 -0
  205. package/dist/chunk-KFZY2OFH.js.map +1 -0
  206. package/dist/{chunk-4OKLXWDZ.js → chunk-KNB7IBBU.js} +2 -2
  207. package/dist/{chunk-QLULYKWZ.js → chunk-KSXJOC4F.js} +2 -2
  208. package/dist/{chunk-2S6QHZGJ.js → chunk-L2DPF4DF.js} +1 -1
  209. package/dist/{chunk-JI5AVXYO.js → chunk-LEPOP46W.js} +6 -6
  210. package/dist/{chunk-O7BBFJLP.js → chunk-LTAVSOZW.js} +2 -2
  211. package/dist/{chunk-E3VODCC3.js → chunk-LUDXM7MD.js} +14 -2
  212. package/dist/{chunk-E3VODCC3.js.map → chunk-LUDXM7MD.js.map} +1 -1
  213. package/dist/{chunk-2IZAGAJR.js → chunk-LULR4IUW.js} +3 -3
  214. package/dist/{chunk-QQGPUKMT.js → chunk-MC5Q3J7S.js} +398 -7
  215. package/dist/chunk-MC5Q3J7S.js.map +1 -0
  216. package/dist/{chunk-WMWVO45V.js → chunk-MC6XO7T4.js} +2 -2
  217. package/dist/chunk-MKQBXQKU.js +107 -0
  218. package/dist/chunk-MKQBXQKU.js.map +1 -0
  219. package/dist/{chunk-7PND4PUC.js → chunk-MMGGVZ4Q.js} +29 -9
  220. package/dist/{chunk-7PND4PUC.js.map → chunk-MMGGVZ4Q.js.map} +1 -1
  221. package/dist/{chunk-D6RIFG4O.js → chunk-MNB5RMAY.js} +2 -2
  222. package/dist/{chunk-Q5WG43OP.js → chunk-MYFQ3ED4.js} +7 -7
  223. package/dist/{chunk-V3UE5I5F.js → chunk-MYVPLJOO.js} +2 -2
  224. package/dist/chunk-NINSR6LX.js +83 -0
  225. package/dist/chunk-NINSR6LX.js.map +1 -0
  226. package/dist/{chunk-MTWKDOVO.js → chunk-NLE6TSLG.js} +2 -2
  227. package/dist/{chunk-OAZVR2BV.js → chunk-OGCAYLNA.js} +8 -6
  228. package/dist/{chunk-OAZVR2BV.js.map → chunk-OGCAYLNA.js.map} +1 -1
  229. package/dist/{chunk-DBRYEIGY.js → chunk-OJP3N7UK.js} +2 -2
  230. package/dist/{chunk-VDW4VU7B.js → chunk-OQJIB32H.js} +28 -23
  231. package/dist/chunk-OQJIB32H.js.map +1 -0
  232. package/dist/{chunk-SMX5267P.js → chunk-OZKOPQCM.js} +2 -2
  233. package/dist/{chunk-JCK7V6SN.js → chunk-P65YJEEL.js} +2 -2
  234. package/dist/{chunk-MTR7BZQN.js → chunk-PBGWYM3H.js} +3 -3
  235. package/dist/chunk-PIG4WJFQ.js +87 -0
  236. package/dist/chunk-PIG4WJFQ.js.map +1 -0
  237. package/dist/chunk-PJSK6OJM.js +201 -0
  238. package/dist/chunk-PJSK6OJM.js.map +1 -0
  239. package/dist/{chunk-OVJ2HIPE.js → chunk-PMUD7ERF.js} +158 -125
  240. package/dist/chunk-PMUD7ERF.js.map +1 -0
  241. package/dist/chunk-PQVCH2AE.js +76 -0
  242. package/dist/chunk-PQVCH2AE.js.map +1 -0
  243. package/dist/{chunk-AXTXN4T6.js → chunk-PWFCHOB3.js} +2 -2
  244. package/dist/{chunk-FDPZVY6D.js → chunk-QFN4U7AG.js} +2 -2
  245. package/dist/{chunk-K2ZLHESQ.js → chunk-QIEUU4UK.js} +2 -2
  246. package/dist/{chunk-DYP3YYJJ.js → chunk-QJAQNXWI.js} +39 -5
  247. package/dist/chunk-QJAQNXWI.js.map +1 -0
  248. package/dist/{chunk-3D6AFGQR.js → chunk-QVT3E4CE.js} +7 -7
  249. package/dist/{chunk-FIJUY7GG.js → chunk-R26ZMXR2.js} +23 -23
  250. package/dist/{chunk-FIJUY7GG.js.map → chunk-R26ZMXR2.js.map} +1 -1
  251. package/dist/chunk-R3DJVOSM.js +34 -0
  252. package/dist/chunk-R3DJVOSM.js.map +1 -0
  253. package/dist/{chunk-SFQ6QNL7.js → chunk-R6YJI3HE.js} +2 -1
  254. package/dist/{chunk-5CJVLG3H.js → chunk-RFDD3B7W.js} +5 -5
  255. package/dist/{chunk-JBPKEARU.js → chunk-RKNJBZ55.js} +4 -4
  256. package/dist/chunk-ROI7BK7H.js +88 -0
  257. package/dist/chunk-ROI7BK7H.js.map +1 -0
  258. package/dist/{chunk-FNZQGN76.js → chunk-S2BBISHU.js} +4 -4
  259. package/dist/{chunk-IALLX7EE.js → chunk-S2FSBU4H.js} +3 -3
  260. package/dist/{chunk-BFPETA3S.js → chunk-SCCO46KZ.js} +3 -2
  261. package/dist/chunk-SCCO46KZ.js.map +1 -0
  262. package/dist/chunk-SK7AMF2J.js +168 -0
  263. package/dist/chunk-SK7AMF2J.js.map +1 -0
  264. package/dist/{chunk-KSBEEMQF.js → chunk-TG6IHVE2.js} +151 -6
  265. package/dist/chunk-TG6IHVE2.js.map +1 -0
  266. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  267. package/dist/{chunk-DPAENM7O.js → chunk-U3ZAVRP3.js} +2 -2
  268. package/dist/{chunk-ODPLEWB6.js → chunk-UFGFMWAD.js} +47 -17
  269. package/dist/chunk-UFGFMWAD.js.map +1 -0
  270. package/dist/{chunk-4KJLYTLS.js → chunk-V57NLO5P.js} +2 -2
  271. package/dist/{chunk-FLVL4L3L.js → chunk-VDX2J7OX.js} +2 -2
  272. package/dist/{chunk-AJLLIIML.js → chunk-W4FBGYGK.js} +1 -1
  273. package/dist/{chunk-TXLGHDHS.js → chunk-W4XJFLAL.js} +53 -32
  274. package/dist/chunk-W4XJFLAL.js.map +1 -0
  275. package/dist/{chunk-6SXVCD7W.js → chunk-W7IGLX4G.js} +2 -2
  276. package/dist/{chunk-KQDNAXOM.js → chunk-WG5HSQ4P.js} +19 -6
  277. package/dist/chunk-WG5HSQ4P.js.map +1 -0
  278. package/dist/{chunk-LTJAMRGI.js → chunk-WL5EBRDH.js} +17 -3
  279. package/dist/chunk-WL5EBRDH.js.map +1 -0
  280. package/dist/{chunk-KAWTOYAW.js → chunk-WLZYGLJ4.js} +2 -2
  281. package/dist/{chunk-RO4LQGT3.js → chunk-WON4APQY.js} +4 -4
  282. package/dist/{chunk-PQVK2S3J.js → chunk-WZFAPHIK.js} +6 -6
  283. package/dist/{chunk-KQPJLK3X.js → chunk-XL24QQ63.js} +2 -2
  284. package/dist/{chunk-LZOV7MX7.js → chunk-XQDRKZ7V.js} +6476 -5747
  285. package/dist/chunk-XQDRKZ7V.js.map +1 -0
  286. package/dist/{chunk-RVZRYUQH.js → chunk-YROFNEG5.js} +7 -7
  287. package/dist/{chunk-RAR2BSEM.js → chunk-YV32N67O.js} +1 -1
  288. package/dist/chunk-YV32N67O.js.map +1 -0
  289. package/dist/{chunk-PBSAPHHA.js → chunk-YVKF3HEW.js} +1 -1
  290. package/dist/chunk-YVKF3HEW.js.map +1 -0
  291. package/dist/{chunk-VRAD2FGO.js → chunk-Z54EM5YZ.js} +12 -12
  292. package/dist/{chunk-2VN4JAX7.js → chunk-ZOKZIR5K.js} +95 -33
  293. package/dist/chunk-ZOKZIR5K.js.map +1 -0
  294. package/dist/{chunk-DCFV7A7H.js → chunk-ZVAYK7GU.js} +101 -91
  295. package/dist/chunk-ZVAYK7GU.js.map +1 -0
  296. package/dist/{cli-Cd5fMmhq.d.ts → cli-5tNLVTvJ.d.ts} +28 -12
  297. package/dist/cli.d.ts +16 -9
  298. package/dist/cli.js +142 -127
  299. package/dist/compounding/engine.d.ts +5 -2
  300. package/dist/compounding/engine.js +36 -26
  301. package/dist/compounding/preference-consolidator.d.ts +3 -1
  302. package/dist/compounding/preference-consolidator.js +1 -1
  303. package/dist/compression-optimizer.d.ts +3 -1
  304. package/dist/config-qmd.d.ts +8 -0
  305. package/dist/config-qmd.js +20 -0
  306. package/dist/config-qmd.js.map +1 -0
  307. package/dist/config.d.ts +3 -1
  308. package/dist/config.js +15 -10
  309. package/dist/connectors/codex-materialize-runner.d.ts +3 -1
  310. package/dist/connectors/codex-materialize-runner.js +36 -26
  311. package/dist/connectors/codex-materialize.d.ts +3 -1
  312. package/dist/connectors/codex-materialize.js +2 -2
  313. package/dist/connectors/index.d.ts +3 -1
  314. package/dist/connectors/index.js +41 -32
  315. package/dist/consolidation-provenance-check.d.ts +5 -2
  316. package/dist/consolidation-undo.d.ts +5 -2
  317. package/dist/contradiction/index.d.ts +5 -2
  318. package/dist/contradiction/index.js +10 -4
  319. package/dist/{contradiction-scan-J57T5QV7.js → contradiction-scan-RJBABNRH.js} +4 -4
  320. package/dist/contradiction-scan-RJBABNRH.js.map +1 -0
  321. package/dist/conversation-index/backend.d.ts +3 -1
  322. package/dist/conversation-index/backend.js +5 -5
  323. package/dist/conversation-index/chunker.d.ts +3 -1
  324. package/dist/conversation-index/cleanup.js +2 -2
  325. package/dist/conversation-index/faiss-adapter.d.ts +3 -1
  326. package/dist/conversation-index/faiss-adapter.js +2 -2
  327. package/dist/conversation-index/indexer.d.ts +3 -1
  328. package/dist/conversation-index/indexer.js +2 -2
  329. package/dist/conversation-index/search.d.ts +3 -1
  330. package/dist/conversation-index/search.js +2 -2
  331. package/dist/cross-namespace-budget.d.ts +45 -1
  332. package/dist/cross-namespace-budget.js +5 -3
  333. package/dist/dashboard-runtime.js +2 -2
  334. package/dist/day-summary.d.ts +3 -1
  335. package/dist/day-summary.js +3 -3
  336. package/dist/delinearize.d.ts +3 -1
  337. package/dist/direct-answer-wiring.d.ts +3 -1
  338. package/dist/direct-answer.d.ts +3 -1
  339. package/dist/{dreams-ledger-6UODQOX6.js → dreams-ledger-567VKVOU.js} +4 -2
  340. package/dist/dreams-ledger-567VKVOU.js.map +1 -0
  341. package/dist/embedding-fallback.d.ts +3 -1
  342. package/dist/embedding-fallback.js +3 -3
  343. package/dist/enrichment/index.d.ts +3 -1
  344. package/dist/entity-retrieval.d.ts +5 -2
  345. package/dist/entity-retrieval.js +35 -26
  346. package/dist/entity-schema.d.ts +3 -1
  347. package/dist/explicit-capture.d.ts +13 -8
  348. package/dist/explicit-capture.js +7 -3
  349. package/dist/extraction-faithfulness.d.ts +3 -1
  350. package/dist/extraction-faithfulness.js +5 -5
  351. package/dist/extraction-judge-telemetry.d.ts +3 -1
  352. package/dist/extraction-judge-telemetry.js +2 -2
  353. package/dist/extraction-judge-training.d.ts +3 -1
  354. package/dist/extraction-judge-training.js +2 -2
  355. package/dist/extraction-judge.d.ts +3 -1
  356. package/dist/extraction-judge.js +5 -5
  357. package/dist/extraction.d.ts +3 -1
  358. package/dist/extraction.js +13 -12
  359. package/dist/faithfulness-config.js +3 -2
  360. package/dist/fallback-llm.d.ts +3 -1
  361. package/dist/fallback-llm.js +4 -4
  362. package/dist/{first-start-migration-TI67YMLG.js → first-start-migration-CSRHCJIQ.js} +2 -2
  363. package/dist/{forget-CQCLB5LB.js → forget-HRPLVB3W.js} +5 -5
  364. package/dist/graph-dashboard-diff.d.ts +3 -1
  365. package/dist/graph-dashboard-key.d.ts +3 -1
  366. package/dist/graph-dashboard-parser.d.ts +3 -1
  367. package/dist/{graph-edge-decay-IOGBBAGC.js → graph-edge-decay-Z6ENALU2.js} +3 -3
  368. package/dist/graph-edge-decay-Z6ENALU2.js.map +1 -0
  369. package/dist/graph-edge-reinforcement.d.ts +3 -1
  370. package/dist/graph-snapshot.d.ts +3 -1
  371. package/dist/graph-snapshot.js +2 -2
  372. package/dist/graph.d.ts +3 -1
  373. package/dist/graph.js +1 -1
  374. package/dist/identity-continuity.d.ts +1 -2
  375. package/dist/importance.d.ts +3 -1
  376. package/dist/importers/index.d.ts +3 -1
  377. package/dist/in-flight-reads.d.ts +3 -1
  378. package/dist/index.d.ts +473 -464
  379. package/dist/index.js +287 -239
  380. package/dist/intent.d.ts +3 -1
  381. package/dist/lcm/archive.js +2 -2
  382. package/dist/lcm/engine.d.ts +3 -1
  383. package/dist/lcm/engine.js +6 -6
  384. package/dist/lcm/index.d.ts +3 -1
  385. package/dist/lcm/index.js +13 -13
  386. package/dist/lcm/schema.js +2 -2
  387. package/dist/lcm/summarizer.js +3 -3
  388. package/dist/lcm/tools.d.ts +3 -1
  389. package/dist/lifecycle.d.ts +3 -1
  390. package/dist/live-connectors-runner.d.ts +3 -1
  391. package/dist/local-llm.d.ts +5 -2
  392. package/dist/local-llm.js +3 -3
  393. package/dist/local-model-endpoint.d.ts +3 -1
  394. package/dist/logger.d.ts +3 -1
  395. package/dist/logger.js +7 -3
  396. package/dist/maintenance/archive-observations.js +2 -2
  397. package/dist/maintenance/memory-governance.d.ts +3 -1
  398. package/dist/maintenance/memory-governance.js +35 -25
  399. package/dist/maintenance/migrate-observations.js +3 -3
  400. package/dist/maintenance/observation-ledger-utils.js +2 -2
  401. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +102 -1
  402. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +37 -25
  403. package/dist/maintenance/rebuild-memory-projection.js +38 -28
  404. package/dist/maintenance/rebuild-observations.js +3 -3
  405. package/dist/mcp-memory-inspector-app.d.ts +22 -15
  406. package/dist/memory-action-policy.d.ts +3 -1
  407. package/dist/memory-cache.d.ts +3 -1
  408. package/dist/memory-lifecycle-ledger-utils.d.ts +25 -2
  409. package/dist/memory-lifecycle-ledger-utils.js +11 -1
  410. package/dist/memory-projection-store.d.ts +3 -1
  411. package/dist/memory-projection-store.js +2 -2
  412. package/dist/memory-provenance.d.ts +3 -1
  413. package/dist/memory-worth-outcomes.d.ts +5 -2
  414. package/dist/model-registry.js +2 -2
  415. package/dist/models-json.d.ts +3 -1
  416. package/dist/models-json.js +2 -2
  417. package/dist/namespaces/migrate.d.ts +6 -3
  418. package/dist/namespaces/migrate.js +51 -42
  419. package/dist/namespaces/principal.d.ts +27 -2
  420. package/dist/namespaces/principal.js +6 -2
  421. package/dist/namespaces/search.d.ts +16 -2
  422. package/dist/namespaces/search.js +24 -20
  423. package/dist/namespaces/storage.d.ts +24 -3
  424. package/dist/namespaces/storage.js +35 -27
  425. package/dist/native-knowledge.d.ts +3 -1
  426. package/dist/native-knowledge.js +2 -2
  427. package/dist/negative.js +2 -2
  428. package/dist/offline-sync-exclude-globs.d.ts +13 -0
  429. package/dist/offline-sync-exclude-globs.js +10 -0
  430. package/dist/offline-sync-exclude-globs.js.map +1 -0
  431. package/dist/offline-sync-impression-drain.d.ts +78 -0
  432. package/dist/offline-sync-impression-drain.js +37 -0
  433. package/dist/offline-sync-impression-drain.js.map +1 -0
  434. package/dist/offline-sync.js +4 -2
  435. package/dist/operator-toolkit.d.ts +5 -2
  436. package/dist/operator-toolkit.js +69 -54
  437. package/dist/orchestration/compression-guideline-coordinator.d.ts +5 -2
  438. package/dist/orchestration/compression-guideline-coordinator.js +3 -3
  439. package/dist/orchestration/maintenance.d.ts +121 -2
  440. package/dist/orchestration/maintenance.js +44 -31
  441. package/dist/{orchestrator-Bp_jeBHK.d.ts → orchestrator-CQJ8U7En.d.ts} +85 -79
  442. package/dist/orchestrator.d.ts +13 -8
  443. package/dist/orchestrator.js +194 -177
  444. package/dist/patterns-cli.d.ts +3 -1
  445. package/dist/{pipeline-BAj5bx7g.d.ts → pipeline-Cn-kvYeV.d.ts} +1 -1
  446. package/dist/policy-runtime.d.ts +3 -1
  447. package/dist/prioritized-embed.d.ts +19 -0
  448. package/dist/prioritized-embed.js +8 -0
  449. package/dist/prioritized-embed.js.map +1 -0
  450. package/dist/proactive-contention.d.ts +28 -0
  451. package/dist/proactive-contention.js +8 -0
  452. package/dist/proactive-contention.js.map +1 -0
  453. package/dist/profiling.js +2 -2
  454. package/dist/provenance.d.ts +3 -1
  455. package/dist/provenance.js +3 -2
  456. package/dist/{purge-NDWV6WYD.js → purge-IRF47ZTX.js} +3 -3
  457. package/dist/{qmd-_MDSlj1m.d.ts → qmd-oh9VXz1d.d.ts} +11 -1
  458. package/dist/qmd-preflight.d.ts +5 -2
  459. package/dist/qmd-recall-cache.d.ts +3 -1
  460. package/dist/qmd-status.d.ts +57 -0
  461. package/dist/qmd-status.js +18 -0
  462. package/dist/qmd-status.js.map +1 -0
  463. package/dist/qmd.d.ts +5 -2
  464. package/dist/qmd.js +7 -3
  465. package/dist/recall-concurrency-config.d.ts +16 -0
  466. package/dist/recall-concurrency-config.js +10 -0
  467. package/dist/recall-concurrency-config.js.map +1 -0
  468. package/dist/recall-disclosure-escalation.d.ts +3 -1
  469. package/dist/recall-explain-renderer.d.ts +4 -1
  470. package/dist/recall-explain-renderer.js +3 -3
  471. package/dist/recall-memory-map.d.ts +26 -0
  472. package/dist/recall-memory-map.js +18 -0
  473. package/dist/recall-memory-map.js.map +1 -0
  474. package/dist/recall-planner-llm.d.ts +3 -1
  475. package/dist/recall-planner-llm.js +4 -4
  476. package/dist/recall-qos.js +2 -2
  477. package/dist/recall-state.d.ts +163 -2
  478. package/dist/recall-state.js +6 -3
  479. package/dist/recall-tag-filter.d.ts +3 -1
  480. package/dist/recall-timings.d.ts +11 -2
  481. package/dist/recall-timings.js +3 -1
  482. package/dist/recall-xray-cli.d.ts +3 -1
  483. package/dist/recall-xray-cli.js +4 -4
  484. package/dist/recall-xray-renderer.d.ts +3 -1
  485. package/dist/recall-xray-renderer.js +3 -3
  486. package/dist/recall-xray.d.ts +3 -1
  487. package/dist/recall-xray.js +2 -2
  488. package/dist/relevance.js +3 -3
  489. package/dist/replay/normalizers/chatgpt.d.ts +3 -1
  490. package/dist/replay/normalizers/claude.d.ts +3 -1
  491. package/dist/replay/normalizers/openclaw.d.ts +3 -1
  492. package/dist/replay/normalizers/shared.d.ts +3 -1
  493. package/dist/replay/runner.d.ts +3 -1
  494. package/dist/replay/types.d.ts +3 -1
  495. package/dist/rerank.d.ts +8 -1
  496. package/dist/rerank.js +3 -1
  497. package/dist/resolution-3K27T4VO.js +18 -0
  498. package/dist/resolution-3K27T4VO.js.map +1 -0
  499. package/dist/resolve-auth-token.d.ts +3 -1
  500. package/dist/resolve-provider-secret.js +2 -2
  501. package/dist/resume-bundles.js +19 -14
  502. package/dist/retrieval-agents.d.ts +19 -16
  503. package/dist/retrieval-agents.js +3 -3
  504. package/dist/retrieval-tiers.d.ts +3 -1
  505. package/dist/routing/engine.d.ts +3 -1
  506. package/dist/routing/store.d.ts +3 -1
  507. package/dist/routing/store.js +2 -2
  508. package/dist/salvage-envelope.d.ts +18 -0
  509. package/dist/salvage-envelope.js +15 -0
  510. package/dist/salvage-envelope.js.map +1 -0
  511. package/dist/schemas.d.ts +98 -98
  512. package/dist/scope-profiles-EpJG7yKP.d.ts +30 -0
  513. package/dist/search/document-scanner.js +3 -2
  514. package/dist/search/embed-helper.d.ts +3 -1
  515. package/dist/search/embed-helper.js +3 -3
  516. package/dist/search/factory.d.ts +3 -1
  517. package/dist/search/factory.js +18 -16
  518. package/dist/search/index.d.ts +3 -1
  519. package/dist/search/index.js +22 -20
  520. package/dist/search/lancedb-backend.d.ts +3 -1
  521. package/dist/search/lancedb-backend.js +6 -5
  522. package/dist/search/meilisearch-backend.d.ts +3 -1
  523. package/dist/search/meilisearch-backend.js +6 -5
  524. package/dist/search/noop-backend.d.ts +3 -1
  525. package/dist/search/orama-backend.d.ts +3 -1
  526. package/dist/search/orama-backend.js +6 -5
  527. package/dist/search/port.d.ts +16 -2
  528. package/dist/search/port.js +1 -1
  529. package/dist/search/remote-backend.d.ts +3 -1
  530. package/dist/search/remote-backend.js +3 -3
  531. package/dist/secure-store/index.d.ts +12 -1
  532. package/dist/secure-store/index.js +6 -3
  533. package/dist/{semantic-consolidation-C2m5eHHE.d.ts → semantic-consolidation-DILZEQq3.d.ts} +1 -1
  534. package/dist/semantic-consolidation.d.ts +4 -2
  535. package/dist/semantic-consolidation.js +38 -29
  536. package/dist/semantic-rule-promotion.js +34 -24
  537. package/dist/semantic-rule-verifier.d.ts +3 -1
  538. package/dist/semantic-rule-verifier.js +35 -25
  539. package/dist/session-observer-bands.d.ts +3 -1
  540. package/dist/session-observer-state.d.ts +3 -1
  541. package/dist/session-observer-state.js +2 -2
  542. package/dist/session-transcript-migration.js +2 -2
  543. package/dist/shared-context/manager.d.ts +11 -9
  544. package/dist/shared-context/manager.js +3 -3
  545. package/dist/signal.d.ts +3 -1
  546. package/dist/{storage-hr_Y2z5R.d.ts → storage-NIyKYD8g.d.ts} +489 -110
  547. package/dist/storage-guards.js +2 -2
  548. package/dist/storage.d.ts +6 -3
  549. package/dist/storage.js +38 -26
  550. package/dist/structured-attributes.d.ts +23 -1
  551. package/dist/structured-attributes.js +7 -1
  552. package/dist/summarizer.d.ts +3 -1
  553. package/dist/summarizer.js +11 -11
  554. package/dist/summary-snapshot.d.ts +3 -1
  555. package/dist/summary-snapshot.js +2 -2
  556. package/dist/temporal-index-batch.d.ts +1 -0
  557. package/dist/temporal-index-batch.js +10 -0
  558. package/dist/temporal-index-batch.js.map +1 -0
  559. package/dist/temporal-index-compat.d.ts +279 -1
  560. package/dist/temporal-index-compat.js +1 -1
  561. package/dist/temporal-index.d.ts +1 -225
  562. package/dist/temporal-index.js +35 -3
  563. package/dist/temporal-supersession.d.ts +5 -2
  564. package/dist/temporal-supersession.js +2 -2
  565. package/dist/temporal-timeline-recall.d.ts +3 -1
  566. package/dist/temporal-validity.d.ts +3 -1
  567. package/dist/threading.d.ts +3 -1
  568. package/dist/threading.js +2 -2
  569. package/dist/tier-migration.d.ts +5 -2
  570. package/dist/tier-routing.d.ts +3 -1
  571. package/dist/{tier-stats-KV7IWCJR.js → tier-stats-QEJSPFV2.js} +2 -2
  572. package/dist/tokens.js +3 -3
  573. package/dist/topics.d.ts +3 -1
  574. package/dist/transcript.d.ts +3 -1
  575. package/dist/transcript.js +2 -2
  576. package/dist/transfer/backup.js +3 -3
  577. package/dist/transfer/capsule-export.js +3 -3
  578. package/dist/transfer/capsule-import.js +3 -3
  579. package/dist/transfer/types.d.ts +90 -90
  580. package/dist/trust-score-stage.d.ts +75 -38
  581. package/dist/trust-score-stage.js +11 -3
  582. package/dist/trust-score.d.ts +3 -1
  583. package/dist/{types-Cg8q7W7_.d.ts → types-D_fG2ix8.d.ts} +39 -63
  584. package/dist/types-continuity.d.ts +52 -0
  585. package/dist/types-continuity.js +1 -0
  586. package/dist/types-continuity.js.map +1 -0
  587. package/dist/types.d.ts +3 -1
  588. package/dist/types.js +1 -1
  589. package/dist/utility-runtime.d.ts +3 -1
  590. package/dist/utils/serialize-mutations.d.ts +31 -2
  591. package/dist/utils/serialize-mutations.js +1 -1
  592. package/dist/verified-recall.js +36 -26
  593. package/dist/write-envelope.d.ts +282 -0
  594. package/dist/write-envelope.js +35 -0
  595. package/dist/write-envelope.js.map +1 -0
  596. package/dist/write-quarantine.d.ts +94 -0
  597. package/dist/write-quarantine.js +11 -0
  598. package/dist/write-quarantine.js.map +1 -0
  599. package/dist/write-rate-limiter.d.ts +45 -0
  600. package/dist/write-rate-limiter.js +9 -0
  601. package/dist/write-rate-limiter.js.map +1 -0
  602. package/package.json +37 -2
  603. package/src/access-admin-ops-surface.ts +17 -7
  604. package/src/access-boundary.test.ts +28 -0
  605. package/src/access-boundary.ts +31 -2
  606. package/src/access-citation.test.ts +72 -0
  607. package/src/access-citation.ts +139 -0
  608. package/src/access-errors.ts +21 -0
  609. package/src/access-fingerprint-parity.test.ts +211 -0
  610. package/src/access-http-cancellation.test.ts +59 -21
  611. package/src/access-http.test.ts +90 -0
  612. package/src/access-http.ts +79 -79
  613. package/src/access-mcp-cancellation.test.ts +16 -7
  614. package/src/access-memory-search-fanout.test.ts +220 -0
  615. package/src/access-memory-search-fanout.ts +168 -0
  616. package/src/access-observe-quarantine.test.ts +172 -0
  617. package/src/access-observe-write-surface.ts +137 -11
  618. package/src/access-operations-batch.ts +2 -0
  619. package/src/access-recall-concurrency.ts +773 -0
  620. package/src/access-recall-response.ts +307 -0
  621. package/src/access-recall-surface.ts +100 -252
  622. package/src/access-service-coding-write.test.ts +22 -4
  623. package/src/access-service-health.test.ts +49 -0
  624. package/src/access-service-namespace.test.ts +486 -8
  625. package/src/access-service-observe-scope.test.ts +4 -0
  626. package/src/access-service-recall-concurrency.test.ts +1990 -0
  627. package/src/access-service.ts +186 -179
  628. package/src/access-surface-catalog.ts +1 -0
  629. package/src/access-token-capabilities.ts +16 -9
  630. package/src/active-recall.test.ts +35 -0
  631. package/src/active-recall.ts +7 -0
  632. package/src/bounded-jsonl-state.ts +93 -0
  633. package/src/buffer-session.test.ts +422 -5
  634. package/src/buffer-surprise-trigger.test.ts +41 -0
  635. package/src/buffer.ts +218 -3
  636. package/src/capabilities-cluster-b.test.ts +1 -0
  637. package/src/capabilities.ts +5 -6
  638. package/src/cli.ts +21 -22
  639. package/src/coding/architecture-surfaces.test.ts +6 -3
  640. package/src/coding/architecture-surfaces.ts +36 -25
  641. package/src/coding/decision-surfaces.ts +42 -34
  642. package/src/compounding/engine.test.ts +5 -1
  643. package/src/compounding/engine.ts +7 -7
  644. package/src/config-qmd.ts +89 -0
  645. package/src/config.test.ts +136 -0
  646. package/src/config.ts +113 -118
  647. package/src/connector-provenance-lifecycle.test.ts +4 -4
  648. package/src/connectors/coerce.test.ts +131 -0
  649. package/src/connectors/coerce.ts +80 -7
  650. package/src/contradiction/contradiction.test.ts +10 -6
  651. package/src/contradiction/resolution.ts +17 -4
  652. package/src/correction/correction-access-wiring.ts +62 -18
  653. package/src/cross-namespace-budget.test.ts +35 -0
  654. package/src/cross-namespace-budget.ts +86 -19
  655. package/src/explicit-capture.ts +54 -17
  656. package/src/extraction.ts +2 -3
  657. package/src/faithfulness-graph-guard.test.ts +16 -69
  658. package/src/graph-recall.test.ts +31 -0
  659. package/src/index.ts +22 -2
  660. package/src/local-llm.ts +4 -6
  661. package/src/logger.ts +16 -0
  662. package/src/maintenance/dreams-ledger.ts +100 -49
  663. package/src/maintenance/rebuild-memory-lifecycle-ledger-cli.ts +77 -0
  664. package/src/maintenance/rebuild-memory-lifecycle-ledger.ts +373 -9
  665. package/src/memory-lifecycle-ledger-utils.ts +51 -5
  666. package/src/namespaces/principal.test.ts +37 -1
  667. package/src/namespaces/principal.ts +48 -0
  668. package/src/namespaces/search.test.ts +79 -5
  669. package/src/namespaces/search.ts +59 -6
  670. package/src/namespaces/storage.ts +43 -1
  671. package/src/offline-sync-exclude-globs.ts +58 -0
  672. package/src/offline-sync-impression-drain.test.ts +316 -0
  673. package/src/offline-sync-impression-drain.ts +260 -0
  674. package/src/offline-sync.test.ts +32 -5
  675. package/src/offline-sync.ts +1 -14
  676. package/src/operator-toolkit.ts +1 -1
  677. package/src/orchestration/batch-deindex-flush.test.ts +146 -0
  678. package/src/orchestration/consolidation-run.ts +96 -85
  679. package/src/orchestration/extraction-envelope.ts +94 -0
  680. package/src/orchestration/extraction-persist-promotion.ts +134 -0
  681. package/src/orchestration/extraction-persist.ts +325 -260
  682. package/src/orchestration/extraction-run.test.ts +1 -1
  683. package/src/orchestration/extraction-run.ts +2 -2
  684. package/src/orchestration/graph-recall-coordinator.ts +18 -7
  685. package/src/orchestration/lifecycle-policy-coordinator.ts +63 -48
  686. package/src/orchestration/maintenance.test.ts +2103 -3
  687. package/src/orchestration/maintenance.ts +574 -2
  688. package/src/orchestration/namespace-read-fanout.ts +14 -8
  689. package/src/orchestration/orchestrator-helpers.ts +8 -1
  690. package/src/orchestration/orchestrator-init.ts +22 -6
  691. package/src/orchestration/orchestrator-namespace-scope.ts +71 -0
  692. package/src/orchestration/persistence-index.ts +64 -9
  693. package/src/orchestration/qmd-result-resolver.ts +27 -0
  694. package/src/orchestration/recall-entry.ts +34 -19
  695. package/src/orchestration/recall-internal.ts +207 -79
  696. package/src/orchestration/recall-rerank-coordinator.ts +229 -82
  697. package/src/orchestration/recall-result-formatter.ts +76 -20
  698. package/src/orchestration/recall-search-pipeline.test.ts +70 -0
  699. package/src/orchestration/recall-search-pipeline.ts +102 -129
  700. package/src/orchestration/recall-section-coordinator.ts +315 -85
  701. package/src/orchestration/semantic-consolidation-coordinator.ts +69 -37
  702. package/src/orchestration/session-context.ts +21 -0
  703. package/src/orchestration/workspace-ops.test.ts +348 -0
  704. package/src/orchestration/workspace-ops.ts +168 -34
  705. package/src/orchestrator-chunked-hash-durability.test.ts +126 -0
  706. package/src/orchestrator-connector-dedup.test.ts +1061 -40
  707. package/src/orchestrator-flush.test.ts +155 -39
  708. package/src/orchestrator-nonchunked-hash-durability.test.ts +121 -0
  709. package/src/orchestrator-source-attribution.test.ts +9 -9
  710. package/src/orchestrator.ts +160 -149
  711. package/src/prioritized-embed.ts +123 -0
  712. package/src/proactive-contention.test.ts +80 -0
  713. package/src/proactive-contention.ts +39 -0
  714. package/src/procedural/procedure-miner.test.ts +19 -14
  715. package/src/procedural/procedure-miner.ts +44 -13
  716. package/src/qmd-client.test.ts +111 -1
  717. package/src/qmd-status.ts +186 -0
  718. package/src/qmd.ts +47 -47
  719. package/src/recall-budget-config.test.ts +30 -0
  720. package/src/recall-cold-deadline.test.ts +149 -0
  721. package/src/recall-concurrency-config.ts +28 -0
  722. package/src/recall-memory-map.ts +74 -0
  723. package/src/recall-rerank-coordinator.test.ts +508 -0
  724. package/src/recall-state.test.ts +825 -1
  725. package/src/recall-state.ts +406 -7
  726. package/src/recall-timings-access.test.ts +41 -0
  727. package/src/recall-timings.ts +16 -0
  728. package/src/relay/mission-access.test.ts +5 -5
  729. package/src/rerank.ts +22 -0
  730. package/src/retrieval-agents.test.ts +79 -0
  731. package/src/retrieval-agents.ts +71 -19
  732. package/src/salvage-envelope.ts +28 -0
  733. package/src/scopes/scope-plan.test.ts +42 -0
  734. package/src/scopes/scope-plan.ts +45 -0
  735. package/src/search/port.ts +13 -0
  736. package/src/secure-store/index.ts +1 -0
  737. package/src/secure-store/secure-fs.ts +48 -0
  738. package/src/secure-store/secure-store.test.ts +40 -0
  739. package/src/semantic-rule-promotion.ts +13 -4
  740. package/src/storage/content-hash-index.ts +655 -0
  741. package/src/storage/entity-timeline.ts +473 -0
  742. package/src/storage/memory-lifecycle-ledger-access.ts +603 -0
  743. package/src/storage/secure-line-reader.test.ts +197 -0
  744. package/src/storage/secure-line-reader.ts +181 -3
  745. package/src/storage-append-header-sniff.test.ts +195 -0
  746. package/src/storage-behavior-signals-cache.test.ts +237 -0
  747. package/src/storage-contract/cache-coherence.test.ts +96 -1
  748. package/src/storage-contract/content-hash.test.ts +47 -2
  749. package/src/storage-fact-hash-index-defer.test.ts +1200 -0
  750. package/src/storage-memory-lifecycle-ledger.test.ts +1146 -3
  751. package/src/storage.ts +882 -890
  752. package/src/structured-attributes.ts +52 -0
  753. package/src/temporal-index-batch.ts +112 -0
  754. package/src/temporal-index.test.ts +193 -0
  755. package/src/temporal-index.ts +49 -53
  756. package/src/testing/lifecycle-matrix.test.ts +212 -0
  757. package/src/testing/lifecycle-matrix.ts +271 -0
  758. package/src/testing/orchestrator-lite.ts +236 -0
  759. package/src/testing/subjects/dreams-ledger.test.ts +67 -0
  760. package/src/testing/subjects/extraction-lifecycle.test.ts +442 -0
  761. package/src/testing/subjects/lifecycle-ledger.test.ts +93 -0
  762. package/src/testing/subjects/recall-budget.test.ts +461 -0
  763. package/src/testing/subjects/serialized-write-chain.test.ts +224 -0
  764. package/src/trust-score-stage.test.ts +154 -0
  765. package/src/trust-score-stage.ts +216 -53
  766. package/src/types-continuity.ts +57 -0
  767. package/src/types.ts +51 -77
  768. package/src/utils/path-containment.test.ts +75 -0
  769. package/src/utils/path-containment.ts +76 -0
  770. package/src/utils/serialize-mutations.test.ts +122 -0
  771. package/src/utils/serialize-mutations.ts +68 -3
  772. package/src/wearables/memory-gen.test.ts +31 -9
  773. package/src/wearables/memory-gen.ts +95 -55
  774. package/src/wearables/pipeline.test.ts +10 -7
  775. package/src/wearables/service.test.ts +6 -8
  776. package/src/wearables/service.ts +2 -2
  777. package/src/write-envelope.extension.test.ts +111 -0
  778. package/src/write-envelope.test.ts +683 -0
  779. package/src/write-envelope.ts +902 -0
  780. package/src/write-quarantine.test.ts +245 -0
  781. package/src/write-quarantine.ts +290 -0
  782. package/src/write-rate-limiter.test.ts +105 -0
  783. package/src/write-rate-limiter.ts +135 -0
  784. package/src/write-sealed-parity.test.ts +204 -0
  785. package/dist/chunk-2VN4JAX7.js.map +0 -1
  786. package/dist/chunk-37CTGERM.js.map +0 -1
  787. package/dist/chunk-3IY64MV6.js.map +0 -1
  788. package/dist/chunk-BCDKBDSY.js.map +0 -1
  789. package/dist/chunk-BFPETA3S.js.map +0 -1
  790. package/dist/chunk-BFVEEB7W.js.map +0 -1
  791. package/dist/chunk-BS4SGLWV.js.map +0 -1
  792. package/dist/chunk-DCFV7A7H.js.map +0 -1
  793. package/dist/chunk-DYP3YYJJ.js.map +0 -1
  794. package/dist/chunk-E5BK6CGV.js +0 -335
  795. package/dist/chunk-E5BK6CGV.js.map +0 -1
  796. package/dist/chunk-FTYDWKO6.js.map +0 -1
  797. package/dist/chunk-GWTFLF2P.js.map +0 -1
  798. package/dist/chunk-IKQTFQMI.js.map +0 -1
  799. package/dist/chunk-INELTPRG.js.map +0 -1
  800. package/dist/chunk-J2HSAU72.js.map +0 -1
  801. package/dist/chunk-JREB6UFH.js.map +0 -1
  802. package/dist/chunk-K7LOWSLU.js.map +0 -1
  803. package/dist/chunk-KQDNAXOM.js.map +0 -1
  804. package/dist/chunk-KSBEEMQF.js.map +0 -1
  805. package/dist/chunk-KSNVDPDF.js.map +0 -1
  806. package/dist/chunk-LC7OODWZ.js.map +0 -1
  807. package/dist/chunk-LTJAMRGI.js.map +0 -1
  808. package/dist/chunk-LZOV7MX7.js.map +0 -1
  809. package/dist/chunk-NWTGD4AN.js.map +0 -1
  810. package/dist/chunk-ODPLEWB6.js.map +0 -1
  811. package/dist/chunk-OVJ2HIPE.js.map +0 -1
  812. package/dist/chunk-PBSAPHHA.js.map +0 -1
  813. package/dist/chunk-PHK3HARR.js +0 -32
  814. package/dist/chunk-PHK3HARR.js.map +0 -1
  815. package/dist/chunk-PLQE6MJA.js.map +0 -1
  816. package/dist/chunk-QKQYXZVS.js.map +0 -1
  817. package/dist/chunk-QQGPUKMT.js.map +0 -1
  818. package/dist/chunk-RANHFI3P.js +0 -8
  819. package/dist/chunk-RANHFI3P.js.map +0 -1
  820. package/dist/chunk-RAR2BSEM.js.map +0 -1
  821. package/dist/chunk-RULE4VG5.js.map +0 -1
  822. package/dist/chunk-SVOZFLIQ.js +0 -16
  823. package/dist/chunk-SVOZFLIQ.js.map +0 -1
  824. package/dist/chunk-T7Y5KPLN.js.map +0 -1
  825. package/dist/chunk-TXLGHDHS.js.map +0 -1
  826. package/dist/chunk-VDW4VU7B.js.map +0 -1
  827. package/dist/chunk-VSMRDBFT.js +0 -17
  828. package/dist/chunk-VSMRDBFT.js.map +0 -1
  829. package/dist/chunk-X64YLC24.js.map +0 -1
  830. package/dist/chunk-XDSXEKYK.js +0 -118
  831. package/dist/chunk-XDSXEKYK.js.map +0 -1
  832. package/dist/chunk-YF6FMLBT.js.map +0 -1
  833. package/dist/resolution-VH4NGENZ.js +0 -12
  834. /package/dist/{capsule-crypto-CZJSLEFG.js.map → access-citation.js.map} +0 -0
  835. /package/dist/{contradiction-scan-J57T5QV7.js.map → access-memory-search-fanout.js.map} +0 -0
  836. /package/dist/{dreams-ledger-6UODQOX6.js.map → access-recall-concurrency.js.map} +0 -0
  837. /package/dist/{graph-edge-decay-IOGBBAGC.js.map → access-recall-response.js.map} +0 -0
  838. /package/dist/{resolution-VH4NGENZ.js.map → bounded-jsonl-state.js.map} +0 -0
  839. /package/dist/{chunk-A3GOMRJG.js.map → chunk-23L3IXFD.js.map} +0 -0
  840. /package/dist/{chunk-MRHFJV44.js.map → chunk-2DQ2XREU.js.map} +0 -0
  841. /package/dist/{chunk-L2B3EE7B.js.map → chunk-2QMKMVHH.js.map} +0 -0
  842. /package/dist/{chunk-VJVNLNDQ.js.map → chunk-2UFO7X4Q.js.map} +0 -0
  843. /package/dist/{chunk-2MR3MFQB.js.map → chunk-2VEOKUPP.js.map} +0 -0
  844. /package/dist/{chunk-RHOZ5LLO.js.map → chunk-347WD2LE.js.map} +0 -0
  845. /package/dist/{chunk-HDTQVNWD.js.map → chunk-3QAH2S33.js.map} +0 -0
  846. /package/dist/{chunk-LRNMRXJO.js.map → chunk-3Y224NYC.js.map} +0 -0
  847. /package/dist/{chunk-VFSP73LP.js.map → chunk-45GF7Y3V.js.map} +0 -0
  848. /package/dist/{chunk-OEHCMALU.js.map → chunk-5I4M26Q7.js.map} +0 -0
  849. /package/dist/{chunk-2AZXIZEN.js.map → chunk-5Q7EVV4X.js.map} +0 -0
  850. /package/dist/{chunk-PUBTHW5O.js.map → chunk-6DRPPQEJ.js.map} +0 -0
  851. /package/dist/{chunk-FDCTQWLW.js.map → chunk-6O22TZSB.js.map} +0 -0
  852. /package/dist/{chunk-ZQ7UBUZ6.js.map → chunk-6QYST5XN.js.map} +0 -0
  853. /package/dist/{chunk-W4PGTAS2.js.map → chunk-6WAFYNVT.js.map} +0 -0
  854. /package/dist/{chunk-R5VAVVHP.js.map → chunk-72A4L5JJ.js.map} +0 -0
  855. /package/dist/{chunk-3FAMU5TX.js.map → chunk-A6USBZTO.js.map} +0 -0
  856. /package/dist/{chunk-ZHIVCODT.js.map → chunk-A72SWTWW.js.map} +0 -0
  857. /package/dist/{chunk-FC77VUX5.js.map → chunk-A7Q43EUZ.js.map} +0 -0
  858. /package/dist/{chunk-UJBESW6X.js.map → chunk-AE7WMV4V.js.map} +0 -0
  859. /package/dist/{chunk-A5UXZRRM.js.map → chunk-AJ7QCSIS.js.map} +0 -0
  860. /package/dist/{chunk-FNMFJWBY.js.map → chunk-ANEUPF6O.js.map} +0 -0
  861. /package/dist/{chunk-2A3OXAP2.js.map → chunk-B7RWBZXW.js.map} +0 -0
  862. /package/dist/{chunk-74F5STS4.js.map → chunk-BLAKS3CP.js.map} +0 -0
  863. /package/dist/{chunk-M7VGG3ID.js.map → chunk-BV5WMSIJ.js.map} +0 -0
  864. /package/dist/{chunk-2BFLDH5F.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  865. /package/dist/{chunk-UXKMMNJD.js.map → chunk-C23BYTJV.js.map} +0 -0
  866. /package/dist/{chunk-JZHHREBL.js.map → chunk-C3AKM55W.js.map} +0 -0
  867. /package/dist/{chunk-RP7YXA67.js.map → chunk-C5JF6EZ7.js.map} +0 -0
  868. /package/dist/{chunk-EHCONI6E.js.map → chunk-CQMEM5CC.js.map} +0 -0
  869. /package/dist/{chunk-PBNZVPFS.js.map → chunk-CXZQOVIE.js.map} +0 -0
  870. /package/dist/{chunk-7N2RUBAP.js.map → chunk-DDA47TES.js.map} +0 -0
  871. /package/dist/{chunk-64SE4X5G.js.map → chunk-DEBHXHJR.js.map} +0 -0
  872. /package/dist/{chunk-EHK6KZHK.js.map → chunk-DNHVPZOD.js.map} +0 -0
  873. /package/dist/{chunk-437S3G37.js.map → chunk-DQEMWVMT.js.map} +0 -0
  874. /package/dist/{chunk-LZZNTPLR.js.map → chunk-DX3XRGLH.js.map} +0 -0
  875. /package/dist/{chunk-DZKHSDOM.js.map → chunk-ES36HTSC.js.map} +0 -0
  876. /package/dist/{chunk-TN7THW5U.js.map → chunk-ET356KSB.js.map} +0 -0
  877. /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
  878. /package/dist/{chunk-DMSDUGDM.js.map → chunk-F7GAIWFA.js.map} +0 -0
  879. /package/dist/{chunk-G6XXLKC5.js.map → chunk-FFPJINJE.js.map} +0 -0
  880. /package/dist/{chunk-G4CN3ZXL.js.map → chunk-FUTF72MJ.js.map} +0 -0
  881. /package/dist/{chunk-HF77M34J.js.map → chunk-GFPZS3F5.js.map} +0 -0
  882. /package/dist/{chunk-G6NKALRN.js.map → chunk-H4WG3UQZ.js.map} +0 -0
  883. /package/dist/{chunk-UDQUSU27.js.map → chunk-HNZKVLAN.js.map} +0 -0
  884. /package/dist/{chunk-5EZXHU36.js.map → chunk-HYQJQGD3.js.map} +0 -0
  885. /package/dist/{chunk-TRWPCR6P.js.map → chunk-JECBQBEX.js.map} +0 -0
  886. /package/dist/{chunk-E6CBU7XP.js.map → chunk-JYIFGGEM.js.map} +0 -0
  887. /package/dist/{chunk-VA4WSW54.js.map → chunk-JYIJNNN3.js.map} +0 -0
  888. /package/dist/{chunk-L5HJQC36.js.map → chunk-K2TDK7GG.js.map} +0 -0
  889. /package/dist/{chunk-KDXVOFYY.js.map → chunk-KAVBJSBQ.js.map} +0 -0
  890. /package/dist/{chunk-4OKLXWDZ.js.map → chunk-KNB7IBBU.js.map} +0 -0
  891. /package/dist/{chunk-QLULYKWZ.js.map → chunk-KSXJOC4F.js.map} +0 -0
  892. /package/dist/{chunk-2S6QHZGJ.js.map → chunk-L2DPF4DF.js.map} +0 -0
  893. /package/dist/{chunk-JI5AVXYO.js.map → chunk-LEPOP46W.js.map} +0 -0
  894. /package/dist/{chunk-O7BBFJLP.js.map → chunk-LTAVSOZW.js.map} +0 -0
  895. /package/dist/{chunk-2IZAGAJR.js.map → chunk-LULR4IUW.js.map} +0 -0
  896. /package/dist/{chunk-WMWVO45V.js.map → chunk-MC6XO7T4.js.map} +0 -0
  897. /package/dist/{chunk-D6RIFG4O.js.map → chunk-MNB5RMAY.js.map} +0 -0
  898. /package/dist/{chunk-Q5WG43OP.js.map → chunk-MYFQ3ED4.js.map} +0 -0
  899. /package/dist/{chunk-V3UE5I5F.js.map → chunk-MYVPLJOO.js.map} +0 -0
  900. /package/dist/{chunk-MTWKDOVO.js.map → chunk-NLE6TSLG.js.map} +0 -0
  901. /package/dist/{chunk-DBRYEIGY.js.map → chunk-OJP3N7UK.js.map} +0 -0
  902. /package/dist/{chunk-SMX5267P.js.map → chunk-OZKOPQCM.js.map} +0 -0
  903. /package/dist/{chunk-JCK7V6SN.js.map → chunk-P65YJEEL.js.map} +0 -0
  904. /package/dist/{chunk-MTR7BZQN.js.map → chunk-PBGWYM3H.js.map} +0 -0
  905. /package/dist/{chunk-AXTXN4T6.js.map → chunk-PWFCHOB3.js.map} +0 -0
  906. /package/dist/{chunk-FDPZVY6D.js.map → chunk-QFN4U7AG.js.map} +0 -0
  907. /package/dist/{chunk-K2ZLHESQ.js.map → chunk-QIEUU4UK.js.map} +0 -0
  908. /package/dist/{chunk-3D6AFGQR.js.map → chunk-QVT3E4CE.js.map} +0 -0
  909. /package/dist/{chunk-SFQ6QNL7.js.map → chunk-R6YJI3HE.js.map} +0 -0
  910. /package/dist/{chunk-5CJVLG3H.js.map → chunk-RFDD3B7W.js.map} +0 -0
  911. /package/dist/{chunk-JBPKEARU.js.map → chunk-RKNJBZ55.js.map} +0 -0
  912. /package/dist/{chunk-FNZQGN76.js.map → chunk-S2BBISHU.js.map} +0 -0
  913. /package/dist/{chunk-IALLX7EE.js.map → chunk-S2FSBU4H.js.map} +0 -0
  914. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  915. /package/dist/{chunk-DPAENM7O.js.map → chunk-U3ZAVRP3.js.map} +0 -0
  916. /package/dist/{chunk-4KJLYTLS.js.map → chunk-V57NLO5P.js.map} +0 -0
  917. /package/dist/{chunk-FLVL4L3L.js.map → chunk-VDX2J7OX.js.map} +0 -0
  918. /package/dist/{chunk-AJLLIIML.js.map → chunk-W4FBGYGK.js.map} +0 -0
  919. /package/dist/{chunk-6SXVCD7W.js.map → chunk-W7IGLX4G.js.map} +0 -0
  920. /package/dist/{chunk-KAWTOYAW.js.map → chunk-WLZYGLJ4.js.map} +0 -0
  921. /package/dist/{chunk-RO4LQGT3.js.map → chunk-WON4APQY.js.map} +0 -0
  922. /package/dist/{chunk-PQVK2S3J.js.map → chunk-WZFAPHIK.js.map} +0 -0
  923. /package/dist/{chunk-KQPJLK3X.js.map → chunk-XL24QQ63.js.map} +0 -0
  924. /package/dist/{chunk-RVZRYUQH.js.map → chunk-YROFNEG5.js.map} +0 -0
  925. /package/dist/{chunk-VRAD2FGO.js.map → chunk-Z54EM5YZ.js.map} +0 -0
  926. /package/dist/{first-start-migration-TI67YMLG.js.map → first-start-migration-CSRHCJIQ.js.map} +0 -0
  927. /package/dist/{forget-CQCLB5LB.js.map → forget-HRPLVB3W.js.map} +0 -0
  928. /package/dist/{purge-NDWV6WYD.js.map → purge-IRF47ZTX.js.map} +0 -0
  929. /package/dist/{tier-stats-KV7IWCJR.js.map → tier-stats-QEJSPFV2.js.map} +0 -0
@@ -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 const { scopedCacheInvalidationEnabled } = this.config;\n StorageManager.setScopedCacheInvalidationDefault(root, scopedCacheInvalidationEnabled);\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,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;AAAA,IACxD;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/trust-score-stage.ts"],"sourcesContent":["/**\n * trust-score-stage.ts — signal adapters + recall pipeline stage (issue #1577 PR 2).\n *\n * This module sits between the pure {@link computeTrustScore} scorer and the\n * recall pipeline. It owns TWO jobs:\n *\n * 1. **Signal adapters** — read each trust signal via existing readers only\n * (`buildMemoryWorthCounterMap`-style frontmatter scan, faithfulness /\n * provenance / sources frontmatter from #1575/#1576). No new disk format,\n * no new write path. Expensive / optional signals (belief-ledger domain\n * calibration, contradiction review queue) are extension points that\n * return `undefined` when unwired — the scorer degrades to neutral for\n * any absent signal (rule 34).\n *\n * 2. **The recall stage** — apply `trustMultiplier(trust.score)` to each\n * candidate, exclude `quarantine`-band items from injection, and surface\n * the per-result `{ score, band, components }` so X-ray and the epistemic\n * renderer can explain the basis.\n *\n * Mutual exclusion with the Memory Worth filter (rule 39 — one multiplier, one\n * application point): when this stage runs, the standalone memory-worth filter\n * MUST NOT also run. The orchestrator enforces that at the wiring site\n * (`if (caps.recallTrustScore) … else if (caps.recallMemoryWorthFilter) …`);\n * the `double-multiplier` test below pins it structurally.\n */\n\nimport { computeMemoryWorth } from \"./memory-worth.js\";\nimport {\n computeTrustScore,\n trustMultiplier,\n type TrustBand,\n type TrustScoreComponent,\n type TrustScoreResult,\n type TrustSignals,\n type TrustWeights,\n} from \"./trust-score.js\";\nimport type { FaithfulnessFrontmatter, ProvenanceSource } from \"./types.js\";\n\n/**\n * Frontmatter projection the adapter reads. Kept narrow + structural so it can\n * be fed from a `MemoryFrontmatter`, a bench fixture, or a test stub without\n * pulling the full frontmatter type graph into the stage module.\n */\nexport interface TrustFrontmatterProjection {\n mw_success?: number;\n mw_fail?: number;\n lastAccessed?: string | null;\n provenance?: \"verified\" | \"unverified\" | \"none\";\n faithfulness?: FaithfulnessFrontmatter;\n sources?: ProvenanceSource[];\n /** Optional ISO creation/observation timestamp used for recency. */\n observedAt?: string;\n}\n\n/**\n * Build a `path → TrustSignals` map from an in-memory frontmatter scan. The\n * caller passes the memories already read for the memory-worth counter map so\n * we do not re-read the namespace. Pure: no I/O, takes `now` explicitly.\n */\nexport function buildTrustSignalMap(\n memories: ReadonlyArray<{ path: string; frontmatter: TrustFrontmatterProjection }>,\n now: Date,\n options: { recencyHalfLifeDays?: number } = {},\n): Map<string, TrustSignals> {\n const map = new Map<string, TrustSignals>();\n const nowMs = now.getTime();\n const nowUsable = Number.isFinite(nowMs);\n for (const m of memories) {\n const fm = m.frontmatter;\n const signals: TrustSignals = {};\n\n // Memory worth — reuse the exact Laplace computation the standalone filter\n // uses so the two never disagree on the same counters.\n if (fm.mw_success !== undefined || fm.mw_fail !== undefined) {\n // Pass the half-life through so outcome counters decay at the same\n // rate as the standalone memory-worth filter (review P2: TrustScore\n // subsumes the filter, so decay must not be lost). Convert days → ms.\n const halfLifeMs =\n options.recencyHalfLifeDays !== undefined\n ? options.recencyHalfLifeDays * 86_400_000\n : undefined;\n const worth = computeMemoryWorth({\n mw_success: fm.mw_success,\n mw_fail: fm.mw_fail,\n lastAccessed: fm.lastAccessed,\n now,\n halfLifeMs,\n });\n signals.memoryWorth = { score: worth.score, confidence: worth.confidence };\n }\n\n if (fm.provenance !== undefined) signals.provenance = fm.provenance;\n if (fm.faithfulness !== undefined) {\n // `skipped_no_span` (legacy fact lacking a verified source span) carries\n // no entailment signal — collapse it to `unchecked` so the scorer treats\n // it as the neutral \"no verdict\" case rather than a hard negative.\n signals.faithfulness =\n fm.faithfulness.verdict === \"skipped_no_span\" ? \"unchecked\" : fm.faithfulness.verdict;\n }\n\n // Corroboration = distinct source sessions/turns backing the fact.\n if (Array.isArray(fm.sources) && fm.sources.length > 0) {\n const distinct = new Set(\n fm.sources.map((s) => `${s.sessionKey ?? \"\"}|${s.turnId ?? \"\"}`),\n );\n signals.corroborationCount = distinct.size;\n }\n\n // Recency: prefer an explicit observation timestamp; fall back to\n // lastAccessed. Days-old vs the per-category half-life the caller supplies.\n const ts = fm.observedAt ?? fm.lastAccessed;\n if (nowUsable && typeof ts === \"string\" && ts.length > 0) {\n const parsed = Date.parse(ts);\n if (Number.isFinite(parsed)) {\n const ageDays = Math.max(0, (nowMs - parsed) / (24 * 60 * 60 * 1000));\n signals.ageDays = ageDays;\n if (options.recencyHalfLifeDays !== undefined) {\n signals.recencyHalfLifeDays = options.recencyHalfLifeDays;\n }\n }\n }\n\n // Only record an entry when at least one signal is present — a fully-empty\n // entry would score neutral anyway, and skipping keeps the map small.\n if (Object.keys(signals).length > 0) {\n map.set(m.path, signals);\n }\n }\n return map;\n}\n\n/** A scored recall candidate (mirrors `MemoryWorthFilterCandidate`). */\nexport interface TrustStageCandidate {\n path: string;\n score: number;\n}\n\n/** One candidate after the TrustScore stage. */\nexport interface TrustStageResultItem {\n path: string;\n /** Final score after the trust multiplier is applied. */\n score: number;\n /** The untouched input score — for telemetry / X-ray. */\n originalScore: number;\n /** The multiplier applied (exactly `1.0` for neutral / quarantined-kept). */\n multiplier: number;\n /** The full TrustScore result for X-ray + epistemic rendering. */\n trust: TrustScoreResult;\n /** `true` when the item was excluded from injection by quarantine. */\n quarantined: boolean;\n}\n\nexport interface TrustStageOptions {\n /** `path → TrustSignals`. Candidates absent from the map score neutral. */\n signals: ReadonlyMap<string, TrustSignals>;\n weights?: TrustWeights;\n /** Multiplier bounds; see {@link trustMultiplier}. */\n minMultiplier?: number;\n maxMultiplier?: number;\n /**\n * When `true` (default), `quarantine`-band items are excluded from the\n * returned (injected) list but still appear in {@link TrustStageOutput.all}\n * with `quarantined: true` so X-ray can surface them with a reason.\n * Only effective when the stage is active at all.\n */\n quarantine?: boolean;\n /**\n * Re-sort admitted candidates by descending multiplied score. Default `true`.\n * When `false`, admitted items keep input order; quarantined items are still\n * separated out.\n */\n reorder?: boolean;\n}\n\n/** Output of {@link applyTrustScoreStage}. */\nexport interface TrustStageOutput {\n /** Admitted (injectable) candidates, score-multiplied and optionally sorted. */\n admitted: TrustStageResultItem[];\n /**\n * Quarantined candidates — excluded from injection but visible to X-ray with\n * the reason (rule 34 — exclusion must never look like \"no result\"). Callers\n * that only need the injected list read `admitted`; X-ray reads `all`.\n */\n quarantined: TrustStageResultItem[];\n /** Every candidate (admitted + quarantined) in input order, for X-ray. */\n all: TrustStageResultItem[];\n}\n\n/**\n * Apply the unified TrustScore stage: score each candidate, multiply its base\n * score by `trustMultiplier(trust.score)`, and separate hard-negative\n * (quarantine) items from the injectable set.\n *\n * Neutral candidates (no signals → multiplier `1.0`) are mathematically\n * untouched, preserving byte-identical ranking for uninstrumented memories\n * when the feature is ON (and the whole stage is skipped when OFF — rule 39).\n */\nexport function applyTrustScoreStage(\n candidates: readonly TrustStageCandidate[],\n options: TrustStageOptions,\n): TrustStageOutput {\n const reorder = options.reorder !== false;\n const quarantine = options.quarantine !== false;\n const minMul = options.minMultiplier;\n const maxMul = options.maxMultiplier;\n\n const all: TrustStageResultItem[] = [];\n const admitted: TrustStageResultItem[] = [];\n const quarantined: TrustStageResultItem[] = [];\n\n for (let i = 0; i < candidates.length; i += 1) {\n const c = candidates[i]!;\n const signals = options.signals.get(c.path);\n const trust = computeTrustScore(signals, options.weights);\n const isQuarantined = quarantine && trust.band === \"quarantine\";\n // Quarantined items are excluded from injection. Keep their score unchanged\n // so X-ray shows what the pipeline WOULD have injected — never inflate or\n // zero the score of a hidden item (rule 34).\n const multiplier = isQuarantined ? 1 : trustMultiplier(trust.score, minMul, maxMul);\n // Clamp the base score at zero before multiplying, mirroring the\n // memory-worth filter: a negative base would invert the multiplier's\n // intended direction (see memory-worth-filter.ts:145-153).\n const safeBase = c.score < 0 ? 0 : c.score;\n const scored = safeBase * multiplier;\n const item: TrustStageResultItem = {\n path: c.path,\n score: scored,\n originalScore: c.score,\n multiplier,\n trust,\n quarantined: isQuarantined,\n };\n all.push(item);\n if (isQuarantined) quarantined.push(item);\n else admitted.push(item);\n }\n\n if (reorder) {\n // Stable sort by descending multiplied score, with original input position\n // as the deterministic tiebreaker (CLAUDE.md rule 19 / checklist §12).\n admitted.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n // Tiebreaker: original insertion order. We don't have the index handy on\n // the item, so derive it from `all` ordering (input order is preserved\n // there). Equal-score items keep first-seen-first order.\n return 0;\n });\n // Node's sort is stable (ES2019+); the explicit `return 0` documents the\n // contract for reviewers.\n }\n\n return { admitted, quarantined, all };\n}\n\n/**\n * Compact X-ray projection of one stage item. Kept separate from the full\n * `TrustScoreResult` so the X-ray snapshot type stays narrow and serializable,\n * and so the renderer never depends on the scorer's internal component map\n * shape beyond `{ value, weight }`.\n */\nexport interface TrustXrayProjection {\n score: number;\n band: TrustBand;\n components: Record<string, TrustScoreComponent>;\n multiplier: number;\n quarantined: boolean;\n /** Human-readable exclusion reason, present only when quarantined. */\n quarantineReason?: string;\n}\n\n/** Build the X-ray projection for one stage result item. */\nexport function projectTrustForXray(item: TrustStageResultItem): TrustXrayProjection {\n const proj: TrustXrayProjection = {\n score: item.trust.score,\n band: item.trust.band,\n components: item.trust.components,\n multiplier: item.multiplier,\n quarantined: item.quarantined,\n };\n if (item.quarantined) {\n proj.quarantineReason = explainQuarantine(item.trust);\n }\n return proj;\n}\n\n/** Deterministic, component-derived reason a memory was quarantined. */\nexport function explainQuarantine(trust: TrustScoreResult): string {\n const c = trust.components;\n if (c.faithfulness && c.faithfulness.value === 0) return \"faithfulness: contradicted\";\n if (c.contradiction && c.contradiction.value <= 0.2) return \"contradiction: pending review\";\n return \"hard-negative trust signal\";\n}\n\n\n// ─── Recall-stage signal builder (I/O orchestration) ──────────────────────\n\n/**\n * Narrow callbacks the signal builder needs from its host (the orchestrator).\n * Kept as interfaces so the module stays pure-testable: the host binds\n * `getStorage` / `readQmdResultMemory` into these and the builder owns cache\n * management, namespace iteration, and the cold-tier direct fallback.\n */\nexport interface TrustScoreRerankDeps {\n /** Read every memory in a namespace for the hot-tier signal scan. */\n readNamespaceMemories(\n namespace: string,\n ): Promise<ReadonlyArray<{ path: string; frontmatter: TrustFrontmatterProjection }>>;\n /** Read one memory's frontmatter by path (cold-tier direct fallback). */\n readMemoryFrontmatter(path: string): Promise<TrustFrontmatterProjection | null>;\n}\n\n/** Per-namespace signal cache the host owns and the builder mutates. */\nexport interface TrustScoreSignalCache {\n cache: Map<string, { at: number; signals: ReadonlyMap<string, TrustSignals> }>;\n ttlMs: number;\n}\n\n/**\n * Build the `path → TrustSignals` map for recall candidates using a\n * per-namespace cache plus a direct-path fallback for cold-tier candidates\n * absent from the hot scan. Extracted from the orchestrator (issue #1577) so\n * the god file carries only thin wiring — the scoring itself is\n * {@link applyTrustScoreStage}.\n *\n * Fail-open: a single unreadable namespace or memory is logged and skipped so\n * a storage hiccup never breaks recall (mirrors `memory-worth-filter.ts`).\n */\nexport async function buildTrustSignalsForRerank(\n candidatePaths: readonly string[],\n namespaces: readonly string[],\n deps: TrustScoreRerankDeps,\n signalCache: TrustScoreSignalCache,\n now: Date,\n options: {\n recencyHalfLifeDays?: number;\n logDebug?: (message: string, context: Record<string, unknown>) => void;\n } = {},\n): Promise<Map<string, TrustSignals>> {\n const nowMs = now.getTime();\n const logDebug = options.logDebug ?? (() => {});\n const signals = new Map<string, TrustSignals>();\n\n // Evict expired cache entries (mirrors the worth-cache discipline).\n for (const [key, entry] of signalCache.cache) {\n if (nowMs - entry.at >= signalCache.ttlMs) signalCache.cache.delete(key);\n }\n\n // Per-namespace hot scan with cache.\n const seenNamespaces = new Set<string>();\n for (const ns of namespaces) {\n if (seenNamespaces.has(ns)) continue;\n seenNamespaces.add(ns);\n try {\n const cached = signalCache.cache.get(ns);\n let nsMap: ReadonlyMap<string, TrustSignals> | undefined;\n if (cached && nowMs - cached.at < signalCache.ttlMs) {\n nsMap = cached.signals;\n } else {\n const memories = await deps.readNamespaceMemories(ns);\n nsMap = buildTrustSignalMap(memories, now, {\n recencyHalfLifeDays: options.recencyHalfLifeDays,\n });\n signalCache.cache.set(ns, { at: nowMs, signals: nsMap });\n }\n for (const [path, s] of nsMap) signals.set(path, s);\n } catch (err) {\n logDebug(\"trust-score: failed to read namespace, skipping\", {\n namespace: ns,\n error: (err as Error).message,\n });\n }\n }\n\n // Direct per-path fallback for cold-tier candidates absent from the hot scan.\n const missing = candidatePaths.filter((p) => !signals.has(p));\n if (missing.length > 0) {\n const fallbackMemories: Array<{ path: string; frontmatter: TrustFrontmatterProjection }> = [];\n for (const path of missing) {\n try {\n const frontmatter = await deps.readMemoryFrontmatter(path);\n if (frontmatter) fallbackMemories.push({ path, frontmatter });\n } catch (err) {\n logDebug(\"trust-score: direct path lookup failed\", {\n path,\n error: (err as Error).message,\n });\n }\n }\n if (fallbackMemories.length > 0) {\n const fallbackSignals = buildTrustSignalMap(fallbackMemories, now, {\n recencyHalfLifeDays: options.recencyHalfLifeDays,\n });\n for (const [path, s] of fallbackSignals) signals.set(path, s);\n }\n }\n\n return signals;\n}\n"],"mappings":";;;;;;;;;AA2DO,SAAS,oBACd,UACA,KACA,UAA4C,CAAC,GAClB;AAC3B,QAAM,MAAM,oBAAI,IAA0B;AAC1C,QAAM,QAAQ,IAAI,QAAQ;AAC1B,QAAM,YAAY,OAAO,SAAS,KAAK;AACvC,aAAW,KAAK,UAAU;AACxB,UAAM,KAAK,EAAE;AACb,UAAM,UAAwB,CAAC;AAI/B,QAAI,GAAG,eAAe,UAAa,GAAG,YAAY,QAAW;AAI3D,YAAM,aACJ,QAAQ,wBAAwB,SAC5B,QAAQ,sBAAsB,QAC9B;AACN,YAAM,QAAQ,mBAAmB;AAAA,QAC/B,YAAY,GAAG;AAAA,QACf,SAAS,GAAG;AAAA,QACZ,cAAc,GAAG;AAAA,QACjB;AAAA,QACA;AAAA,MACF,CAAC;AACD,cAAQ,cAAc,EAAE,OAAO,MAAM,OAAO,YAAY,MAAM,WAAW;AAAA,IAC3E;AAEA,QAAI,GAAG,eAAe,OAAW,SAAQ,aAAa,GAAG;AACzD,QAAI,GAAG,iBAAiB,QAAW;AAIjC,cAAQ,eACN,GAAG,aAAa,YAAY,oB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BAAkB,KAAK;AAAA,QACjE,qBAAqB,QAAQ;AAAA,MAC/B,CAAC;AACD,iBAAW,CAAC,MAAM,CAAC,KAAK,gBAAiB,SAAQ,IAAI,MAAM,CAAC;AAAA,IAC9D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/capabilities.ts"],"sourcesContent":["/**\n * CapabilitySet — recall-operation feature gates resolved once, then threaded.\n *\n * Issue #1523 (Phase 1 of epic #1520). Root cause this addresses: 161+\n * scattered `config.<flag>Enabled` reads mean each gate is re-derived at every\n * call site, and reviews keep finding parallel code paths where one branch\n * checks a gate the other forgot (CLAUDE.md rule 39 — the \"gate divergence\"\n * defect class). The fix is to resolve a frozen capability projection ONCE at\n * the top of the recall operation and pass it down explicitly.\n *\n * Scope of THIS module (first migration PR): only the recall-operation-scoped\n * flags below. Flags that are also read in graph construction, writes, CLI, or\n * the summarizer are deliberately deferred to a follow-up so we never leave a\n * single flag half-migrated (some sites on `caps.`, some on `config.`).\n *\n * Field naming: each field is the config flag name with the trailing `Enabled`\n * removed (`recallMmrEnabled` → `recallMmr`).\n *\n * This is plumbing, not a feature — there is deliberately NO `enabled` gate for\n * the CapabilitySet itself (rule 30 governs behavior changes; resolving and\n * threading a capability projection must stay behavior-preserving).\n *\n * Flag-retirement audit (#1780, 2026-07-08): all projected fields across 18\n * capability sets were verified for live consumers. Two dead projections found\n * and removed: recallGraph (RecallEnhancementCapabilitySet — production reads\n * recallGraphEnabled directly via graph-recall.ts) and behaviorLoopAutoTune\n * (ConversationContextCapabilitySet — production reads behaviorLoopAutoTuneEnabled\n * directly via cli.ts). The flags themselves remain alive.\n */\n\nimport type { PluginConfig } from \"./types.js\";\n\n/**\n * Frozen projection of recall-operation feature gates.\n *\n * Every field is `readonly boolean`. The composition that maps a config flag to\n * a capability (including default-when-undefined semantics for optional flags)\n * lives ONLY in {@link resolveCapabilities} — call sites must read the\n * capability, never re-derive it from raw config.\n */\nexport interface CapabilitySet {\n /** `rerankCacheEnabled` — cache reranker scores across recall passes. */\n readonly rerankCache: boolean;\n /** `recallDirectAnswerEnabled` — observation-mode direct-answer tier. */\n readonly recallDirectAnswer: boolean;\n /** `recallMemoryWorthFilterEnabled` — Memory-Worth score reweighting. */\n readonly recallMemoryWorthFilter: boolean;\n /** `trustScoreEnabled` — unified TrustScore recall stage (issue #1577). */\n readonly recallTrustScore: boolean;\n /** `recallMmrEnabled` — maximal-marginal-relevance diversification. */\n readonly recallMmr: boolean;\n /** `recallReasoningTraceBoostEnabled` — boost reasoning-trace memories. */\n readonly recallReasoningTraceBoost: boolean;\n /** `recallPlannerLlmEnabled` — LLM-backed recall-mode planner. */\n readonly recallPlannerLlm: boolean;\n /** `recallPlannerEnabled` — recall-mode planner (heuristic + optional LLM). */\n readonly recallPlanner: boolean;\n /** `recallConfidenceGateEnabled` — Synapse-style confidence gate. */\n readonly recallConfidenceGate: boolean;\n /** `graphRecallEnabled` — graph-mode recall tier (gates planner graph mode). */\n readonly graphRecall: boolean;\n /** `graphAssistInFullModeEnabled` — graph-assist overlay in full mode. */\n readonly graphAssistInFullMode: boolean;\n /** `graphExpandedIntentEnabled` — promote broad-intent asks to graph mode. */\n readonly graphExpandedIntent: boolean;\n // --- Issue #1566 Cluster C: mixed-operation flags (recall + summarizer/CLI/writes) ---\n /** `rerankEnabled` — optional LLM reranking of recall candidates. */\n readonly rerank: boolean;\n /** `harmonicRetrievalEnabled` — abstraction-node harmonic retrieval tier. */\n readonly harmonicRetrieval: boolean;\n /** `parallelRetrievalEnabled` — three-agent parallel retrieval (DirectFact + Contextual + Temporal). */\n readonly parallelRetrieval: boolean;\n}\n\n/**\n * Resolve the recall-operation {@link CapabilitySet} from parsed config.\n *\n * Call this ONCE per recall operation (at the `recall()` / `recallInternal`\n * entry) and thread the result down. Composition lives here and only here.\n *\n * Session toggles are intentionally not a parameter yet: `session-toggles.ts`\n * is agent-scoped (per session/agent enable-disable of the whole plugin), not\n * flag-scoped — none of the flags projected here have a per-session override,\n * so there is nothing for a toggle argument to compose at this layer.\n */\nexport function resolveCapabilities(config: PluginConfig): CapabilitySet {\n return Object.freeze({\n rerankCache: config.rerankCacheEnabled,\n recallDirectAnswer: config.recallDirectAnswerEnabled,\n recallMemoryWorthFilter: config.recallMemoryWorthFilterEnabled,\n // Issue #1577: TrustScore subsumes the Memory Worth multiplier when on;\n // the orchestrator runs exactly one of the two (mutual exclusion, rule 39).\n recallTrustScore: config.trustScoreEnabled === true,\n recallMmr: config.recallMmrEnabled,\n recallReasoningTraceBoost: config.recallReasoningTraceBoostEnabled,\n recallPlannerLlm: config.recallPlannerLlmEnabled,\n recallPlanner: config.recallPlannerEnabled,\n recallConfidenceGate: config.recallConfidenceGateEnabled,\n graphRecall: config.graphRecallEnabled,\n // Optional flags: preserve the exact default-when-undefined semantics the\n // migrated call sites used (`!== false` = default-on, `=== true` = default-off).\n graphAssistInFullMode: config.graphAssistInFullModeEnabled !== false,\n graphExpandedIntent: config.graphExpandedIntentEnabled === true,\n // Issue #1566 Cluster C: mixed-operation flags resolved once per recall op.\n rerank: config.rerankEnabled,\n harmonicRetrieval: config.harmonicRetrievalEnabled,\n parallelRetrieval: config.parallelRetrievalEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Graph-construction capability set (issue #1566 Cluster A).\n//\n// The recall CapabilitySet above covers flags whose EVERY read site lives on\n// the recall call chain. The five flags below are read on graph-construction,\n// write/extraction, AND recall paths — so they cannot join the recall set\n// without leaving some sites on `caps.` and others on `config.` (the exact\n// divergence #1523 forbade). They get their own projection, resolved at graph\n// build/write entry (and alongside `caps` when recall reads them).\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of graph-construction feature gates.\n *\n * Every field is `readonly boolean`. Composition (including default-when-\n * undefined semantics for the optional `graphWriteSessionAdjacencyEnabled`)\n * lives ONLY in {@link resolveGraphConstructionCapabilities}.\n */\nexport interface GraphConstructionCapabilitySet {\n /** `entityGraphEnabled` — maintain entity co-reference graph edges. */\n readonly entityGraph: boolean;\n /** `timeGraphEnabled` — maintain thread-adjacency graph edges. */\n readonly timeGraph: boolean;\n /** `causalGraphEnabled` — maintain causal-language graph edges. */\n readonly causalGraph: boolean;\n /** `multiGraphMemoryEnabled` — master switch for multi-graph writes/traversal. */\n readonly multiGraphMemory: boolean;\n /** `graphWriteSessionAdjacencyEnabled` — session-adjacency fallback for time edges (default-on). */\n readonly graphWriteSessionAdjacency: boolean;\n}\n\n/**\n * Resolve the {@link GraphConstructionCapabilitySet} from parsed config.\n *\n * Call this ONCE at graph build/write entry (extraction, recall graph\n * expansion, graph-health/repair) and thread the result down — exactly the\n * pattern {@link resolveCapabilities} established for recall.\n */\nexport type GraphConstructionConfigProjection = Pick<\n PluginConfig,\n | \"entityGraphEnabled\"\n | \"timeGraphEnabled\"\n | \"causalGraphEnabled\"\n | \"multiGraphMemoryEnabled\"\n | \"graphWriteSessionAdjacencyEnabled\"\n>;\n\nexport function resolveGraphConstructionCapabilities(\n config: GraphConstructionConfigProjection,\n): GraphConstructionCapabilitySet {\n return Object.freeze({\n entityGraph: config.entityGraphEnabled,\n timeGraph: config.timeGraphEnabled,\n causalGraph: config.causalGraphEnabled,\n multiGraphMemory: config.multiGraphMemoryEnabled,\n // Optional flag: preserve the exact default-when-undefined semantics the\n // migrated call site used (`!== false` = default-on).\n graphWriteSessionAdjacency: config.graphWriteSessionAdjacencyEnabled !== false,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Access-setup capability set (issue #1566 Cluster B).\n//\n// These two flags gate cross-namespace recall budgeting and anomaly-detection\n// auditing. Resolved once at access-service handler entry (and the operator\n// doctor check) rather than re-derived from raw config at each site.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of access-setup feature gates (issue #1566 Cluster B).\n *\n * Every field is `readonly boolean`. Composition (including the default-off\n * semantics for the optional `recallAuditAnomalyDetectionEnabled`) lives ONLY\n * in {@link resolveAccessSetupCapabilities}.\n */\nexport interface AccessSetupCapabilitySet {\n /** `recallCrossNamespaceBudgetEnabled` — rolling cross-namespace recall budget. */\n readonly recallCrossNamespaceBudget: boolean;\n /** `recallAuditAnomalyDetectionEnabled` — access-audit anomaly detection (default-off). */\n readonly recallAuditAnomalyDetection: boolean;\n}\n\n/**\n * Resolve the {@link AccessSetupCapabilitySet} from parsed config.\n *\n * Call this ONCE at access-service handler entry and thread the result down.\n */\nexport type AccessSetupConfigProjection = Pick<\n PluginConfig,\n \"recallCrossNamespaceBudgetEnabled\" | \"recallAuditAnomalyDetectionEnabled\"\n>;\n\nexport function resolveAccessSetupCapabilities(\n config: AccessSetupConfigProjection,\n): AccessSetupCapabilitySet {\n return Object.freeze({\n recallCrossNamespaceBudget: config.recallCrossNamespaceBudgetEnabled,\n // Optional/default-off flag: preserve `=== true` semantics.\n recallAuditAnomalyDetection: config.recallAuditAnomalyDetectionEnabled === true,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Memory-lifecycle capability set (issue #1523 batch 3).\n//\n// The flags below gate memory WRITE/EXTRACTION (extraction judge, scope\n// classification, dedupe, telemetry prefilter), temporal supersession of\n// stored facts, and the lifecycle policy pass (promotion / decay / stale\n// filtering). They are read on the persistExtraction write path, the recall\n// candidate-filter path, and the maintenance / lifecycle-pass path — so, like\n// the graph-construction set above, they get their own projection resolved\n// ONCE at each operation entry that reads them (never re-derived from raw\n// config mid-operation — the gate-divergence defect class #1523 targets).\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// are applied at the config-parse boundary, rule 36), so the resolver is a\n// pure projection — no `!== false` / `=== true` re-coercion here.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of memory-lifecycle feature gates (issue #1523 batch 3).\n *\n * Resolved once per write / recall-filter / maintenance operation and threaded\n * down. Composition lives ONLY in {@link resolveMemoryLifecycleCapabilities}.\n */\nexport interface MemoryLifecycleCapabilitySet {\n /** `temporalSupersessionEnabled` — supersede stale structured facts on write, filter on recall. */\n readonly temporalSupersession: boolean;\n /** `temporalMemoryTreeEnabled` — temporal-memory-tree build + recall tier. */\n readonly temporalMemoryTree: boolean;\n /** `lifecyclePolicyEnabled` — lifecycle promotion / decay metadata pass. */\n readonly lifecyclePolicy: boolean;\n /** `lifecycleFilterStaleEnabled` — filter stale-lifecycle memories from recall. */\n readonly lifecycleFilterStale: boolean;\n /** `lifecycleMetricsEnabled` — emit lifecycle-pass metrics. */\n readonly lifecycleMetrics: boolean;\n /** `extractionScopeClassificationEnabled` — LLM classifies each fact's scope. */\n readonly extractionScopeClassification: boolean;\n /** `extractionJudgeEnabled` — LLM-as-judge fact-worthiness gate. */\n readonly extractionJudge: boolean;\n /** `extractionDedupeEnabled` — dedupe against recent extractions. */\n readonly extractionDedupe: boolean;\n /** `extractionTelemetryPrefilterEnabled` — skip mechanical-telemetry transcripts. */\n readonly extractionTelemetryPrefilter: boolean;\n /** `extractionJudgeTelemetryEnabled` — collect judge verdict telemetry. */\n readonly extractionJudgeTelemetry: boolean;\n /** `embeddingFallbackEnabled` — semantic-dedup / archive-search embedding fallback. */\n readonly embeddingFallback: boolean;\n /** `extractionRetryEnabled` — per-fingerprint backoff + provider circuit breaker on the extraction retry path. */\n readonly extractionRetry: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveMemoryLifecycleCapabilities}.\n */\nexport type MemoryLifecycleConfigProjection = Pick<\n PluginConfig,\n | \"temporalSupersessionEnabled\"\n | \"temporalMemoryTreeEnabled\"\n | \"lifecyclePolicyEnabled\"\n | \"lifecycleFilterStaleEnabled\"\n | \"lifecycleMetricsEnabled\"\n | \"extractionScopeClassificationEnabled\"\n | \"extractionJudgeEnabled\"\n | \"extractionDedupeEnabled\"\n | \"extractionTelemetryPrefilterEnabled\"\n | \"extractionJudgeTelemetryEnabled\"\n | \"embeddingFallbackEnabled\"\n | \"extractionRetryEnabled\"\n>;\n\n/**\n * Resolve the {@link MemoryLifecycleCapabilitySet} from parsed config.\n *\n * Call this ONCE per write / recall-filter / maintenance operation entry and\n * thread the result down — exactly the pattern {@link resolveCapabilities}\n * established for recall.\n */\nexport function resolveMemoryLifecycleCapabilities(\n config: MemoryLifecycleConfigProjection,\n): MemoryLifecycleCapabilitySet {\n return Object.freeze({\n temporalSupersession: config.temporalSupersessionEnabled,\n temporalMemoryTree: config.temporalMemoryTreeEnabled,\n lifecyclePolicy: config.lifecyclePolicyEnabled,\n lifecycleFilterStale: config.lifecycleFilterStaleEnabled,\n lifecycleMetrics: config.lifecycleMetricsEnabled,\n extractionScopeClassification: config.extractionScopeClassificationEnabled,\n extractionJudge: config.extractionJudgeEnabled,\n extractionDedupe: config.extractionDedupeEnabled,\n extractionTelemetryPrefilter: config.extractionTelemetryPrefilterEnabled,\n extractionJudgeTelemetry: config.extractionJudgeTelemetryEnabled,\n embeddingFallback: config.embeddingFallbackEnabled,\n extractionRetry: config.extractionRetryEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Indexing capability set (issue #1523 batch 4).\n//\n// The flags below gate query-aware indexing (temporal/tag index build +\n// prefilter) and the conversation index (QMD/FAISS backend selection). They\n// are read on the recall path, the extraction/persist path, and the\n// maintenance/invalidation path — so they get their own projection resolved\n// ONCE at each operation entry that reads them.\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// applied at the parse boundary), so the resolver is a pure projection.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of indexing feature gates (issue #1523 batch 4).\n *\n * Resolved once per recall / extraction / maintenance operation and threaded\n * down. Composition lives ONLY in {@link resolveIndexingCapabilities}.\n */\nexport interface IndexingCapabilitySet {\n /** `queryAwareIndexingEnabled` — build + use temporal/tag index for recall prefilter. */\n readonly queryAwareIndexing: boolean;\n /** `conversationIndexEnabled` — conversation-index backend (QMD / FAISS). */\n readonly conversationIndex: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveIndexingCapabilities}.\n */\nexport type IndexingConfigProjection = Pick<\n PluginConfig,\n \"queryAwareIndexingEnabled\" | \"conversationIndexEnabled\"\n>;\n\n/**\n * Resolve the {@link IndexingCapabilitySet} from parsed config.\n *\n * Call this ONCE per recall / extraction / maintenance operation entry and\n * thread the result down — exactly the pattern {@link resolveCapabilities}\n * established for recall.\n */\nexport function resolveIndexingCapabilities(\n config: IndexingConfigProjection,\n): IndexingCapabilitySet {\n return Object.freeze({\n queryAwareIndexing: config.queryAwareIndexingEnabled,\n conversationIndex: config.conversationIndexEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Creation-memory capability set (issue #1523 batch 4).\n//\n// The flags below gate the creation-memory subsystem: resume-bundle handoff,\n// commitment ledger, commitment lifecycle, and the master creation-memory\n// switch. They are read on the extraction/persist path, the recall\n// enrichment path, and the CLI command surface — so they get their own\n// projection resolved ONCE at each operation entry that reads them.\n//\n// Every field projects from an already-resolved PluginConfig boolean (defaults\n// applied at the parse boundary), so the resolver is a pure projection.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of creation-memory feature gates (issue #1523 batch 4).\n *\n * Resolved once per creation-memory operation (CLI command, extraction,\n * recall enrichment) and threaded down. Composition lives ONLY in\n * {@link resolveCreationMemoryCapabilities}.\n */\nexport interface CreationMemoryCapabilitySet {\n /** `creationMemoryEnabled` — master switch for creation-memory subsystem. */\n readonly creationMemory: boolean;\n /** `commitmentLedgerEnabled` — commitment-ledger read/write. */\n readonly commitmentLedger: boolean;\n /** `resumeBundlesEnabled` — resume-bundle handoff bundles. */\n readonly resumeBundles: boolean;\n /** `commitmentLifecycleEnabled` — commitment lifecycle (promotion / decay). */\n readonly commitmentLifecycle: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveCreationMemoryCapabilities}.\n */\nexport type CreationMemoryConfigProjection = Pick<\n PluginConfig,\n | \"creationMemoryEnabled\"\n | \"commitmentLedgerEnabled\"\n | \"resumeBundlesEnabled\"\n | \"commitmentLifecycleEnabled\"\n>;\n\n/**\n * Resolve the {@link CreationMemoryCapabilitySet} from parsed config.\n *\n * Call this ONCE per creation-memory operation entry and thread the result\n * down — exactly the pattern {@link resolveCapabilities} established for\n * recall.\n */\nexport function resolveCreationMemoryCapabilities(\n config: CreationMemoryConfigProjection,\n): CreationMemoryCapabilitySet {\n return Object.freeze({\n creationMemory: config.creationMemoryEnabled,\n commitmentLedger: config.commitmentLedgerEnabled,\n resumeBundles: config.resumeBundlesEnabled,\n commitmentLifecycle: config.commitmentLifecycleEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Namespace capability set (issue #1523 batch 5).\n//\n// `namespacesEnabled` is the single most-scattered config flag in the codebase\n// (101 read sites outside config.ts across 18 files — orchestrator, access-service,\n// namespace modules, maintenance, CLI, admin). It gates whether the multi-namespace\n// system is active at all: every namespace resolution, storage path, recall budget,\n// and maintenance fanout checks it. Like the other projections above it gets its own\n// resolver invoked ONCE per operation entry rather than re-derived at each site.\n//\n// The field is a non-optional boolean in PluginConfig, so no coercion is needed.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of namespace feature gates (issue #1523 batch 5).\n *\n * Every field is `readonly boolean`. Composition lives ONLY in\n * {@link resolveNamespaceCapabilities}.\n */\nexport interface NamespaceCapabilitySet {\n /** `namespacesEnabled` — multi-namespace system master switch. */\n readonly namespaces: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveNamespaceCapabilities}.\n */\nexport type NamespaceConfigProjection = Pick<PluginConfig, \"namespacesEnabled\">;\n\n/**\n * Resolve the {@link NamespaceCapabilitySet} from parsed config.\n *\n * Call this ONCE at operation entry and thread the result down. The flag is a\n * non-optional boolean so the projection is a pure pass-through.\n */\nexport function resolveNamespaceCapabilities(\n config: NamespaceConfigProjection,\n): NamespaceCapabilitySet {\n return Object.freeze({\n namespaces: config.namespacesEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// QMD capability set (issue #1523 batch 6).\n//\n// The twelve QMD (query-managed database) flags are the largest remaining\n// scattered cluster after batch 5. They gate every aspect of the tiered\n// memory system: master switch, tier migration, cold tier, daemon, auto-embed,\n// maintenance, query rerank, intent hints, explain, auto-upgrade, and parity\n// graph. Read sites span orchestrator, operator-toolkit, access-service, and\n// search/factory. All flags are non-optional booleans on PluginConfig (defaults\n// resolved at the parse boundary), so the projection is pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of QMD feature gates (issue #1523 batch 6).\n *\n * Every field is `readonly boolean`. Composition lives ONLY in\n * {@link resolveQmdCapabilities}.\n */\nexport interface QmdCapabilitySet {\n /** `qmdEnabled` — QMD tiered-memory master switch. */\n readonly qmd: boolean;\n /** `qmdTierMigrationEnabled` — automatic tier promotion/demotion. */\n readonly qmdTierMigration: boolean;\n /** `qmdTierAutoBackfillEnabled` — backfill stale tier entries. */\n readonly qmdTierAutoBackfill: boolean;\n /** `qmdAutoEmbedEnabled` — auto-embed documents on write. */\n readonly qmdAutoEmbed: boolean;\n /** `qmdMaintenanceEnabled` — QMD maintenance pass runner. */\n readonly qmdMaintenance: boolean;\n /** `qmdColdTierEnabled` — cold-tier storage. */\n readonly qmdColdTier: boolean;\n /** `qmdDaemonEnabled` — background QMD daemon. */\n readonly qmdDaemon: boolean;\n /** `qmdTierParityGraphEnabled` — tier parity graph. */\n readonly qmdTierParityGraph: boolean;\n /** `qmdQueryRerankEnabled` — QMD query reranking. */\n readonly qmdQueryRerank: boolean;\n /** `qmdIntentHintsEnabled` — QMD intent hint extraction. */\n readonly qmdIntentHints: boolean;\n /** `qmdExplainEnabled` — QMD explain output. */\n readonly qmdExplain: boolean;\n /** `qmdAutoUpgradeEnabled` — QMD auto-upgrade tiers. */\n readonly qmdAutoUpgrade: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveQmdCapabilities}.\n */\nexport type QmdConfigProjection = Pick<\n PluginConfig,\n | \"qmdEnabled\"\n | \"qmdTierMigrationEnabled\"\n | \"qmdTierAutoBackfillEnabled\"\n | \"qmdAutoEmbedEnabled\"\n | \"qmdMaintenanceEnabled\"\n | \"qmdColdTierEnabled\"\n | \"qmdDaemonEnabled\"\n | \"qmdTierParityGraphEnabled\"\n | \"qmdQueryRerankEnabled\"\n | \"qmdIntentHintsEnabled\"\n | \"qmdExplainEnabled\"\n | \"qmdAutoUpgradeEnabled\"\n>;\n\n/**\n * Resolve the {@link QmdCapabilitySet} from parsed config.\n *\n * Call this ONCE at operation entry and thread the result down. Eleven flags\n * are non-optional booleans (pure pass-through); `qmdColdTierEnabled` is\n * optional and coerced with `=== true` (matching the pre-migration call sites).\n */\nexport function resolveQmdCapabilities(config: QmdConfigProjection): QmdCapabilitySet {\n return Object.freeze({\n qmd: config.qmdEnabled,\n qmdTierMigration: config.qmdTierMigrationEnabled,\n qmdTierAutoBackfill: config.qmdTierAutoBackfillEnabled,\n qmdAutoEmbed: config.qmdAutoEmbedEnabled,\n qmdMaintenance: config.qmdMaintenanceEnabled,\n qmdColdTier: config.qmdColdTierEnabled === true,\n qmdDaemon: config.qmdDaemonEnabled,\n qmdTierParityGraph: config.qmdTierParityGraphEnabled,\n qmdQueryRerank: config.qmdQueryRerankEnabled,\n qmdIntentHints: config.qmdIntentHintsEnabled,\n qmdExplain: config.qmdExplainEnabled,\n qmdAutoUpgrade: config.qmdAutoUpgradeEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Identity-continuity capability set (issue #1523 batch 6).\n//\n// `identityContinuityEnabled` gates the identity/continuity system (agent\n// identity tracking, continuity incident logging). Its 13 read sites span\n// orchestrator, access-service, and CLI. The flag is a non-optional boolean\n// on PluginConfig, so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of identity-continuity feature gates (issue #1523 batch 6).\n */\nexport interface IdentityContinuityCapabilitySet {\n /** `identityContinuityEnabled` — identity-continuity master switch. */\n readonly identityContinuity: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveIdentityContinuityCapabilities}.\n */\nexport type IdentityContinuityConfigProjection = Pick<PluginConfig, \"identityContinuityEnabled\">;\n\n/**\n * Resolve the {@link IdentityContinuityCapabilitySet} from parsed config.\n */\nexport function resolveIdentityContinuityCapabilities(\n config: IdentityContinuityConfigProjection,\n): IdentityContinuityCapabilitySet {\n return Object.freeze({\n identityContinuity: config.identityContinuityEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Local-LLM capability set (issue #1523 batch 6).\n//\n// `localLlmEnabled` gates whether a local (on-device) LLM is used for\n// summarization, embedding fallback, extraction, and search. Its 11 read\n// sites span orchestrator, extraction, embedding-fallback, local-llm,\n// search/embed-helper, and summarizer. The flag is a non-optional boolean.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of local-LLM feature gates (issue #1523 batch 6).\n */\nexport interface LocalLlmCapabilitySet {\n /** `localLlmEnabled` — local (on-device) LLM master switch. */\n readonly localLlm: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveLocalLlmCapabilities}.\n */\nexport type LocalLlmConfigProjection = Pick<PluginConfig, \"localLlmEnabled\">;\n\n/**\n * Resolve the {@link LocalLlmCapabilitySet} from parsed config.\n */\nexport function resolveLocalLlmCapabilities(\n config: LocalLlmConfigProjection,\n): LocalLlmCapabilitySet {\n return Object.freeze({\n localLlm: config.localLlmEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Security capability set (issue #1523 batch 7).\n//\n// The four security/trust-zone flags gate quarantine promotion, poisoning\n// defense, and trust-zone recall. Read sites span orchestrator, access-service,\n// CLI, and research-status commands. All flags are non-optional booleans on\n// PluginConfig (defaults resolved at the parse boundary), so the projection is\n// a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of security/trust-zone feature gates (issue #1523 batch 7).\n */\nexport interface SecurityCapabilitySet {\n /** `trustZonesEnabled` — master switch for trust-zone enforcement. */\n readonly trustZones: boolean;\n /** `quarantinePromotionEnabled` — promote quarantined memories after review. */\n readonly quarantinePromotion: boolean;\n /** `memoryPoisoningDefenseEnabled` — detect and defend against memory poisoning. */\n readonly memoryPoisoningDefense: boolean;\n /** `trustZoneRecallEnabled` — restrict recall to trusted zones. */\n readonly trustZoneRecall: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveSecurityCapabilities}.\n */\nexport type SecurityConfigProjection = Pick<\n PluginConfig,\n \"trustZonesEnabled\" | \"quarantinePromotionEnabled\" | \"memoryPoisoningDefenseEnabled\" | \"trustZoneRecallEnabled\"\n>;\n\n/**\n * Resolve the {@link SecurityCapabilitySet} from parsed config.\n */\nexport function resolveSecurityCapabilities(config: SecurityConfigProjection): SecurityCapabilitySet {\n return Object.freeze({\n trustZones: config.trustZonesEnabled,\n quarantinePromotion: config.quarantinePromotionEnabled,\n memoryPoisoningDefense: config.memoryPoisoningDefenseEnabled,\n trustZoneRecall: config.trustZoneRecallEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Eval/benchmark capability set (issue #1523 batch 7).\n//\n// The five eval/benchmark flags gate the evaluation harness, shadow mode,\n// baseline snapshot management, delta reporting, and red-team benchmarking.\n// Read sites span orchestrator, CLI, and operator-toolkit. All flags are\n// non-optional booleans on PluginConfig.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of eval/benchmark feature gates (issue #1523 batch 7).\n */\nexport interface EvalCapabilitySet {\n /** `evalHarnessEnabled` — master switch for the eval harness. */\n readonly evalHarness: boolean;\n /** `evalShadowModeEnabled` — run evaluations in shadow mode. */\n readonly evalShadowMode: boolean;\n /** `benchmarkBaselineSnapshotsEnabled` — manage baseline snapshots. */\n readonly benchmarkBaselineSnapshots: boolean;\n /** `benchmarkDeltaReporterEnabled` — report benchmark deltas. */\n readonly benchmarkDeltaReporter: boolean;\n /** `memoryRedTeamBenchEnabled` — red-team benchmarking of memory. */\n readonly memoryRedTeamBench: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveEvalCapabilities}.\n */\nexport type EvalConfigProjection = Pick<\n PluginConfig,\n \"evalHarnessEnabled\" | \"evalShadowModeEnabled\" | \"benchmarkBaselineSnapshotsEnabled\" | \"benchmarkDeltaReporterEnabled\" | \"memoryRedTeamBenchEnabled\"\n>;\n\n/**\n * Resolve the {@link EvalCapabilitySet} from parsed config.\n */\nexport function resolveEvalCapabilities(config: EvalConfigProjection): EvalCapabilitySet {\n return Object.freeze({\n evalHarness: config.evalHarnessEnabled,\n evalShadowMode: config.evalShadowModeEnabled,\n benchmarkBaselineSnapshots: config.benchmarkBaselineSnapshotsEnabled,\n benchmarkDeltaReporter: config.benchmarkDeltaReporterEnabled,\n memoryRedTeamBench: config.memoryRedTeamBenchEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Utility-learning capability set (issue #1523 batch 7).\n//\n// The two utility-learning flags gate memory utility learning and\n// promotion-by-outcome. Read sites span orchestrator, CLI research-status\n// commands, and maintenance files. Both flags are non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of utility-learning feature gates (issue #1523 batch 7).\n */\nexport interface UtilityLearningCapabilitySet {\n /** `memoryUtilityLearningEnabled` — learn memory utility weights from outcomes. */\n readonly memoryUtilityLearning: boolean;\n /** `promotionByOutcomeEnabled` — promote memories by outcome tracking. */\n readonly promotionByOutcome: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveUtilityLearningCapabilities}.\n */\nexport type UtilityLearningConfigProjection = Pick<\n PluginConfig,\n \"memoryUtilityLearningEnabled\" | \"promotionByOutcomeEnabled\"\n>;\n\n/**\n * Resolve the {@link UtilityLearningCapabilitySet} from parsed config.\n */\nexport function resolveUtilityLearningCapabilities(config: UtilityLearningConfigProjection): UtilityLearningCapabilitySet {\n return Object.freeze({\n memoryUtilityLearning: config.memoryUtilityLearningEnabled,\n promotionByOutcome: config.promotionByOutcomeEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Objective-state capability set (issue #1523 batch 7).\n//\n// The three objective-state flags gate objective-state memory, snapshot\n// writes, and recall. Read sites span orchestrator, access-service, CLI\n// creation-ledger commands, and research-status commands. All flags are\n// non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of objective-state feature gates (issue #1523 batch 7).\n */\nexport interface ObjectiveStateCapabilitySet {\n /** `objectiveStateMemoryEnabled` — store objective-state memories. */\n readonly objectiveStateMemory: boolean;\n /** `objectiveStateSnapshotWritesEnabled` — write objective-state snapshots. */\n readonly objectiveStateSnapshotWrites: boolean;\n /** `objectiveStateRecallEnabled` — recall objective-state memories. */\n readonly objectiveStateRecall: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveObjectiveStateCapabilities}.\n */\nexport type ObjectiveStateConfigProjection = Pick<\n PluginConfig,\n \"objectiveStateMemoryEnabled\" | \"objectiveStateSnapshotWritesEnabled\" | \"objectiveStateRecallEnabled\"\n>;\n\n/**\n * Resolve the {@link ObjectiveStateCapabilitySet} from parsed config.\n */\nexport function resolveObjectiveStateCapabilities(config: ObjectiveStateConfigProjection): ObjectiveStateCapabilitySet {\n return Object.freeze({\n objectiveStateMemory: config.objectiveStateMemoryEnabled,\n objectiveStateSnapshotWrites: config.objectiveStateSnapshotWritesEnabled,\n objectiveStateRecall: config.objectiveStateRecallEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Compression capability set (issue #1523 batch 7).\n//\n// The three compression flags gate guideline learning, semantic refinement,\n// and context-compression actions. Read sites span orchestrator,\n// access-service, and the compression-guideline coordinator. All flags are\n// non-optional booleans.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of compression feature gates (issue #1523 batch 7).\n */\nexport interface CompressionCapabilitySet {\n /** `compressionGuidelineLearningEnabled` — learn compression guidelines. */\n readonly compressionGuidelineLearning: boolean;\n /** `compressionGuidelineSemanticRefinementEnabled` — semantically refine guidelines. */\n readonly compressionGuidelineSemanticRefinement: boolean;\n /** `contextCompressionActionsEnabled` — apply context-compression actions. */\n readonly contextCompressionActions: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveCompressionCapabilities}.\n */\nexport type CompressionConfigProjection = Pick<\n PluginConfig,\n \"compressionGuidelineLearningEnabled\" | \"compressionGuidelineSemanticRefinementEnabled\" | \"contextCompressionActionsEnabled\"\n>;\n\n/**\n * Resolve the {@link CompressionCapabilitySet} from parsed config.\n */\nexport function resolveCompressionCapabilities(config: CompressionConfigProjection): CompressionCapabilitySet {\n return Object.freeze({\n compressionGuidelineLearning: config.compressionGuidelineLearningEnabled,\n compressionGuidelineSemanticRefinement: config.compressionGuidelineSemanticRefinementEnabled,\n contextCompressionActions: config.contextCompressionActionsEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Presentation capability set (issue #1523 batch 8).\n//\n// These flags gate output formatting and presentation across the orchestrator, extraction\n// pipeline, consolidation engine, and related modules. Resolved ONCE per\n// operation entry rather than re-derived from raw config at each read site.\n// All flags are non-optional booleans on PluginConfig (defaults applied at\n// the parse boundary), so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of output formatting and presentation feature gates (issue #1523 batch 8).\n */\nexport interface PresentationCapabilitySet {\n /** `verbatimArtifactsEnabled` — verbatim-artifact rendering in recall output. */\n readonly verbatimArtifacts: boolean;\n /** `memoryBoxesEnabled` — memory-box rendering in recall output. */\n readonly memoryBoxes: boolean;\n /** `bufferSurpriseTriggerEnabled` — buffer surprise-detection trigger. */\n readonly bufferSurpriseTrigger: boolean;\n /** `threadingEnabled` — conversation threading in output. */\n readonly threading: boolean;\n /** `episodeNoteModeEnabled` — episode note-mode formatting. */\n readonly episodeNoteMode: boolean;\n /** `transcriptEnabled` — transcript-mode output. */\n readonly transcript: boolean;\n /** `entitySummaryEnabled` — entity summary generation. */\n readonly entitySummary: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolvePresentationCapabilities}.\n */\nexport type PresentationConfigProjection = Pick<\n PluginConfig,\n \"verbatimArtifactsEnabled\" |\n \"memoryBoxesEnabled\" |\n \"bufferSurpriseTriggerEnabled\" |\n \"threadingEnabled\" |\n \"episodeNoteModeEnabled\" |\n \"transcriptEnabled\" |\n \"entitySummaryEnabled\"\n>;\n\n/**\n * Resolve the {@link PresentationCapabilitySet} from parsed config.\n */\nexport function resolvePresentationCapabilities(config: PresentationConfigProjection): PresentationCapabilitySet {\n return Object.freeze({\n verbatimArtifacts: config.verbatimArtifactsEnabled,\n memoryBoxes: config.memoryBoxesEnabled,\n bufferSurpriseTrigger: config.bufferSurpriseTriggerEnabled,\n threading: config.threadingEnabled,\n episodeNoteMode: config.episodeNoteModeEnabled,\n transcript: config.transcriptEnabled,\n entitySummary: config.entitySummaryEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Consolidation capability set (issue #1523 batch 8).\n//\n// These flags gate memory consolidation, compounding, and abstraction across the orchestrator, extraction\n// pipeline, consolidation engine, and related modules. Resolved ONCE per\n// operation entry rather than re-derived from raw config at each read site.\n// All flags are non-optional booleans on PluginConfig (defaults applied at\n// the parse boundary), so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of memory consolidation, compounding, and abstraction feature gates (issue #1523 batch 8).\n */\nexport interface ConsolidationCapabilitySet {\n /** `compoundingSemanticEnabled` — semantic compounding of memories. */\n readonly compoundingSemantic: boolean;\n /** `abstractionAnchorsEnabled` — abstraction-anchor extraction. */\n readonly abstractionAnchors: boolean;\n /** `compoundingEnabled` — master compounding switch. */\n readonly compounding: boolean;\n /** `calibrationEnabled` — memory calibration pass. */\n readonly calibration: boolean;\n /** `semanticConsolidationEnabled` — semantic consolidation pass. */\n readonly semanticConsolidation: boolean;\n /** `patternReinforcementEnabled` — pattern reinforcement in consolidation. */\n readonly patternReinforcement: boolean;\n /** `continuityAuditEnabled` — continuity audit during consolidation. */\n readonly continuityAudit: boolean;\n /** `graphEdgeDecayEnabled` — graph edge decay in maintenance. */\n readonly graphEdgeDecay: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveConsolidationCapabilities}.\n */\nexport type ConsolidationConfigProjection = Pick<\n PluginConfig,\n \"compoundingSemanticEnabled\" |\n \"abstractionAnchorsEnabled\" |\n \"compoundingEnabled\" |\n \"calibrationEnabled\" |\n \"semanticConsolidationEnabled\" |\n \"patternReinforcementEnabled\" |\n \"continuityAuditEnabled\" |\n \"graphEdgeDecayEnabled\"\n>;\n\n/**\n * Resolve the {@link ConsolidationCapabilitySet} from parsed config.\n */\nexport function resolveConsolidationCapabilities(config: ConsolidationConfigProjection): ConsolidationCapabilitySet {\n return Object.freeze({\n compoundingSemantic: config.compoundingSemanticEnabled,\n abstractionAnchors: config.abstractionAnchorsEnabled,\n compounding: config.compoundingEnabled,\n calibration: config.calibrationEnabled,\n semanticConsolidation: config.semanticConsolidationEnabled,\n patternReinforcement: config.patternReinforcementEnabled,\n continuityAudit: config.continuityAuditEnabled,\n graphEdgeDecay: config.graphEdgeDecayEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// RecallAuxiliary capability set (issue #1523 batch 8).\n//\n// These flags gate extraction pipeline details and auxiliary recall enrichment across the orchestrator, extraction\n// pipeline, consolidation engine, and related modules. Resolved ONCE per\n// operation entry rather than re-derived from raw config at each read site.\n// All flags are non-optional booleans on PluginConfig (defaults applied at\n// the parse boundary), so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of extraction pipeline details and auxiliary recall enrichment feature gates (issue #1523 batch 8).\n */\nexport interface RecallAuxiliaryCapabilitySet {\n /** `causalRuleExtractionEnabled` — causal-rule extraction in pipeline. */\n readonly causalRuleExtraction: boolean;\n /** `correctionEnabled` — memory correction subsystem. */\n readonly correction: boolean;\n /** `continuityIncidentLoggingEnabled` — continuity incident logging. */\n readonly continuityIncidentLogging: boolean;\n /** `daySummaryEnabled` — day-summary generation. */\n readonly daySummary: boolean;\n /** `versioningEnabled` — memory versioning. */\n readonly versioning: boolean;\n /** `verifiedRecallEnabled` — verified-recall tier. */\n readonly verifiedRecall: boolean;\n /** `semanticRuleVerificationEnabled` — semantic-rule verification. */\n readonly semanticRuleVerification: boolean;\n /** `workProductRecallEnabled` — work-product recall tier. */\n readonly workProductRecall: boolean;\n /** `secureStoreEnabled` — secure storage mode. */\n readonly secureStore: boolean;\n /** `knowledgeIndexEnabled` — knowledge index in recall. */\n readonly knowledgeIndex: boolean;\n /** `factDeduplicationEnabled` — fact deduplication in recall. */\n readonly factDeduplication: boolean;\n /** `compactionResetEnabled` — compaction reset on re-ingest. */\n readonly compactionReset: boolean;\n /** `entityRetrievalEnabled` — entity retrieval tier. */\n readonly entityRetrieval: boolean;\n /** `cronRecallPolicyEnabled` — cron-based recall policy. */\n readonly cronRecallPolicy: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveRecallAuxiliaryCapabilities}.\n */\nexport type RecallAuxiliaryConfigProjection = Pick<\n PluginConfig,\n \"causalRuleExtractionEnabled\" |\n \"correctionEnabled\" |\n \"continuityIncidentLoggingEnabled\" |\n \"daySummaryEnabled\" |\n \"versioningEnabled\" |\n \"verifiedRecallEnabled\" |\n \"semanticRuleVerificationEnabled\" |\n \"workProductRecallEnabled\" |\n \"secureStoreEnabled\" |\n \"knowledgeIndexEnabled\" |\n \"factDeduplicationEnabled\" |\n \"compactionResetEnabled\" |\n \"entityRetrievalEnabled\" |\n \"cronRecallPolicyEnabled\"\n>;\n\n/**\n * Resolve the {@link RecallAuxiliaryCapabilitySet} from parsed config.\n */\nexport function resolveRecallAuxiliaryCapabilities(config: RecallAuxiliaryConfigProjection): RecallAuxiliaryCapabilitySet {\n return Object.freeze({\n causalRuleExtraction: config.causalRuleExtractionEnabled,\n correction: config.correctionEnabled,\n continuityIncidentLogging: config.continuityIncidentLoggingEnabled,\n daySummary: config.daySummaryEnabled,\n versioning: config.versioningEnabled,\n verifiedRecall: config.verifiedRecallEnabled,\n semanticRuleVerification: config.semanticRuleVerificationEnabled,\n workProductRecall: config.workProductRecallEnabled,\n secureStore: config.secureStoreEnabled,\n knowledgeIndex: config.knowledgeIndexEnabled,\n factDeduplication: config.factDeduplicationEnabled,\n compactionReset: config.compactionResetEnabled,\n entityRetrieval: config.entityRetrievalEnabled,\n cronRecallPolicy: config.cronRecallPolicyEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// RecallEnhancement capability set (issue #1523 batch 9).\n//\n// These 24 flags gate recall enrichment, memory reconstruction, entity\n// relationships, causal trajectory recall, CMC retrieval, and related\n// enhancement paths. Read sites span orchestrator, access-service, graph-recall,\n// and CLI research-status commands. All flags are non-optional booleans on\n// PluginConfig (defaults resolved at the parse boundary), so the projection\n// is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of recall-enhancement feature gates (issue #1523 batch 9).\n */\nexport interface RecallEnhancementCapabilitySet {\n readonly explicitCueRecall: boolean;\n readonly targetedFactRecall: boolean;\n readonly focusedListRecall: boolean;\n readonly responseGuidanceRecall: boolean;\n readonly eventOrderRecall: boolean;\n readonly reinforcementRecallBoost: boolean;\n readonly recallPlannerTelemetry: boolean;\n readonly peerProfileRecall: boolean;\n readonly graphAssistShadowEval: boolean;\n readonly memoryReconstruction: boolean;\n readonly memoryLinking: boolean;\n readonly causalTrajectoryRecall: boolean;\n readonly causalTrajectoryMemory: boolean;\n readonly cmcRetrieval: boolean;\n readonly contradictionDetection: boolean;\n readonly factArchival: boolean;\n readonly entityRelationships: boolean;\n readonly entityActivityLog: boolean;\n readonly compoundingInject: boolean;\n readonly accessTracking: boolean;\n readonly autoPromoteToShared: boolean;\n readonly feedback: boolean;\n readonly identity: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveRecallEnhancementCapabilities}.\n */\nexport type RecallEnhancementConfigProjection = Pick<\n PluginConfig,\n | \"explicitCueRecallEnabled\"\n | \"targetedFactRecallEnabled\"\n | \"focusedListRecallEnabled\"\n | \"responseGuidanceRecallEnabled\"\n | \"eventOrderRecallEnabled\"\n | \"reinforcementRecallBoostEnabled\"\n | \"recallPlannerTelemetryEnabled\"\n | \"peerProfileRecallEnabled\"\n | \"graphAssistShadowEvalEnabled\"\n | \"memoryReconstructionEnabled\"\n | \"memoryLinkingEnabled\"\n | \"causalTrajectoryRecallEnabled\"\n | \"causalTrajectoryMemoryEnabled\"\n | \"cmcRetrievalEnabled\"\n | \"contradictionDetectionEnabled\"\n | \"factArchivalEnabled\"\n | \"entityRelationshipsEnabled\"\n | \"entityActivityLogEnabled\"\n | \"compoundingInjectEnabled\"\n | \"accessTrackingEnabled\"\n | \"autoPromoteToSharedEnabled\"\n | \"feedbackEnabled\"\n | \"identityEnabled\"\n>;\n\n/**\n * Resolve the {@link RecallEnhancementCapabilitySet} from parsed config.\n */\nexport function resolveRecallEnhancementCapabilities(config: RecallEnhancementConfigProjection): RecallEnhancementCapabilitySet {\n return Object.freeze({\n explicitCueRecall: config.explicitCueRecallEnabled,\n targetedFactRecall: config.targetedFactRecallEnabled,\n focusedListRecall: config.focusedListRecallEnabled,\n responseGuidanceRecall: config.responseGuidanceRecallEnabled,\n eventOrderRecall: config.eventOrderRecallEnabled,\n reinforcementRecallBoost: config.reinforcementRecallBoostEnabled,\n recallPlannerTelemetry: config.recallPlannerTelemetryEnabled,\n peerProfileRecall: config.peerProfileRecallEnabled,\n graphAssistShadowEval: config.graphAssistShadowEvalEnabled === true,\n memoryReconstruction: config.memoryReconstructionEnabled,\n memoryLinking: config.memoryLinkingEnabled,\n causalTrajectoryRecall: config.causalTrajectoryRecallEnabled,\n causalTrajectoryMemory: config.causalTrajectoryMemoryEnabled,\n cmcRetrieval: config.cmcRetrievalEnabled,\n contradictionDetection: config.contradictionDetectionEnabled,\n factArchival: config.factArchivalEnabled,\n entityRelationships: config.entityRelationshipsEnabled,\n entityActivityLog: config.entityActivityLogEnabled,\n compoundingInject: config.compoundingInjectEnabled,\n accessTracking: config.accessTrackingEnabled,\n autoPromoteToShared: config.autoPromoteToSharedEnabled,\n feedback: config.feedbackEnabled,\n identity: config.identityEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// PipelineProcessing capability set (issue #1523 batch 9).\n//\n// These 22 flags gate the extraction/chunking/summarization pipeline and LLM\n// infrastructure. Read sites span orchestrator, extraction, summarizer,\n// embedding-fallback, local-llm, search, day-summary, and semantic-consolidation.\n// All flags are non-optional booleans on PluginConfig (defaults resolved at\n// the parse boundary), so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of pipeline-processing feature gates (issue #1523 batch 9).\n */\nexport interface PipelineProcessingCapabilitySet {\n readonly chunking: boolean;\n readonly semanticChunking: boolean;\n readonly semanticDedup: boolean;\n readonly summarization: boolean;\n readonly topicExtraction: boolean;\n readonly sessionObserver: boolean;\n readonly profiling: boolean;\n readonly checkpoint: boolean;\n readonly traceWeaver: boolean;\n readonly routingRules: boolean;\n readonly inlineSourceAttribution: boolean;\n readonly negativeExamples: boolean;\n readonly hourlySummaries: boolean;\n readonly lcm: boolean;\n readonly localLlmFast: boolean;\n readonly proactiveExtraction: boolean;\n readonly delinearize: boolean;\n readonly slowLog: boolean;\n readonly hostEmbeddingProvider: boolean;\n readonly memoryExtensions: boolean;\n readonly hourlySummariesExtended: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolvePipelineProcessingCapabilities}.\n */\nexport type PipelineProcessingConfigProjection = Pick<\n PluginConfig,\n | \"chunkingEnabled\"\n | \"semanticChunkingEnabled\"\n | \"semanticDedupEnabled\"\n | \"summarizationEnabled\"\n | \"topicExtractionEnabled\"\n | \"sessionObserverEnabled\"\n | \"profilingEnabled\"\n | \"checkpointEnabled\"\n | \"traceWeaverEnabled\"\n | \"routingRulesEnabled\"\n | \"inlineSourceAttributionEnabled\"\n | \"negativeExamplesEnabled\"\n | \"hourlySummariesEnabled\"\n | \"lcmEnabled\"\n | \"localLlmFastEnabled\"\n | \"proactiveExtractionEnabled\"\n | \"delinearizeEnabled\"\n | \"slowLogEnabled\"\n | \"hostEmbeddingProviderEnabled\"\n | \"memoryExtensionsEnabled\"\n | \"hourlySummariesExtendedEnabled\"\n>;\n\n/**\n * Resolve the {@link PipelineProcessingCapabilitySet} from parsed config.\n */\nexport function resolvePipelineProcessingCapabilities(config: PipelineProcessingConfigProjection): PipelineProcessingCapabilitySet {\n return Object.freeze({\n chunking: config.chunkingEnabled,\n semanticChunking: config.semanticChunkingEnabled,\n semanticDedup: config.semanticDedupEnabled,\n summarization: config.summarizationEnabled,\n topicExtraction: config.topicExtractionEnabled,\n sessionObserver: config.sessionObserverEnabled === true,\n profiling: config.profilingEnabled,\n checkpoint: config.checkpointEnabled,\n traceWeaver: config.traceWeaverEnabled,\n routingRules: config.routingRulesEnabled,\n inlineSourceAttribution: config.inlineSourceAttributionEnabled,\n negativeExamples: config.negativeExamplesEnabled,\n hourlySummaries: config.hourlySummariesEnabled,\n lcm: config.lcmEnabled,\n localLlmFast: config.localLlmFastEnabled,\n proactiveExtraction: config.proactiveExtractionEnabled,\n delinearize: config.delinearizeEnabled,\n slowLog: config.slowLogEnabled,\n hostEmbeddingProvider: config.hostEmbeddingProviderEnabled,\n memoryExtensions: config.memoryExtensionsEnabled,\n hourlySummariesExtended: config.hourlySummariesExtendedEnabled,\n });\n}\n\n// ---------------------------------------------------------------------------\n// ConversationContext capability set (issue #1523 batch 9).\n//\n// These 12 flags gate conversation context, shared signals, intent routing,\n// operator-aware consolidation, CMC consolidation, maintenance fanout, CLI\n// presentation, and code connectors. Read sites span orchestrator, CLI,\n// shared-context/manager, semantic-consolidation-coordinator, compounding/engine,\n// maintenance modules, procedural stats, connectors, and wearables. All flags\n// are non-optional booleans on PluginConfig (defaults resolved at the parse\n// boundary), so the projection is a pure pass-through.\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen projection of conversation/context feature gates (issue #1523 batch 9).\n */\nexport interface ConversationContextCapabilitySet {\n readonly sharedContext: boolean;\n readonly intentRouting: boolean;\n readonly crossSignalsSemantic: boolean;\n readonly sharedCrossSignalSemantic: boolean;\n readonly operatorAwareConsolidation: boolean;\n readonly peerProfileReasoner: boolean;\n readonly cmcConsolidation: boolean;\n readonly maintenanceNamespaceFanout: boolean;\n readonly citations: boolean;\n readonly semanticRulePromotion: boolean;\n readonly codexMarketplace: boolean;\n}\n\n/**\n * Config projection consumed by {@link resolveConversationContextCapabilities}.\n */\nexport type ConversationContextConfigProjection = Pick<\n PluginConfig,\n | \"sharedContextEnabled\"\n | \"intentRoutingEnabled\"\n | \"crossSignalsSemanticEnabled\"\n | \"sharedCrossSignalSemanticEnabled\"\n | \"operatorAwareConsolidationEnabled\"\n | \"peerProfileReasonerEnabled\"\n | \"cmcConsolidationEnabled\"\n | \"maintenanceNamespaceFanoutEnabled\"\n | \"citationsEnabled\"\n | \"semanticRulePromotionEnabled\"\n | \"codexMarketplaceEnabled\"\n>;\n\n/**\n * Resolve the {@link ConversationContextCapabilitySet} from parsed config.\n */\nexport function resolveConversationContextCapabilities(config: ConversationContextConfigProjection): ConversationContextCapabilitySet {\n return Object.freeze({\n sharedContext: config.sharedContextEnabled,\n intentRouting: config.intentRoutingEnabled,\n crossSignalsSemantic: config.crossSignalsSemanticEnabled,\n sharedCrossSignalSemantic: config.sharedCrossSignalSemanticEnabled === true,\n operatorAwareConsolidation: config.operatorAwareConsolidationEnabled,\n peerProfileReasoner: config.peerProfileReasonerEnabled,\n cmcConsolidation: config.cmcConsolidationEnabled,\n maintenanceNamespaceFanout: config.maintenanceNamespaceFanoutEnabled,\n citations: config.citationsEnabled,\n semanticRulePromotion: config.semanticRulePromotionEnabled,\n codexMarketplace: config.codexMarketplaceEnabled,\n });\n}\n"],"mappings":";AAqFO,SAAS,oBAAoB,QAAqC;AACvE,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,oBAAoB,OAAO;AAAA,IAC3B,yBAAyB,OAAO;AAAA;AAAA;AAAA,IAGhC,kBAAkB,OAAO,sBAAsB;AAAA,IAC/C,WAAW,OAAO;AAAA,IAClB,2BAA2B,OAAO;AAAA,IAClC,kBAAkB,OAAO;AAAA,IACzB,eAAe,OAAO;AAAA,IACtB,sBAAsB,OAAO;AAAA,IAC7B,aAAa,OAAO;AAAA;AAAA;AAAA,IAGpB,uBAAuB,OAAO,iCAAiC;AAAA,IAC/D,qBAAqB,OAAO,+BAA+B;AAAA;AAAA,IAE3D,QAAQ,OAAO;AAAA,IACf,mBAAmB,OAAO;AAAA,IAC1B,mBAAmB,OAAO;AAAA,EAC5B,CAAC;AACH;AAiDO,SAA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,OAAO;AAAA,IACnB,eAAe,OAAO;AAAA,IACtB,eAAe,OAAO;AAAA,IACtB,sBAAsB,OAAO;AAAA,IAC7B,2BAA2B,OAAO,qCAAqC;AAAA,IACvE,4BAA4B,OAAO;AAAA,IACnC,qBAAqB,OAAO;AAAA,IAC5B,kBAAkB,OAAO;AAAA,IACzB,4BAA4B,OAAO;AAAA,IACnC,WAAW,OAAO;AAAA,IAClB,uBAAuB,OAAO;AAAA,IAC9B,kBAAkB,OAAO;AAAA,EAC3B,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/explicit-capture.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Orchestrator } from \"./orchestrator.js\";\nimport { isSafeRouteNamespace } from \"./routing/engine.js\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { ContentHashIndex } from \"./storage.js\";\nimport type { CaptureMode, MemoryCategory, MemoryLifecycleEvent, PluginConfig } from \"./types.js\";\n\nexport type ExplicitCaptureInput = {\n content: string;\n category?: string;\n confidence?: number;\n namespace?: string;\n tags?: string[];\n entityRef?: string;\n sourceConnector?: string;\n ttl?: string;\n sourceReason?: string;\n};\n\nexport type ValidExplicitCapture = {\n content: string;\n category: MemoryCategory;\n confidence: number;\n namespace?: string;\n tags: string[];\n entityRef?: string;\n sourceConnector?: string;\n expiresAt?: string;\n sourceReason?: string;\n /**\n * When true, `namespace` was already resolved AND authorized by the caller\n * (the access service's `resolveCodingScopedWriteNamespace`, which auth-checks\n * the base and derives a session-owned `project-*` overlay). The persist /\n * queue layer then routes to it directly instead of re-validating against the\n * static policy allow-list — which would otherwise reject legitimately-derived\n * dynamic project namespaces (#1434). Callers that do NOT pre-authorize the\n * namespace must leave this unset so the allow-list guard still applies.\n */\n namespacePreResolved?: boolean;\n};\n\nexport type ExplicitCaptureSource = \"memory_store\" | \"memory_capture\" | \"suggestion_submit\" | \"inline\";\ntype ExplicitCaptureValidationMode = \"legacy_tool\" | \"strict_explicit\";\n\n// Bounded body {0,100000} instead of an unbounded lazy *? so scanning for the\n// closing tag cannot backtrack polynomially on unterminated <memory_note>\n// markup in hostile turn text (CodeQL js/polynomial-redos). 100 000 chars far\n// exceeds any real inline note, so matching is behavior-preserving; the outer\n// \\s* groups were also dropped (body absorbs whitespace; captures are trimmed).\nconst INLINE_NOTE_RE = /<memory_note>([\\s\\S]{0,100000}?)<\\/memory_note>/gi;\nconst INLINE_NOTE_MARKUP_RE = /<memory_note>[\\s\\S]{0,100000}?<\\/memory_note>/i;\nconst INLINE_ALLOWED_CATEGORIES = new Set<MemoryCategory>([\n \"fact\",\n \"preference\",\n \"correction\",\n \"entity\",\n \"decision\",\n \"relationship\",\n \"principle\",\n \"commitment\",\n \"moment\",\n \"skill\",\n \"rule\",\n \"procedure\",\n \"reasoning_trace\",\n]);\n\nconst SECRET_PATTERNS: RegExp[] = [\n /\\bsk-[A-Za-z0-9]{16,}\\b/,\n /\\bAKIA[0-9A-Z]{16}\\b/,\n /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/i,\n /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/i,\n /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/i,\n];\nconst SECRET_REDACTION_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [\n { pattern: /\\bsk-[A-Za-z0-9]{16,}\\b/g, replacement: \"[redacted openai key]\" },\n { pattern: /\\bAKIA[0-9A-Z]{16}\\b/g, replacement: \"[redacted aws key]\" },\n { pattern: /\\bBearer\\s+[A-Za-z0-9._-]{16,}\\b/gi, replacement: \"Bearer [redacted token]\" },\n {\n pattern: /\\b(?:api[_-]?key|secret|token|password|passwd)\\s*[:=]\\s*[^\\s]{8,}\\b/gi,\n replacement: \"[redacted credential]\",\n },\n {\n pattern: /\\b(?:authorization)\\s*:\\s*[^\\s]{8,}\\b/gi,\n replacement: \"authorization: [redacted credential]\",\n },\n];\nconst EXPLICIT_CAPTURE_REVIEW_TAGS = [\"explicit-capture\", \"queued-review\"];\n\nfunction explicitCaptureActor(source: ExplicitCaptureSource): string {\n switch (source) {\n case \"inline\":\n return \"inline.memory_note\";\n case \"memory_store\":\n return \"tool.memory_store\";\n case \"suggestion_submit\":\n return \"tool.suggestion_submit\";\n default:\n return \"tool.memory_capture\";\n }\n}\n\nfunction asTrimmed(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeCaptureContent(value: string): string {\n return value\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction redactSecrets(value: string): string {\n let redacted = value;\n for (const { pattern, replacement } of SECRET_REDACTION_PATTERNS) {\n redacted = redacted.replace(pattern, replacement);\n }\n return redacted;\n}\n\nfunction containsSecretLikeValue(value: string): boolean {\n return SECRET_PATTERNS.some((pattern) => pattern.test(value));\n}\n\nfunction assertNoSecretLikeMetadata(field: string, value: string | undefined): void {\n const trimmed = asTrimmed(value);\n if (trimmed && containsSecretLikeValue(trimmed)) {\n throw new Error(`${field} appears to contain a secret or credential`);\n }\n}\n\nfunction assertNoSecretLikeMetadataList(field: string, values: string[] | undefined): void {\n for (const value of values ?? []) {\n assertNoSecretLikeMetadata(field, value);\n }\n}\n\nfunction sanitizeReviewText(value: string | undefined, fallback: string): string {\n const redacted = redactSecrets(asTrimmed(value) ?? fallback);\n const sanitized = sanitizeMemoryContent(redacted);\n const safe = sanitized.text.trim();\n return safe.length > 0 ? safe : fallback;\n}\n\nfunction sanitizeReviewMetadata(value: string | undefined): string | undefined {\n const trimmed = asTrimmed(value);\n if (!trimmed) return undefined;\n return sanitizeReviewText(trimmed, \"[redacted]\");\n}\n\nfunction sanitizeReviewTags(tags: string[] | undefined): string[] {\n return Array.from(new Set((tags ?? [])\n .map((tag) => sanitizeReviewMetadata(tag))\n .filter((tag): tag is string => typeof tag === \"string\" && tag.length > 0)));\n}\n\nfunction normalizeExplicitCaptureError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) return error.message.trim();\n const rendered = String(error).trim();\n return rendered.length > 0 ? rendered : \"explicit capture failed\";\n}\n\nfunction resolveExplicitCaptureReviewNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n return resolveExplicitCaptureNamespace(orchestrator, normalized);\n}\n\nfunction resolveExplicitCaptureNamespace(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n): string | undefined {\n const normalized = asTrimmed(namespace);\n if (!normalized) return undefined;\n if (!resolveNamespaceCapabilities(orchestrator.config).namespaces) {\n if (normalized !== orchestrator.config.defaultNamespace) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n }\n const allowed = new Set([\n orchestrator.config.defaultNamespace,\n orchestrator.config.sharedNamespace,\n ...orchestrator.config.namespacePolicies.map((policy) => policy.name),\n ].map((value) => value.trim()).filter(Boolean));\n if (!allowed.has(normalized)) {\n throw new Error(`unsupported namespace: ${normalized}`);\n }\n return normalized;\n}\n\nfunction parseExplicitCaptureTtl(ttl: string | undefined): string | undefined {\n const raw = asTrimmed(ttl);\n if (!raw) return undefined;\n\n const absoluteMs = Date.parse(raw);\n if (Number.isFinite(absoluteMs)) {\n return new Date(absoluteMs).toISOString();\n }\n\n const relative = raw.match(/^(\\d+)\\s*([mhdw])$/i);\n if (!relative) {\n throw new Error(\"ttl must be an ISO-8601 timestamp or relative duration like 30m, 12h, 7d, or 2w\");\n }\n\n const amount = Number.parseInt(relative[1] ?? \"\", 10);\n const unit = (relative[2] ?? \"\").toLowerCase();\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(\"ttl duration must be a positive integer\");\n }\n\n const multiplier =\n unit === \"m\" ? 60_000\n : unit === \"h\" ? 60 * 60_000\n : unit === \"d\" ? 24 * 60 * 60_000\n : 7 * 24 * 60 * 60_000;\n return new Date(Date.now() + amount * multiplier).toISOString();\n}\n\nfunction parseInlineConfidence(value: string): number {\n const trimmed = value.trim();\n if (!/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(trimmed)) {\n return Number.NaN;\n }\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : Number.NaN;\n}\n\nfunction parseInlineNote(block: string): ExplicitCaptureInput | null {\n const lines = block.replace(/\\r/g, \"\").split(\"\\n\");\n const note: Partial<ExplicitCaptureInput> = {};\n let idx = 0;\n\n while (idx < lines.length) {\n const rawLine = lines[idx] ?? \"\";\n const line = rawLine.trim();\n idx += 1;\n if (line.length === 0) continue;\n const colonIdx = line.indexOf(\":\");\n if (colonIdx < 0) continue;\n const key = line.slice(0, colonIdx).trim();\n const value = line.slice(colonIdx + 1).trim();\n\n if (key === \"content\" && value === \"|\") {\n const contentLines: string[] = [];\n while (idx < lines.length) {\n const next = lines[idx] ?? \"\";\n if (next.startsWith(\" \") || next.startsWith(\"\\t\")) {\n contentLines.push(next.replace(/^( |\\t)/, \"\"));\n idx += 1;\n continue;\n }\n if (next.trim().length === 0) {\n contentLines.push(\"\");\n idx += 1;\n continue;\n }\n break;\n }\n note.content = contentLines.join(\"\\n\").trim();\n continue;\n }\n\n switch (key) {\n case \"content\":\n note.content = value;\n break;\n case \"category\":\n note.category = value;\n break;\n case \"confidence\":\n note.confidence = parseInlineConfidence(value);\n break;\n case \"namespace\":\n note.namespace = value;\n break;\n case \"tags\":\n note.tags = value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter(Boolean);\n break;\n case \"entityRef\":\n note.entityRef = value;\n break;\n case \"ttl\":\n note.ttl = value;\n break;\n case \"sourceReason\":\n note.sourceReason = value;\n break;\n default:\n break;\n }\n }\n\n return asTrimmed(note.content) ? (note as ExplicitCaptureInput) : null;\n}\n\nexport function parseInlineExplicitCaptureNotes(text: string): ExplicitCaptureInput[] {\n const notes: ExplicitCaptureInput[] = [];\n for (const match of text.matchAll(INLINE_NOTE_RE)) {\n const parsed = parseInlineNote(match[1] ?? \"\");\n if (parsed) notes.push(parsed);\n }\n return notes;\n}\n\nexport function hasInlineExplicitCaptureMarkup(text: string): boolean {\n return INLINE_NOTE_MARKUP_RE.test(text);\n}\n\nexport function stripInlineExplicitCaptureNotes(text: string): string {\n return text.replace(INLINE_NOTE_RE, \"\").trim();\n}\n\nexport function validateExplicitCaptureInput(\n input: ExplicitCaptureInput,\n mode: ExplicitCaptureValidationMode = \"strict_explicit\",\n): ValidExplicitCapture {\n const content = asTrimmed(input.content);\n if (!content) throw new Error(\"content is required\");\n if (mode === \"strict_explicit\") {\n if (content.length < 10) throw new Error(\"content must be at least 10 characters\");\n if (content.length > 4000) throw new Error(\"content must be 4000 characters or fewer\");\n }\n if (/<memory_note>/i.test(content) || /<\\/memory_note>/i.test(content)) {\n throw new Error(\"nested memory_note blocks are not allowed\");\n }\n\n const category = (asTrimmed(input.category) ?? \"fact\") as MemoryCategory;\n if (!INLINE_ALLOWED_CATEGORIES.has(category)) {\n throw new Error(`unsupported category: ${input.category ?? category}`);\n }\n\n const sanitized = sanitizeMemoryContent(content);\n if (!sanitized.clean) {\n throw new Error(\"content failed memory sanitization\");\n }\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.test(content)) {\n throw new Error(\"content appears to contain a secret or credential\");\n }\n }\n assertNoSecretLikeMetadata(\"sourceReason\", input.sourceReason);\n assertNoSecretLikeMetadata(\"entityRef\", input.entityRef);\n assertNoSecretLikeMetadata(\"ttl\", input.ttl);\n assertNoSecretLikeMetadataList(\"tags\", input.tags);\n\n if (input.confidence !== undefined && !Number.isFinite(input.confidence)) {\n throw new Error(\"confidence must be a finite number\");\n }\n const confidence = input.confidence === undefined ? 0.95 : Number(input.confidence);\n if (confidence < 0 || confidence > 1) {\n throw new Error(\"confidence must be between 0 and 1\");\n }\n const requestedNamespace = asTrimmed(input.namespace);\n if (requestedNamespace && !isSafeRouteNamespace(requestedNamespace)) {\n throw new Error(`unsafe namespace: ${requestedNamespace}`);\n }\n const expiresAt = parseExplicitCaptureTtl(input.ttl);\n\n return {\n content,\n category,\n confidence,\n namespace: asTrimmed(input.namespace),\n tags: Array.from(new Set((input.tags ?? []).map((tag) => tag.trim()).filter(Boolean))),\n entityRef: asTrimmed(input.entityRef),\n sourceReason: asTrimmed(input.sourceReason),\n sourceConnector: input.sourceConnector,\n expiresAt,\n };\n}\n\nasync function findDuplicateExplicitCapture(\n orchestrator: Orchestrator,\n resolvedNamespace: string | undefined,\n candidate: ValidExplicitCapture,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(resolvedNamespace);\n if (\n candidate.category === \"fact\"\n && typeof (storage as { hasFactContentHash?: (content: string) => Promise<boolean> }).hasFactContentHash === \"function\"\n ) {\n try {\n const hasHash = await (storage as { hasFactContentHash: (content: string) => Promise<boolean> }).hasFactContentHash(\n candidate.content,\n );\n if (!hasHash) {\n const authoritative =\n typeof (storage as { isFactContentHashAuthoritative?: () => Promise<boolean> | boolean }).isFactContentHashAuthoritative\n === \"function\"\n ? await (storage as { isFactContentHashAuthoritative: () => Promise<boolean> | boolean })\n .isFactContentHashAuthoritative()\n : false;\n if (authoritative) return null;\n }\n } catch (err) {\n // Fail open: hash index is only an optimization, so fall back to the full corpus scan.\n void err;\n }\n }\n const existing = await storage.readAllMemories();\n const normalizedCandidate = normalizeCaptureContent(candidate.content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"active\") return false;\n if (memory.frontmatter.category !== candidate.category) return false;\n if (normalizeCaptureContent(memory.content) !== normalizedCandidate) return false;\n // Connector-aware dedup: same content from different connectors is NOT\n // a duplicate. Operator (undefined) and connector-tagged memories are\n // always distinct. Normalize empty strings to undefined.\n const existingConnector = memory.frontmatter.sourceConnector?.trim() || undefined;\n const newConnector = candidate.sourceConnector?.trim() || undefined;\n if (existingConnector !== newConnector) return false;\n return true;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function persistExplicitCapture(\n orchestrator: Orchestrator,\n candidate: ValidExplicitCapture,\n source: ExplicitCaptureSource,\n): Promise<{ id: string; duplicateOf?: string; tombstoneBlocked?: boolean }> {\n const resolvedNamespace = candidate.namespacePreResolved\n ? asTrimmed(candidate.namespace)\n : resolveExplicitCaptureNamespace(orchestrator, candidate.namespace);\n const duplicateOf = await findDuplicateExplicitCapture(orchestrator, resolvedNamespace, candidate);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const storage = await orchestrator.getStorage(resolvedNamespace);\n // #1645 (review thread yG-): surface the tombstone block so callers\n // (memory_store tool, access-service HTTP/MCP) can report the capture as\n // queued for review instead of a successfully stored active memory.\n const { id, tombstoneBlocked } = await storage.writeMemory(candidate.category, candidate.content, {\n confidence: candidate.confidence,\n tags: candidate.tags,\n entityRef: candidate.entityRef,\n expiresAt: candidate.expiresAt,\n source: source === \"inline\" ? \"explicit-inline\" : \"explicit\",\n ...(candidate.sourceConnector ? { sourceConnector: candidate.sourceConnector } : {}),\n });\n // #1522: catalog touch handled at the storage chokepoint — the StorageManager's\n // post-write hook records the namespace touch automatically.\n\n const created = new Date().toISOString();\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_accepted\",\n timestamp: created,\n actor: explicitCaptureActor(source),\n reasonCode: candidate.sourceReason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n\n return { id, tombstoneBlocked };\n}\n\nfunction buildExplicitCaptureReviewContent(input: ExplicitCaptureInput, reason: string): string {\n const requestedContent = asTrimmed(input.content);\n const safeContent = sanitizeReviewText(requestedContent, \"[empty explicit capture]\");\n const safeCategory = sanitizeReviewMetadata(input.category);\n const safeNamespace = sanitizeReviewMetadata(input.namespace);\n const safeEntityRef = sanitizeReviewMetadata(input.entityRef);\n const safeTtl = sanitizeReviewMetadata(input.ttl);\n const safeSourceReason = sanitizeReviewMetadata(input.sourceReason);\n const safeTags = sanitizeReviewTags(input.tags);\n const lines = [\n \"Explicit capture queued for review.\",\n \"\",\n `Reason: ${reason}`,\n \"\",\n \"Submitted content:\",\n safeContent,\n ];\n const metadata = [\n safeCategory ? `Requested category: ${safeCategory}` : undefined,\n safeNamespace ? `Requested namespace: ${safeNamespace}` : undefined,\n safeEntityRef ? `Requested entityRef: ${safeEntityRef}` : undefined,\n safeTtl ? `Requested ttl: ${safeTtl}` : undefined,\n safeSourceReason ? `Requested sourceReason: ${safeSourceReason}` : undefined,\n safeTags.length > 0 ? `Requested tags: ${safeTags.join(\", \")}` : undefined,\n ].filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0);\n if (metadata.length > 0) {\n lines.push(\"\", ...metadata);\n }\n return lines.join(\"\\n\");\n}\n\nasync function findQueuedExplicitCaptureDuplicate(\n orchestrator: Orchestrator,\n namespace: string | undefined,\n content: string,\n sourceConnector?: string,\n): Promise<string | null> {\n const storage = await orchestrator.getStorage(namespace);\n const existing = await storage.readAllMemories();\n const normalized = normalizeCaptureContent(content);\n const match = existing.find((memory) => {\n const status = memory.frontmatter.status ?? \"active\";\n if (status !== \"pending_review\") return false;\n if (!(memory.frontmatter.tags ?? []).includes(\"queued-review\")) return false;\n if (normalizeCaptureContent(memory.content) !== normalized) return false;\n const existingConnector = memory.frontmatter.sourceConnector?.trim() || undefined;\n const newConnector = sourceConnector?.trim() || undefined;\n if (existingConnector !== newConnector) return false;\n return true;\n });\n return match?.frontmatter.id ?? null;\n}\n\nexport async function queueExplicitCaptureForReview(\n orchestrator: Orchestrator,\n input: ExplicitCaptureInput,\n source: ExplicitCaptureSource,\n error: unknown,\n): Promise<{ id: string; duplicateOf?: string }> {\n const reason = sanitizeReviewText(normalizeExplicitCaptureError(error), \"explicit capture failed\");\n const requestedNamespace = asTrimmed(input.namespace);\n // A caller-pre-authorized namespace (e.g. a session-owned project overlay\n // from the access service) routes directly; otherwise apply the static\n // policy allow-list guard (#1434).\n const queueNamespace = (input as { namespacePreResolved?: boolean }).namespacePreResolved\n ? requestedNamespace\n : resolveExplicitCaptureReviewNamespace(orchestrator, requestedNamespace);\n const content = buildExplicitCaptureReviewContent(input, reason);\n const duplicateOf = await findQueuedExplicitCaptureDuplicate(orchestrator, queueNamespace, content, input.sourceConnector);\n if (duplicateOf) {\n return { id: duplicateOf, duplicateOf };\n }\n\n const requestedCategory = asTrimmed(input.category);\n const reviewCategory = requestedCategory && INLINE_ALLOWED_CATEGORIES.has(requestedCategory as MemoryCategory)\n ? requestedCategory as MemoryCategory\n : \"fact\";\n const requestedTags = sanitizeReviewTags(input.tags);\n const storage = await orchestrator.getStorage(queueNamespace);\n const { id: id } = await storage.writeMemory(reviewCategory, content, {\n confidence: 0.2,\n tags: Array.from(new Set([...EXPLICIT_CAPTURE_REVIEW_TAGS, ...requestedTags])),\n entityRef: sanitizeReviewMetadata(input.entityRef),\n source: source === \"inline\" ? \"explicit-inline-review\" : \"explicit-review\",\n ...(input.sourceConnector ? { sourceConnector: input.sourceConnector } : {}),\n });\n try {\n const created = await storage.getMemoryById(id);\n if (created) {\n await storage.writeMemoryFrontmatter(created, {\n status: \"pending_review\",\n updated: new Date().toISOString(),\n }, {\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n });\n }\n } finally {\n // Record the catalog write touch (issue #1499, round 5/6 codex P2; NIhUg).\n // A queued review capture writes memory to the namespace's root (the DEFAULT\n // root when undefined), so its `lastWriteAt` must reflect the write once\n // `writeMemory` returns an id. If the later pending-review frontmatter update\n // fails, the memory file is still durable and must not disappear from\n // writtenSince/maintenance scheduling. Guarded optional hook (rule #33).\n // #1522: catalog touch handled at the storage chokepoint.\n }\n const event: MemoryLifecycleEvent = {\n eventId: `mle-${randomUUID()}`,\n memoryId: id,\n eventType: \"explicit_capture_queued\",\n timestamp: new Date().toISOString(),\n actor: explicitCaptureActor(source),\n reasonCode: reason,\n ruleVersion: \"explicit-capture.v1\",\n };\n await storage.appendMemoryLifecycleEvents([event]);\n return { id };\n}\n\nexport function shouldSkipImplicitExtraction(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode === \"explicit\";\n}\n\nexport function shouldProcessInlineExplicitCapture(cfg: Pick<PluginConfig, \"captureMode\">): boolean {\n return cfg.captureMode !== \"implicit\";\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,kBAAkB;AAiD3B,IAAM,iBAAiB;AACvB,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,oBAAI,IAAoB;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,kBAA4B;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,4BAA6E;AAAA,EACjF,EAAE,SAAS,4BAA4B,aAAa,wBAAwB;AAAA,EAC5E,EAAE,SAAS,yBAAyB,aAAa,qBAAqB;AAAA,EACtE,EAAE,SAAS,sCAAsC,aAAa,0BAA0B;AAAA,EACxF;AAAA,IACE,SAAS;AAAA,IACT,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,aAAa;AAAA,EACf;AACF;AACA,IAAM,+BAA+B,CAAC,oBAAoB,eAAe;AAEzE,SAAS,qBAAqB,QAAuC;AACnE,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAAS,UAAU,OAA+C;AAChE,QAAM,UAAU,OAAO,KAAK;AAC5B,SAAO,WAAW,QAAQ,SAAS,IAAI,UAAU;AACnD;AAEA,SAAS,wBAAwB,OAAuB;AACtD,SAAO,MACJ,YAAY,EACZ,QAAQ,QAAQ,GAAG,EACnB,KAAK;AAC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OAAO,qBAAqB,MAAM;AAAA,IAClC,YAAY;AAAA,IACZ,aAAa;AAAA,EACf;AACA,QAAM,QAAQ,4BAA4B,CAAC,KAAK,CAAC;AACjD,SAAO,EAAE,GAAG;AACd;AAEO,SAAS,6BAA6B,KAAiD;AAC5F,SAAO,IAAI,gBAAgB;AAC7B;AAEO,SAAS,mCAAmC,KAAiD;AAClG,SAAO,IAAI,gBAAgB;AAC7B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/access-boundary.ts"],"sourcesContent":["/**\n * Single input-validation and error boundary for the CLI/MCP/HTTP access\n * surfaces (issue #1525, epic #1520 Phase 1).\n *\n * Every operation that crosses the access-service facade passes through ONE\n * registry entry: a zod-validated request envelope, a shared error mapper,\n * and the \"reject invalid input and list valid options\" behavior that\n * CLAUDE.md rules 14/17/24/28/36/48/51 previously had to be re-implemented\n * per handler. The three surfaces become thin adapters — one operation\n * definition, three transports — so a validation fix lands everywhere at\n * once.\n *\n * Host-agnostic (rule 31): operation names carry no `openclaw-*`/`engram-*`\n * prefix. Session/namespace tenancy stays in the handler layer (resolved via\n * ScopePlan #1521); the boundary validates SHAPE, not tenancy.\n */\n\nimport { z } from \"zod\";\nimport { EngramAccessInputError, type EngramAccessService } from \"./access-service.js\";\nimport { assertFleetWideOperationAllowed, assertOperationAllowed, tokenCapabilityStore } from \"./access-token-capabilities.js\";\nimport { expandTildePath } from \"./utils/path.js\";\n\n// ---------------------------------------------------------------------------\n// Canonical operation names — host-agnostic (rule 31)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical operation ids. One id is shared by the MCP tool, the HTTP route,\n * and the CLI command that expose the same operation. Add to this union as\n * each domain-group migration PR (memory ops → connectors → namespaces …)\n * lands; the fitness test in `access-surface-catalog.test.ts` treats the\n * registered set as the migration state.\n */\nexport const OPERATION_NAMES = [\n \"memory_get\",\n \"memory_search\",\n \"memory_store\",\n \"coding_decision\",\n \"coding_architecture\",\n // codegraph parity tools (issue #1554) -- each maps to one codegraph_*\n // boundary operation that delegates to the surface handler in\n // coding/codegraph-surfaces.ts. Names match the external tool suffixes.\n \"codegraph_index\",\n \"codegraph_list_projects\",\n \"codegraph_delete_project\",\n \"codegraph_index_status\",\n \"codegraph_search_graph\",\n \"codegraph_trace_path\",\n \"codegraph_detect_changes\",\n \"codegraph_query_graph\",\n \"codegraph_get_schema\",\n \"codegraph_get_snippet\",\n \"codegraph_get_architecture\",\n \"codegraph_search_code\",\n \"codegraph_manage_adr\",\n \"codegraph_ingest_traces\",\n \"memory_correct_plan\",\n \"memory_correct_apply\",\n \"coding_delta\",\n // Remaining MCP/HTTP handlers migrated through the boundary (issue #1525).\n \"recall\",\n \"recall_explain\",\n \"set_coding_context\",\n \"recall_tier_explain\",\n \"recall_xray\",\n \"wearables_status\",\n \"wearables_sync\",\n \"transcript_day\",\n \"transcript_search\",\n \"transcript_memories\",\n \"action_confidence\",\n \"chatgpt_memory_inspector\",\n \"day_summary\",\n \"capsule_export\",\n \"capsule_import\",\n \"capsule_list\",\n \"memory_governance_run\",\n \"procedure_mining_run\",\n \"pattern_reinforcement_run\",\n \"procedural_stats\",\n \"memory_timeline\",\n \"suggestion_submit\",\n \"entity_get\",\n \"review_queue_list\",\n \"correction_pending\",\n \"observe\",\n \"lcm_search\",\n \"lcm_compaction_flush\",\n \"lcm_compaction_record\",\n \"continuity_audit_generate\",\n \"continuity_incident_open\",\n \"continuity_incident_close\",\n \"continuity_incident_list\",\n \"continuity_loop_add_or_update\",\n \"continuity_loop_review\",\n \"identity_anchor_get\",\n \"identity_anchor_update\",\n \"memory_identity\",\n \"work_task\",\n \"work_project\",\n \"work_board\",\n \"shared_context_write_output\",\n \"shared_feedback_record\",\n \"shared_priorities_append\",\n \"relay_mission_append\",\n \"relay_mission_read\",\n \"shared_context_cross_signals_run\",\n \"shared_context_curate_daily\",\n \"compounding_weekly_synthesize\",\n \"compounding_promote_candidate\",\n \"compression_guidelines_optimize\",\n \"compression_guidelines_activate\",\n \"memory_profile\",\n \"memory_entities_list\",\n \"memory_questions\",\n \"memory_last_recall\",\n \"memory_intent_debug\",\n \"memory_qmd_debug\",\n \"memory_graph_explain\",\n \"graph_snapshot\",\n \"memory_feedback\",\n \"memory_promote\",\n \"memory_outcome\",\n \"memory_action_apply\",\n \"context_checkpoint\",\n \"briefing\",\n \"review_list\",\n \"review_resolve\",\n \"contradiction_scan_run\",\n \"memory_summarize_hourly\",\n \"conversation_index_update\",\n \"profiling_report\",\n \"graph_edge_decay_run\",\n \"live_connectors_run\",\n \"peer_list\",\n \"peer_get\",\n \"peer_set\",\n \"peer_delete\",\n \"peer_profile_get\",\n \"peer_forget\",\n \"console_state\",\n \"dreams_status\",\n \"dreams_run\",\n // HTTP-only routes (no direct MCP tool equivalent).\n \"adapters_status\",\n \"offline_sync_snapshot\",\n \"offline_sync_snapshot_stream\",\n \"offline_sync_files\",\n \"offline_sync_file_content\",\n \"offline_sync_apply_file_content\",\n \"offline_sync_apply\",\n \"lcm_status\",\n \"memory_list\",\n \"recall_timings\",\n \"entity_list\",\n \"maintenance_status\",\n \"quality_status\",\n \"trust_zones_status\",\n \"trust_zones_records\",\n \"review_disposition\",\n \"trust_zones_promote\",\n \"trust_zones_demo_seed\",\n \"citations_observed\",\n \"contradiction_detail\",\n \"graph_events\",\n // Chat surface — conversational memory inspection/correction (issue #1583).\n \"chat_message\",\n \"chat_events\",\n] as const;\n\n/**\n * Canonical operation ids. One id is shared by the MCP tool, the HTTP route,\n * and the CLI command that expose the same operation. Derived from\n * {@link OPERATION_NAMES} (single source of truth) so the runtime catalog\n * used for token-capability validation cannot drift from the type. The\n * fitness test in `access-surface-catalog.test.ts` treats the registered set\n * as the migration state.\n */\nexport type OperationName = (typeof OPERATION_NAMES)[number];\n\n// ---------------------------------------------------------------------------\n// Operation context — what every handler receives\n// ---------------------------------------------------------------------------\n\n/**\n * Per-call context. `service` is the facade the handler delegates to; the\n * boundary never reaches past it. `authenticatedPrincipal` is resolved by\n * the SURFACE (MCP header / HTTP identity / CLI flag) before the boundary\n * runs, so handlers stay principal-source-agnostic. `hooks` carries\n * transport-level callbacks (e.g. HTTP write-quota enforcement) that must\n * fire atomically inside the service call; surfaces that have no such hook\n * leave it undefined.\n */\nexport interface OperationContext {\n readonly service: EngramAccessService;\n readonly authenticatedPrincipal?: string;\n readonly operatorPrincipal?: string;\n /** Per-request cancellation supplied by transports that own a request lifecycle. */\n readonly abortSignal?: AbortSignal;\n /** Server-resolved connector identity (Phase 1 provenance). Set by the HTTP auth boundary from the matched token's connector; flows to write handlers so frontmatter records which connector submitted the memory. Client-supplied values are always overridden. */\n readonly sourceConnector?: string;\n readonly hooks?: OperationHooks;\n}\n\n/**\n * Transport-level callbacks a handler forwards into the service call. Kept\n * narrow on purpose: the boundary owns validation + dispatch shape, not\n * transport policy. Add fields here only when a surface genuinely needs a\n * callback the service itself consumes.\n */\nexport interface OperationHooks {\n /** HTTP write-quota gate; throws to reject the write when exhausted. */\n readonly enforceWriteQuota?: () => void | Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Operation spec + bound operation\n// ---------------------------------------------------------------------------\n\nexport interface OperationSpec<In, Out> {\n /** Canonical operation id; matches an {@link OperationName}. */\n readonly name: OperationName;\n readonly description: string;\n /** Zod schema validating the raw request envelope. */\n readonly schema: z.ZodType<In>;\n /** Handler invoked with the parsed input; throws EngramAccessInputError for domain faults. */\n readonly handler: (input: In, ctx: OperationContext) => Promise<Out>;\n /**\n * Marks an operation as inherently FLEET-WIDE / global — it runs across ALL\n * namespaces (or against a single non-namespaced global layer) and carries no\n * `namespace` argument, so the MCP `tools/call` effective-namespace chokepoint\n * never applies. When set, {@link defineOperation}'s run wrapper rejects any\n * namespace-SCOPED token (fail closed) via assertFleetWideOperationAllowed\n * BEFORE the handler — no side effect on denial. Unrestricted/legacy tokens\n * (cron, internal callers, no capability record) are unaffected (issue #1850).\n */\n readonly fleetWide?: boolean;\n}\n\nexport interface BoundOperation<In = unknown, Out = unknown> {\n readonly spec: OperationSpec<In, Out>;\n /** Validate the raw envelope, then invoke the handler. Throws EngramAccessInputError on any validation failure. */\n readonly run: (rawInput: unknown, ctx: OperationContext) => Promise<Out>;\n}\n\n// ---------------------------------------------------------------------------\n// Shared normalizers the boundary owns (rules 17, 28, 36, 48, 51)\n// ---------------------------------------------------------------------------\n\n/**\n * Coerce boolean-like strings at the edge (rule 36). Accepts actual booleans\n * and the string spellings clients send (\"true\"/\"false\"/\"1\"/\"0\"/\"yes\"/\"no\"/\n * \"on\"/\"off\", case-insensitive). Rejects anything else loudly — `Boolean(\"false\")`\n * would silently be `true`, which is the bug rule 36 exists to prevent.\n *\n * `undefined`/`null`/`\"\"` → `undefined`, so callers can keep treating an\n * absent flag as \"use the default\" without a separate presence check.\n */\nexport function coerceBooleanLike(value: unknown): boolean | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const lower = value.trim().toLowerCase();\n if (lower === \"true\" || lower === \"1\" || lower === \"yes\" || lower === \"on\") return true;\n if (lower === \"false\" || lower === \"0\" || lower === \"no\" || lower === \"off\") return false;\n }\n throw new EngramAccessInputError(\n `expected a boolean-like value (true|false|1|0|yes|no|on|off); got ${JSON.stringify(value)}`,\n );\n}\n\n/**\n * Coerce + validate a positive integer from a numeric string or number\n * (rule 28). Loosely-typed MCP/CLI clients send `\"5\"`; `typeof saved === \"number\"`\n * on read-back would reject it later, so we coerce at the edge and reject\n * booleans/objects loudly (`Number(true) === 1` would silently pass otherwise).\n *\n * `undefined`/`null`/`\"\"` → `undefined`.\n */\nexport function coercePositiveInteger(value: unknown, label: string): number | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n return value;\n }\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!/^[+-]?\\d+$/.test(trimmed)) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n const parsed = Number(trimmed);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n return parsed;\n }\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n}\n\n/**\n * Expand `~` in a path-shaped input (rule 17). Node `fs` does NOT expand `~`;\n * ad-hoc regex drifts. `undefined`/`null`/`\"\"` → `undefined`.\n */\nexport function normalizeOptionalPath(value: unknown): string | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") {\n throw new EngramAccessInputError(`expected a path string; got ${JSON.stringify(value)}`);\n }\n return expandTildePath(value);\n}\n\n// ---------------------------------------------------------------------------\n// Error formatting — rule 51: list valid options, never silently default\n// ---------------------------------------------------------------------------\n\n/**\n * Turn a zod failure into an {@link EngramAccessInputError} whose message\n * names the offending field and — for enum/union issues — lists the valid\n * options, so the caller can correct rather than guess (rule 51).\n */\nexport function formatZodIssues(error: z.ZodError): string {\n const parts: string[] = [];\n for (const issue of error.issues) {\n // Collapse array-index paths (e.g. [\"currentContextScopes\", 1]) to\n // the field name so the message reads \"field: must be ...\" not\n // \"field.1: must be ...\".\n const hasNumeric = issue.path.some((p) => typeof p === \"number\");\n const path = hasNumeric\n ? issue.path.filter((p) => typeof p === \"string\").join(\".\") || \"(root)\"\n : issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n const options = enumOptionsFromIssue(issue);\n const suffix = options ? `. Valid: ${options.join(\", \")}` : \"\";\n parts.push(`${path}: ${issue.message}${suffix}`);\n }\n return parts.length > 0\n ? `request validation failed: ${parts.join(\"; \")}`\n : \"request validation failed\";\n}\n\nfunction enumOptionsFromIssue(issue: z.ZodIssue): readonly string[] | undefined {\n // zod exposes accepted enum values on the issue for ZodEnum / ZodNativeEnum\n // and on the options of invalid_union discriminators. Reading them here\n // keeps \"list valid options\" in ONE place rather than per handler.\n if (issue.code === z.ZodIssueCode.invalid_enum_value) {\n const rawOptions = (issue as { options?: unknown }).options;\n if (Array.isArray(rawOptions)) {\n return rawOptions.map((opt) => String(opt));\n }\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\nconst registry = new Map<OperationName, BoundOperation>();\n\n/**\n * Register an operation. Throws if the name is already registered — duplicate\n * registration is a programming error, not a runtime input fault, so it throws\n * a plain Error (not the input-error class surfaces translate for clients).\n */\n/**\n * Error map that converts Zod's generic type-mismatch messages into\n * human-readable \"must be a <type>\" messages (rule 51). Applied at the\n * boundary chokepoint so every operation gets consistent messaging\n * without per-handler boilerplate.\n */\nconst humanReadableErrorMap: z.ZodErrorMap = (issue, ctx) => {\n if (issue.code === z.ZodIssueCode.invalid_type) {\n if (issue.received === \"undefined\") return { message: ctx.defaultError };\n // Array-element type errors — collapse to field-level message.\n if (issue.path.some((p) => typeof p === \"number\")) {\n const arrField = issue.path.filter((p) => typeof p === \"string\").join(\".\");\n return { message: `${arrField} must be an array of ${issue.expected}s` };\n }\n const fieldName = issue.path.length > 0 ? String(issue.path[issue.path.length - 1]) : \"value\";\n switch (issue.expected) {\n case \"string\": return { message: `${fieldName} must be a string` };\n case \"boolean\": return { message: `${fieldName} must be a boolean` };\n case \"number\": return { message: `${fieldName} must be a number` };\n case \"array\": return { message: `${fieldName} must be an array` };\n case \"object\": return { message: `${fieldName} must be an object` };\n default: return { message: ctx.defaultError };\n }\n }\n return { message: ctx.defaultError };\n};\n\nexport function defineOperation<In, Out>(spec: OperationSpec<In, Out>): BoundOperation<In, Out> {\n if (registry.has(spec.name)) {\n throw new Error(`access-boundary: operation already registered: ${spec.name}`);\n }\n const bound: BoundOperation<In, Out> = {\n spec,\n run: async (rawInput, ctx) => {\n const parseResult = spec.schema.safeParse(rawInput, { errorMap: humanReadableErrorMap });\n if (!parseResult.success) {\n throw new EngramAccessInputError(formatZodIssues(parseResult.error));\n }\n // Per-token capability enforcement (issue #1837): when the presenting\n // token carries an ops allow-list, reject operations not in it. The\n // capability record is carried via AsyncLocalStorage, set once per\n // authorized HTTP/MCP request; absent (CLI/tests/direct callers) ⇒\n // unrestricted. Default-deny ONLY when an ops axis is present — legacy\n // tokens (absent record) and explicit-unrestricted new tokens are\n // unaffected.\n assertOperationAllowed(tokenCapabilityStore.getStore(), spec.name);\n // Fleet-wide / global maintenance ops (issue #1850 round 10): these run\n // across all namespaces with no `namespace` arg, so the tools/call\n // effective-namespace gate never fires. A namespace-SCOPED token must not\n // trigger cross-namespace maintenance — fail closed BEFORE the handler so\n // a denial never leaks a partial mutation. No-op for unrestricted/legacy.\n if (spec.fleetWide) {\n assertFleetWideOperationAllowed(tokenCapabilityStore.getStore());\n }\n return spec.handler(parseResult.data, ctx);\n },\n };\n // Store under the canonical name; the cast is safe because In/Out are\n // erased at the registry boundary and recovered by callers via getOperation.\n registry.set(spec.name, bound as unknown as BoundOperation);\n return bound;\n}\n\n/** Look up a registered operation by canonical name. */\nexport function getOperation(name: OperationName): BoundOperation | undefined {\n return registry.get(name);\n}\n\n/** All registered operation names. */\nexport function listRegisteredOperations(): readonly OperationName[] {\n return [...registry.keys()];\n}\n\n/** Test-only: clear the registry so pilot definitions can be re-registered. */\nexport function __resetRegistryForTest(): void {\n registry.clear();\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAS,SAAS;AAgBX,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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