@remnic/core 10.0.190 → 10.0.192

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 (296) hide show
  1. package/dist/abstraction-nodes.js +4 -4
  2. package/dist/access-admin-ops-surface.js +76 -75
  3. package/dist/access-cli.js +76 -75
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-extraction-force-flush-preempt.js +76 -75
  6. package/dist/access-extraction-force-flush.js +76 -75
  7. package/dist/access-http-briefing.js +76 -75
  8. package/dist/access-http-query.js +76 -75
  9. package/dist/access-http.js +76 -75
  10. package/dist/access-identity-continuity-surface.js +76 -75
  11. package/dist/access-lcm-surface.js +76 -75
  12. package/dist/access-mcp.js +76 -75
  13. package/dist/access-observe-write-surface.js +76 -75
  14. package/dist/access-operations-batch.js +76 -75
  15. package/dist/access-operations.js +76 -75
  16. package/dist/access-recall-concurrency.js +76 -75
  17. package/dist/access-recall-diagnostics.js +2 -2
  18. package/dist/access-recall-response.js +76 -75
  19. package/dist/access-recall-surface.js +76 -75
  20. package/dist/access-service.js +76 -75
  21. package/dist/active-recall.js +16 -16
  22. package/dist/admin/admin-surfaces.d.ts +11 -0
  23. package/dist/admin/admin-surfaces.d.ts.map +1 -1
  24. package/dist/admin/admin-surfaces.js +43 -0
  25. package/dist/briefing.js +16 -16
  26. package/dist/buffer-persistence.d.ts +7 -0
  27. package/dist/buffer-persistence.d.ts.map +1 -1
  28. package/dist/buffer-persistence.js +1 -1
  29. package/dist/buffer.d.ts +2 -0
  30. package/dist/buffer.d.ts.map +1 -1
  31. package/dist/buffer.js +6 -6
  32. package/dist/{capsule-merge-BADOICNP.js → capsule-merge-3FARYIHP.js} +5 -5
  33. package/dist/causal-consolidation.js +17 -17
  34. package/dist/{chunk-IMSLPQJB.js → chunk-2QW5HPKU.js} +2 -2
  35. package/dist/{chunk-KNYUEYB6.js → chunk-2YJ2ST23.js} +2 -2
  36. package/dist/{chunk-X3ERYOLO.js → chunk-3BICT225.js} +2 -2
  37. package/dist/{chunk-UWKHLWUE.js → chunk-3RZ4GDOH.js} +2 -2
  38. package/dist/{chunk-ODIBCZLG.js → chunk-3YID7KZ6.js} +2 -2
  39. package/dist/{chunk-56BNHKZM.js → chunk-4EAVEDLG.js} +9 -9
  40. package/dist/{chunk-TLRIRISJ.js → chunk-4LCA2GEX.js} +2 -2
  41. package/dist/{chunk-4N33L4HY.js → chunk-5GIYIYJI.js} +2 -2
  42. package/dist/{chunk-65DWWJKI.js → chunk-75K6DRPN.js} +12 -9
  43. package/dist/chunk-75K6DRPN.js.map +1 -0
  44. package/dist/{chunk-ZDLVHGIC.js → chunk-7EP4FURO.js} +2 -2
  45. package/dist/{chunk-CAUADFDM.js → chunk-7SOKOEAZ.js} +2 -2
  46. package/dist/{chunk-7Q74DD2W.js → chunk-7V6GNQC2.js} +2 -2
  47. package/dist/{chunk-QXHWOUS6.js → chunk-AALJHIKH.js} +3 -3
  48. package/dist/{chunk-ATPY63F5.js → chunk-AJ7JHHRY.js} +2 -2
  49. package/dist/{chunk-B7GZL7PR.js → chunk-ARD2TEY2.js} +4 -4
  50. package/dist/{chunk-QSVWIKNY.js → chunk-BDFSVUUZ.js} +9 -7
  51. package/dist/chunk-BDFSVUUZ.js.map +1 -0
  52. package/dist/{chunk-3DADRUGW.js → chunk-BGA7S5EF.js} +3 -3
  53. package/dist/{chunk-RPOG6HLI.js → chunk-CJSTQNE5.js} +2 -2
  54. package/dist/{chunk-VQQZJ6KJ.js → chunk-DYUPSTCV.js} +3 -3
  55. package/dist/{chunk-E5QI6C6C.js → chunk-E3LGAZJC.js} +3 -3
  56. package/dist/{chunk-TAPF7T26.js → chunk-EEA2RM4B.js} +2 -2
  57. package/dist/{chunk-BL7WULM5.js → chunk-FDO7ITP6.js} +2 -2
  58. package/dist/{chunk-K3JGILZC.js → chunk-FGFU6J26.js} +3 -3
  59. package/dist/{chunk-6TIQLG7I.js → chunk-FKHXXL42.js} +2 -2
  60. package/dist/{chunk-QPD7EYGI.js → chunk-G2MS56KM.js} +2 -2
  61. package/dist/{chunk-2I3ETW3G.js → chunk-GH7IKABD.js} +2 -2
  62. package/dist/{chunk-KVTUUU7H.js → chunk-GYCUX3N4.js} +2 -2
  63. package/dist/{chunk-2VNMSEZR.js → chunk-HEJFE3BC.js} +3 -3
  64. package/dist/{chunk-KM4QO4LN.js → chunk-HLQANATZ.js} +2 -2
  65. package/dist/{chunk-AXSQGJSG.js → chunk-J7RQ3RP7.js} +11 -11
  66. package/dist/{chunk-H442UKDV.js → chunk-JITK24KX.js} +7 -7
  67. package/dist/{chunk-EJYUAN5F.js → chunk-K6UXWVQ6.js} +2 -2
  68. package/dist/{chunk-RVODERA5.js → chunk-KJ65WZHB.js} +2 -2
  69. package/dist/{chunk-QGT5KNQT.js → chunk-KOVQZJ27.js} +2 -2
  70. package/dist/{chunk-O6QSBI3U.js → chunk-KZ4BJRGQ.js} +2 -2
  71. package/dist/{chunk-D3FP4JQI.js → chunk-LR6LWX33.js} +4 -4
  72. package/dist/{chunk-NTS2RCQK.js → chunk-NAULI3EG.js} +2 -2
  73. package/dist/{chunk-V5W67PQV.js → chunk-NOKHMWMW.js} +4 -4
  74. package/dist/{chunk-7X6EZ2QB.js → chunk-ODI4K32P.js} +5 -5
  75. package/dist/{chunk-H7USCTPQ.js → chunk-OLD2GKQJ.js} +3 -3
  76. package/dist/{chunk-D7HOJFDS.js → chunk-ONSEODO2.js} +2 -2
  77. package/dist/{chunk-R3YMWUF3.js → chunk-P3IAZQPS.js} +2 -2
  78. package/dist/{chunk-LL6WEMTC.js → chunk-P3OONWJJ.js} +2 -2
  79. package/dist/chunk-P3OONWJJ.js.map +1 -0
  80. package/dist/{chunk-ZG4GNPRE.js → chunk-PBE7NFB5.js} +5 -5
  81. package/dist/{chunk-7KC6LT7U.js → chunk-PSQ347YP.js} +3 -3
  82. package/dist/{chunk-TQODBIMW.js → chunk-QFKNIKUF.js} +2 -2
  83. package/dist/{chunk-RFVX4WE7.js → chunk-QIPRDRGM.js} +1 -1
  84. package/dist/chunk-QIPRDRGM.js.map +1 -0
  85. package/dist/{chunk-C6Y2YHJL.js → chunk-QZMGZBTF.js} +2 -2
  86. package/dist/{chunk-PCGBESAN.js → chunk-SKJM4PKE.js} +2 -2
  87. package/dist/{chunk-T7R42MWB.js → chunk-STSORBX5.js} +2 -2
  88. package/dist/{chunk-XWPYK5T4.js → chunk-T765HQ5U.js} +3 -3
  89. package/dist/{chunk-RFEQ7DQN.js → chunk-TDG5NZAZ.js} +2 -2
  90. package/dist/{chunk-DLPS5YP3.js → chunk-TJV5HGSC.js} +4 -4
  91. package/dist/{chunk-YVXR7CPS.js → chunk-TWYYUMYO.js} +2 -2
  92. package/dist/{chunk-6MDHK6NO.js → chunk-TZ7ZA2LM.js} +2 -2
  93. package/dist/{chunk-ABPOW3SX.js → chunk-UAEJKURK.js} +92 -493
  94. package/dist/chunk-UAEJKURK.js.map +1 -0
  95. package/dist/{chunk-6OHCNTKU.js → chunk-UH2VY2QQ.js} +3 -3
  96. package/dist/{chunk-XQF2KLV5.js → chunk-VHQNJW4Q.js} +2 -2
  97. package/dist/{chunk-K6BS5RB4.js → chunk-WEI6HEUX.js} +11 -6
  98. package/dist/chunk-WEI6HEUX.js.map +1 -0
  99. package/dist/{chunk-3IA2SUWM.js → chunk-WRVKI6ZO.js} +2 -2
  100. package/dist/chunk-XC4PRJWM.js +593 -0
  101. package/dist/chunk-XC4PRJWM.js.map +1 -0
  102. package/dist/{chunk-R5S57GRK.js → chunk-XSRZM6CQ.js} +38 -13
  103. package/dist/chunk-XSRZM6CQ.js.map +1 -0
  104. package/dist/{chunk-OA7YDB6A.js → chunk-XZLCAL5O.js} +2 -2
  105. package/dist/{chunk-CIAQK2OU.js → chunk-XZMQLON4.js} +430 -292
  106. package/dist/chunk-XZMQLON4.js.map +1 -0
  107. package/dist/{chunk-HL53XYHC.js → chunk-YCJJODER.js} +5 -5
  108. package/dist/chunk-YCJJODER.js.map +1 -0
  109. package/dist/{chunk-GGQ3CJVH.js → chunk-YTT6XJNX.js} +4 -4
  110. package/dist/{chunk-A32EBVCZ.js → chunk-Z6EFSXU3.js} +2 -2
  111. package/dist/{chunk-GRX5BE73.js → chunk-ZNCCX7P6.js} +2 -2
  112. package/dist/cli.js +76 -75
  113. package/dist/coding/export-okf-codegraph.js +15 -15
  114. package/dist/compounding/engine.js +17 -17
  115. package/dist/config.d.ts.map +1 -1
  116. package/dist/config.js +16 -16
  117. package/dist/connectors/codex-materialize-runner.js +16 -16
  118. package/dist/connectors/index.js +16 -16
  119. package/dist/consolidation-provenance-check.js +5 -5
  120. package/dist/consolidation-undo.js +4 -4
  121. package/dist/contradiction/index.js +3 -3
  122. package/dist/convergence-refresh.js +18 -18
  123. package/dist/corpus-watermark.js +18 -18
  124. package/dist/cue-anchors.js +5 -5
  125. package/dist/{entity-canonical-id-migration-74IDJFPB.js → entity-canonical-id-migration-46EMEXTB.js} +4 -4
  126. package/dist/entity-retrieval.d.ts.map +1 -1
  127. package/dist/entity-retrieval.js +16 -16
  128. package/dist/explicit-capture.js +76 -75
  129. package/dist/extraction.js +20 -20
  130. package/dist/harmonic-construction.js +6 -6
  131. package/dist/harmonic-graph-version.js +3 -3
  132. package/dist/harmonic-retrieval.d.ts +15 -0
  133. package/dist/harmonic-retrieval.d.ts.map +1 -1
  134. package/dist/harmonic-retrieval.js +21 -19
  135. package/dist/index.js +97 -96
  136. package/dist/lcm/engine.js +2 -2
  137. package/dist/lcm/index.js +5 -5
  138. package/dist/location/index.js +17 -17
  139. package/dist/maintenance/memory-governance.js +16 -16
  140. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +16 -16
  141. package/dist/maintenance/rebuild-memory-projection-runner.js +18 -18
  142. package/dist/maintenance/rebuild-memory-projection.js +17 -17
  143. package/dist/memory-browse.js +5 -5
  144. package/dist/memory-cache.d.ts +44 -3
  145. package/dist/memory-cache.d.ts.map +1 -1
  146. package/dist/memory-cache.js +9 -1
  147. package/dist/memory-corpus-version.js +2 -2
  148. package/dist/namespaces/migrate.js +17 -17
  149. package/dist/namespaces/search.js +9 -9
  150. package/dist/namespaces/storage.js +16 -16
  151. package/dist/operator-doctor-corpus.js +19 -19
  152. package/dist/operator-toolkit.js +24 -24
  153. package/dist/orchestration/backlog-scheduler.js +77 -76
  154. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  155. package/dist/orchestration/buffer-drain-runner.js +77 -76
  156. package/dist/orchestration/maintenance.js +24 -24
  157. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  158. package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
  159. package/dist/orchestrator.js +76 -75
  160. package/dist/page-versioning.js +4 -4
  161. package/dist/qmd.js +2 -2
  162. package/dist/recall-explain-renderer.js +3 -3
  163. package/dist/recall-navigate-access.js +2 -2
  164. package/dist/recall-navigate-disclosure.js +2 -2
  165. package/dist/recall-navigate.js +2 -2
  166. package/dist/recall-navigation.js +76 -75
  167. package/dist/recall-state-view-admission.js +5 -5
  168. package/dist/recall-why-service.js +5 -5
  169. package/dist/recall-xray-cli.js +4 -4
  170. package/dist/recall-xray-renderer.js +3 -3
  171. package/dist/recall-xray.js +2 -2
  172. package/dist/{resolution-RWIGFH2W.js → resolution-4QPPLDEN.js} +4 -4
  173. package/dist/resolution-4QPPLDEN.js.map +1 -0
  174. package/dist/resume-bundles.js +17 -17
  175. package/dist/search/factory.js +8 -8
  176. package/dist/search/index.js +13 -13
  177. package/dist/search/lancedb-backend.js +2 -2
  178. package/dist/search/meilisearch-backend.js +2 -2
  179. package/dist/search/orama-backend.js +2 -2
  180. package/dist/semantic-consolidation.js +17 -17
  181. package/dist/semantic-rule-promotion.js +16 -16
  182. package/dist/semantic-rule-verifier.js +16 -16
  183. package/dist/source-agent-qualifier.js +19 -19
  184. package/dist/standup/build.js +16 -16
  185. package/dist/storage/entity-listing.d.ts +20 -0
  186. package/dist/storage/entity-listing.d.ts.map +1 -0
  187. package/dist/storage/entity-store.d.ts +5 -0
  188. package/dist/storage/entity-store.d.ts.map +1 -1
  189. package/dist/storage/hot-cache-validation.d.ts +60 -0
  190. package/dist/storage/hot-cache-validation.d.ts.map +1 -0
  191. package/dist/storage.d.ts +2 -0
  192. package/dist/storage.d.ts.map +1 -1
  193. package/dist/storage.js +15 -15
  194. package/dist/transfer/capsule-import.js +5 -5
  195. package/dist/transfer/export-okf.js +16 -16
  196. package/dist/types.d.ts +2 -0
  197. package/dist/types.d.ts.map +1 -1
  198. package/dist/types.js +1 -1
  199. package/dist/verified-recall.js +16 -16
  200. package/dist/who-knows-cli.js +17 -17
  201. package/dist/who-knows.js +16 -16
  202. package/package.json +12 -2
  203. package/src/admin/admin-surfaces.test.ts +171 -0
  204. package/src/admin/admin-surfaces.ts +215 -2
  205. package/src/buffer-large-session-defer.test.ts +81 -0
  206. package/src/buffer-persistence.ts +8 -1
  207. package/src/buffer.ts +9 -4
  208. package/src/config.test.ts +9 -0
  209. package/src/config.ts +3 -6
  210. package/src/entity-recall-hot-cache.test.ts +116 -0
  211. package/src/entity-retrieval.ts +22 -4
  212. package/src/harmonic-graph-cache.test.ts +28 -9
  213. package/src/harmonic-retrieval.ts +20 -4
  214. package/src/memory-cache-hot.test.ts +47 -0
  215. package/src/memory-cache.ts +96 -17
  216. package/src/observe-flush-force-keys.test.ts +130 -0
  217. package/src/orchestration/recall-internal.ts +1 -0
  218. package/src/orchestration/turn-ingestion-buffered.test.ts +6 -2
  219. package/src/orchestration/turn-ingestion-buffered.ts +5 -1
  220. package/src/storage/entity-listing.ts +73 -0
  221. package/src/storage/entity-store.ts +25 -26
  222. package/src/storage/hot-cache-validation.ts +149 -0
  223. package/src/storage-contract/cache-coherence.test.ts +42 -5
  224. package/src/storage-hot-cache-stat-validate.test.ts +112 -0
  225. package/src/storage.ts +58 -44
  226. package/src/types.ts +2 -0
  227. package/dist/chunk-65DWWJKI.js.map +0 -1
  228. package/dist/chunk-ABPOW3SX.js.map +0 -1
  229. package/dist/chunk-CIAQK2OU.js.map +0 -1
  230. package/dist/chunk-HL53XYHC.js.map +0 -1
  231. package/dist/chunk-K6BS5RB4.js.map +0 -1
  232. package/dist/chunk-LL6WEMTC.js.map +0 -1
  233. package/dist/chunk-QSVWIKNY.js.map +0 -1
  234. package/dist/chunk-R5S57GRK.js.map +0 -1
  235. package/dist/chunk-RFVX4WE7.js.map +0 -1
  236. /package/dist/{entity-canonical-id-migration-74IDJFPB.js.map → admin/admin-surfaces.js.map} +0 -0
  237. /package/dist/{capsule-merge-BADOICNP.js.map → capsule-merge-3FARYIHP.js.map} +0 -0
  238. /package/dist/{chunk-IMSLPQJB.js.map → chunk-2QW5HPKU.js.map} +0 -0
  239. /package/dist/{chunk-KNYUEYB6.js.map → chunk-2YJ2ST23.js.map} +0 -0
  240. /package/dist/{chunk-X3ERYOLO.js.map → chunk-3BICT225.js.map} +0 -0
  241. /package/dist/{chunk-UWKHLWUE.js.map → chunk-3RZ4GDOH.js.map} +0 -0
  242. /package/dist/{chunk-ODIBCZLG.js.map → chunk-3YID7KZ6.js.map} +0 -0
  243. /package/dist/{chunk-56BNHKZM.js.map → chunk-4EAVEDLG.js.map} +0 -0
  244. /package/dist/{chunk-TLRIRISJ.js.map → chunk-4LCA2GEX.js.map} +0 -0
  245. /package/dist/{chunk-4N33L4HY.js.map → chunk-5GIYIYJI.js.map} +0 -0
  246. /package/dist/{chunk-ZDLVHGIC.js.map → chunk-7EP4FURO.js.map} +0 -0
  247. /package/dist/{chunk-CAUADFDM.js.map → chunk-7SOKOEAZ.js.map} +0 -0
  248. /package/dist/{chunk-7Q74DD2W.js.map → chunk-7V6GNQC2.js.map} +0 -0
  249. /package/dist/{chunk-QXHWOUS6.js.map → chunk-AALJHIKH.js.map} +0 -0
  250. /package/dist/{chunk-ATPY63F5.js.map → chunk-AJ7JHHRY.js.map} +0 -0
  251. /package/dist/{chunk-B7GZL7PR.js.map → chunk-ARD2TEY2.js.map} +0 -0
  252. /package/dist/{chunk-3DADRUGW.js.map → chunk-BGA7S5EF.js.map} +0 -0
  253. /package/dist/{chunk-RPOG6HLI.js.map → chunk-CJSTQNE5.js.map} +0 -0
  254. /package/dist/{chunk-VQQZJ6KJ.js.map → chunk-DYUPSTCV.js.map} +0 -0
  255. /package/dist/{chunk-E5QI6C6C.js.map → chunk-E3LGAZJC.js.map} +0 -0
  256. /package/dist/{chunk-TAPF7T26.js.map → chunk-EEA2RM4B.js.map} +0 -0
  257. /package/dist/{chunk-BL7WULM5.js.map → chunk-FDO7ITP6.js.map} +0 -0
  258. /package/dist/{chunk-K3JGILZC.js.map → chunk-FGFU6J26.js.map} +0 -0
  259. /package/dist/{chunk-6TIQLG7I.js.map → chunk-FKHXXL42.js.map} +0 -0
  260. /package/dist/{chunk-QPD7EYGI.js.map → chunk-G2MS56KM.js.map} +0 -0
  261. /package/dist/{chunk-2I3ETW3G.js.map → chunk-GH7IKABD.js.map} +0 -0
  262. /package/dist/{chunk-KVTUUU7H.js.map → chunk-GYCUX3N4.js.map} +0 -0
  263. /package/dist/{chunk-2VNMSEZR.js.map → chunk-HEJFE3BC.js.map} +0 -0
  264. /package/dist/{chunk-KM4QO4LN.js.map → chunk-HLQANATZ.js.map} +0 -0
  265. /package/dist/{chunk-AXSQGJSG.js.map → chunk-J7RQ3RP7.js.map} +0 -0
  266. /package/dist/{chunk-H442UKDV.js.map → chunk-JITK24KX.js.map} +0 -0
  267. /package/dist/{chunk-EJYUAN5F.js.map → chunk-K6UXWVQ6.js.map} +0 -0
  268. /package/dist/{chunk-RVODERA5.js.map → chunk-KJ65WZHB.js.map} +0 -0
  269. /package/dist/{chunk-QGT5KNQT.js.map → chunk-KOVQZJ27.js.map} +0 -0
  270. /package/dist/{chunk-O6QSBI3U.js.map → chunk-KZ4BJRGQ.js.map} +0 -0
  271. /package/dist/{chunk-D3FP4JQI.js.map → chunk-LR6LWX33.js.map} +0 -0
  272. /package/dist/{chunk-NTS2RCQK.js.map → chunk-NAULI3EG.js.map} +0 -0
  273. /package/dist/{chunk-V5W67PQV.js.map → chunk-NOKHMWMW.js.map} +0 -0
  274. /package/dist/{chunk-7X6EZ2QB.js.map → chunk-ODI4K32P.js.map} +0 -0
  275. /package/dist/{chunk-H7USCTPQ.js.map → chunk-OLD2GKQJ.js.map} +0 -0
  276. /package/dist/{chunk-D7HOJFDS.js.map → chunk-ONSEODO2.js.map} +0 -0
  277. /package/dist/{chunk-R3YMWUF3.js.map → chunk-P3IAZQPS.js.map} +0 -0
  278. /package/dist/{chunk-ZG4GNPRE.js.map → chunk-PBE7NFB5.js.map} +0 -0
  279. /package/dist/{chunk-7KC6LT7U.js.map → chunk-PSQ347YP.js.map} +0 -0
  280. /package/dist/{chunk-TQODBIMW.js.map → chunk-QFKNIKUF.js.map} +0 -0
  281. /package/dist/{chunk-C6Y2YHJL.js.map → chunk-QZMGZBTF.js.map} +0 -0
  282. /package/dist/{chunk-PCGBESAN.js.map → chunk-SKJM4PKE.js.map} +0 -0
  283. /package/dist/{chunk-T7R42MWB.js.map → chunk-STSORBX5.js.map} +0 -0
  284. /package/dist/{chunk-XWPYK5T4.js.map → chunk-T765HQ5U.js.map} +0 -0
  285. /package/dist/{chunk-RFEQ7DQN.js.map → chunk-TDG5NZAZ.js.map} +0 -0
  286. /package/dist/{chunk-DLPS5YP3.js.map → chunk-TJV5HGSC.js.map} +0 -0
  287. /package/dist/{chunk-YVXR7CPS.js.map → chunk-TWYYUMYO.js.map} +0 -0
  288. /package/dist/{chunk-6MDHK6NO.js.map → chunk-TZ7ZA2LM.js.map} +0 -0
  289. /package/dist/{chunk-6OHCNTKU.js.map → chunk-UH2VY2QQ.js.map} +0 -0
  290. /package/dist/{chunk-XQF2KLV5.js.map → chunk-VHQNJW4Q.js.map} +0 -0
  291. /package/dist/{chunk-3IA2SUWM.js.map → chunk-WRVKI6ZO.js.map} +0 -0
  292. /package/dist/{chunk-OA7YDB6A.js.map → chunk-XZLCAL5O.js.map} +0 -0
  293. /package/dist/{chunk-GGQ3CJVH.js.map → chunk-YTT6XJNX.js.map} +0 -0
  294. /package/dist/{chunk-A32EBVCZ.js.map → chunk-Z6EFSXU3.js.map} +0 -0
  295. /package/dist/{chunk-GRX5BE73.js.map → chunk-ZNCCX7P6.js.map} +0 -0
  296. /package/dist/{resolution-RWIGFH2W.js.map → entity-canonical-id-migration-46EMEXTB.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/admin/admin-surfaces.ts"],"sourcesContent":["/**\n * Admin console surfaces (issue #1502).\n *\n * Pure delegation functions that read from the SAME core APIs the runtime\n * uses — `resolveScopePlan` (issue #1521), `NamespaceCatalog` (#1499),\n * `NamespaceSearchRouter` health, the session-transcript migration planner\n * (#1496), and `StorageManager` writes. The admin HTTP layer and the static\n * console shell call these; they NEVER re-resolve scope, re-derive promotion\n * targets, or re-implement namespace listing. That is the #1492/#1494\n * invariant: the dashboard is not a second source of truth for namespace\n * authorization or scope resolution.\n *\n * Security contract (issue #1502 \"Security and Privacy Requirements\"):\n * - every list/inspection surface redacts fields that may carry credentials\n * (`redactSensitive` strips bearer-token-shaped strings);\n * - promotion requires a non-empty reason and authorizes the target through\n * `canWriteNamespace` (or the scope-profile promotion resolution) before\n * any write;\n * - transcript audit is dry-run only — the destructive apply path lives in\n * the CLI migration command, not here.\n *\n * Chokepoints used: ScopePlan resolver (#1521), NamespaceCatalog (#1499),\n * NamespaceSearchRouter health. No new scope-resolution or namespace-listing\n * logic is introduced.\n */\nimport { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport type { NamespaceCatalog, NamespaceRecord } from \"../namespaces/catalog.js\";\nimport { canReadNamespace, canWriteNamespace } from \"../namespaces/principal.js\";\nimport type { ResolvedScopeProfilePlan } from \"../namespaces/scope-profiles.js\";\nimport { type ScopePlan, resolveScopePlan } from \"../scopes/scope-plan.js\";\nimport { type SessionMigrationPlan, planSessionTranscriptMigration } from \"../session-transcript-migration.js\";\nimport type { CodingContext, MemoryCategory, MemoryFrontmatter, PluginConfig } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Shared redaction\n// ---------------------------------------------------------------------------\n\n/**\n * Marker substituted for any string value that looks like a credential.\n * The dashboard must never echo back a bearer token, API key, or password\n * that an operator may have pasted into a namespace alias / note field.\n */\nexport const REDACTED = \"<redacted>\";\n\nconst SENSITIVE_KEY_SOURCE = \"(?:token|secret|password|api[_-]?key|bearer|authorization|credential|private[_-]?key)\";\nconst SENSITIVE_KEY_RE = new RegExp(SENSITIVE_KEY_SOURCE, \"i\");\nconst BEARER_VALUE_RE = /^(bearer|sk-|pk-|xox[bp]-|AKIA)/i;\nconst LONG_OPAQUE_RE = /^[A-Za-z0-9_\\-]{32,}$/;\n\n/**\n * Diagnostic keys whose name collides with the sensitive-key regex (e.g.\n * `identityToken` contains \"token\") but are NOT credentials. `identityToken`\n * is the deterministic namespace storage-path hash (`ns-<hex>`); operators\n * need it for routing diagnostics and it is derived from the namespace name,\n * never from a secret. Listed keys skip the sensitive-key redaction branch;\n * the bearer-value and long-opaque checks below still apply.\n */\nconst SAFE_DIAGNOSTIC_KEYS = new Set([\"identityToken\"]);\n\n/**\n * Walk a parsed JSON value and replace credential-shaped values in place.\n * The check is conservative on purpose — values that LOOK like a long opaque\n * secret OR sit under a sensitive key are redacted. Namespace identity tokens\n * (16-hex `storagePathHash` outputs) are explicitly NOT redacted: operators\n * need them for storage diagnostics and they are derived from the namespace\n * name, not credentials.\n */\nexport function redactSensitive<T>(value: T): T {\n return walkRedact(value, undefined) as T;\n}\n\nfunction walkRedact(value: unknown, key: string | undefined): unknown {\n if (typeof value === \"string\") {\n if (\n key &&\n SENSITIVE_KEY_RE.test(key) &&\n !SAFE_DIAGNOSTIC_KEYS.has(key)\n ) {\n return REDACTED;\n }\n if (BEARER_VALUE_RE.test(value)) return REDACTED;\n if (!(key && SAFE_DIAGNOSTIC_KEYS.has(key)) && LONG_OPAQUE_RE.test(value) && value.length >= 40 && !/^[0-9a-f]{16}$/.test(value)) {\n return REDACTED;\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((entry) => walkRedact(entry, undefined));\n }\n // value is `object` here (Array branch handled above). Object.entries accepts\n // a plain object; the explicit record type documents the iteration contract.\n if (value && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(record)) {\n // A sensitive name redacts the COMPLETE value regardless of type: arrays\n // and objects under e.g. `apiKeys` / `credentials` carry credentials just\n // as strings do (recursing dropped the key and leaked short members).\n out[k] = SENSITIVE_KEY_RE.test(k) && !SAFE_DIAGNOSTIC_KEYS.has(k) ? REDACTED : walkRedact(v, k);\n }\n return out;\n }\n return value;\n}\n\n/**\n * Remove `/* *\\/` and `//` comments outside JSON strings and drop trailing\n * commas, so JSONC-style configs can take the structured redaction path\n * (JSON.parse rejects both). A trailing comma is a comma whose next\n * non-whitespace character is a closing `}` or `]`. Unterminated constructs\n * truncate the remainder, keeping the conservative regex fallback in charge.\n * Linear scan: tracks string state with escape handling, so comments and\n * commas inside string values (e.g. URLs) are never touched.\n */\nfunction stripJsonComments(text: string): string {\n let out = \"\";\n let inString = false;\n for (let i = 0; i < text.length; i += 1) {\n const ch = text[i];\n if (inString) {\n out += ch;\n if (ch === \"\\\\\" && i + 1 < text.length) {\n out += text[i + 1];\n i += 1;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n out += ch;\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"*\") {\n const end = text.indexOf(\"*/\", i + 2);\n if (end === -1) break;\n i = end + 1;\n continue;\n }\n if (ch === \"/\" && text[i + 1] === \"/\") {\n const end = text.indexOf(\"\\n\", i + 2);\n if (end === -1) break;\n i = end;\n continue;\n }\n if (ch === \",\") {\n let j = i + 1;\n while (j < text.length && (text[j] === \" \" || text[j] === \"\\t\" || text[j] === \"\\n\" || text[j] === \"\\r\")) j += 1;\n if (text[j] === \"}\" || text[j] === \"]\") continue;\n out += ch;\n continue;\n }\n out += ch;\n }\n return out;\n}\n\n/**\n * Redact a raw config-file text dump for display (COS-825). Parses JSON and\n * walks it with `redactSensitive`, so nested credentials (e.g. replica peer\n * tokens) get the same key/value rules the admin surfaces use. JSONC-style\n * comments are stripped first (outside strings), so files humans edit by hand\n * still take the structured path. Files that still do not parse keep their\n * comment-stripped text under a conservative regex: every\n * `\"<sensitive-key>\": \"<value>\"` pair at any depth has its value replaced\n * with the redaction marker.\n */\nexport function redactConfigText(raw: string): string {\n const withoutComments = stripJsonComments(raw);\n try {\n const parsed: unknown = JSON.parse(withoutComments);\n return JSON.stringify(redactSensitive(parsed), null, 2);\n } catch {\n return redactFallbackPairs(withoutComments);\n }\n}\n\n/**\n * Last-resort redaction for text JSON.parse still refuses (real syntax\n * errors): walk the text linearly, decode each property name\n * (`\"auth\\u0054oken\"` names `authToken`), and replace the whole string value\n * of a sensitive property with the redaction marker. Unterminated string\n * values under a sensitive property are cut at end of line. Non-string\n * values stay visible: anything JSONC-tolerant already took the structured\n * path above, so this only sees genuinely broken files. Scanner, not regex —\n * the pair shape is unbounded and check:regex-safety rejects such patterns.\n */\nfunction redactFallbackPairs(text: string): string {\n const out: string[] = [];\n const n = text.length;\n let i = 0;\n while (i < n) {\n if (text[i] !== '\"') {\n out.push(text[i]);\n i += 1;\n continue;\n }\n const keyStart = i;\n const keyEnd = scanJsonString(text, i);\n if (keyEnd === -1) {\n out.push(text.slice(i));\n break;\n }\n if (text[keyEnd] !== '\"') {\n // A raw CR/LF cut the key: the fragment cannot pair safely, and the\n // following line's leading quote would open a phantom string that\n // detaches later credentials from their pairs. Drop through the end of\n // that line instead of exposing them.\n const nl = text.indexOf(\"\\n\", keyEnd);\n out.push(text.slice(i, keyEnd));\n i = nl === -1 ? n : nl + 1;\n continue;\n }\n let k = skipJsonWhitespace(text, keyEnd + 1);\n if (text[k] !== \":\") {\n // Orphan string (no colon follows): pairing in this broken text is not\n // trustworthy, so suppress through the rest of the line instead of\n // risking a later credential pairing past its key.\n out.push(text.slice(i, keyEnd + 1));\n const nl = text.indexOf(\"\\n\", keyEnd + 1);\n i = nl === -1 ? n : nl + 1;\n continue;\n }\n k = skipJsonWhitespace(text, k + 1);\n out.push(text.slice(i, k));\n i = k;\n const decodedKey = decodeJsonKeyName(text.slice(keyStart + 1, keyEnd));\n if (text[i] !== '\"') {\n // Non-string value: `{` / `[` are transparent — pairs nested inside are\n // processed by the main loop, so sensitive keys never hide under a\n // non-sensitive parent. Scalars stop at the next quote so a missing\n // comma never swallows a following property (old regex redacted those).\n // Anything JSONC-tolerant already took the structured path above.\n if (text[i] === \"{\" || text[i] === \"[\") {\n out.push(text[i]);\n i += 1;\n continue;\n }\n const valueEnd = scanToValueEnd(text, i);\n out.push(text.slice(i, valueEnd));\n i = valueEnd;\n continue;\n }\n const valueEnd = scanJsonString(text, i);\n if (valueEnd === -1) {\n // Unterminated at EOF under a sensitive key: nothing after is\n // trustworthy, redact to end of input.\n if (SENSITIVE_KEY_RE.test(decodedKey)) {\n out.push(REDACTED);\n i = n;\n } else {\n const stop = text.indexOf(\"\\n\", i);\n const stopAt = stop === -1 ? n : stop + 1;\n out.push(text.slice(i, stopAt));\n i = stopAt;\n }\n continue;\n }\n if (SENSITIVE_KEY_RE.test(decodedKey)) {\n out.push(REDACTED);\n // A raw CR/LF ended the string: the credential spans a broken line and\n // its real end is unknowable, so redact everything after it too.\n if (text[valueEnd] !== '\"') {\n i = n;\n } else {\n i = valueEnd + 1;\n }\n } else {\n out.push(text.slice(i, valueEnd + 1));\n i = valueEnd + 1;\n }\n }\n return out.join(\"\");\n}\n\n/** Index just past the JSON string opening at `start`, or -1 if unterminated. Raw CR/LF terminate the scan (invalid JSON recovery). */\nfunction scanJsonString(text: string, start: number): number {\n let i = start + 1;\n const n = text.length;\n while (i < n) {\n const ch = text[i];\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n if (ch === '\"' || ch === \"\\n\" || ch === \"\\r\") return i;\n i += 1;\n }\n return -1;\n}\n\nfunction skipJsonWhitespace(text: string, start: number): number {\n let i = start;\n while (i < text.length && (text[i] === \" \" || text[i] === \"\\t\" || text[i] === \"\\n\" || text[i] === \"\\r\")) i += 1;\n return i;\n}\n\nfunction scanToValueEnd(text: string, start: number): number {\n let i = start;\n while (i < text.length && text[i] !== \",\" && text[i] !== \"}\" && text[i] !== \"]\" && text[i] !== \"\\n\" && text[i] !== '\"') i += 1;\n return i;\n}\n\nfunction decodeJsonKeyName(rawKey: string): string {\n try {\n // SAFETY: JSON.parse of a double-quoted string literal always yields a\n // string; malformed escapes throw and the raw key is used instead.\n return JSON.parse(`\"${rawKey}\"`) as string;\n } catch {\n return rawKey;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Effective scope inspector\n// ---------------------------------------------------------------------------\n\n/**\n * One layer's contribution to the effective scope, with a human-readable\n * reason it was included or skipped. Mirrors the layer set surfaced by the\n * scope-profile plan plus the coding overlay and explicit override.\n */\nexport interface ScopeInspectionLayer {\n /** Layer id — `userProject` / `teamProject` / `userGlobal` / `serverShared` / `coding` / `explicit` / `self`. */\n id: string;\n /** Resolved namespace for the layer, when applicable. */\n namespace?: string;\n /** Whether the layer is in the active read set. */\n readable: boolean;\n /** Whether the layer is the effective write target. */\n writable: boolean;\n /** Whether the layer is an authorized promotion target. */\n promotable: boolean;\n /** Human-readable explanation — used verbatim by the console \"why\" column. */\n reason: string;\n}\n\n/** Promotion target resolved against policy + scope profile. */\nexport interface ScopeInspectionPromotionTarget {\n target: string;\n namespace?: string;\n authorized: boolean;\n reason: string;\n}\n\n/** Output of {@link inspectScope}. */\nexport interface ScopeInspection {\n /** Resolved principal (or `undefined` in single-user mode). */\n principal: string | undefined;\n /** Explicit namespace override, when readable. */\n namespaceOverride: string | undefined;\n /** Effective write namespace. */\n writeNamespace: string;\n /** Read namespaces in the order recall searches them. */\n readNamespaces: string[];\n /** Coding overlay details (branch → project → root fallbacks). */\n codingOverlay: { namespace: string; readFallbacks: readonly string[] } | null;\n /** Active scope profile id, if any. */\n scopeProfileId: string | null;\n /** Per-layer explanations. */\n layers: ScopeInspectionLayer[];\n /** Promotion targets available for this session/principal. */\n promotionTargets: ScopeInspectionPromotionTarget[];\n /** Operator warnings (missing project, disabled scope, auth failures, …). */\n warnings: string[];\n /**\n * Frozen copy of the {@link ScopePlan} the runtime resolver produced. The\n * dashboard MUST display this verbatim — never a re-derived copy — so the\n * \"scope inspector returns the same plan as runtime resolver\" acceptance\n * test (issue #1502) holds by construction.\n */\n plan: ScopePlan;\n}\n\n/** Operation type the caller intends to inspect (informational only). */\nexport type ScopeInspectionOperation = \"recall\" | \"observe\" | \"memory_store\" | \"maintenance\" | \"dashboard\";\n\n/** Inputs for {@link inspectScope}. */\nexport interface InspectScopeOptions {\n readonly config: PluginConfig;\n readonly sessionKey?: string;\n readonly namespace?: string;\n readonly principalOverride?: string;\n readonly codingContext?: CodingContext | null;\n readonly operation?: ScopeInspectionOperation;\n /**\n * Whether namespace routing is enabled. Callers that already resolved the\n * flag (e.g. the access-service layer, threading it through the shared\n * scope-plan chokepoint) pass it here so this pure helper does not need to\n * re-read the namespace gate. Defaults to reading the config flag when\n * omitted so direct callers (tests, CLI) keep working.\n */\n readonly namespacesEnabled?: boolean;\n}\n\n/**\n * Resolve an effective scope inspection by delegating to the runtime\n * {@link resolveScopePlan} resolver and decorating its result with the\n * per-layer explanations the console renders. Pure — no side effects.\n */\nexport function inspectScope(options: InspectScopeOptions): ScopeInspection {\n const { config } = options;\n // Honour the pre-read flag when the caller supplied one (avoids a scattered\n // read here); fall back to the config flag for direct callers (tests/CLI).\n const namespacesEnabled = options.namespacesEnabled ?? resolveNamespaceCapabilities(config).namespaces === true;\n\n const plan = resolveScopePlan({\n config,\n sessionKey: options.sessionKey,\n namespace: options.namespace,\n principalOverride: options.principalOverride,\n codingContext: options.codingContext ?? null,\n namespacesEnabled,\n });\n\n const warnings: string[] = [];\n if (namespacesEnabled && !plan.principal) {\n warnings.push(\"namespace routing is enabled but no principal resolved for this session key\");\n }\n if (config.codingMode?.projectScope && namespacesEnabled && options.codingContext && !plan.codingOverlay) {\n warnings.push(\"coding project scope is enabled but the overlay was suppressed by an explicit namespace override\");\n }\n if (options.namespace && options.namespace.trim().length > 0 && !plan.namespaceOverride) {\n warnings.push(\n `requested namespace override '${options.namespace}' is not readable by this principal and was ignored`\n );\n }\n // Issue #1658 thread 6: when an explicit namespace override is readable but\n // NOT writable, it still becomes the effective write namespace (baseNamespace\n // in the scope plan). Surface the mismatch honestly so the operator knows\n // writes will be rejected rather than reading writeNamespace as a usable\n // target. (The per-layer writable flag already records this, but the\n // top-level writeNamespace field does not.)\n if (plan.namespaceOverride && !canWriteNamespace(plan.principal, plan.namespaceOverride, config)) {\n warnings.push(\n `explicit namespace override '${plan.namespaceOverride}' is readable but not writable by this principal; it is the effective write namespace but writes will be rejected`\n );\n }\n\n const layers: ScopeInspectionLayer[] = [];\n const scopeProfilePlan = plan.scopeProfilePlan;\n if (scopeProfilePlan) {\n for (const layer of scopeProfilePlan.layers) {\n layers.push({\n id: layer.id,\n namespace: layer.namespace,\n readable: layer.readable,\n writable: layer.writable,\n promotable: layer.promotable,\n reason: layer.reason,\n });\n }\n for (const target of scopeProfilePlan.promotionTargets) {\n if (!layers.some((layer) => layer.id === target.target)) {\n layers.push({\n id: target.target,\n namespace: target.namespace,\n readable: false,\n writable: false,\n promotable: target.authorized,\n reason: target.reason,\n });\n }\n }\n } else {\n // Non-profile scope: synthesize a self layer + optional coding + override.\n layers.push({\n id: \"self\",\n namespace: plan.baseNamespace,\n readable: canReadNamespace(plan.principal, plan.baseNamespace, config),\n writable: canWriteNamespace(plan.principal, plan.baseNamespace, config),\n promotable: false,\n reason: \"principal self namespace (no scope profile active)\",\n });\n }\n if (plan.codingOverlay) {\n layers.push({\n id: \"coding\",\n namespace: plan.codingOverlay.namespace,\n readable: true,\n writable: true,\n promotable: false,\n reason: \"coding overlay namespace combined with the principal base (rule 42)\",\n });\n }\n if (plan.namespaceOverride) {\n layers.push({\n id: \"explicit\",\n namespace: plan.namespaceOverride,\n readable: true,\n writable: canWriteNamespace(plan.principal, plan.namespaceOverride, config),\n promotable: false,\n reason: \"explicit namespace override authorized for this principal\",\n });\n }\n\n const promotionTargets: ScopeInspectionPromotionTarget[] = scopeProfilePlan\n ? scopeProfilePlan.promotionTargets.map((target) => ({\n target: target.target,\n namespace: target.namespace,\n authorized: target.authorized,\n reason: target.reason,\n }))\n : [];\n\n for (const warning of scopeProfilePlan?.warnings ?? []) {\n warnings.push(warning);\n }\n\n return {\n principal: plan.principal,\n namespaceOverride: plan.namespaceOverride,\n writeNamespace: plan.baseNamespace,\n readNamespaces: [...plan.readNamespaces],\n codingOverlay: plan.codingOverlay\n ? {\n namespace: plan.codingOverlay.namespace,\n readFallbacks: plan.codingOverlay.readFallbacks,\n }\n : null,\n scopeProfileId: scopeProfilePlan?.profileId ?? null,\n layers,\n promotionTargets,\n warnings,\n plan,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Namespace browser\n// ---------------------------------------------------------------------------\n\n/** Filters the namespace browser accepts (superset of {@link NamespaceCatalogFilter}). */\nexport interface AdminNamespaceFilter {\n kind?: NamespaceRecord[\"kind\"];\n discoveredBy?: NamespaceRecord[\"discoveredBy\"];\n /** Only namespaces with a write at/after this instant. */\n writtenSince?: Date;\n /** Only namespaces whose last write is older than this instant (stale). */\n staleBefore?: Date;\n}\n\n/** One namespace row augmented with the operator-facing diagnostics the issue lists. */\nexport interface AdminNamespaceEntry {\n namespace: string;\n identityToken: string;\n kind: NamespaceRecord[\"kind\"];\n createdAt: string;\n lastReadAt?: string;\n lastWriteAt?: string;\n lastMaintenanceAt?: Record<string, string>;\n storageDir: string;\n discoveredBy: NamespaceRecord[\"discoveredBy\"];\n /** True when last write is older than `staleThresholdDays` (or never written). */\n stale: boolean;\n}\n\n/** Output of {@link listAdminNamespaces}. */\nexport interface AdminNamespaceList {\n /** Whether the namespace catalog is enabled. `false` collapses the list. */\n enabled: boolean;\n entries: AdminNamespaceEntry[];\n}\n\n/** Inputs for {@link listAdminNamespaces}. */\nexport interface ListAdminNamespacesOptions {\n readonly catalog: NamespaceCatalog;\n readonly filter?: AdminNamespaceFilter;\n /** A namespace whose last write is older than this many days is \"stale\". */\n readonly staleThresholdDays?: number;\n}\n\n/**\n * List configured + discovered namespaces from the catalog, applying the\n * admin filters the console exposes. Delegates to {@link NamespaceCatalog}\n * — never re-scans disk.\n */\nexport async function listAdminNamespaces(options: ListAdminNamespacesOptions): Promise<AdminNamespaceList> {\n const { catalog, filter } = options;\n if (!catalog.enabled) {\n return { enabled: false, entries: [] };\n }\n const staleMs = (options.staleThresholdDays ?? 30) * 24 * 60 * 60 * 1000;\n const staleBefore = new Date(Date.now() - staleMs);\n\n const records = await catalog.listNamespaces({\n kind: filter?.kind,\n discoveredBy: filter?.discoveredBy,\n writtenSince: filter?.writtenSince,\n });\n\n let entries: AdminNamespaceEntry[] = records.map((record) => toAdminEntry(record, staleBefore));\n\n if (filter?.staleBefore) {\n const cutoff = filter.staleBefore.getTime();\n entries = entries.filter((entry) => {\n if (!entry.lastWriteAt) return true;\n const ms = Date.parse(entry.lastWriteAt);\n return Number.isFinite(ms) && ms <= cutoff;\n });\n }\n\n return { enabled: true, entries };\n}\n\nfunction toAdminEntry(record: NamespaceRecord, staleBefore: Date): AdminNamespaceEntry {\n const lastWriteMs = record.lastWriteAt ? Date.parse(record.lastWriteAt) : Number.NaN;\n const stale = !Number.isFinite(lastWriteMs) || lastWriteMs < staleBefore.getTime();\n return {\n namespace: record.namespace,\n identityToken: record.identityToken,\n kind: record.kind,\n createdAt: record.createdAt,\n lastReadAt: record.lastReadAt,\n lastWriteAt: record.lastWriteAt,\n lastMaintenanceAt: record.lastMaintenanceAt,\n storageDir: record.storageDir,\n discoveredBy: record.discoveredBy,\n stale,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Maintenance and QMD health\n// ---------------------------------------------------------------------------\n\n/**\n * Honest, distinguishable classification of a namespace's QMD/search health\n * (issue #1658 thread 1). A single `qmdDegraded` bit collapses the legitimate\n * transient \"unknown\" (QMD reachable but collection status not yet populated,\n * normal during startup/reindex) together with the actionable \"missing\"\n * (collection not built — operator must act) and \"unavailable\" (backend down).\n * Surfacing a classified state lets the dashboard render each case honestly\n * instead of a flat degraded flag or a silent blank.\n */\nexport type AdminNamespaceQmdState =\n /** Backend reachable and collection present (or intentionally skipped). */\n | \"healthy\"\n /** Backend reachable but collection status not yet determined (transient). */\n | \"unknown\"\n /** Backend reachable but the collection is not built for this namespace. */\n | \"missing\"\n /** Backend unreachable / probe threw. */\n | \"unavailable\"\n /** No QMD probe was run for this report (provider omitted or returned null). */\n | \"not_probed\";\n\n/** QMD/search health snapshot for one namespace (delegated to NamespaceSearchRouter). */\nexport interface AdminNamespaceQmdHealth {\n namespace: string;\n collection: string;\n available: boolean;\n collectionState: string;\n debugStatus: string;\n installedVersion: string | null;\n supportedVersion: string | null;\n supported: boolean | null;\n upgradeAvailable: boolean | null;\n daemonMode: boolean | null;\n}\n\n/** Maintenance + QMD health for one namespace. */\nexport interface AdminNamespaceHealth {\n namespace: string;\n kind?: NamespaceRecord[\"kind\"];\n lastMaintenanceAt?: Record<string, string>;\n /** True when no maintenance has ever been recorded. */\n maintenanceMissing: boolean;\n /**\n * True when QMD is unavailable OR its collection is missing/unknown for this\n * namespace. Matches the NamespaceSearchRouter health path so the aggregate\n * `degradedMode` flag stays consistent with runtime alerting.\n */\n qmdDegraded: boolean;\n /**\n * Honest, distinguishable QMD state (issue #1658 thread 1). Complements\n * `qmdDegraded` so the dashboard can render \"unknown\" (transient) separately\n * from \"missing\"/\"unavailable\" (action needed) instead of a flat bit.\n */\n qmdState: AdminNamespaceQmdState;\n /** Human-readable explanation of {@link qmdState}, safe to show operators. */\n qmdStateReason: string;\n qmd?: AdminNamespaceQmdHealth;\n /** Reason the QMD probe failed, when it did. */\n qmdError?: string;\n}\n\n/** Output of {@link gatherMaintenanceHealth}. */\nexport interface MaintenanceHealthReport {\n /** Whether the catalog is enabled. */\n enabled: boolean;\n /** Aggregate degraded-mode flag — true when ANY namespace is QMD-degraded. */\n degradedMode: boolean;\n perNamespace: AdminNamespaceHealth[];\n}\n\n/**\n * Injected per-namespace QMD health probe. Implementations call\n * `orchestrator.searchHealthForNamespace(namespace)` — the admin module\n * stays free of orchestrator/state coupling.\n */\nexport type NamespaceQmdHealthProvider = (namespace: string) => Promise<AdminNamespaceQmdHealth | null>;\n\n/** Inputs for {@link gatherMaintenanceHealth}. */\nexport interface MaintenanceHealthOptions {\n readonly catalog: NamespaceCatalog;\n /** When omitted, QMD columns stay empty (catalog-only report). */\n readonly qmdHealthProvider?: NamespaceQmdHealthProvider;\n}\n\n/**\n * Build a per-namespace maintenance + QMD health report. Reads maintenance\n * timestamps from the catalog and (optionally) QMD diagnostics from the\n * injected provider.\n */\n/**\n * Classify a QMD health snapshot into an honest, distinguishable state bucket\n * (issue #1658 thread 1). The `degraded` bit mirrors the NamespaceSearchRouter\n * health path (unavailable / missing / unknown) so the aggregate `degradedMode`\n * flag and any downstream alerting stay consistent; the classified `state` +\n * `reason` let the dashboard render each case distinctly instead of a flat bit.\n */\nfunction classifyQmdState(qmd: AdminNamespaceQmdHealth): {\n state: AdminNamespaceQmdState;\n reason: string;\n degraded: boolean;\n} {\n if (!qmd.available) {\n return {\n state: \"unavailable\",\n reason: \"QMD backend is unavailable for this namespace\",\n degraded: true,\n };\n }\n // collectionState is the router's string (\"present\" | \"missing\" | \"unknown\"\n // | \"skipped\"); classify defensively — an unrecognized value is reported as\n // \"unknown\" rather than silently treated as healthy.\n switch (qmd.collectionState) {\n case \"present\":\n return { state: \"healthy\", reason: \"QMD collection is ready\", degraded: false };\n case \"skipped\":\n // \"skipped\" means QMD is intentionally disabled for this namespace; it is\n // neither degraded nor a blank — surface it honestly as healthy/idle.\n return {\n state: \"healthy\",\n reason: \"QMD is skipped for this namespace (intentionally disabled)\",\n degraded: false,\n };\n case \"missing\":\n return {\n state: \"missing\",\n reason: \"QMD collection is not built for this namespace — add the collection to the QMD index\",\n degraded: true,\n };\n case \"unknown\":\n return {\n state: \"unknown\",\n reason: \"QMD collection status could not be determined (transient during startup/reindex)\",\n degraded: true,\n };\n default:\n // Preserve the ORIGINAL qmdDegraded invariant exactly: an available\n // backend with an unrecognized collectionState was NOT degraded before\n // this PR (the pre-image only flagged missing/unknown/unavailable). We\n // still surface the unrecognized value HONESTLY via state/reason so the\n // dashboard can render it, but we do not flip the degraded bit — that\n // would change alerting and contradict the \"unchanged semantics\" claim.\n return {\n state: \"unknown\",\n reason: `QMD reported an unrecognized collection state '${qmd.collectionState}'`,\n degraded: false,\n };\n }\n}\n\nexport async function gatherMaintenanceHealth(options: MaintenanceHealthOptions): Promise<MaintenanceHealthReport> {\n const { catalog, qmdHealthProvider } = options;\n if (!catalog.enabled) {\n return { enabled: false, degradedMode: false, perNamespace: [] };\n }\n const records = await catalog.listNamespaces();\n let degradedMode = false;\n const perNamespace: AdminNamespaceHealth[] = await Promise.all(\n records.map(async (record): Promise<AdminNamespaceHealth> => {\n const entry: AdminNamespaceHealth = {\n namespace: record.namespace,\n kind: record.kind,\n lastMaintenanceAt: record.lastMaintenanceAt,\n maintenanceMissing: !record.lastMaintenanceAt || Object.keys(record.lastMaintenanceAt).length === 0,\n qmdDegraded: false,\n qmdState: \"not_probed\",\n qmdStateReason: \"QMD health probe not run for this report\",\n };\n if (qmdHealthProvider) {\n try {\n const qmd = await qmdHealthProvider(record.namespace);\n if (qmd) {\n entry.qmd = qmd;\n // Classify the collection state into an honest, distinguishable\n // bucket (issue #1658 thread 1) and derive the degraded bit from\n // the same inputs the NamespaceSearchRouter health path uses.\n const classified = classifyQmdState(qmd);\n entry.qmdState = classified.state;\n entry.qmdStateReason = classified.reason;\n entry.qmdDegraded = classified.degraded;\n } else {\n entry.qmdState = \"not_probed\";\n entry.qmdStateReason = \"QMD health not available for this namespace\";\n }\n } catch (err) {\n // Sanitize: never echo raw error messages to the dashboard. The\n // generic diagnostic is sufficient for operators; the full error\n // is logged by the qmdHealthProvider's caller (access-service).\n entry.qmdDegraded = true;\n entry.qmdState = \"unavailable\";\n entry.qmdStateReason = \"QMD health probe failed\";\n entry.qmdError = \"QMD health probe failed\";\n }\n }\n if (entry.qmdDegraded) degradedMode = true;\n return entry;\n })\n );\n return { enabled: true, degradedMode, perNamespace };\n}\n\n// ---------------------------------------------------------------------------\n// Transcript / session audit\n// ---------------------------------------------------------------------------\n\n/** One file the dry-run migration planner would re-home. */\nexport interface TranscriptAuditFile {\n sourceRelPath: string;\n fileName: string;\n distinctSessions: number;\n movedEntries: number;\n unmovableLines: number;\n}\n\n/** Output of {@link auditTranscripts}. */\nexport interface TranscriptAuditReport {\n /** Generated timestamp (ISO). */\n generatedAt: string;\n /** Always true — the admin surface is dry-run only. */\n dryRun: true;\n /** Absolute transcripts directory scanned. */\n transcriptsDir: string;\n /** True when any legacy fallback file (e.g. `other/default`) holds mixed sessions. */\n mixedOtherDefault: boolean;\n /** Distinct sessions the planner would re-home. */\n distinctSessions: number;\n /** Total JSONL entries that would move. */\n movedEntries: number;\n /** Per-file plans with at least one entry to move. */\n files: TranscriptAuditFile[];\n /** Operator-facing summary of the risk. */\n summary: string;\n}\n\n/**\n * Run a dry-run transcript/session audit. Delegates to\n * {@link planSessionTranscriptMigration} with `apply: false` — the admin\n * surface never applies a destructive migration. The CLI owns the apply\n * path with its confirmation flow.\n */\nexport async function auditTranscripts(memoryDir: string): Promise<TranscriptAuditReport> {\n const plan: SessionMigrationPlan = await planSessionTranscriptMigration({\n memoryDir,\n apply: false,\n });\n const files: TranscriptAuditFile[] = plan.files.map((file) => ({\n sourceRelPath: file.sourceRelPath,\n fileName: file.fileName,\n distinctSessions: file.groups.length,\n movedEntries: file.groups.reduce((sum, group) => sum + group.entryCount, 0),\n unmovableLines: file.unmovableLines,\n }));\n const mixedOtherDefault = files.some((file) => file.sourceRelPath.split(path.sep).includes(\"other\"));\n const summary =\n plan.movedEntries === 0\n ? \"No mixed-session transcript data detected; nothing to migrate.\"\n : `Found ${plan.movedEntries} entries across ${plan.distinctSessions} distinct sessions stranded in shared/legacy directories. Run the CLI migration command to re-home them.`;\n return {\n generatedAt: plan.generatedAt,\n dryRun: true,\n transcriptsDir: plan.transcriptsDir,\n mixedOtherDefault,\n distinctSessions: plan.distinctSessions,\n movedEntries: plan.movedEntries,\n files,\n summary,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Memory promotion (manual, reason-required, policy-enforced)\n// ---------------------------------------------------------------------------\n\n/** Promotion target kind the console can request. */\nexport type MemoryPromotionTargetKind = \"teamProject\" | \"serverShared\" | \"userProject\" | \"userGlobal\" | \"explicit\";\n\n/** Result of one promotion attempt. */\nexport interface MemoryPromotionTargetResult {\n target: MemoryPromotionTargetKind;\n namespace: string;\n authorized: boolean;\n promoted: boolean;\n promotedMemoryId?: string;\n reason: string;\n}\n\n/** Output of {@link promoteMemory}. */\nexport interface MemoryPromotionResult {\n /** Whether the caller-supplied reason was accepted. */\n ok: boolean;\n /** Source memory id. */\n sourceMemoryId: string;\n /** Source namespace the memory was read from. */\n sourceNamespace: string;\n /** Per-target outcomes. Empty when authorization fails up front. */\n targets: MemoryPromotionTargetResult[];\n /** Audit record — caller appends to the access audit log. */\n audit: MemoryPromotionAudit;\n}\n\n/** Audit trail for a promotion operation. */\nexport interface MemoryPromotionAudit {\n at: string;\n actor: string;\n sourceMemoryId: string;\n sourceNamespace: string;\n reason: string;\n targets: Array<{ target: MemoryPromotionTargetKind; namespace: string; promoted: boolean }>;\n}\n\n/** Error thrown when a required promotion field is missing or unauthorized. */\nexport class AdminPromotionError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"AdminPromotionError\";\n this.code = code;\n }\n}\n\n/**\n * Storage accessor injected by the service layer. Keeps the admin module\n * decoupled from `StorageManager` and the orchestrator's storage router.\n */\nexport interface PromotionStorageProvider {\n /** Read a memory from the source namespace. Returns null when missing. */\n readMemory(\n namespace: string,\n memoryId: string\n ): Promise<{\n category: MemoryCategory;\n content: string;\n frontmatter: MemoryFrontmatter;\n } | null>;\n /** Write a promoted memory into the target namespace. Returns the new id. */\n writePromotedMemory(\n namespace: string,\n memory: {\n category: MemoryCategory;\n content: string;\n confidence: number;\n tags: string[];\n entityRef?: string;\n sourceMemoryId: string;\n sourceNamespace: string;\n reason: string;\n actor: string;\n validAt?: string;\n /**\n * Lineage persisted onto the promoted memory's frontmatter. Always\n * `[sourceMemoryId]` so a downstream reader can trace a promotion\n * back to its origin (matches the runtime extraction pipeline).\n */\n lineage: string[];\n sourceConnector?: string;\n toolScoped?: true;\n }\n ): Promise<string>;\n}\n\n/** Inputs for {@link promoteMemory}. */\nexport interface PromoteMemoryOptions {\n readonly config: PluginConfig;\n readonly sourceMemoryId: string;\n /** Source namespace (resolved through the readable resolver BEFORE this call). */\n readonly sourceNamespace: string;\n /** Authenticated principal driving the promotion. */\n readonly principal?: string;\n /** Requested targets. */\n readonly targets: ReadonlyArray<{\n kind: MemoryPromotionTargetKind;\n /** Required when kind === \"explicit\". Must be writable by the principal. */\n namespace?: string;\n }>;\n /** Non-empty operator reason (audit-logged). */\n readonly reason: string;\n /** Operator identity for the audit trail. */\n readonly actor: string;\n readonly storage: PromotionStorageProvider;\n /** Optional scope-profile plan, used to resolve teamProject/userProject/serverShared targets. */\n readonly scopeProfilePlan?: ResolvedScopeProfilePlan | null;\n}\n\n/**\n * Manually promote a memory into one or more authorized targets. Reuses the\n * same `canWriteNamespace` gate and scope-profile promotion resolution that\n * the runtime extraction pipeline uses — there is no dashboard-only write\n * path. Requires a non-empty reason; throws {@link AdminPromotionError}\n * (`reason_required`) otherwise.\n */\nexport async function promoteMemory(options: PromoteMemoryOptions): Promise<MemoryPromotionResult> {\n const reason = options.reason.trim();\n if (reason.length === 0) {\n throw new AdminPromotionError(\"reason_required\", \"promotion requires a non-empty reason\");\n }\n if (options.targets.length === 0) {\n throw new AdminPromotionError(\"targets_required\", \"promotion requires at least one target\");\n }\n const { config, principal, scopeProfilePlan } = options;\n\n // Resolve each requested target to a concrete namespace + authorization flag.\n const resolvedTargets: MemoryPromotionTargetResult[] = options.targets.map((requested) => {\n if (requested.kind === \"explicit\") {\n const namespace = requested.namespace?.trim();\n if (!namespace) {\n return {\n target: requested.kind,\n namespace: \"\",\n authorized: false,\n promoted: false,\n reason: \"explicit promotion requires a namespace\",\n };\n }\n const authorized = canWriteNamespace(principal, namespace, config);\n return {\n target: requested.kind,\n namespace,\n authorized,\n promoted: false,\n reason: authorized\n ? \"explicit namespace writable by this principal\"\n : \"explicit namespace is not writable by this principal\",\n };\n }\n if (!scopeProfilePlan) {\n // Issue #1658 thread 2: distinguish \"no active scope profile\" from\n // \"profile does not configure this target\". A project-scoped target\n // (userProject/teamProject) cannot resolve without an active profile +\n // coding context; report that honestly instead of a generic \"not\n // configured\" message that implies a profile is active.\n return {\n target: requested.kind,\n namespace: \"\",\n authorized: false,\n promoted: false,\n reason:\n requested.kind === \"userProject\" || requested.kind === \"teamProject\"\n ? `no active scope profile; '${requested.kind}' promotion requires an active scope profile with a coding context (pass a sessionKey)`\n : `no active scope profile; '${requested.kind}' promotion requires an active scope profile`,\n };\n }\n const layer = scopeProfilePlan.promotionTargets.find((t) => t.target === requested.kind);\n if (!layer) {\n return {\n target: requested.kind,\n namespace: \"\",\n authorized: false,\n promoted: false,\n reason: `promotion target '${requested.kind}' is not configured on the active scope profile`,\n };\n }\n return {\n target: requested.kind,\n namespace: layer.namespace ?? \"\",\n authorized: layer.authorized && Boolean(layer.namespace),\n promoted: false,\n reason: layer.reason,\n };\n });\n\n const sourceMemory = await options.storage.readMemory(options.sourceNamespace, options.sourceMemoryId);\n if (!sourceMemory) {\n throw new AdminPromotionError(\n \"source_not_found\",\n `source memory ${options.sourceMemoryId} not found in namespace ${options.sourceNamespace}`\n );\n }\n\n const auditTargets: MemoryPromotionAudit[\"targets\"] = [];\n for (const target of resolvedTargets) {\n if (!target.authorized || !target.namespace) {\n auditTargets.push({ target: target.target, namespace: target.namespace, promoted: false });\n continue;\n }\n if (target.namespace === options.sourceNamespace) {\n target.reason = \"target namespace equals source namespace; nothing to promote\";\n auditTargets.push({ target: target.target, namespace: target.namespace, promoted: false });\n continue;\n }\n try {\n const promotedId = await options.storage.writePromotedMemory(target.namespace, {\n category: sourceMemory.category,\n content: sourceMemory.content,\n confidence: sourceMemory.frontmatter.confidence ?? 0.5,\n tags: [...(sourceMemory.frontmatter.tags ?? []), `admin-promotion-${target.target}`],\n entityRef: sourceMemory.frontmatter.entityRef,\n sourceMemoryId: options.sourceMemoryId,\n sourceNamespace: options.sourceNamespace,\n reason,\n actor: options.actor,\n validAt: sourceMemory.frontmatter.valid_at,\n lineage: [options.sourceMemoryId],\n ...(sourceMemory.frontmatter.sourceConnector ? { sourceConnector: sourceMemory.frontmatter.sourceConnector } : {}),\n ...(sourceMemory.frontmatter.toolScoped ? { toolScoped: true as const } : {}),\n });\n target.promoted = true;\n target.promotedMemoryId = promotedId;\n auditTargets.push({ target: target.target, namespace: target.namespace, promoted: true });\n } catch (err) {\n // Sanitize: never echo raw error messages in the promotion result.\n // The operator sees a generic failure indicator; the full error is\n // logged server-side by the storage provider.\n target.reason = \"promotion write failed\";\n auditTargets.push({ target: target.target, namespace: target.namespace, promoted: false });\n }\n }\n\n const at = new Date().toISOString();\n const audit: MemoryPromotionAudit = {\n at,\n actor: options.actor,\n sourceMemoryId: options.sourceMemoryId,\n sourceNamespace: options.sourceNamespace,\n reason,\n targets: auditTargets,\n };\n\n return {\n ok: resolvedTargets.some((t) => t.promoted),\n sourceMemoryId: options.sourceMemoryId,\n sourceNamespace: options.sourceNamespace,\n targets: resolvedTargets,\n audit,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,OAAO,UAAU;AAiBV,IAAM,WAAW;AAExB,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB,IAAI,OAAO,sBAAsB,GAAG;AAC7D,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AAUvB,IAAM,uBAAuB,oBAAI,IAAI,CAAC,eAAe,CAAC;AAU/C,SAAS,gBAAmB,OAAa;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Q;AAAA,QACf,SAAS,aAAa,YAAY;AAAA,QAClC,SAAS,CAAC,QAAQ,cAAc;AAAA,QAChC,GAAI,aAAa,YAAY,kBAAkB,EAAE,iBAAiB,aAAa,YAAY,gBAAgB,IAAI,CAAC;AAAA,QAChH,GAAI,aAAa,YAAY,aAAa,EAAE,YAAY,KAAc,IAAI,CAAC;AAAA,MAC7E,CAAC;AACD,aAAO,WAAW;AAClB,aAAO,mBAAmB;AAC1B,mBAAa,KAAK,EAAE,QAAQ,OAAO,QAAQ,WAAW,OAAO,WAAW,UAAU,KAAK,CAAC;AAAA,IAC1F,SAAS,KAAK;AAIZ,aAAO,SAAS;AAChB,mBAAa,KAAK,EAAE,QAAQ,OAAO,QAAQ,WAAW,OAAO,WAAW,UAAU,MAAM,CAAC;AAAA,IAC3F;AAAA,EACF;AAEA,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY;AAClC,QAAM,QAA8B;AAAA,IAClC;AAAA,IACA,OAAO,QAAQ;AAAA,IACf,gBAAgB,QAAQ;AAAA,IACxB,iBAAiB,QAAQ;AAAA,IACzB;AAAA,IACA,SAAS;AAAA,EACX;AAEA,SAAO;AAAA,IACL,IAAI,gBAAgB,KAAK,CAAC,MAAM,EAAE,QAAQ;AAAA,IAC1C,gBAAgB,QAAQ;AAAA,IACxB,iBAAiB,QAAQ;AAAA,IACzB,SAAS;AAAA,IACT;AAAA,EACF;AACF;","names":["valueEnd"]}
@@ -5,6 +5,7 @@ import {
5
5
 
6
6
  // src/memory-cache.ts
7
7
  import { AsyncLocalStorage } from "async_hooks";
8
+ var hotCacheReadStats = { validatedHits: 0, fullScans: 0 };
8
9
  var hotCacheByDir = /* @__PURE__ */ new Map();
9
10
  var archiveCacheByDir = /* @__PURE__ */ new Map();
10
11
  function sweepExpiredHotEntries(now) {
@@ -26,20 +27,38 @@ function getCachedMemories(baseDir, currentVersion, keyId = "", ttlMs = 0) {
26
27
  const entry = getVersionedCacheEntry(hotCacheByDir, baseDir, currentVersion, keyId, ttlMs);
27
28
  return entry ? [...entry.memories.values()] : null;
28
29
  }
29
- function setCachedMemories(baseDir, memories, version, keyId = "", ttlMs = 0) {
30
+ function setCachedMemories(baseDir, memories, version, keyId = "", ttlMs = 0, stats) {
30
31
  const map = /* @__PURE__ */ new Map();
31
32
  for (const m of memories) map.set(m.path, m);
32
33
  const now = Date.now();
33
- hotCacheByDir.set(baseDir, { memories: map, version, loadedAt: now, keyId, ttlMs });
34
+ hotCacheByDir.set(baseDir, { memories: map, version, loadedAt: now, keyId, ttlMs, stats });
34
35
  sweepExpiredHotEntries(now);
35
36
  }
37
+ function getHotCacheEntry(baseDir, keyId) {
38
+ const entry = hotCacheByDir.get(baseDir);
39
+ if (!entry || entry.keyId !== keyId || !entry.stats) return null;
40
+ return { memories: entry.memories, stats: entry.stats, loadedAt: entry.loadedAt };
41
+ }
42
+ function promoteHotCacheVersion(baseDir, version, keyId) {
43
+ const entry = hotCacheByDir.get(baseDir);
44
+ if (!entry || entry.keyId !== keyId || version === 0) return null;
45
+ entry.version = version;
46
+ hotCacheReadStats.validatedHits++;
47
+ return [...entry.memories.values()];
48
+ }
36
49
  function updateCacheOnWrite(baseDir, memory, keyId = "") {
37
50
  const entry = hotCacheByDir.get(baseDir);
38
- if (entry && entry.keyId === keyId) entry.memories.set(memory.path, memory);
51
+ if (entry && entry.keyId === keyId) {
52
+ entry.memories.set(memory.path, memory);
53
+ entry.stats = void 0;
54
+ }
39
55
  }
40
56
  function updateCacheOnDelete(baseDir, filePath, keyId = "") {
41
57
  const entry = hotCacheByDir.get(baseDir);
42
- if (entry && entry.keyId === keyId) entry.memories.delete(filePath);
58
+ if (entry && entry.keyId === keyId) {
59
+ entry.memories.delete(filePath);
60
+ entry.stats?.delete(filePath);
61
+ }
43
62
  }
44
63
  function getCachedArchivedMemories(baseDir, currentVersion, keyId = "") {
45
64
  const entry = getVersionedCacheEntry(archiveCacheByDir, baseDir, currentVersion, keyId, 0);
@@ -51,6 +70,7 @@ function setCachedArchivedMemories(baseDir, memories, version, keyId = "") {
51
70
  archiveCacheByDir.set(baseDir, { memories: map, version, loadedAt: Date.now(), keyId, ttlMs: 0 });
52
71
  }
53
72
  var entityCacheByDir = /* @__PURE__ */ new Map();
73
+ var entityCacheStats = { hits: 0, rebuilds: 0 };
54
74
  function normalizeEntitySchemaKey(schemaKey) {
55
75
  return schemaKey ?? "";
56
76
  }
@@ -60,16 +80,13 @@ function entityCacheKeyPrefix(baseDir) {
60
80
  function buildEntityCacheKey(baseDir, schemaKey) {
61
81
  return `${entityCacheKeyPrefix(baseDir)}${normalizeEntitySchemaKey(schemaKey)}`;
62
82
  }
63
- function getCachedEntities(baseDir, currentVersion, schemaKey = "") {
64
- if (currentVersion === 0) return null;
65
- const entry = entityCacheByDir.get(buildEntityCacheKey(baseDir, schemaKey));
66
- if (!entry || entry.version !== currentVersion) return null;
67
- return entry.entities;
83
+ function getCachedEntities(baseDir, cacheKey) {
84
+ return entityCacheByDir.get(buildEntityCacheKey(baseDir, cacheKey)) ?? null;
68
85
  }
69
- function setCachedEntities(baseDir, entities, version, schemaKey = "") {
70
- entityCacheByDir.set(buildEntityCacheKey(baseDir, schemaKey), {
86
+ function setCachedEntities(baseDir, entities, cacheKey, listing) {
87
+ entityCacheByDir.set(buildEntityCacheKey(baseDir, cacheKey), {
71
88
  entities,
72
- version,
89
+ listing,
73
90
  loadedAt: Date.now()
74
91
  });
75
92
  }
@@ -230,6 +247,10 @@ function clearMemoryCache(baseDir) {
230
247
  for (const layer of ALL_CACHE_LAYERS) {
231
248
  layer.clearAll();
232
249
  }
250
+ hotCacheReadStats.validatedHits = 0;
251
+ hotCacheReadStats.fullScans = 0;
252
+ entityCacheStats.hits = 0;
253
+ entityCacheStats.rebuilds = 0;
233
254
  }
234
255
  function clearQmdResultCaches() {
235
256
  qmdSearchCache.clear();
@@ -247,12 +268,16 @@ function getMemoryCacheStats(baseDir) {
247
268
  }
248
269
 
249
270
  export {
271
+ hotCacheReadStats,
250
272
  getCachedMemories,
251
273
  setCachedMemories,
274
+ getHotCacheEntry,
275
+ promoteHotCacheVersion,
252
276
  updateCacheOnWrite,
253
277
  updateCacheOnDelete,
254
278
  getCachedArchivedMemories,
255
279
  setCachedArchivedMemories,
280
+ entityCacheStats,
256
281
  getCachedEntities,
257
282
  setCachedEntities,
258
283
  invalidateCachedEntities,
@@ -272,4 +297,4 @@ export {
272
297
  clearQmdResultCaches,
273
298
  getMemoryCacheStats
274
299
  };
275
- //# sourceMappingURL=chunk-R5S57GRK.js.map
300
+ //# sourceMappingURL=chunk-XSRZM6CQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory-cache.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { EntityFile, MemoryFile } from \"./types.js\";\nimport { clearQmdRecallCache, qmdRecallCacheSize } from \"./qmd-recall-cache.js\";\n\ninterface CacheEntry {\n memories: Map<string, MemoryFile>; // keyed by file path\n version: number;\n loadedAt: number;\n // Secure-store key identity that decrypted these memories (issue #1902, Codex\n // P1). \"\" for plaintext/locked stores. A manager only reads an entry whose\n // keyId matches its own, so a locked/unkeyed instance never sees content\n // another instance decrypted under a key for the same baseDir.\n keyId: string;\n // Effective TTL (ms) this entry was stored under (issue #1902, Codex Medium),\n // so the opportunistic sweep can evict abandoned corpora that are never\n // revisited. 0 = no TTL (never swept by age).\n ttlMs: number;\n // COS-825: per-file stat snapshot (path -> mtime+size) taken when the entry\n // was read from disk. Lets a version-mismatched entry be validated by\n // metadata instead of a full corpus re-read (the write path patches the\n // entry in place, so its contents are usually already current).\n stats?: HotCacheStatsSnapshot;\n}\n\n/** COS-825: one file's entry in a hot-cache stat snapshot. */\nexport interface HotCacheStatEntry {\n mtimeMs: number;\n size: number;\n}\n\n/** COS-825: per-file stat snapshot carried by a hot-cache entry. */\nexport type HotCacheStatsSnapshot = Map<string, HotCacheStatEntry>;\n\n/** COS-825 diagnostics for the hot-memories read path. */\nexport const hotCacheReadStats = { validatedHits: 0, fullScans: 0 };\n\n// Module-level singleton — shared across all StorageManager instances and sessions\nconst hotCacheByDir = new Map<string, CacheEntry>();\nconst archiveCacheByDir = new Map<string, CacheEntry>();\n\n/**\n * Evict every hot entry whose own TTL has elapsed (issue #1902, Codex Medium).\n * Called opportunistically on each set so a long-running process that reads many\n * namespace/temporary roots and never revisits some of them still releases their\n * (potentially hundreds-of-MB) corpora within the TTL, instead of holding them\n * resident until an explicit global clear. O(entries) over a small map.\n */\nfunction sweepExpiredHotEntries(now: number): void {\n for (const [dir, entry] of hotCacheByDir) {\n if (entry.ttlMs > 0 && now - entry.loadedAt > entry.ttlMs) hotCacheByDir.delete(dir);\n }\n}\n\n/**\n * Shared read gate for every versioned cache layer (issue #2481): serve an\n * entry only when its version and secure-store keyId match the caller.\n * `currentVersion === 0` means version tracking is unavailable (tests, fresh\n * installs) and always misses so disk is read. The TTL is a safety net for\n * external filesystem edits that bypass the version sentinel (issue #1902):\n * ttlMs <= 0 disables it, and on expiry the entry is evicted — not just\n * skipped — so a stale dir releases its resident corpus instead of lingering\n * until an explicit clear.\n */\nfunction getVersionedCacheEntry<K, E extends { version: number; keyId: string; loadedAt: number }>(\n cache: Map<K, E>,\n key: K,\n currentVersion: number,\n keyId: string,\n ttlMs: number,\n): E | null {\n if (currentVersion === 0) return null;\n const entry = cache.get(key);\n if (!entry || entry.version !== currentVersion || entry.keyId !== keyId) return null;\n if (ttlMs > 0 && Date.now() - entry.loadedAt > ttlMs) {\n cache.delete(key);\n return null;\n }\n return entry;\n}\n\nexport function getCachedMemories(\n baseDir: string,\n currentVersion: number,\n keyId = \"\",\n ttlMs = 0,\n): MemoryFile[] | null {\n const entry = getVersionedCacheEntry(hotCacheByDir, baseDir, currentVersion, keyId, ttlMs);\n return entry ? [...entry.memories.values()] : null;\n}\n\nexport function setCachedMemories(\n baseDir: string,\n memories: MemoryFile[],\n version: number,\n keyId = \"\",\n ttlMs = 0,\n stats?: HotCacheStatsSnapshot,\n): void {\n const map = new Map<string, MemoryFile>();\n for (const m of memories) map.set(m.path, m);\n const now = Date.now();\n hotCacheByDir.set(baseDir, { memories: map, version, loadedAt: now, keyId, ttlMs, stats });\n // Release abandoned corpora that expired but were never revisited (Codex Medium).\n sweepExpiredHotEntries(now);\n}\n\n/**\n * COS-825: the raw entry for stat validation. Returns the entry only when its\n * secure-store key identity matches AND it carries a stat snapshot; callers\n * validate the snapshot against disk and then promote via\n * {@link promoteHotCacheVersion}.\n */\nexport function getHotCacheEntry(\n baseDir: string,\n keyId: string,\n): {\n memories: ReadonlyMap<string, MemoryFile>;\n stats: HotCacheStatsSnapshot;\n loadedAt: number;\n} | null {\n const entry = hotCacheByDir.get(baseDir);\n if (!entry || entry.keyId !== keyId || !entry.stats) return null;\n return { memories: entry.memories, stats: entry.stats, loadedAt: entry.loadedAt };\n}\n\n/**\n * COS-825: after stat validation passes, re-key the patched entry to the\n * current corpus version and serve it — the equivalent of a fresh full read\n * without the read. Counts as a validated hit.\n */\nexport function promoteHotCacheVersion(baseDir: string, version: number, keyId: string): MemoryFile[] | null {\n const entry = hotCacheByDir.get(baseDir);\n if (!entry || entry.keyId !== keyId || version === 0) return null;\n entry.version = version;\n // loadedAt is deliberately NOT refreshed: the TTL is the recovery bound for\n // edits that preserve size and mtime, and resetting it here would let\n // repeated version churn defer that fresh scan indefinitely (COS-825 review\n // round 3).\n hotCacheReadStats.validatedHits++;\n return [...entry.memories.values()];\n}\n\nexport function updateCacheOnWrite(baseDir: string, memory: MemoryFile, keyId = \"\"): void {\n const entry = hotCacheByDir.get(baseDir);\n // Only mutate an entry that belongs to THIS key identity (issue #1902, Codex\n // Medium). A concurrent differently-keyed manager may have replaced the\n // single hotCacheByDir slot during an awaited parse; inserting our decrypted\n // MemoryFile into its entry would leak plaintext across the key boundary.\n if (entry && entry.keyId === keyId) {\n entry.memories.set(memory.path, memory);\n // COS-825 review: a peer can rewrite the same path between our content\n // write and any stat we take, which would let the snapshot vouch the\n // peer's bytes for our content on every later validation. Drop the\n // snapshot instead: the entry keeps serving at its current version, and\n // the next version churn costs the same full re-read as before this\n // optimization. Never a false pass.\n entry.stats = undefined;\n }\n}\n\nexport function updateCacheOnDelete(baseDir: string, filePath: string, keyId = \"\"): void {\n const entry = hotCacheByDir.get(baseDir);\n if (entry && entry.keyId === keyId) {\n entry.memories.delete(filePath);\n entry.stats?.delete(filePath);\n }\n}\n// Archive cache — same pattern, separate store\nexport function getCachedArchivedMemories(\n baseDir: string,\n currentVersion: number,\n keyId = \"\",\n): MemoryFile[] | null {\n // ttlMs 0: the archive cache has no age TTL; it is version-keyed and cleared\n // via invalidation.\n const entry = getVersionedCacheEntry(archiveCacheByDir, baseDir, currentVersion, keyId, 0);\n return entry ? [...entry.memories.values()] : null;\n}\n\nexport function setCachedArchivedMemories(\n baseDir: string,\n memories: MemoryFile[],\n version: number,\n keyId = \"\",\n): void {\n const map = new Map<string, MemoryFile>();\n for (const m of memories) map.set(m.path, m);\n // ttlMs: 0 — the archive cache has no age TTL; it is version-keyed and cleared\n // via invalidation. The field satisfies the shared CacheEntry shape (#1902).\n archiveCacheByDir.set(baseDir, { memories: map, version, loadedAt: Date.now(), keyId, ttlMs: 0 });\n}\n\n// Entity cache — same pattern as memory cache, but keyed by schema-aware parse inputs.\n// COS-825: validity is the entities-dir listing snapshot (name, mtime, size)\n// carried by the entry, NOT the memory-status version — status churns with\n// unrelated memory lifecycle writes (supersede/archive/cleanup) and used to\n// bust this cache on every recall under observe traffic. Entity-file changes\n// always change the listing (and bump the entity-mutation version, which is\n// part of the caller's cache key).\ninterface EntityCacheEntry {\n entities: EntityFile[];\n loadedAt: number;\n /** Snapshot of the entities dir at build time: name -> `${mtimeMs}:${size}`. */\n listing: ReadonlyMap<string, string>;\n}\n\nconst entityCacheByDir = new Map<string, EntityCacheEntry>();\n\n/** COS-825 diagnostics: a hit is a served cache entry whose listing validated. */\nexport const entityCacheStats = { hits: 0, rebuilds: 0 };\n\n/**\n * Single normalization point for the entity-cache schema key (issue #1535).\n * BOTH the set/get key builder and the prefix invalidation derive from here so\n * `undefined` vs `\"\"` (or any future normalization rule) can never diverge\n * between the write path and the invalidate path (rule 38 cousin).\n */\nfunction normalizeEntitySchemaKey(schemaKey: string | undefined): string {\n return schemaKey ?? \"\";\n}\n\n/** Prefix shared by every entity-cache key for a dir, regardless of schemaKey. */\nfunction entityCacheKeyPrefix(baseDir: string): string {\n return `${baseDir}\\u0000`;\n}\n\nfunction buildEntityCacheKey(baseDir: string, schemaKey?: string): string {\n return `${entityCacheKeyPrefix(baseDir)}${normalizeEntitySchemaKey(schemaKey)}`;\n}\n\nexport function getCachedEntities(baseDir: string, cacheKey: string): EntityCacheEntry | null {\n return entityCacheByDir.get(buildEntityCacheKey(baseDir, cacheKey)) ?? null;\n}\n\nexport function setCachedEntities(\n baseDir: string,\n entities: EntityFile[],\n cacheKey: string,\n listing: ReadonlyMap<string, string>,\n): void {\n entityCacheByDir.set(buildEntityCacheKey(baseDir, cacheKey), {\n entities,\n listing,\n loadedAt: Date.now(),\n });\n}\n\nexport function invalidateCachedEntities(baseDir: string): void {\n const prefix = entityCacheKeyPrefix(baseDir);\n for (const key of entityCacheByDir.keys()) {\n if (key.startsWith(prefix)) entityCacheByDir.delete(key);\n }\n}\n\n// Derived caches — pre-filtered views invalidated alongside the main cache.\n// These avoid O(146K) filter+map on every verified recall/rules call.\ninterface DerivedCacheEntry<T> {\n data: T;\n version: number; // matches the hot cache version it was derived from\n keyId: string; // secure-store key identity of the corpus it was derived from (#1902)\n loadedAt: number; // build time — bounds staleness from external edits via ttlMs (#1902)\n}\n\nconst episodeMapByDir = new Map<string, DerivedCacheEntry<Map<string, MemoryFile>>>();\nconst ruleMemoriesByDir = new Map<string, DerivedCacheEntry<{ all: MemoryFile[]; byId: Map<string, MemoryFile> }>>();\n\nexport function getCachedEpisodeMap(\n baseDir: string,\n currentVersion: number,\n keyId = \"\",\n ttlMs = 0,\n): Map<string, MemoryFile> | null {\n const entry = getVersionedCacheEntry(episodeMapByDir, baseDir, currentVersion, keyId, ttlMs);\n return entry ? entry.data : null;\n}\n\n/** Build and cache the episode memory map from the full memory list. */\nexport function setCachedEpisodeMap(\n baseDir: string,\n memories: MemoryFile[],\n version: number,\n cache = true,\n keyId = \"\",\n): Map<string, MemoryFile> {\n const map = new Map<string, MemoryFile>();\n for (const m of memories) {\n if (m.frontmatter.status === \"archived\" || m.frontmatter.status === \"forgotten\") continue;\n if (m.frontmatter.memoryKind !== \"episode\") continue;\n map.set(m.frontmatter.id, m);\n }\n if (cache) episodeMapByDir.set(baseDir, { data: map, version, keyId, loadedAt: Date.now() });\n return map;\n}\n\n/** Get pre-filtered rule memories. Derived from hot cache. */\nexport function getCachedRuleMemories(\n baseDir: string,\n currentVersion: number,\n keyId = \"\",\n ttlMs = 0,\n): { all: MemoryFile[]; byId: Map<string, MemoryFile> } | null {\n const entry = getVersionedCacheEntry(ruleMemoriesByDir, baseDir, currentVersion, keyId, ttlMs);\n return entry ? entry.data : null;\n}\n\n/** Build and cache the rule memories from the full memory list. */\nexport function setCachedRuleMemories(\n baseDir: string,\n memories: MemoryFile[],\n version: number,\n cache = true,\n keyId = \"\",\n): { all: MemoryFile[]; byId: Map<string, MemoryFile> } {\n const byId = new Map<string, MemoryFile>();\n const all: MemoryFile[] = [];\n for (const m of memories) {\n byId.set(m.frontmatter.id, m);\n if (\n m.frontmatter.category === \"rule\" &&\n m.frontmatter.status !== \"archived\" &&\n m.frontmatter.status !== \"forgotten\"\n ) {\n all.push(m);\n }\n }\n const result = { all, byId };\n if (cache) ruleMemoriesByDir.set(baseDir, { data: result, version, keyId, loadedAt: Date.now() });\n return result;\n}\n\n// QMD search result cache — short-lived (60s TTL) to avoid stale results\n// while reducing redundant daemon calls for repeated/similar queries.\ninterface QmdCacheEntry {\n results: unknown[];\n cachedAt: number;\n}\nconst QMD_CACHE_TTL_MS = 60_000;\nconst qmdSearchCache = new Map<string, QmdCacheEntry>();\n\nconst qmdSearchCacheRecallTtl = new AsyncLocalStorage<number>();\n\nexport async function runInQmdSearchCacheRecallScope<T>(\n ttlMs: number,\n run: () => Promise<T>,\n): Promise<T> {\n const ttl = Number.isFinite(ttlMs)\n ? Math.max(QMD_CACHE_TTL_MS, Math.floor(ttlMs))\n : QMD_CACHE_TTL_MS;\n return qmdSearchCacheRecallTtl.run(ttl, run);\n}\n\nexport function getCachedQmdSearch(cacheKey: string): unknown[] | null {\n const entry = qmdSearchCache.get(cacheKey);\n if (!entry) return null;\n const ttl = qmdSearchCacheRecallTtl.getStore() ?? QMD_CACHE_TTL_MS;\n // A concurrent recall can still use an entry that is too old for this recall.\n if (Date.now() - entry.cachedAt > ttl) return null;\n return entry.results;\n}\n\nexport function setCachedQmdSearch(cacheKey: string, results: unknown[]): void {\n qmdSearchCache.delete(cacheKey);\n qmdSearchCache.set(cacheKey, { results, cachedAt: Date.now() });\n if (qmdSearchCache.size > 200) {\n const oldest = qmdSearchCache.keys().next();\n if (!oldest.done) qmdSearchCache.delete(oldest.value);\n }\n}\n\n/**\n * Mutation scopes (issue #1904). A cache layer declares (via `evictOn`) which\n * of these mutation kinds evict it, so the invalidation chokepoint can clear\n * only the layers a given write actually affects instead of nuking every\n * layer on every write (the permanently-cold-cache regression #1904 fixes).\n */\nexport type MemoryMutationScope =\n | \"memory-create\" // a new memory doc added; no existing doc's recall-visibility changes\n | \"memory-mutate\" // existing doc changed/moved/removed/status-changed (update, supersede,\n // archive, invalidate, frontmatter, cold-tier change, bulk delete)\n | \"entity-write\" // an entity file changed\n | \"secure-key-change\"; // encryption key rotated; everything is now unreadable → evict all\n\n/**\n * Cache-layer registry (issue #1535).\n *\n * EVERY process-level cache that can serve memory-derived content is\n * enumerated here, and the single invalidation chokepoint\n * (`invalidateAllForDir`) iterates this list. Adding a new cache layer to\n * this module (or qmd-recall-cache.ts) REQUIRES registering it here —\n * otherwise mutations will never invalidate it (the exact bug this registry\n * exists to prevent) and the enumerate-all-layers fitness test in\n * tests/cache-invalidation-coherence.test.ts fails.\n */\nexport interface MemoryCacheLayer {\n /** Stable identifier used by tests and diagnostics. */\n readonly name: string;\n /** \"dir\" layers evict only entries for the given baseDir. \"global\" layers\n * are fully cleared on any mutation: their keys embed queries, namespaces,\n * and strategies rather than a storage dir, so a per-dir selective clear\n * is not possible without recording the dir in each entry. Full clear is\n * the simple-and-correct choice — these caches are re-warmable\n * (issue #1535, implementation guide option (b)). */\n readonly scope: \"dir\" | \"global\";\n /** Which mutation scopes evict this layer (issue #1904). A `memory-create`\n * only refreshes the full-memory-list views (hot + derived episode/rule); a\n * `memory-mutate`/`entity-write`/`secure-key-change` evicts every layer whose\n * content it can affect. Adding a layer REQUIRES declaring this. */\n readonly evictOn: Partial<Record<MemoryMutationScope, true>>;\n /** Evict entries for baseDir (\"dir\" scope) or everything (\"global\" scope). */\n readonly invalidateForDir: (baseDir: string) => void;\n /** Evict every entry across all dirs. */\n readonly clearAll: () => void;\n /** True when the layer still holds entries for baseDir (\"dir\" scope) or\n * any entries at all (\"global\" scope). */\n readonly hasEntriesFor: (baseDir: string) => boolean;\n}\n\nexport const ALL_CACHE_LAYERS: readonly MemoryCacheLayer[] = [\n {\n name: \"hot-memories\",\n scope: \"dir\",\n evictOn: { \"memory-create\": true, \"memory-mutate\": true, \"secure-key-change\": true },\n invalidateForDir: (baseDir) => void hotCacheByDir.delete(baseDir),\n clearAll: () => hotCacheByDir.clear(),\n hasEntriesFor: (baseDir) => hotCacheByDir.has(baseDir),\n },\n {\n name: \"archive-memories\",\n scope: \"dir\",\n evictOn: { \"memory-mutate\": true, \"secure-key-change\": true },\n invalidateForDir: (baseDir) => void archiveCacheByDir.delete(baseDir),\n clearAll: () => archiveCacheByDir.clear(),\n hasEntriesFor: (baseDir) => archiveCacheByDir.has(baseDir),\n },\n {\n name: \"entities\",\n scope: \"dir\",\n evictOn: { \"entity-write\": true, \"secure-key-change\": true },\n invalidateForDir: (baseDir) => invalidateCachedEntities(baseDir),\n clearAll: () => entityCacheByDir.clear(),\n hasEntriesFor: (baseDir) => {\n const prefix = entityCacheKeyPrefix(baseDir);\n for (const key of entityCacheByDir.keys()) {\n if (key.startsWith(prefix)) return true;\n }\n return false;\n },\n },\n {\n name: \"derived-episode-map\",\n scope: \"dir\",\n evictOn: { \"memory-create\": true, \"memory-mutate\": true, \"secure-key-change\": true },\n invalidateForDir: (baseDir) => void episodeMapByDir.delete(baseDir),\n clearAll: () => episodeMapByDir.clear(),\n hasEntriesFor: (baseDir) => episodeMapByDir.has(baseDir),\n },\n {\n name: \"derived-rule-memories\",\n scope: \"dir\",\n evictOn: { \"memory-create\": true, \"memory-mutate\": true, \"secure-key-change\": true },\n invalidateForDir: (baseDir) => void ruleMemoriesByDir.delete(baseDir),\n clearAll: () => ruleMemoriesByDir.clear(),\n hasEntriesFor: (baseDir) => ruleMemoriesByDir.has(baseDir),\n },\n {\n name: \"qmd-search\",\n scope: \"global\",\n evictOn: { \"memory-mutate\": true, \"entity-write\": true, \"secure-key-change\": true },\n invalidateForDir: () => qmdSearchCache.clear(),\n clearAll: () => qmdSearchCache.clear(),\n hasEntriesFor: () => qmdSearchCache.size > 0,\n },\n {\n name: \"qmd-recall\",\n scope: \"global\",\n evictOn: { \"memory-mutate\": true, \"entity-write\": true, \"secure-key-change\": true },\n invalidateForDir: () => clearQmdRecallCache(),\n clearAll: () => clearQmdRecallCache(),\n hasEntriesFor: () => qmdRecallCacheSize() > 0,\n },\n];\n\n/**\n * The single invalidation chokepoint (issue #1535, rule 37).\n *\n * Every memory/entity mutation path must route through this function —\n * storage.ts calls it from its internal invalidation funnels\n * (invalidateAllMemoriesCache / invalidateColdMemoriesCache /\n * bumpMemoryStatusVersion / setSecureStoreKey). Nothing may clear an\n * individual layer ad hoc: partial clears are how the stale-recall bug\n * happened (qmdRecallCache was never invalidated on mutations, so recall\n * served pre-edit bundles for the remainder of its fresh/stale TTL window).\n */\nexport function invalidateAllForDir(baseDir: string): void {\n for (const layer of ALL_CACHE_LAYERS) {\n layer.invalidateForDir(baseDir);\n }\n}\n\n/**\n * Scope-aware invalidation chokepoint (issue #1904). Evicts only the layers\n * whose `evictOn` includes `scope`, so the highest-frequency write\n * (`memory-create`, fired continuously by extraction) stops nuking the QMD\n * result caches and the version-keyed entity cache it cannot affect. This is\n * the single scoped entry point — like `invalidateAllForDir`, it iterates the\n * `ALL_CACHE_LAYERS` registry rather than clearing any layer ad hoc, so the\n * single-chokepoint invariant (#1535) holds: a new layer only participates by\n * declaring `evictOn`.\n */\nexport function invalidateForScope(baseDir: string, scope: MemoryMutationScope): void {\n for (const layer of ALL_CACHE_LAYERS) {\n if (layer.evictOn[scope]) layer.invalidateForDir(baseDir);\n }\n}\n\n/**\n * Companion to {@link invalidateForScope} for the single-file write fast path\n * (issue #1902 + #1904): it patches the hot-memories entry in place and\n * re-keys it, so this evicts every OTHER layer the scope would clear but leaves\n * hot-memories alone. A `memory-create` thus evicts only the derived\n * episode/rule views (hot patched, QMD/entities/archive kept warm), which is\n * the whole point of #1904 — a create must not evict the QMD result caches.\n */\nexport function invalidateForScopeExceptHot(baseDir: string, scope: MemoryMutationScope): void {\n for (const layer of ALL_CACHE_LAYERS) {\n if (layer.name === \"hot-memories\") continue;\n if (layer.evictOn[scope]) layer.invalidateForDir(baseDir);\n }\n}\n\n/**\n * Invalidate every cache layer for `baseDir` EXCEPT the hot-memories layer\n * (issue #1902). Single-file write paths use this instead of\n * `invalidateAllForDir` because they patch the hot-memories entry in place\n * (via `updateCacheOnWrite`/`updateCacheOnDelete`) and re-key it to the bumped\n * version — so dropping it here would defeat the whole warm-cache fast path.\n * The derived episode/rule views and the global QMD caches are cheap to\n * rebuild and are not patched, so they are still evicted here. Every other\n * layer remains reachable for the wholesale `invalidateAllForDir` /\n * `clearMemoryCache` chokepoint used by bulk/ambiguous mutations.\n */\nexport function invalidateDerivedAndGlobalForDir(baseDir: string): void {\n // Preserve the layers a single-file write intentionally keeps warm (issue\n // #1902, Codex Medium): hot-memories is patched + re-keyed in place; the\n // entities layer is keyed on memory-status, which plain create/content writes\n // deliberately do NOT bump (so entity retrieval stays warm); and the\n // archive-memories layer is version-keyed on the archive tier, untouched by a\n // hot-tier write. Evict ONLY the derived (episode/rule) and global (QMD) views.\n for (const layer of ALL_CACHE_LAYERS) {\n if (\n layer.name === \"hot-memories\" ||\n layer.name === \"entities\" ||\n layer.name === \"archive-memories\"\n ) {\n continue;\n }\n layer.invalidateForDir(baseDir);\n }\n}\n\nexport function clearMemoryCache(baseDir?: string): void {\n if (baseDir) {\n invalidateAllForDir(baseDir);\n return;\n }\n for (const layer of ALL_CACHE_LAYERS) {\n layer.clearAll();\n }\n hotCacheReadStats.validatedHits = 0;\n hotCacheReadStats.fullScans = 0;\n entityCacheStats.hits = 0;\n entityCacheStats.rebuilds = 0;\n}\n\n/**\n * Clear ONLY the two global QMD result caches (qmd-search + qmd-recall), leaving\n * every dir-scoped layer (hot/archive/entities/derived) untouched. Called after\n * a successful QMD maintenance update+embed (#1904, Codex): a newly-persisted\n * fact becomes searchable at that moment, so any cached pre-index recall/search\n * bundle is now stale and must not be served. This lets the create path keep the\n * QMD caches warm during index lag (perf win) while guaranteeing invalidation\n * the moment the fact is actually indexed — no extended stale window.\n */\nexport function clearQmdResultCaches(): void {\n qmdSearchCache.clear();\n clearQmdRecallCache();\n}\n\nexport function getMemoryCacheStats(baseDir: string): {\n hotSize: number;\n archiveSize: number;\n hotVersion: number | null;\n archiveVersion: number | null;\n} {\n const hot = hotCacheByDir.get(baseDir);\n const archive = archiveCacheByDir.get(baseDir);\n return {\n hotSize: hot?.memories.size ?? 0,\n archiveSize: archive?.memories.size ?? 0,\n hotVersion: hot?.version ?? null,\n archiveVersion: archive?.version ?? null,\n };\n}\n"],"mappings":";;;;;;AAAA,SAAS,yBAAyB;AAkC3B,IAAM,oBAAoB,EAAE,eAAe,GAAG,WAAW,EAAE;AAGlE,IAAM,gBAAgB,oBAAI,IAAwB;AAClD,IAAM,oBAAoB,oBAAI,IAAwB;AAStD,SAAS,uBAAuB,KAAmB;AACjD,aAAW,CAAC,KAAK,KAAK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AAEO,SAAS,iBAAiB,SAAwB;AACvD,MAAI,SAAS;AACX,wBAAoB,OAAO;AAC3B;AAAA,EACF;AACA,aAAW,SAAS,kBAAkB;AACpC,UAAM,SAAS;AAAA,EACjB;AACA,oBAAkB,gBAAgB;AAClC,oBAAkB,YAAY;AAC9B,mBAAiB,OAAO;AACxB,mBAAiB,WAAW;AAC9B;AAWO,SAAS,uBAA6B;AAC3C,iBAAe,MAAM;AACrB,sBAAoB;AACtB;AAEO,SAAS,oBAAoB,SAKlC;AACA,QAAM,MAAM,cAAc,IAAI,OAAO;AACrC,QAAM,UAAU,kBAAkB,IAAI,OAAO;AAC7C,SAAO;AAAA,IACL,SAAS,KAAK,SAAS,QAAQ;AAAA,IAC/B,aAAa,SAAS,SAAS,QAAQ;AAAA,IACvC,YAAY,KAAK,WAAW;AAAA,IAC5B,gBAAgB,SAAS,WAAW;AAAA,EACtC;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createSearchBackend
3
- } from "./chunk-AXSQGJSG.js";
3
+ } from "./chunk-J7RQ3RP7.js";
4
4
  import {
5
5
  reportSearchDegradation
6
6
  } from "./chunk-FZF7JX76.js";
@@ -652,4 +652,4 @@ export {
652
652
  normalizeQmdResultPath,
653
653
  resolveNamespaceResultPath
654
654
  };
655
- //# sourceMappingURL=chunk-OA7YDB6A.js.map
655
+ //# sourceMappingURL=chunk-XZLCAL5O.js.map