@remnic/core 9.7.13 → 9.7.15

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 (358) hide show
  1. package/dist/access-admin-ops-surface.d.ts +6 -6
  2. package/dist/access-admin-ops-surface.js +22 -22
  3. package/dist/access-boundary.d.ts +6 -6
  4. package/dist/access-boundary.js +23 -23
  5. package/dist/access-cli.js +51 -51
  6. package/dist/access-http.d.ts +6 -6
  7. package/dist/access-http.js +28 -28
  8. package/dist/access-identity-continuity-surface.d.ts +5 -5
  9. package/dist/access-identity-continuity-surface.js +22 -22
  10. package/dist/access-lcm-surface.d.ts +6 -6
  11. package/dist/access-lcm-surface.js +22 -22
  12. package/dist/access-mcp.d.ts +6 -6
  13. package/dist/access-mcp.js +27 -27
  14. package/dist/access-observe-write-surface.d.ts +6 -6
  15. package/dist/access-observe-write-surface.js +22 -22
  16. package/dist/access-operations-batch.js +25 -25
  17. package/dist/access-operations.d.ts +6 -6
  18. package/dist/access-operations.js +26 -26
  19. package/dist/access-recall-surface.d.ts +6 -6
  20. package/dist/access-recall-surface.js +22 -22
  21. package/dist/{access-service-tHd3eQpd.d.ts → access-service-DpcYZ9Nl.d.ts} +4 -4
  22. package/dist/access-service.d.ts +6 -6
  23. package/dist/access-service.js +22 -22
  24. package/dist/access-surface-catalog.d.ts +6 -6
  25. package/dist/action-confidence.d.ts +1 -1
  26. package/dist/active-memory-bridge.d.ts +1 -1
  27. package/dist/active-recall.d.ts +1 -1
  28. package/dist/active-recall.js +1 -1
  29. package/dist/behavior-learner.d.ts +1 -1
  30. package/dist/behavior-signals.d.ts +1 -1
  31. package/dist/bootstrap.d.ts +5 -5
  32. package/dist/briefing.d.ts +2 -2
  33. package/dist/briefing.js +6 -6
  34. package/dist/buffer-surprise-report.d.ts +1 -1
  35. package/dist/buffer.d.ts +2 -2
  36. package/dist/bulk-import/index.d.ts +3 -3
  37. package/dist/calibration.d.ts +1 -1
  38. package/dist/capabilities.d.ts +1 -1
  39. package/dist/{capsule-merge-Z2HUO6IK.js → capsule-merge-5KKJQBWQ.js} +4 -4
  40. package/dist/{catalog-DEMiw6HZ.d.ts → catalog-C9444P10.d.ts} +1 -1
  41. package/dist/causal-behavior.d.ts +1 -1
  42. package/dist/causal-behavior.js +2 -2
  43. package/dist/causal-chain.js +2 -2
  44. package/dist/causal-consolidation.d.ts +1 -1
  45. package/dist/causal-consolidation.js +9 -9
  46. package/dist/causal-retrieval.js +2 -2
  47. package/dist/causal-trajectory-graph.d.ts +1 -1
  48. package/dist/causal-trajectory-graph.js +1 -1
  49. package/dist/causal-trajectory.js +1 -1
  50. package/dist/{chunk-2RSL6YRA.js → chunk-2AZXIZEN.js} +3 -3
  51. package/dist/{chunk-OBMR4VIX.js → chunk-2S6QHZGJ.js} +186 -15
  52. package/dist/chunk-2S6QHZGJ.js.map +1 -0
  53. package/dist/{chunk-5S7Z5SHA.js → chunk-34RC5RT7.js} +2 -2
  54. package/dist/{chunk-JKLJ6A7W.js → chunk-3D6AFGQR.js} +2 -2
  55. package/dist/{chunk-2AL7N3BH.js → chunk-3IY64MV6.js} +4 -2
  56. package/dist/chunk-3IY64MV6.js.map +1 -0
  57. package/dist/{chunk-VZ5OJE4X.js → chunk-5VQJBH2G.js} +2 -2
  58. package/dist/{chunk-N3JDIRBW.js → chunk-74F5STS4.js} +2 -2
  59. package/dist/{chunk-OC35KQIN.js → chunk-A5UXZRRM.js} +3 -3
  60. package/dist/{chunk-OKUEZOGW.js → chunk-AITCS2RC.js} +2 -2
  61. package/dist/{chunk-7XGSIUP5.js → chunk-AJLLIIML.js} +1 -1
  62. package/dist/{chunk-CE3GMHT4.js → chunk-BS4SGLWV.js} +2 -2
  63. package/dist/{chunk-2V5QI6NQ.js → chunk-DCFV7A7H.js} +6 -6
  64. package/dist/{chunk-I3GKTDM2.js → chunk-DMSDUGDM.js} +3 -3
  65. package/dist/{chunk-D4TLWDYR.js → chunk-DPAENM7O.js} +2 -2
  66. package/dist/{chunk-AHLPZ2SF.js → chunk-DYP3YYJJ.js} +7 -3
  67. package/dist/chunk-DYP3YYJJ.js.map +1 -0
  68. package/dist/{chunk-7MW3CVLD.js → chunk-DZKHSDOM.js} +2 -2
  69. package/dist/{chunk-HG32URJJ.js → chunk-E6CBU7XP.js} +2 -2
  70. package/dist/{chunk-675YU5IK.js → chunk-EHCONI6E.js} +2 -2
  71. package/dist/{chunk-NVXQTRBL.js → chunk-FDCTQWLW.js} +2 -2
  72. package/dist/{chunk-PA6DMYEK.js → chunk-FIJUY7GG.js} +9 -9
  73. package/dist/{chunk-UTRJFDP2.js → chunk-FNZQGN76.js} +2 -2
  74. package/dist/{chunk-V53GJUSL.js → chunk-G4CN3ZXL.js} +6 -6
  75. package/dist/{chunk-IQULRIZM.js → chunk-G6XXLKC5.js} +3 -3
  76. package/dist/{chunk-CLFY35ED.js → chunk-HDTQVNWD.js} +3 -3
  77. package/dist/{chunk-TMGK6YE7.js → chunk-HF77M34J.js} +2 -2
  78. package/dist/{chunk-6N7R7TR2.js → chunk-INELTPRG.js} +15 -1
  79. package/dist/chunk-INELTPRG.js.map +1 -0
  80. package/dist/{chunk-ZC3HG22I.js → chunk-JREB6UFH.js} +2 -2
  81. package/dist/{chunk-TRH533CA.js → chunk-K7LOWSLU.js} +38 -9
  82. package/dist/chunk-K7LOWSLU.js.map +1 -0
  83. package/dist/{chunk-TWGGNUWJ.js → chunk-KDXVOFYY.js} +2 -2
  84. package/dist/{chunk-RT7IP3D3.js → chunk-KSNVDPDF.js} +2 -2
  85. package/dist/{chunk-ZIDSD6VC.js → chunk-LRNMRXJO.js} +2 -2
  86. package/dist/{chunk-QPZCAVDC.js → chunk-LZOV7MX7.js} +12 -12
  87. package/dist/{chunk-VY6LKKVN.js → chunk-NWTGD4AN.js} +6 -1
  88. package/dist/chunk-NWTGD4AN.js.map +1 -0
  89. package/dist/{chunk-Z6WN2KSH.js → chunk-OAZVR2BV.js} +3 -3
  90. package/dist/{chunk-KQMKF4G2.js → chunk-OVJ2HIPE.js} +21 -21
  91. package/dist/{chunk-OCY3CRPG.js → chunk-PBNZVPFS.js} +3 -3
  92. package/dist/{chunk-G5PVJJRA.js → chunk-PBSAPHHA.js} +1 -1
  93. package/dist/chunk-PBSAPHHA.js.map +1 -0
  94. package/dist/{chunk-XVLEGMJI.js → chunk-PLQE6MJA.js} +2 -2
  95. package/dist/{chunk-NKCPUHCI.js → chunk-PQVK2S3J.js} +2 -2
  96. package/dist/{chunk-OIFZII6J.js → chunk-Q5WG43OP.js} +3 -3
  97. package/dist/{chunk-YI7XUXLX.js → chunk-QKQYXZVS.js} +28 -26
  98. package/dist/chunk-QKQYXZVS.js.map +1 -0
  99. package/dist/{chunk-XUQUBZ7O.js → chunk-QQGPUKMT.js} +2 -2
  100. package/dist/{chunk-XUQUBZ7O.js.map → chunk-QQGPUKMT.js.map} +1 -1
  101. package/dist/{chunk-WU46YPY6.js → chunk-RAR2BSEM.js} +1 -1
  102. package/dist/{chunk-WU46YPY6.js.map → chunk-RAR2BSEM.js.map} +1 -1
  103. package/dist/{chunk-3SIC3E65.js → chunk-RO4LQGT3.js} +2 -2
  104. package/dist/{chunk-BQTSGK5Y.js → chunk-RVZRYUQH.js} +2 -2
  105. package/dist/{chunk-T6U7HDIY.js → chunk-T7Y5KPLN.js} +2 -2
  106. package/dist/{chunk-HLTAPHZZ.js → chunk-UDQUSU27.js} +2 -2
  107. package/dist/{chunk-2ZPQUTMW.js → chunk-VDW4VU7B.js} +5 -5
  108. package/dist/{chunk-ZRXSHGXT.js → chunk-VJVNLNDQ.js} +3 -3
  109. package/dist/{chunk-UTZW3X2R.js → chunk-XDSXEKYK.js} +2 -2
  110. package/dist/{chunk-X47LWMKA.js → chunk-XMMESCPD.js} +26 -1
  111. package/dist/chunk-XMMESCPD.js.map +1 -0
  112. package/dist/{chunk-FUUF7FMX.js → chunk-ZHIVCODT.js} +2 -2
  113. package/dist/{cli-D8Tsa4Sh.d.ts → cli-Cd5fMmhq.d.ts} +5 -5
  114. package/dist/cli.d.ts +8 -8
  115. package/dist/cli.js +42 -42
  116. package/dist/compounding/engine.d.ts +2 -2
  117. package/dist/compounding/engine.js +6 -6
  118. package/dist/compounding/preference-consolidator.d.ts +1 -1
  119. package/dist/compression-optimizer.d.ts +1 -1
  120. package/dist/config.d.ts +1 -1
  121. package/dist/config.js +1 -1
  122. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  123. package/dist/connectors/codex-materialize-runner.js +6 -6
  124. package/dist/connectors/codex-materialize.d.ts +1 -1
  125. package/dist/connectors/index.d.ts +1 -1
  126. package/dist/connectors/index.js +6 -6
  127. package/dist/consolidation-provenance-check.d.ts +2 -2
  128. package/dist/consolidation-provenance-check.js +4 -4
  129. package/dist/consolidation-undo.d.ts +2 -2
  130. package/dist/consolidation-undo.js +3 -3
  131. package/dist/contradiction/index.d.ts +2 -2
  132. package/dist/conversation-index/backend.d.ts +1 -1
  133. package/dist/conversation-index/chunker.d.ts +1 -1
  134. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  135. package/dist/conversation-index/indexer.d.ts +1 -1
  136. package/dist/conversation-index/search.d.ts +1 -1
  137. package/dist/day-summary.d.ts +1 -1
  138. package/dist/delinearize.d.ts +1 -1
  139. package/dist/direct-answer-wiring.d.ts +1 -1
  140. package/dist/direct-answer.d.ts +1 -1
  141. package/dist/embedding-fallback.d.ts +1 -1
  142. package/dist/enrichment/index.d.ts +1 -1
  143. package/dist/entity-retrieval.d.ts +2 -2
  144. package/dist/entity-retrieval.js +6 -6
  145. package/dist/entity-schema.d.ts +1 -1
  146. package/dist/explicit-capture.d.ts +5 -5
  147. package/dist/extraction-faithfulness.d.ts +1 -1
  148. package/dist/extraction-judge-telemetry.d.ts +1 -1
  149. package/dist/extraction-judge-training.d.ts +1 -1
  150. package/dist/extraction-judge.d.ts +1 -1
  151. package/dist/extraction.d.ts +1 -1
  152. package/dist/extraction.js +2 -2
  153. package/dist/fallback-llm.d.ts +1 -1
  154. package/dist/graph-dashboard-diff.d.ts +1 -1
  155. package/dist/graph-dashboard-key.d.ts +1 -1
  156. package/dist/graph-dashboard-parser.d.ts +1 -1
  157. package/dist/{graph-edge-decay-FO7AM4UR.js → graph-edge-decay-IOGBBAGC.js} +3 -3
  158. package/dist/graph-edge-reinforcement.d.ts +1 -1
  159. package/dist/graph-snapshot.d.ts +1 -1
  160. package/dist/graph-snapshot.js +2 -2
  161. package/dist/graph.d.ts +55 -10
  162. package/dist/graph.js +1 -1
  163. package/dist/identity-continuity.d.ts +1 -1
  164. package/dist/importance.d.ts +1 -1
  165. package/dist/importers/index.d.ts +1 -1
  166. package/dist/in-flight-reads.d.ts +1 -1
  167. package/dist/index.d.ts +14 -14
  168. package/dist/index.js +51 -51
  169. package/dist/intent.d.ts +1 -1
  170. package/dist/lcm/engine.d.ts +1 -1
  171. package/dist/lcm/index.d.ts +1 -1
  172. package/dist/lcm/tools.d.ts +1 -1
  173. package/dist/lifecycle.d.ts +1 -1
  174. package/dist/live-connectors-runner.d.ts +1 -1
  175. package/dist/local-llm.d.ts +1 -1
  176. package/dist/local-llm.js +1 -1
  177. package/dist/local-model-endpoint.d.ts +1 -1
  178. package/dist/maintenance/memory-governance.d.ts +1 -1
  179. package/dist/maintenance/memory-governance.js +6 -6
  180. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +6 -6
  181. package/dist/maintenance/rebuild-memory-projection.js +7 -7
  182. package/dist/mcp-memory-inspector-app.d.ts +6 -6
  183. package/dist/memory-action-policy.d.ts +1 -1
  184. package/dist/memory-cache.d.ts +44 -2
  185. package/dist/memory-cache.js +7 -1
  186. package/dist/memory-corpus-version.js +2 -2
  187. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  188. package/dist/memory-projection-store.d.ts +1 -1
  189. package/dist/memory-provenance.d.ts +1 -1
  190. package/dist/memory-worth-outcomes.d.ts +2 -2
  191. package/dist/models-json.d.ts +1 -1
  192. package/dist/namespaces/migrate.d.ts +3 -3
  193. package/dist/namespaces/migrate.js +15 -15
  194. package/dist/namespaces/principal.d.ts +1 -1
  195. package/dist/namespaces/search.d.ts +1 -1
  196. package/dist/namespaces/search.js +9 -9
  197. package/dist/namespaces/storage.d.ts +3 -3
  198. package/dist/namespaces/storage.js +6 -6
  199. package/dist/native-knowledge.d.ts +1 -1
  200. package/dist/operator-toolkit.d.ts +2 -2
  201. package/dist/operator-toolkit.js +21 -21
  202. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  203. package/dist/orchestration/maintenance.d.ts +2 -2
  204. package/dist/orchestration/maintenance.js +8 -8
  205. package/dist/{orchestrator-B_WXBmuE.d.ts → orchestrator-Bp_jeBHK.d.ts} +4 -4
  206. package/dist/orchestrator.d.ts +5 -5
  207. package/dist/orchestrator.js +51 -51
  208. package/dist/page-versioning.js +3 -3
  209. package/dist/patterns-cli.d.ts +1 -1
  210. package/dist/{pipeline-Dvtvt141.d.ts → pipeline-BAj5bx7g.d.ts} +1 -1
  211. package/dist/policy-runtime.d.ts +1 -1
  212. package/dist/provenance.d.ts +1 -1
  213. package/dist/{qmd-DwBLh_hl.d.ts → qmd-_MDSlj1m.d.ts} +1 -1
  214. package/dist/qmd-preflight.d.ts +2 -2
  215. package/dist/qmd-recall-cache.d.ts +1 -1
  216. package/dist/qmd.d.ts +2 -2
  217. package/dist/qmd.js +3 -3
  218. package/dist/recall-disclosure-escalation.d.ts +1 -1
  219. package/dist/recall-explain-renderer.d.ts +1 -1
  220. package/dist/recall-explain-renderer.js +3 -3
  221. package/dist/recall-planner-llm.d.ts +1 -1
  222. package/dist/recall-state.d.ts +1 -1
  223. package/dist/recall-tag-filter.d.ts +1 -1
  224. package/dist/recall-timings.d.ts +1 -1
  225. package/dist/recall-xray-cli.d.ts +1 -1
  226. package/dist/recall-xray-cli.js +4 -4
  227. package/dist/recall-xray-renderer.d.ts +1 -1
  228. package/dist/recall-xray-renderer.js +3 -3
  229. package/dist/recall-xray.d.ts +1 -1
  230. package/dist/recall-xray.js +2 -2
  231. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  232. package/dist/replay/normalizers/claude.d.ts +1 -1
  233. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  234. package/dist/replay/normalizers/shared.d.ts +1 -1
  235. package/dist/replay/runner.d.ts +1 -1
  236. package/dist/replay/types.d.ts +1 -1
  237. package/dist/resolve-auth-token.d.ts +1 -1
  238. package/dist/resume-bundles.js +2 -2
  239. package/dist/retrieval-agents.d.ts +2 -2
  240. package/dist/retrieval-tiers.d.ts +1 -1
  241. package/dist/routing/engine.d.ts +1 -1
  242. package/dist/routing/store.d.ts +1 -1
  243. package/dist/search/embed-helper.d.ts +1 -1
  244. package/dist/search/factory.d.ts +1 -1
  245. package/dist/search/factory.js +8 -8
  246. package/dist/search/index.d.ts +1 -1
  247. package/dist/search/index.js +8 -8
  248. package/dist/search/lancedb-backend.d.ts +1 -1
  249. package/dist/search/lancedb-backend.js +2 -2
  250. package/dist/search/meilisearch-backend.d.ts +1 -1
  251. package/dist/search/meilisearch-backend.js +2 -2
  252. package/dist/search/noop-backend.d.ts +1 -1
  253. package/dist/search/orama-backend.d.ts +1 -1
  254. package/dist/search/orama-backend.js +2 -2
  255. package/dist/search/port.d.ts +12 -1
  256. package/dist/search/port.js +1 -1
  257. package/dist/search/remote-backend.d.ts +1 -1
  258. package/dist/search/remote-backend.js +2 -2
  259. package/dist/{semantic-consolidation-Dia_6FOn.d.ts → semantic-consolidation-C2m5eHHE.d.ts} +1 -1
  260. package/dist/semantic-consolidation.d.ts +2 -2
  261. package/dist/semantic-consolidation.js +7 -7
  262. package/dist/semantic-rule-promotion.js +6 -6
  263. package/dist/semantic-rule-verifier.d.ts +1 -1
  264. package/dist/semantic-rule-verifier.js +6 -6
  265. package/dist/session-observer-bands.d.ts +1 -1
  266. package/dist/session-observer-state.d.ts +1 -1
  267. package/dist/shared-context/manager.d.ts +1 -1
  268. package/dist/signal.d.ts +1 -1
  269. package/dist/{storage-RshM7i8-.d.ts → storage-hr_Y2z5R.d.ts} +17 -1
  270. package/dist/storage.d.ts +2 -2
  271. package/dist/storage.js +5 -5
  272. package/dist/summarizer.d.ts +1 -1
  273. package/dist/summarizer.js +2 -2
  274. package/dist/summary-snapshot.d.ts +1 -1
  275. package/dist/temporal-supersession.d.ts +2 -2
  276. package/dist/temporal-timeline-recall.d.ts +1 -1
  277. package/dist/temporal-validity.d.ts +1 -1
  278. package/dist/threading.d.ts +1 -1
  279. package/dist/tier-migration.d.ts +2 -2
  280. package/dist/tier-routing.d.ts +1 -1
  281. package/dist/topics.d.ts +1 -1
  282. package/dist/transcript.d.ts +1 -1
  283. package/dist/transfer/capsule-import.js +4 -4
  284. package/dist/trust-score-stage.d.ts +1 -1
  285. package/dist/trust-score.d.ts +1 -1
  286. package/dist/{types-CHSXOq7s.d.ts → types-Cg8q7W7_.d.ts} +16 -0
  287. package/dist/types.d.ts +1 -1
  288. package/dist/types.js +1 -1
  289. package/dist/utility-runtime.d.ts +1 -1
  290. package/dist/verified-recall.js +6 -6
  291. package/package.json +2 -2
  292. package/src/config.ts +18 -0
  293. package/src/graph.test.ts +137 -1
  294. package/src/graph.ts +274 -17
  295. package/src/local-llm-thinking.test.ts +55 -1
  296. package/src/local-llm.ts +14 -0
  297. package/src/memory-cache.ts +70 -0
  298. package/src/namespaces/storage.ts +2 -0
  299. package/src/orchestration/maintenance.ts +7 -0
  300. package/src/orchestration/workspace-ops.ts +4 -0
  301. package/src/orchestrator.ts +6 -1
  302. package/src/qmd.test.ts +22 -0
  303. package/src/qmd.ts +13 -1
  304. package/src/search/port.ts +11 -0
  305. package/src/storage.ts +60 -13
  306. package/src/types.ts +21 -0
  307. package/dist/chunk-2AL7N3BH.js.map +0 -1
  308. package/dist/chunk-6N7R7TR2.js.map +0 -1
  309. package/dist/chunk-AHLPZ2SF.js.map +0 -1
  310. package/dist/chunk-G5PVJJRA.js.map +0 -1
  311. package/dist/chunk-OBMR4VIX.js.map +0 -1
  312. package/dist/chunk-TRH533CA.js.map +0 -1
  313. package/dist/chunk-VY6LKKVN.js.map +0 -1
  314. package/dist/chunk-X47LWMKA.js.map +0 -1
  315. package/dist/chunk-YI7XUXLX.js.map +0 -1
  316. /package/dist/{capsule-merge-Z2HUO6IK.js.map → capsule-merge-5KKJQBWQ.js.map} +0 -0
  317. /package/dist/{chunk-2RSL6YRA.js.map → chunk-2AZXIZEN.js.map} +0 -0
  318. /package/dist/{chunk-5S7Z5SHA.js.map → chunk-34RC5RT7.js.map} +0 -0
  319. /package/dist/{chunk-JKLJ6A7W.js.map → chunk-3D6AFGQR.js.map} +0 -0
  320. /package/dist/{chunk-VZ5OJE4X.js.map → chunk-5VQJBH2G.js.map} +0 -0
  321. /package/dist/{chunk-N3JDIRBW.js.map → chunk-74F5STS4.js.map} +0 -0
  322. /package/dist/{chunk-OC35KQIN.js.map → chunk-A5UXZRRM.js.map} +0 -0
  323. /package/dist/{chunk-OKUEZOGW.js.map → chunk-AITCS2RC.js.map} +0 -0
  324. /package/dist/{chunk-7XGSIUP5.js.map → chunk-AJLLIIML.js.map} +0 -0
  325. /package/dist/{chunk-CE3GMHT4.js.map → chunk-BS4SGLWV.js.map} +0 -0
  326. /package/dist/{chunk-2V5QI6NQ.js.map → chunk-DCFV7A7H.js.map} +0 -0
  327. /package/dist/{chunk-I3GKTDM2.js.map → chunk-DMSDUGDM.js.map} +0 -0
  328. /package/dist/{chunk-D4TLWDYR.js.map → chunk-DPAENM7O.js.map} +0 -0
  329. /package/dist/{chunk-7MW3CVLD.js.map → chunk-DZKHSDOM.js.map} +0 -0
  330. /package/dist/{chunk-HG32URJJ.js.map → chunk-E6CBU7XP.js.map} +0 -0
  331. /package/dist/{chunk-675YU5IK.js.map → chunk-EHCONI6E.js.map} +0 -0
  332. /package/dist/{chunk-NVXQTRBL.js.map → chunk-FDCTQWLW.js.map} +0 -0
  333. /package/dist/{chunk-PA6DMYEK.js.map → chunk-FIJUY7GG.js.map} +0 -0
  334. /package/dist/{chunk-UTRJFDP2.js.map → chunk-FNZQGN76.js.map} +0 -0
  335. /package/dist/{chunk-V53GJUSL.js.map → chunk-G4CN3ZXL.js.map} +0 -0
  336. /package/dist/{chunk-IQULRIZM.js.map → chunk-G6XXLKC5.js.map} +0 -0
  337. /package/dist/{chunk-CLFY35ED.js.map → chunk-HDTQVNWD.js.map} +0 -0
  338. /package/dist/{chunk-TMGK6YE7.js.map → chunk-HF77M34J.js.map} +0 -0
  339. /package/dist/{chunk-ZC3HG22I.js.map → chunk-JREB6UFH.js.map} +0 -0
  340. /package/dist/{chunk-TWGGNUWJ.js.map → chunk-KDXVOFYY.js.map} +0 -0
  341. /package/dist/{chunk-RT7IP3D3.js.map → chunk-KSNVDPDF.js.map} +0 -0
  342. /package/dist/{chunk-ZIDSD6VC.js.map → chunk-LRNMRXJO.js.map} +0 -0
  343. /package/dist/{chunk-QPZCAVDC.js.map → chunk-LZOV7MX7.js.map} +0 -0
  344. /package/dist/{chunk-Z6WN2KSH.js.map → chunk-OAZVR2BV.js.map} +0 -0
  345. /package/dist/{chunk-KQMKF4G2.js.map → chunk-OVJ2HIPE.js.map} +0 -0
  346. /package/dist/{chunk-OCY3CRPG.js.map → chunk-PBNZVPFS.js.map} +0 -0
  347. /package/dist/{chunk-XVLEGMJI.js.map → chunk-PLQE6MJA.js.map} +0 -0
  348. /package/dist/{chunk-NKCPUHCI.js.map → chunk-PQVK2S3J.js.map} +0 -0
  349. /package/dist/{chunk-OIFZII6J.js.map → chunk-Q5WG43OP.js.map} +0 -0
  350. /package/dist/{chunk-3SIC3E65.js.map → chunk-RO4LQGT3.js.map} +0 -0
  351. /package/dist/{chunk-BQTSGK5Y.js.map → chunk-RVZRYUQH.js.map} +0 -0
  352. /package/dist/{chunk-T6U7HDIY.js.map → chunk-T7Y5KPLN.js.map} +0 -0
  353. /package/dist/{chunk-HLTAPHZZ.js.map → chunk-UDQUSU27.js.map} +0 -0
  354. /package/dist/{chunk-2ZPQUTMW.js.map → chunk-VDW4VU7B.js.map} +0 -0
  355. /package/dist/{chunk-ZRXSHGXT.js.map → chunk-VJVNLNDQ.js.map} +0 -0
  356. /package/dist/{chunk-UTZW3X2R.js.map → chunk-XDSXEKYK.js.map} +0 -0
  357. /package/dist/{chunk-FUUF7FMX.js.map → chunk-ZHIVCODT.js.map} +0 -0
  358. /package/dist/{graph-edge-decay-FO7AM4UR.js.map → graph-edge-decay-IOGBBAGC.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph.ts"],"sourcesContent":["/**\n * Multi-Graph Memory (MAGMA/SYNAPSE-inspired, v8.2)\n *\n * Maintains three typed edge graphs:\n * entity.jsonl — memories sharing a named entity (entityRef)\n * time.jsonl — consecutive memories in the same thread/session\n * causal.jsonl — memories linked by causal language heuristics\n *\n * Stored under `<memoryDir>/state/graphs/`.\n * All writes are fail-open: errors are caught/logged, never thrown.\n */\n\nimport { appendFile, mkdir, readFile, stat } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { readEdgeConfidence } from \"./graph-edge-reinforcement.js\";\nimport { emitGraphEvent } from \"./graph-events.js\";\nimport type { GraphConstructionCapabilitySet } from \"./capabilities.js\";\n\nexport type GraphType = \"entity\" | \"time\" | \"causal\";\n\nexport interface GraphEdge {\n from: string; // relative memory path (e.g. \"facts/2026-02-22/abc.md\")\n to: string; // relative memory path\n type: GraphType;\n weight: number; // 1.0 default, decay applied during traversal\n label: string; // entity name, threadId, or matched causal phrase\n ts: string; // ISO timestamp of edge creation\n\n // Issue #681 — edge confidence + reinforcement (PR 1/3: schema + primitive only).\n // Both fields are optional so existing edges without confidence still validate.\n // Treat a missing `confidence` as 1.0 (legacy behavior) at read sites.\n // PR 2/3 wires the maintenance decay job; PR 3/3 weights PageRank traversal by confidence.\n confidence?: number; // [0, 1]; missing = 1.0\n lastReinforcedAt?: string; // ISO timestamp of most recent reinforcement\n}\n\nexport interface GraphConfig {\n multiGraphMemoryEnabled: boolean;\n entityGraphEnabled: boolean;\n timeGraphEnabled: boolean;\n causalGraphEnabled: boolean;\n maxGraphTraversalSteps: number;\n graphActivationDecay: number;\n maxEntityGraphEdgesPerMemory: number;\n graphLateralInhibitionEnabled: boolean;\n graphLateralInhibitionBeta: number;\n graphLateralInhibitionTopM: number;\n /**\n * Issue #681 PR 3/3 — minimum edge confidence required for traversal.\n * Edges with confidence below this floor are pruned. Legacy edges\n * (no `confidence` field) are treated as 1.0 and always pass.\n * Range `[0, 1]`. Default 0.2.\n */\n graphTraversalConfidenceFloor: number;\n /**\n * Issue #681 PR 3/3 — number of PageRank-style refinement iterations\n * applied on top of BFS activation. Set to 0 to disable refinement\n * and return raw BFS scores. Default 8.\n */\n graphTraversalPageRankIterations: number;\n /**\n * Issue #1904 — incremental GraphIndex edge cache. When true (the default,\n * and the value when omitted), a single-writer edge append is pushed into the\n * warm edge cache in place (revalidated by file size for cross-process\n * coherence) instead of nulling the cache and paying a full 6 MB re-read +\n * parse on the next traversal. Set false to restore the pre-#1904\n * null-on-every-write behavior. Optional here (unlike the required\n * PluginConfig field parseConfig always sets) so GraphConfig can still be\n * constructed directly with a partial config; only an explicit `false` opts\n * out, so an omitted field keeps the incremental default.\n */\n graphEdgeCacheIncrementalEnabled?: boolean;\n}\n\n/** Default minimum edge confidence required for traversal (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR = 0.2;\n/** Default PageRank-style refinement iteration count (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_PAGERANK_ITERATIONS = 8;\n\n// Causal signal phrases — order matters (most specific first)\nexport const CAUSAL_PHRASES = [\"as a result\", \"led to\", \"because of\", \"therefore\", \"caused\", \"because\"];\n\nexport function graphsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"graphs\");\n}\n\nexport function graphFilePath(memoryDir: string, type: GraphType): string {\n return path.join(graphsDir(memoryDir), `${type}.jsonl`);\n}\n\nexport async function ensureGraphsDir(memoryDir: string): Promise<void> {\n await mkdir(graphsDir(memoryDir), { recursive: true });\n}\n\n// ---------------------------------------------------------------------------\n// Per-graph-file write lock (gotcha #40 promise-chain pattern).\n//\n// Both the append path (`appendEdge`) and the rewrite path used by the\n// decay maintenance job must serialize on the same lock keyed by the\n// JSONL file path. Without this, an extraction can append a new edge\n// between the decay job's read-snapshot and rewrite, silently dropping\n// the appended edge during active traffic (issue #729 / Codex P1).\n// ---------------------------------------------------------------------------\nconst graphWriteLocks = new Map<string, Promise<void>>();\n\n/**\n * Run `fn` while holding the write lock for the given graph JSONL file.\n *\n * The lock is keyed by absolute file path so concurrent writes to\n * different graph types proceed independently. The chain recovers from\n * rejection (gotcha #40) so a single I/O failure does not poison all\n * future writers, but the original error is still surfaced to the\n * caller of `withGraphWriteLock`.\n */\nexport function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n const prev = graphWriteLocks.get(filePath) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n graphWriteLocks.set(\n filePath,\n next.then(\n () => undefined,\n () => undefined\n )\n );\n return next;\n}\n\nexport async function appendEdge(memoryDir: string, edge: GraphEdge): Promise<void> {\n await ensureGraphsDir(memoryDir);\n const filePath = graphFilePath(memoryDir, edge.type);\n const line = `${JSON.stringify(edge)}\\n`;\n await withGraphWriteLock(filePath, async () => {\n await appendFile(filePath, line, \"utf8\");\n });\n // Emit edge-added event for SSE subscribers (issue #691 PR 5/5).\n // Fail-open: emitGraphEvent catches listener errors so a bad SSE client\n // can never surface into the extraction pipeline.\n emitGraphEvent(memoryDir, \"edge-added\", {\n source: edge.from,\n target: edge.to,\n kind: edge.type,\n weight: edge.weight,\n label: edge.label,\n confidence: typeof edge.confidence === \"number\" ? edge.confidence : 1.0,\n });\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\nfunction parseEdgesJsonl(raw: string, expectedType: GraphType): GraphEdge[] {\n const edges: GraphEdge[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (isValidGraphEdge(parsed, expectedType)) {\n edges.push(parsed);\n }\n } catch {\n // skip corrupt lines — fail-open for partial JSONL recovery\n }\n }\n return edges;\n}\n\n/**\n * Read all edges of a given type from the JSONL file.\n * Returns [] if the file doesn't exist or any read error occurs (fail-open).\n *\n * Production traversal callers (recall/PageRank) depend on this fail-open\n * posture so a temporarily missing or unreadable graph file never blocks\n * a recall. Maintenance jobs that need to distinguish ENOENT from real\n * I/O failures must use {@link readEdgesStrict} instead.\n */\nexport async function readEdges(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch {\n return [];\n }\n}\n\n/**\n * Same as {@link readEdges} but only swallows `ENOENT`; all other read\n * errors (`EACCES`, `EIO`, …) are propagated. Used by the graph-edge\n * decay maintenance job so I/O outages surface as a failed run instead\n * of being silently reported as \"no edges to decay\" (issue #729 /\n * Codex P1, line 120).\n */\nexport async function readEdgesStrict(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Read edges from all enabled graph types.\n */\nexport async function readAllEdges(\n memoryDir: string,\n graphCaps: Pick<GraphConstructionCapabilitySet, \"entityGraph\" | \"timeGraph\" | \"causalGraph\">,\n): Promise<GraphEdge[]> {\n const parts: GraphEdge[][] = await Promise.all([\n graphCaps.entityGraph ? readEdges(memoryDir, \"entity\") : Promise.resolve([]),\n graphCaps.timeGraph ? readEdges(memoryDir, \"time\") : Promise.resolve([]),\n graphCaps.causalGraph ? readEdges(memoryDir, \"causal\") : Promise.resolve([]),\n ]);\n return parts.flat();\n}\n\nexport interface GraphHealthFileStats {\n type: GraphType;\n filePath: string;\n exists: boolean;\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n}\n\nexport interface GraphHealthReport {\n generatedAt: string;\n enabledTypes: GraphType[];\n totals: {\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n };\n files: GraphHealthFileStats[];\n repairGuidance?: string[];\n}\n\nfunction isValidGraphEdge(raw: unknown, expectedType: GraphType): raw is GraphEdge {\n if (!raw || typeof raw !== \"object\") return false;\n const edge = raw as Record<string, unknown>;\n return (\n edge.type === expectedType &&\n typeof edge.from === \"string\" &&\n edge.from.length > 0 &&\n typeof edge.to === \"string\" &&\n edge.to.length > 0 &&\n typeof edge.weight === \"number\" &&\n Number.isFinite(edge.weight) &&\n typeof edge.label === \"string\" &&\n typeof edge.ts === \"string\"\n );\n}\n\nexport async function analyzeGraphHealth(\n memoryDir: string,\n options?: {\n entityGraphEnabled?: boolean;\n timeGraphEnabled?: boolean;\n causalGraphEnabled?: boolean;\n includeRepairGuidance?: boolean;\n }\n): Promise<GraphHealthReport> {\n const enabledTypes: GraphType[] = [];\n if (options?.entityGraphEnabled !== false) enabledTypes.push(\"entity\");\n if (options?.timeGraphEnabled !== false) enabledTypes.push(\"time\");\n if (options?.causalGraphEnabled !== false) enabledTypes.push(\"causal\");\n\n const files: GraphHealthFileStats[] = [];\n const globalNodes = new Set<string>();\n\n for (const type of enabledTypes) {\n const filePath = graphFilePath(memoryDir, type);\n let exists = true;\n let totalLines = 0;\n let validEdges = 0;\n let corruptLines = 0;\n const nodes = new Set<string>();\n\n try {\n const raw = await readFile(filePath, \"utf8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n totalLines += 1;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!isValidGraphEdge(parsed, type)) {\n corruptLines += 1;\n continue;\n }\n validEdges += 1;\n nodes.add(parsed.from);\n nodes.add(parsed.to);\n globalNodes.add(parsed.from);\n globalNodes.add(parsed.to);\n } catch {\n corruptLines += 1;\n }\n }\n } catch {\n exists = false;\n }\n\n files.push({\n type,\n filePath,\n exists,\n totalLines,\n validEdges,\n corruptLines,\n uniqueNodes: nodes.size,\n });\n }\n\n const totals = files.reduce(\n (acc, item) => {\n acc.totalLines += item.totalLines;\n acc.validEdges += item.validEdges;\n acc.corruptLines += item.corruptLines;\n return acc;\n },\n {\n totalLines: 0,\n validEdges: 0,\n corruptLines: 0,\n uniqueNodes: globalNodes.size,\n }\n );\n totals.uniqueNodes = globalNodes.size;\n\n const report: GraphHealthReport = {\n generatedAt: new Date().toISOString(),\n enabledTypes,\n totals,\n files,\n };\n\n if (options?.includeRepairGuidance === true) {\n const guidance: string[] = [];\n if (totals.corruptLines > 0) {\n guidance.push(\n \"Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs.\"\n );\n }\n if (totals.validEdges === 0) {\n guidance.push(\n \"No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files.\"\n );\n }\n if (guidance.length > 0) report.repairGuidance = guidance;\n }\n\n return report;\n}\n\n/**\n * Detect causal signal phrases in text. Returns the first matched phrase, or null.\n */\nexport function detectCausalPhrase(text: string): string | null {\n const lower = text.toLowerCase();\n for (const phrase of CAUSAL_PHRASES) {\n if (lower.includes(phrase)) return phrase;\n }\n return null;\n}\n\n/**\n * GraphIndex — builds and updates the three memory graphs.\n *\n * Usage (orchestrator):\n * this.graphIndex = new GraphIndex(config.memoryDir, config);\n *\n * // After each memory write:\n * await this.graphIndex.onMemoryWritten(memoryPath, frontmatter, threadId, recentInThread);\n */\n/**\n * Identity of one graph JSONL file used to validate the incremental edge cache\n * (issue #1904). An absent file (ENOENT) is recorded as the all-zero sentinel\n * `{ size: 0, mtimeMs: 0, ino: 0 }` so a later peer creation (ino becomes\n * non-zero) is detected as a change.\n */\ninterface GraphFileMeta {\n size: number;\n mtimeMs: number;\n ino: number;\n}\n\nexport class GraphIndex {\n private readonly memoryDir: string;\n private readonly cfg: GraphConfig;\n\n // Cache for readAllEdges() result. With 30k+ entity edges (6 MB JSONL) the\n // file read + JSON parse takes 2-4 s per call. This instance-level cache\n // eliminates that overhead on every spreadingActivation() call; it is\n // invalidated (set to null) in onMemoryWritten() so new edges appear promptly.\n private edgeCache: {\n allEdges: GraphEdge[];\n loadedAt: number;\n // Per-file identity of each enabled graph file observed at load (issue\n // #1904). An incremental push is trusted only when every file's identity is\n // explained entirely by OUR own append: size grows by exactly the bytes we\n // appended and the inode is unchanged (a local append keeps the inode; an\n // external atomic temp+rename rewrite — e.g. the edge-decay job — changes\n // it). Untouched files must match size AND mtime AND inode exactly. This\n // closes the size-only holes Codex flagged: a peer append racing cache\n // construction, and an equal-length atomic rewrite (e.g. confidence\n // 0.9->0.8) that preserves byte length. Any divergence forces a full reload.\n meta: Partial<Record<GraphType, GraphFileMeta>>;\n } | null = null;\n private static readonly EDGE_CACHE_TTL_MS = 300_000; // 5 minutes\n\n constructor(memoryDir: string, cfg: GraphConfig) {\n this.memoryDir = memoryDir;\n this.cfg = cfg;\n }\n\n /** Clear the edge cache so the next spreadingActivation() re-reads from disk.\n * Call after any code path that appends edges outside of onMemoryWritten(). */\n invalidateEdgeCache(): void {\n this.edgeCache = null;\n }\n\n private async loadEdgesCached(): Promise<GraphEdge[]> {\n if (this.edgeCache && Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS) {\n return this.edgeCache.allEdges;\n }\n // Consistent snapshot (issue #1904, Codex): capture file identity BEFORE and\n // AFTER reading edges and retry if it changed, so `allEdges` and the recorded\n // `meta` baseline reflect the SAME on-disk state. Without this a peer append\n // landing mid-read would leave the cache holding edges that exclude the peer\n // edge while the baseline already counts its bytes — a later local append\n // would then pass the size-delta check and silently omit the peer edge.\n let allEdges: GraphEdge[] = [];\n let meta = await this.readEnabledGraphFileMeta();\n let stable = false;\n for (let attempt = 0; attempt < 3; attempt++) {\n const before = meta;\n allEdges = await readAllEdges(this.memoryDir, {\n entityGraph: this.cfg.entityGraphEnabled,\n timeGraph: this.cfg.timeGraphEnabled,\n causalGraph: this.cfg.causalGraphEnabled,\n });\n meta = await this.readEnabledGraphFileMeta();\n if (this.graphFileMetaEqual(before, meta)) {\n stable = true;\n break;\n }\n // A write landed during the read; the just-captured `meta` is the new\n // baseline for the next attempt's before-snapshot.\n }\n if (stable) {\n this.edgeCache = { allEdges, loadedAt: Date.now(), meta };\n } else {\n // Contended: a peer kept writing across every attempt, so the final\n // allEdges/meta pair is not guaranteed consistent. Serve THIS read's edges\n // (best effort) but do NOT poison the cache — leave it null so the next\n // call re-reads, instead of installing a baseline that could hide a peer\n // edge for the TTL (Codex).\n this.edgeCache = null;\n }\n return allEdges;\n }\n\n /**\n * Identity ({ size, mtimeMs, ino }) of each ENABLED graph file (issue #1904).\n * Missing files (ENOENT) and any stat error map to the all-zero sentinel so\n * the baseline is fail-open: a later revalidation sees a mismatch (or a peer\n * creation flipping ino from 0 to non-zero) and forces a full reload rather\n * than trusting a stale incremental push.\n */\n private async readEnabledGraphFileMeta(): Promise<Partial<Record<GraphType, GraphFileMeta>>> {\n const enabled: GraphType[] = [];\n if (this.cfg.entityGraphEnabled) enabled.push(\"entity\");\n if (this.cfg.timeGraphEnabled) enabled.push(\"time\");\n if (this.cfg.causalGraphEnabled) enabled.push(\"causal\");\n const meta: Partial<Record<GraphType, GraphFileMeta>> = {};\n for (const type of enabled) {\n try {\n const st = await stat(graphFilePath(this.memoryDir, type));\n meta[type] = { size: st.size, mtimeMs: st.mtimeMs, ino: Number(st.ino) };\n } catch {\n meta[type] = { size: 0, mtimeMs: 0, ino: 0 };\n }\n }\n return meta;\n }\n\n /** True iff both metadata maps carry identical identity for every key. */\n private graphFileMetaEqual(\n a: Partial<Record<GraphType, GraphFileMeta>>,\n b: Partial<Record<GraphType, GraphFileMeta>>,\n ): boolean {\n const types: GraphType[] = [\"entity\", \"time\", \"causal\"];\n for (const type of types) {\n const x = a[type];\n const y = b[type];\n if (!x && !y) continue;\n if (!x || !y) return false;\n if (x.size !== y.size || x.mtimeMs !== y.mtimeMs || x.ino !== y.ino) return false;\n }\n return true;\n }\n\n /**\n * Re-stat every graph file whose identity the cache just committed and return\n * false if any has moved since (issue #1904, Codex). Closes the validation→\n * in-place-push TOCTOU window: a peer process (concurrent CLI / daemon /\n * decay job) can append between edgeFilesUnchangedExceptOurAppends()'s final\n * stat and the allEdges.push(...). Without this re-check the cache would be\n * accepted with identity predating the peer write and miss the peer edge for\n * the TTL. A residual infinitesimal window (peer writes during this re-stat)\n * remains and is TTL-bounded.\n */\n private async edgeCacheIdentityUnchangedSinceCommit(): Promise<boolean> {\n if (!this.edgeCache) return false;\n for (const type of Object.keys(this.edgeCache.meta) as GraphType[]) {\n const committed = this.edgeCache.meta[type];\n if (!committed) continue;\n let cur: GraphFileMeta;\n try {\n const st = await stat(graphFilePath(this.memoryDir, type));\n cur = { size: st.size, mtimeMs: st.mtimeMs, ino: Number(st.ino) };\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code === \"ENOENT\") {\n cur = { size: 0, mtimeMs: 0, ino: 0 };\n } else {\n return false;\n }\n }\n if (\n cur.size !== committed.size ||\n cur.mtimeMs !== committed.mtimeMs ||\n cur.ino !== committed.ino\n ) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Called after a memory is written to disk.\n *\n * @param memoryPath - relative path from memoryDir (e.g. \"facts/2026-02-22/abc.md\")\n * @param entityRef - entityRef frontmatter field (if any)\n * @param content - full memory text (for causal detection)\n * @param created - ISO timestamp of this memory\n * @param threadId - current thread ID (for time graph)\n * @param recentInThread - paths of the N most-recent memories in this thread (for time graph)\n * @param entitySiblings - paths of other memories that share the same entityRef (for entity graph)\n */\n async onMemoryWritten(opts: {\n memoryPath: string;\n entityRef?: string;\n content: string;\n created: string;\n threadId?: string;\n recentInThread?: string[];\n entitySiblings?: string[];\n causalPredecessor?: string;\n /**\n * Optional frozen gate overrides (from GraphConstructionCapabilitySet).\n * When provided, these take precedence over `this.cfg` so the caller's\n * operation-scoped snapshot is the single source of truth (#1566).\n */\n graphCapsOverride?: {\n entityGraph: boolean;\n timeGraph: boolean;\n causalGraph: boolean;\n multiGraphMemory: boolean;\n };\n }): Promise<void> {\n const g = opts.graphCapsOverride;\n const multiGraphOn = g ? g.multiGraphMemory : this.cfg.multiGraphMemoryEnabled;\n if (!multiGraphOn) return;\n const entityOn = g ? g.entityGraph : this.cfg.entityGraphEnabled;\n const timeOn = g ? g.timeGraph : this.cfg.timeGraphEnabled;\n const causalOn = g ? g.causalGraph : this.cfg.causalGraphEnabled;\n const ts = new Date().toISOString();\n // Collect the edges appended this call so a coherent single-writer push can\n // extend the warm edge cache in place instead of nulling it (issue #1904).\n const appended: GraphEdge[] = [];\n\n try {\n // Entity graph\n if (entityOn && opts.entityRef && opts.entitySiblings?.length) {\n const siblings = opts.entitySiblings.slice(0, this.cfg.maxEntityGraphEdgesPerMemory);\n for (const sibling of siblings) {\n const edge: GraphEdge = {\n from: opts.memoryPath,\n to: sibling,\n type: \"entity\",\n weight: 1.0,\n label: opts.entityRef,\n ts,\n };\n appended.push(edge);\n await appendEdge(this.memoryDir, edge);\n }\n }\n\n // Time graph — link to most recent memory in same thread\n if (timeOn && opts.threadId && opts.recentInThread?.length) {\n const predecessor = opts.recentInThread[opts.recentInThread.length - 1];\n if (predecessor && predecessor !== opts.memoryPath) {\n const edge: GraphEdge = {\n from: predecessor,\n to: opts.memoryPath,\n type: \"time\",\n weight: 1.0,\n label: opts.threadId,\n ts,\n };\n appended.push(edge);\n await appendEdge(this.memoryDir, edge);\n }\n }\n\n // Causal graph\n if (causalOn && opts.causalPredecessor) {\n const phrase = detectCausalPhrase(opts.content);\n if (phrase) {\n const edge: GraphEdge = {\n from: opts.causalPredecessor,\n to: opts.memoryPath,\n type: \"causal\",\n weight: 1.0,\n label: phrase,\n ts,\n };\n appended.push(edge);\n await appendEdge(this.memoryDir, edge);\n }\n }\n } catch (err) {\n // Fail-open: graph write errors must never surface to caller\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] onMemoryWritten error: ${err}`);\n } finally {\n // Edge-cache coherence (issue #1904). Legacy behavior nulled the cache on\n // every write, paying a 2-4 s full re-read + parse on the next traversal.\n if (!this.edgeCache || Date.now() - this.edgeCache.loadedAt >= GraphIndex.EDGE_CACHE_TTL_MS) {\n // Nothing warm, or the entry is past its 5-min TTL backstop — reload.\n this.edgeCache = null;\n } else if (this.cfg.graphEdgeCacheIncrementalEnabled === false) {\n // Rollback lever: restore the pre-#1904 null-on-every-write behavior.\n this.edgeCache = null;\n } else {\n // Trust an in-place push ONLY when WE are the sole writer since load:\n // every enabled graph file's on-disk size must equal our baseline plus\n // exactly the bytes we appended to it. A divergence means a peer process\n // (backup daemon / CLI / decay job) also wrote — force a full reload for\n // cross-process coherence. Any stat error fails open to a full reload.\n try {\n if (await this.edgeFilesUnchangedExceptOurAppends(appended)) {\n if (appended.length > 0) {\n this.edgeCache.allEdges.push(...appended);\n // Close the validation→push TOCTOU window (#1904, Codex): a peer\n // process can append between the validation stat above and this\n // in-place push. Re-verify every committed identity; if any file\n // moved, the cache would miss the peer edge for the TTL, so null\n // it and let the next traversal reload. (Skipped when this call\n // pushed nothing — no new window was opened, and the validation\n // already confirmed no peer wrote.)\n if (this.edgeCache && !(await this.edgeCacheIdentityUnchangedSinceCommit())) {\n this.edgeCache = null;\n }\n }\n } else {\n this.edgeCache = null;\n }\n } catch {\n this.edgeCache = null;\n }\n }\n }\n }\n\n /**\n * Cross-process coherence check for the incremental edge cache (issue #1904).\n *\n * Returns true iff every ENABLED graph file's current identity is explained\n * ENTIRELY by THIS call's own append — no other process wrote to any graph\n * file since load. Per file:\n * - inode must be unchanged. A local append (`appendFile`) keeps the inode;\n * an external atomic temp+rename rewrite (e.g. the edge-decay job) changes\n * it, so an inode change — even one that preserves byte length, such as\n * decaying confidence 0.9->0.8 — forces a reload (Codex).\n * - a file WE appended to (delta > 0): size must equal baseline + our exact\n * appended bytes. If it was absent at load (sentinel ino 0), our append\n * created it, so we accept size === delta and adopt the new identity.\n * - a file we did NOT touch (delta 0): size AND mtime must be unchanged, so\n * an in-place equal-length rewrite (mtime bump) or a peer append (size\n * bump) both force a reload.\n * On success it commits the new identity baseline so the next append\n * revalidates against post-this-write truth. Fail-open: an unreadable file\n * (non-ENOENT) returns false, forcing a full reload.\n */\n private async edgeFilesUnchangedExceptOurAppends(appended: GraphEdge[]): Promise<boolean> {\n if (!this.edgeCache) return false;\n const expectedDelta: Partial<Record<GraphType, number>> = {};\n for (const edge of appended) {\n const bytes = Buffer.byteLength(`${JSON.stringify(edge)}\\n`, \"utf8\");\n expectedDelta[edge.type] = (expectedDelta[edge.type] ?? 0) + bytes;\n }\n const enabled: GraphType[] = [];\n if (this.cfg.entityGraphEnabled) enabled.push(\"entity\");\n if (this.cfg.timeGraphEnabled) enabled.push(\"time\");\n if (this.cfg.causalGraphEnabled) enabled.push(\"causal\");\n const observed: Partial<Record<GraphType, GraphFileMeta>> = {};\n for (const type of enabled) {\n let cur: GraphFileMeta;\n try {\n const st = await stat(graphFilePath(this.memoryDir, type));\n cur = { size: st.size, mtimeMs: st.mtimeMs, ino: Number(st.ino) };\n } catch (err) {\n // An absent graph file (ENOENT) is the normal partially-populated state\n // (e.g. entity edges written before any causal edge): treat it as the\n // all-zero sentinel so the incremental cache stays warm. Only a genuine\n // stat failure forces a full reload (#1904, Codex).\n if ((err as NodeJS.ErrnoException)?.code === \"ENOENT\") {\n cur = { size: 0, mtimeMs: 0, ino: 0 };\n } else {\n return false;\n }\n }\n const base = this.edgeCache.meta[type] ?? { size: 0, mtimeMs: 0, ino: 0 };\n const delta = expectedDelta[type] ?? 0;\n if (delta > 0) {\n if (base.ino === 0) {\n // File was absent at load; our append created it. Accept iff its whole\n // size is exactly our appended bytes (nothing else wrote it).\n if (cur.ino === 0 || cur.size !== delta) return false;\n } else {\n // Existing file: our append keeps the inode and grows size by exactly\n // our bytes. An atomic rewrite (ino change) or a peer append (size\n // mismatch) both fail here.\n if (cur.ino !== base.ino || cur.size !== base.size + delta) return false;\n }\n } else {\n // Untouched file: identity must be byte-for-byte unchanged.\n if (cur.ino !== base.ino || cur.size !== base.size || cur.mtimeMs !== base.mtimeMs) {\n return false;\n }\n }\n observed[type] = cur;\n }\n this.edgeCache.meta = observed;\n return true;\n }\n\n /**\n * Spreading activation BFS (SYNAPSE-inspired).\n *\n * Starting from `seeds`, traverse the combined graph for up to `maxSteps` hops.\n * Each candidate gets an activation score = edge.weight × edgeConfidence × decay^hop.\n *\n * Issue #681 PR 3/3 — confidence-aware traversal:\n * - Each edge's `weight` is multiplied by its `confidence` (legacy edges\n * missing `confidence` are treated as 1.0, preserving prior behavior).\n * - Edges with `confidence < graphTraversalConfidenceFloor` are pruned and\n * contribute neither activation nor downstream neighbors.\n * - When `graphTraversalPageRankIterations > 0`, an additional PageRank-\n * style refinement pass redistributes activation along confidence-weighted\n * edges, sharpening the ranking among multi-hop candidates.\n * - Per-result provenance includes the highest-confidence edge that landed\n * on each candidate, so the X-ray surface can attribute pruning and\n * ranking decisions back to specific edges.\n *\n * @param seeds - initial memory paths to expand from (e.g. QMD top results)\n * @param maxSteps - max BFS hops (from config: maxGraphTraversalSteps)\n * @returns Array of {path, score, edgeConfidence, ...} sorted descending, not including seed paths\n */\n async spreadingActivation(\n seeds: string[],\n maxSteps?: number,\n opts?: {\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` and includes low-confidence\n * edges in traversal. Equivalent to forcing the floor to `0`.\n * Default `false` (floor from config is applied).\n */\n includeLowConfidence?: boolean;\n /** Absolute deadline in ms-since-epoch for post-retrieval assembly. */\n deadlineAtMs?: number;\n }\n ): Promise<\n Array<{\n path: string;\n score: number;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Confidence of the edge that produced this candidate's recorded\n * provenance (the strongest edge along the chosen entry path).\n * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.\n */\n edgeConfidence: number;\n }>\n > {\n if (!this.cfg.multiGraphMemoryEnabled) return [];\n const steps = maxSteps ?? this.cfg.maxGraphTraversalSteps;\n const decay = this.cfg.graphActivationDecay;\n // When `includeLowConfidence` is set, use floor=0 so all edges\n // participate in traversal regardless of their decay state.\n // Otherwise clamp the configured floor into [0, 1] so misconfiguration\n // cannot (a) admit edges with negative confidence or (b) reject every\n // edge.\n const floor =\n opts?.includeLowConfidence === true ? 0 : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);\n const iterations = clampPageRankIterations(this.cfg.graphTraversalPageRankIterations);\n const deadlineAtMs = opts?.deadlineAtMs;\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n try {\n if (deadlineExpired()) return [];\n const allEdges = await this.loadEdgesCached();\n if (deadlineExpired()) return [];\n\n // Build adjacency index: from → edges, to → edges (bidirectional for entity/time, directional for causal).\n // Edges below the confidence floor are pruned at index time so neither\n // direct activation nor downstream BFS expansion can re-introduce them.\n const adj = new Map<string, GraphEdge[]>();\n for (let i = 0; i < allEdges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return [];\n const edge = allEdges[i];\n const conf = readEdgeConfidence(edge);\n if (conf < floor) continue;\n if (!adj.has(edge.from)) adj.set(edge.from, []);\n adj.get(edge.from)!.push(edge);\n // Entity and time edges are bidirectional\n if (edge.type !== \"causal\") {\n if (!adj.has(edge.to)) adj.set(edge.to, []);\n adj.get(edge.to)!.push({ ...edge, from: edge.to, to: edge.from });\n }\n }\n\n const seedSet = new Set(seeds);\n const scores = new Map<string, number>(); // candidate path → accumulated activation score\n const provenance = new Map<\n string,\n {\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n edgeConfidence: number;\n }\n >();\n let frontier = new Map<string, { node: string; seed: string; activation: number }>();\n const reachedBySeed = new Map<string, Set<string>>();\n for (const seed of seeds) {\n frontier.set(`${seed}\\0${seed}`, { node: seed, seed, activation: 1 });\n reachedBySeed.set(seed, new Set([seed]));\n }\n const finalizeScores = () =>\n Array.from(scores.entries())\n .map(([p, score]) => ({\n path: p,\n score,\n seed: provenance.get(p)?.seed ?? \"\",\n hopDepth: provenance.get(p)?.hopDepth ?? 0,\n decayedWeight: provenance.get(p)?.decayedWeight ?? 0,\n graphType: provenance.get(p)?.graphType ?? \"entity\",\n edgeConfidence: provenance.get(p)?.edgeConfidence ?? 1,\n }))\n .sort((a, b) => b.score - a.score);\n\n for (let hop = 0; hop < steps && frontier.size > 0; hop++) {\n if (deadlineExpired()) return finalizeScores();\n const nextFrontier = new Map<string, { node: string; seed: string; activation: number }>();\n\n for (const { node, seed: sourceSeed, activation } of frontier.values()) {\n const edges = adj.get(node) ?? [];\n for (let i = 0; i < edges.length; i += 1) {\n if ((i & 1023) === 0 && deadlineExpired()) return finalizeScores();\n const edge = edges[i];\n const neighbor = edge.to === node ? edge.from : edge.to;\n const conf = readEdgeConfidence(edge);\n // Defense in depth: the adjacency build already drops sub-floor\n // edges, but if a synthesized reverse edge ever bypassed that\n // path, this guard keeps spreading activation honest.\n if (conf < floor) continue;\n const score = activation * edge.weight * conf * decay;\n const reachedForSeed = reachedBySeed.get(sourceSeed);\n if (reachedForSeed?.has(neighbor)) {\n continue;\n }\n\n if (!seedSet.has(neighbor)) {\n const existing = scores.get(neighbor) ?? 0;\n scores.set(neighbor, existing + score);\n\n const prev = provenance.get(neighbor);\n if (!prev || hop + 1 < prev.hopDepth || (hop + 1 === prev.hopDepth && score > prev.decayedWeight)) {\n provenance.set(neighbor, {\n seed: sourceSeed,\n hopDepth: hop + 1,\n decayedWeight: score,\n graphType: edge.type,\n edgeConfidence: conf,\n });\n }\n\n if (hop + 1 < steps) {\n const frontierKey = `${sourceSeed}\\0${neighbor}`;\n const existingFrontier = nextFrontier.get(frontierKey);\n if (existingFrontier) {\n existingFrontier.activation += score;\n } else {\n nextFrontier.set(frontierKey, {\n node: neighbor,\n seed: sourceSeed,\n activation: score,\n });\n }\n }\n }\n }\n }\n\n for (const { node, seed } of nextFrontier.values()) {\n reachedBySeed.get(seed)?.add(node);\n }\n frontier = nextFrontier;\n }\n\n // Issue #681 PR 3/3 — optional PageRank-style refinement.\n // Redistributes a node's accumulated activation along its outgoing\n // edges, weighted by edge confidence. Damping is fixed at the\n // canonical 0.85 so the ranking stays comparable across queries;\n // the `iterations` knob bounds compute, not behavior shape.\n if (!deadlineExpired() && iterations > 0 && scores.size > 1) {\n applyPageRankRefinement(scores, adj, {\n iterations,\n floor,\n damping: 0.85,\n deadlineAtMs,\n });\n }\n\n // Apply lateral inhibition if enabled (Synapse-inspired competitive suppression)\n if (deadlineExpired()) return finalizeScores();\n if (this.cfg.graphLateralInhibitionEnabled && scores.size > 1) {\n const inhibited = applyLateralInhibition(scores, {\n beta: this.cfg.graphLateralInhibitionBeta,\n topM: this.cfg.graphLateralInhibitionTopM,\n });\n for (const [k, v] of inhibited) {\n scores.set(k, v);\n }\n }\n\n return finalizeScores();\n } catch (err) {\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] spreadingActivation error: ${err}`);\n return [];\n }\n }\n}\n\n/**\n * Clamp `graphTraversalConfidenceFloor` into the legal range `[0, 1]`.\n * Non-finite or non-numeric values fall back to the documented default\n * so misconfiguration cannot silently disable the floor or reject every edge.\n *\n * Exported for tests; call sites in `spreadingActivation` use it to make\n * the contract explicit at every boundary.\n */\nexport function clampConfidenceFloor(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n return DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR;\n }\n if (raw < 0) return 0;\n if (raw > 1) return 1;\n return raw;\n}\n\n/**\n * Clamp `graphTraversalPageRankIterations` into a non-negative integer.\n * Negative or non-finite values fall back to 0 (disable refinement) so\n * misconfiguration cannot stall recall in an unbounded loop.\n */\nexport function clampPageRankIterations(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) return 0;\n if (raw <= 0) return 0;\n return Math.floor(raw);\n}\n\n/**\n * PageRank-style refinement on top of the BFS activation map.\n *\n * Each iteration redistributes a fraction of every node's score along\n * its outgoing edges, scaled by edge confidence. Confidence below\n * `floor` is filtered out before redistribution, mirroring the BFS\n * pruning rule. Mutates `scores` in place.\n *\n * Exported for tests; in production, call sites pass the same adjacency\n * map already used by BFS so behavior stays consistent.\n */\nexport function applyPageRankRefinement(\n scores: Map<string, number>,\n adj: Map<string, GraphEdge[]>,\n opts: { iterations: number; floor: number; damping: number; deadlineAtMs?: number }\n): void {\n const { iterations, floor, damping, deadlineAtMs } = opts;\n if (iterations <= 0 || scores.size === 0) return;\n const safeDamping = Math.min(1, Math.max(0, damping));\n const deadlineExpired = (): boolean =>\n typeof deadlineAtMs === \"number\" && Date.now() >= deadlineAtMs;\n\n // Pre-compute confidence-weighted out-edge totals for normalization.\n // Done once per refinement, not per iteration, since adjacency is\n // immutable inside the loop.\n //\n // Codex P1 (#735): the denominator MUST be computed over the same\n // eligible-neighbor set the iteration redistributes into — i.e.\n // edges whose neighbor is in `scores`. Counting edges-to-seeds (or\n // edges-to-unseen-nodes) in the denominator while dropping their\n // flow during iteration leaks `safeDamping × score` every pass and\n // collapses leaf candidates' scores instead of just re-ranking them.\n const eligible = (edge: GraphEdge, fromNode: string): boolean => {\n if (readEdgeConfidence(edge) < floor) return false;\n const neighbor = edge.to === fromNode ? edge.from : edge.to;\n return scores.has(neighbor);\n };\n const outboundTotal = new Map<string, number>();\n for (const [node, edges] of adj.entries()) {\n if (deadlineExpired()) return;\n if (!scores.has(node)) continue; // only candidate nodes redistribute\n let sum = 0;\n for (const edge of edges) {\n if (!eligible(edge, node)) continue;\n sum += readEdgeConfidence(edge) * edge.weight;\n }\n if (sum > 0) outboundTotal.set(node, sum);\n }\n\n for (let i = 0; i < iterations; i += 1) {\n if (deadlineExpired()) return;\n const next = new Map<string, number>();\n // Teleport / damping floor: every node retains `(1 - damping) * score`\n // of its current activation so dangling nodes do not bleed to zero.\n for (const [node, score] of scores) {\n next.set(node, (1 - safeDamping) * score);\n }\n for (const [node, score] of scores) {\n const outEdges = adj.get(node);\n const total = outboundTotal.get(node);\n // Dangling-node fallback: when a candidate has zero eligible\n // outflow (no in-scores neighbors above the floor), the\n // `safeDamping × score` portion would otherwise evaporate. Keep\n // it on `node` so total mass is conserved and the score reflects\n // the candidate's standing rather than its in-degree topology.\n if (!outEdges || outEdges.length === 0 || !total || total <= 0) {\n next.set(node, (next.get(node) ?? 0) + safeDamping * score);\n continue;\n }\n for (let edgeIndex = 0; edgeIndex < outEdges.length; edgeIndex += 1) {\n if ((edgeIndex & 1023) === 0 && deadlineExpired()) return;\n const edge = outEdges[edgeIndex];\n if (!eligible(edge, node)) continue;\n const conf = readEdgeConfidence(edge);\n const neighbor = edge.to === node ? edge.from : edge.to;\n const flow = safeDamping * score * ((conf * edge.weight) / total);\n next.set(neighbor, (next.get(neighbor) ?? 0) + flow);\n }\n }\n for (const [node, score] of next) {\n scores.set(node, score);\n }\n }\n}\n\n/**\n * Lateral inhibition (Synapse-inspired).\n *\n * For each node, the top-M higher-activation competitors exert inhibition\n * proportional to their activation difference. Output is clamped to [0, ∞).\n *\n * No sigmoid is applied here — downstream `normalizeGraphActivationScore`\n * already applies x/(1+x) soft squash, so adding a sigmoid would double-\n * normalize and cap graph influence at ~50%.\n *\n * Formula: u_hat_i = max(0, u_i - beta * sum_{k in top-M where u_k > u_i}(u_k - u_i))\n *\n * When beta=0 or topM=0, returns original scores unchanged (no-op).\n */\nexport function applyLateralInhibition(\n scores: Map<string, number>,\n opts: { beta: number; topM: number }\n): Map<string, number> {\n const { beta, topM } = opts;\n if (beta === 0 || topM === 0) return new Map(scores);\n\n const sorted = Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);\n const topCompetitors = sorted.slice(0, topM);\n\n const result = new Map<string, number>();\n for (const [node, u] of scores) {\n let inhibition = 0;\n for (const [, uK] of topCompetitors) {\n if (uK > u) {\n inhibition += uK - u;\n }\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AM,OAAO,cAAc,SAAU,OAAO,KAAK,SAAU;AAC3D,aAAK,IAAI,WAAW,KAAK,IAAI,QAAQ,KAAK,KAAK,IAAI;AAAA,MACrD;AAAA,IACF;AACA,eAAW,CAAC,MAAM,KAAK,KAAK,MAAM;AAChC,aAAO,IAAI,MAAM,KAAK;AAAA,IACxB;AAAA,EACF;AACF;AAgBO,SAAS,uBACd,QACA,MACqB;AACrB,QAAM,EAAE,MAAM,KAAK,IAAI;AACvB,MAAI,SAAS,KAAK,SAAS,EAAG,QAAO,IAAI,IAAI,MAAM;AAEnD,QAAM,SAAS,MAAM,KAAK,OAAO,QAAQ,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AACtE,QAAM,iBAAiB,OAAO,MAAM,GAAG,IAAI;AAE3C,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,CAAC,MAAM,CAAC,KAAK,QAAQ;AAC9B,QAAI,aAAa;AACjB,eAAW,CAAC,EAAE,EAAE,KAAK,gBAAgB;AACnC,UAAI,KAAK,GAAG;AACV,sBAAc,KAAK;AAAA,MACrB;AAAA,IACF;AACA,WAAO,IAAI,MAAM,KAAK,IAAI,GAAG,IAAI,OAAO,UAAU,CAAC;AAAA,EACrD;AAEA,SAAO;AACT;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-G7D6GZ5J.js";
5
5
  import {
6
6
  sidecarKey
7
- } from "./chunk-VZ5OJE4X.js";
7
+ } from "./chunk-5VQJBH2G.js";
8
8
  import {
9
9
  RECALL_FALLBACK_DIRS
10
10
  } from "./chunk-VS2IYZRU.js";
@@ -342,4 +342,4 @@ function isPathWithin(candidate, root) {
342
342
  export {
343
343
  runConsolidationProvenanceCheck
344
344
  };
345
- //# sourceMappingURL=chunk-5S7Z5SHA.js.map
345
+ //# sourceMappingURL=chunk-34RC5RT7.js.map
@@ -8,7 +8,7 @@ import {
8
8
  } from "./chunk-KAWTOYAW.js";
9
9
  import {
10
10
  LocalLlmClient
11
- } from "./chunk-VY6LKKVN.js";
11
+ } from "./chunk-NWTGD4AN.js";
12
12
  import {
13
13
  sessionStoragePaths
14
14
  } from "./chunk-S4DDLTPX.js";
@@ -690,4 +690,4 @@ ${truncatedConversation}`;
690
690
  export {
691
691
  HourlySummarizer
692
692
  };
693
- //# sourceMappingURL=chunk-JKLJ6A7W.js.map
693
+ //# sourceMappingURL=chunk-3D6AFGQR.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-EGGE52UU.js";
5
5
  import {
6
6
  StorageManager
7
- } from "./chunk-TRH533CA.js";
7
+ } from "./chunk-K7LOWSLU.js";
8
8
  import {
9
9
  MutationSerializer
10
10
  } from "./chunk-LTJAMRGI.js";
@@ -190,6 +190,8 @@ var NamespaceStorageRouter = class {
190
190
  this.config.hotMemoriesCacheEnabled,
191
191
  this.config.hotMemoriesCacheTtlMs
192
192
  );
193
+ const { scopedCacheInvalidationEnabled } = this.config;
194
+ StorageManager.setScopedCacheInvalidationDefault(root, scopedCacheInvalidationEnabled);
193
195
  sm.citationTemplate = this.config.inlineSourceAttributionFormat;
194
196
  this.bindCatalogWriteHook(sm, ns);
195
197
  this.applyTombstonesConfig(sm, ns);
@@ -350,4 +352,4 @@ export {
350
352
  resolveNamespaceStorageRoot,
351
353
  NamespaceStorageRouter
352
354
  };
353
- //# sourceMappingURL=chunk-2AL7N3BH.js.map
355
+ //# sourceMappingURL=chunk-3IY64MV6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n // Pass the hot-memories cache gate explicitly (issue #1902, Codex P2): a\n // per-namespace child root is never registered in the per-dir default map,\n // so without this it would fall back to the process-wide default and ignore\n // THIS daemon's hotMemoriesCacheEnabled config. Threading it from config\n // keeps every namespace storage aligned with its owning orchestrator.\n const sm = new StorageManager(\n root,\n this.config.entitySchemas,\n this.config.hotMemoriesCacheEnabled,\n );\n // Register this child root's gate AND TTL in the per-dir maps (issue #1902,\n // Codex P2). The constructor override above fixes the child's own gate, but\n // its TTL is resolved via the per-dir map (hotCacheTtlMs); an unregistered\n // child root would fall back to the last process-wide TTL and could inherit\n // another daemon's value. Registering keyed by root keeps both per-dir.\n StorageManager.setHotMemoriesCacheDefault(\n root,\n this.config.hotMemoriesCacheEnabled,\n this.config.hotMemoriesCacheTtlMs,\n );\n const { scopedCacheInvalidationEnabled } = this.config;\n StorageManager.setScopedCacheInvalidationDefault(root, scopedCacheInvalidationEnabled);\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n this.cache.set(ns, sm);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n // Issue #1903: pure state-file writes only touch the catalog when explicitly\n // opted in. Router-created storages (storageFor) and the legacy default\n // storage both flow through here, so this is the single wiring point.\n sm.touchStateWrites = this.config.namespacesCatalogTouchStateWrites === true;\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n // Flush any coalesced (buffered) touches first so their appends join the\n // pending set below — otherwise this could resolve while a buffered touch's\n // lastWriteAt is still unwritten on disk (#1903, Cursor). No-op when\n // coalescing is disabled (window 0) or the catalog is inert.\n await this.catalog?.flushPendingTouches().catch(() => undefined);\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.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AAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,0BAAyC;AAC7C,WAAO,KAAK,oBAAoB,OAAO,GAAG;AACxC,YAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,mBAAmB,CAAC;AAAA,IACxD;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bumpMemoryCorpusVersionForDir
3
- } from "./chunk-OKUEZOGW.js";
3
+ } from "./chunk-AITCS2RC.js";
4
4
  import {
5
5
  ALL_CATEGORY_DIRS,
6
6
  RECALL_FALLBACK_DIRS
@@ -271,4 +271,4 @@ export {
271
271
  revertToVersion,
272
272
  diffVersions
273
273
  };
274
- //# sourceMappingURL=chunk-VZ5OJE4X.js.map
274
+ //# sourceMappingURL=chunk-5VQJBH2G.js.map
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  reportSearchDegradation,
10
10
  resolveEnsureCollectionArgs
11
- } from "./chunk-WU46YPY6.js";
11
+ } from "./chunk-RAR2BSEM.js";
12
12
  import {
13
13
  log
14
14
  } from "./chunk-37CTGERM.js";
@@ -499,4 +499,4 @@ function isMissingVectorProviderColumnError(err) {
499
499
  export {
500
500
  LanceDbBackend
501
501
  };
502
- //# sourceMappingURL=chunk-N3JDIRBW.js.map
502
+ //# sourceMappingURL=chunk-74F5STS4.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  createVersion
3
- } from "./chunk-VZ5OJE4X.js";
3
+ } from "./chunk-5VQJBH2G.js";
4
4
  import {
5
5
  bumpMemoryCorpusVersionForDir
6
- } from "./chunk-OKUEZOGW.js";
6
+ } from "./chunk-AITCS2RC.js";
7
7
  import {
8
8
  parseExportBundle
9
9
  } from "./chunk-WEHSQBFR.js";
@@ -231,4 +231,4 @@ function mintForkId(capsuleId, originalId, now) {
231
231
  export {
232
232
  importCapsule
233
233
  };
234
- //# sourceMappingURL=chunk-OC35KQIN.js.map
234
+ //# sourceMappingURL=chunk-A5UXZRRM.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  invalidateDerivedAndGlobalForDir
3
- } from "./chunk-X47LWMKA.js";
3
+ } from "./chunk-XMMESCPD.js";
4
4
  import {
5
5
  deleteInFlightReadsForDir
6
6
  } from "./chunk-PDJTHRAW.js";
@@ -24,4 +24,4 @@ export {
24
24
  MEMORY_CORPUS_VERSION_SENTINEL,
25
25
  bumpMemoryCorpusVersionForDir
26
26
  };
27
- //# sourceMappingURL=chunk-OKUEZOGW.js.map
27
+ //# sourceMappingURL=chunk-AITCS2RC.js.map
@@ -216,4 +216,4 @@ export {
216
216
  getCausalTrajectoryStoreStatus,
217
217
  searchCausalTrajectories
218
218
  };
219
- //# sourceMappingURL=chunk-7XGSIUP5.js.map
219
+ //# sourceMappingURL=chunk-AJLLIIML.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-D7FOKIY5.js";
6
6
  import {
7
7
  EngramAccessInputError
8
- } from "./chunk-QPZCAVDC.js";
8
+ } from "./chunk-LZOV7MX7.js";
9
9
  import {
10
10
  expandTildePath
11
11
  } from "./chunk-EYIEWJNI.js";
@@ -276,4 +276,4 @@ export {
276
276
  listRegisteredOperations,
277
277
  __resetRegistryForTest
278
278
  };
279
- //# sourceMappingURL=chunk-CE3GMHT4.js.map
279
+ //# sourceMappingURL=chunk-BS4SGLWV.js.map
@@ -13,10 +13,10 @@ import {
13
13
  processChatMessage,
14
14
  sessionBelongsToPrincipal,
15
15
  subscribeChatTranscript
16
- } from "./chunk-OCY3CRPG.js";
16
+ } from "./chunk-PBNZVPFS.js";
17
17
  import {
18
18
  RelayMissionStoreError
19
- } from "./chunk-Z6WN2KSH.js";
19
+ } from "./chunk-OAZVR2BV.js";
20
20
  import {
21
21
  validateRequest
22
22
  } from "./chunk-2MR3MFQB.js";
@@ -31,7 +31,7 @@ import {
31
31
  } from "./chunk-35NN3ZFA.js";
32
32
  import {
33
33
  getOperation
34
- } from "./chunk-CE3GMHT4.js";
34
+ } from "./chunk-BS4SGLWV.js";
35
35
  import {
36
36
  assertOperationAllowed,
37
37
  enforceNamespaceAllowList,
@@ -41,7 +41,7 @@ import {
41
41
  import {
42
42
  CorrectionContractError,
43
43
  EngramAccessInputError
44
- } from "./chunk-QPZCAVDC.js";
44
+ } from "./chunk-LZOV7MX7.js";
45
45
  import {
46
46
  isTrustZoneName
47
47
  } from "./chunk-JGSKJHF7.js";
@@ -53,7 +53,7 @@ import {
53
53
  } from "./chunk-DEUNUKTD.js";
54
54
  import {
55
55
  isRecallDisclosure
56
- } from "./chunk-G5PVJJRA.js";
56
+ } from "./chunk-PBSAPHHA.js";
57
57
  import {
58
58
  expandTildePath
59
59
  } from "./chunk-EYIEWJNI.js";
@@ -3122,4 +3122,4 @@ function positiveIntQueryParam(value, label) {
3122
3122
  export {
3123
3123
  EngramAccessHttpServer
3124
3124
  };
3125
- //# sourceMappingURL=chunk-2V5QI6NQ.js.map
3125
+ //# sourceMappingURL=chunk-DCFV7A7H.js.map
@@ -10,10 +10,10 @@ import {
10
10
  import {
11
11
  listMemoryGovernanceRuns,
12
12
  readMemoryGovernanceRunArtifact
13
- } from "./chunk-2RSL6YRA.js";
13
+ } from "./chunk-2AZXIZEN.js";
14
14
  import {
15
15
  StorageManager
16
- } from "./chunk-TRH533CA.js";
16
+ } from "./chunk-K7LOWSLU.js";
17
17
  import {
18
18
  MEMORY_LIFECYCLE_EVENT_SORT_ORDER,
19
19
  buildLifecycleEventsForMemory,
@@ -1023,4 +1023,4 @@ export {
1023
1023
  verifyMemoryProjection,
1024
1024
  repairMemoryProjection
1025
1025
  };
1026
- //# sourceMappingURL=chunk-I3GKTDM2.js.map
1026
+ //# sourceMappingURL=chunk-DMSDUGDM.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isRecallDisclosure
3
- } from "./chunk-G5PVJJRA.js";
3
+ } from "./chunk-PBSAPHHA.js";
4
4
  import {
5
5
  normalizeRetrievedMemoryProvenance
6
6
  } from "./chunk-I4WBNM3M.js";
@@ -292,4 +292,4 @@ export {
292
292
  RecallXrayBuilder,
293
293
  summarizeDisclosureTokens
294
294
  };
295
- //# sourceMappingURL=chunk-D4TLWDYR.js.map
295
+ //# sourceMappingURL=chunk-DPAENM7O.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  resolveEnsureCollectionArgs
3
- } from "./chunk-WU46YPY6.js";
3
+ } from "./chunk-RAR2BSEM.js";
4
4
  import {
5
5
  QMD_PROBE_RETRY_BACKOFF_MS,
6
6
  QMD_PROBE_TIMEOUT_MS,
@@ -17,9 +17,10 @@ import {
17
17
  launchProcess
18
18
  } from "./chunk-O75CRYGF.js";
19
19
  import {
20
+ clearQmdResultCaches,
20
21
  getCachedQmdSearch,
21
22
  setCachedQmdSearch
22
- } from "./chunk-X47LWMKA.js";
23
+ } from "./chunk-XMMESCPD.js";
23
24
  import {
24
25
  mergeEnv
25
26
  } from "./chunk-JUC24CTX.js";
@@ -1979,6 +1980,7 @@ var QmdClient = class _QmdClient {
1979
1980
  this.lastUpdateRunAtMs = at;
1980
1981
  globalState.lastGlobalUpdateRunAtMs = at;
1981
1982
  }
1983
+ clearQmdResultCaches();
1982
1984
  log.debug(`QMD update completed for collection=${name}`);
1983
1985
  } catch (err) {
1984
1986
  const at = Date.now();
@@ -2067,6 +2069,7 @@ var QmdClient = class _QmdClient {
2067
2069
  globalState.lastEmbedByCollectionMs[name] = at;
2068
2070
  }
2069
2071
  globalState.lastGlobalEmbedRunAtMs = at;
2072
+ clearQmdResultCaches();
2070
2073
  log.debug(`QMD embed completed for collection=${name}`);
2071
2074
  } catch (err) {
2072
2075
  let failure = err;
@@ -2083,6 +2086,7 @@ var QmdClient = class _QmdClient {
2083
2086
  }
2084
2087
  globalState.lastGlobalEmbedRunAtMs = recoveredAt;
2085
2088
  globalState.lastGlobalEmbedFailAtMs = null;
2089
+ clearQmdResultCaches();
2086
2090
  log.warn(`QMD embed for collection ${name} recovered by forcing a full vector rebuild`);
2087
2091
  return;
2088
2092
  } catch (retryErr) {
@@ -2190,4 +2194,4 @@ export {
2190
2194
  sharedDaemonSessionCountForTest,
2191
2195
  QmdClient
2192
2196
  };
2193
- //# sourceMappingURL=chunk-AHLPZ2SF.js.map
2197
+ //# sourceMappingURL=chunk-DYP3YYJJ.js.map