@remnic/core 9.45.3 → 9.45.5

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 (766) hide show
  1. package/dist/abort-error.d.ts +2 -1
  2. package/dist/abort-error.js +3 -1
  3. package/dist/access-admin-ops-surface.d.ts +14 -10
  4. package/dist/access-admin-ops-surface.js +84 -75
  5. package/dist/access-audit.js +2 -2
  6. package/dist/access-authorization-probe.d.ts +14 -10
  7. package/dist/access-authorization-probe.js +85 -76
  8. package/dist/access-boundary.d.ts +15 -11
  9. package/dist/access-boundary.js +84 -75
  10. package/dist/access-citation-namespace.js +2 -2
  11. package/dist/access-cli.js +191 -177
  12. package/dist/access-cli.js.map +1 -1
  13. package/dist/access-coding-context-resolution.d.ts +16 -0
  14. package/dist/access-coding-context-resolution.js +13 -0
  15. package/dist/access-coding-context-resolution.js.map +1 -0
  16. package/dist/access-extraction-force-flush.d.ts +14 -10
  17. package/dist/access-extraction-force-flush.js +84 -75
  18. package/dist/access-health-types.d.ts +2 -1
  19. package/dist/access-http-lcm-compaction.d.ts +16 -12
  20. package/dist/access-http-lcm-compaction.js +3 -3
  21. package/dist/access-http-lifecycle-flush.d.ts +14 -10
  22. package/dist/access-http-lifecycle-flush.js +2 -2
  23. package/dist/access-http-offline-stream.d.ts +123 -0
  24. package/dist/access-http-offline-stream.js +10 -0
  25. package/dist/access-http-offline-stream.js.map +1 -0
  26. package/dist/access-http-query.js +84 -75
  27. package/dist/access-http.d.ts +15 -11
  28. package/dist/access-http.js +104 -90
  29. package/dist/access-identity-continuity-surface.d.ts +9 -8
  30. package/dist/access-identity-continuity-surface.js +84 -75
  31. package/dist/access-lcm-surface.d.ts +14 -10
  32. package/dist/access-lcm-surface.js +84 -75
  33. package/dist/access-mcp-output-schemas.js +1 -1
  34. package/dist/access-mcp.d.ts +14 -10
  35. package/dist/access-mcp.js +95 -82
  36. package/dist/access-memory-search-fanout.d.ts +3 -2
  37. package/dist/{access-namespace-preflight-5yZ4g6F8.d.ts → access-namespace-preflight-CWUDwB4M.d.ts} +1 -1
  38. package/dist/access-namespace-preflight.d.ts +4 -3
  39. package/dist/access-namespace-preflight.js +84 -75
  40. package/dist/access-observe-helpers.d.ts +1 -0
  41. package/dist/access-observe-helpers.js +1 -1
  42. package/dist/access-observe-write-surface.d.ts +16 -10
  43. package/dist/access-observe-write-surface.js +84 -75
  44. package/dist/access-offline-manifest.d.ts +104 -0
  45. package/dist/access-offline-manifest.js +45 -0
  46. package/dist/access-offline-manifest.js.map +1 -0
  47. package/dist/access-operations-batch.js +86 -77
  48. package/dist/access-operations.d.ts +18 -14
  49. package/dist/access-operations.js +91 -79
  50. package/dist/access-recall-concurrency.d.ts +16 -26
  51. package/dist/access-recall-concurrency.js +86 -76
  52. package/dist/access-recall-response.d.ts +18 -14
  53. package/dist/access-recall-response.js +84 -75
  54. package/dist/access-recall-surface.d.ts +29 -24
  55. package/dist/access-recall-surface.js +84 -75
  56. package/dist/access-schema.d.ts +84 -84
  57. package/dist/access-schema.js +3 -3
  58. package/dist/{access-service-CiJRsgAB.d.ts → access-service-CNN89xyn.d.ts} +25 -16
  59. package/dist/access-service-helpers.d.ts +14 -10
  60. package/dist/access-service.d.ts +14 -10
  61. package/dist/access-service.js +84 -75
  62. package/dist/access-surface-catalog.d.ts +14 -10
  63. package/dist/access-surface-catalog.js +4 -0
  64. package/dist/access-surface-catalog.js.map +1 -1
  65. package/dist/access-wearables-meetings-surface.d.ts +4 -3
  66. package/dist/action-confidence.d.ts +2 -1
  67. package/dist/active-memory-bridge.d.ts +2 -1
  68. package/dist/active-recall.d.ts +2 -1
  69. package/dist/active-recall.js +10 -8
  70. package/dist/active-recall.js.map +1 -1
  71. package/dist/adapters/index.js +4 -4
  72. package/dist/adapters/registry.js +2 -2
  73. package/dist/{auto-sync-5OE5QOZB.js → auto-sync-UPTUVE4X.js} +6 -6
  74. package/dist/behavior-learner.d.ts +2 -1
  75. package/dist/behavior-learner.js +1 -1
  76. package/dist/behavior-signals.d.ts +2 -1
  77. package/dist/bootstrap.d.ts +9 -8
  78. package/dist/briefing.d.ts +3 -2
  79. package/dist/briefing.js +24 -22
  80. package/dist/buffer-surprise-report.d.ts +2 -1
  81. package/dist/buffer-turn-helpers.d.ts +2 -1
  82. package/dist/buffer.d.ts +3 -2
  83. package/dist/buffer.js +12 -11
  84. package/dist/bulk-import/index.d.ts +4 -3
  85. package/dist/calibration.d.ts +2 -1
  86. package/dist/capabilities.d.ts +2 -1
  87. package/dist/{capsule-merge-IDWJPCWK.js → capsule-merge-Q6AR3XL7.js} +67 -54
  88. package/dist/capsule-merge-Q6AR3XL7.js.map +1 -0
  89. package/dist/{catalog-scBmy0sO.d.ts → catalog-bctMURhN.d.ts} +1 -1
  90. package/dist/causal-behavior.d.ts +2 -1
  91. package/dist/causal-behavior.js +2 -2
  92. package/dist/causal-chain.js +2 -2
  93. package/dist/causal-consolidation.d.ts +2 -1
  94. package/dist/causal-consolidation.js +28 -26
  95. package/dist/causal-consolidation.js.map +1 -1
  96. package/dist/causal-retrieval.js +2 -2
  97. package/dist/causal-trajectory-graph.d.ts +2 -1
  98. package/dist/causal-trajectory.js +1 -1
  99. package/dist/{chunk-E5UK4VPE.js → chunk-2FSTB6BJ.js} +5 -5
  100. package/dist/{chunk-5ZE7QHTK.js → chunk-2X2T2UVE.js} +5 -5
  101. package/dist/{chunk-P4DRWEYC.js → chunk-3COYXTGM.js} +2 -2
  102. package/dist/{chunk-5IVLTFOV.js → chunk-44N6ESJ4.js} +2 -2
  103. package/dist/{chunk-DL7ZD3JH.js → chunk-4FBVAGV3.js} +14 -9
  104. package/dist/chunk-4FBVAGV3.js.map +1 -0
  105. package/dist/{chunk-WOCNN776.js → chunk-4POAMKV6.js} +100 -41
  106. package/dist/chunk-4POAMKV6.js.map +1 -0
  107. package/dist/{chunk-HO3QBJEY.js → chunk-5546W5SI.js} +2 -2
  108. package/dist/{chunk-AAIUERNB.js → chunk-5QJQHBLE.js} +6 -6
  109. package/dist/{chunk-6CZPDBJS.js → chunk-5U7ID3EZ.js} +3 -3
  110. package/dist/{chunk-RN7DY3FC.js → chunk-6ISC4AVB.js} +31 -12
  111. package/dist/chunk-6ISC4AVB.js.map +1 -0
  112. package/dist/chunk-773TRRGT.js +36 -0
  113. package/dist/chunk-773TRRGT.js.map +1 -0
  114. package/dist/chunk-7T4TOGMS.js +242 -0
  115. package/dist/chunk-7T4TOGMS.js.map +1 -0
  116. package/dist/{chunk-DLVPUX7U.js → chunk-7YKVM5H3.js} +8 -6
  117. package/dist/chunk-7YKVM5H3.js.map +1 -0
  118. package/dist/chunk-7YQ6ESEA.js +322 -0
  119. package/dist/chunk-7YQ6ESEA.js.map +1 -0
  120. package/dist/{chunk-DNWXFTLD.js → chunk-A4IJCD2Z.js} +2 -2
  121. package/dist/{chunk-3CE77VAP.js → chunk-A4JMGKCD.js} +87 -74
  122. package/dist/chunk-A4JMGKCD.js.map +1 -0
  123. package/dist/chunk-A5KNZSNA.js +26 -0
  124. package/dist/chunk-A5KNZSNA.js.map +1 -0
  125. package/dist/{chunk-PKNLM44P.js → chunk-AC5OWJLV.js} +9 -9
  126. package/dist/{chunk-LZ4LDKHZ.js → chunk-AMAUBUKY.js} +6 -6
  127. package/dist/{chunk-CUM2BBPN.js → chunk-AUMWZSE7.js} +19 -10
  128. package/dist/chunk-AUMWZSE7.js.map +1 -0
  129. package/dist/{chunk-BUE5E2HL.js → chunk-BGLY7EEM.js} +5 -314
  130. package/dist/chunk-BGLY7EEM.js.map +1 -0
  131. package/dist/chunk-BIPBQQFI.js +44 -0
  132. package/dist/chunk-BIPBQQFI.js.map +1 -0
  133. package/dist/{chunk-S5SLVSVY.js → chunk-BQIFZ2MP.js} +5 -5
  134. package/dist/chunk-BTTPKDIL.js +34 -0
  135. package/dist/{chunk-PVGDJXVK.js.map → chunk-BTTPKDIL.js.map} +1 -1
  136. package/dist/chunk-CK5KOVHW.js +69 -0
  137. package/dist/chunk-CK5KOVHW.js.map +1 -0
  138. package/dist/{chunk-Q6IP2ARR.js → chunk-CSOYVTRX.js} +2 -2
  139. package/dist/{chunk-XOQSEF7X.js → chunk-CVILPI77.js} +6 -6
  140. package/dist/{chunk-VWAXN2BN.js → chunk-CX4ZUMC6.js} +91 -83
  141. package/dist/chunk-CX4ZUMC6.js.map +1 -0
  142. package/dist/{chunk-NVRYW264.js → chunk-DAJPRXBR.js} +16 -13
  143. package/dist/chunk-DAJPRXBR.js.map +1 -0
  144. package/dist/{chunk-J7VGGECD.js → chunk-DZPFMQZ7.js} +1 -1
  145. package/dist/chunk-DZPFMQZ7.js.map +1 -0
  146. package/dist/{chunk-4LMA77JH.js → chunk-E5XQIWAL.js} +3 -3
  147. package/dist/{chunk-WUNIWKY4.js → chunk-ELIL2A37.js} +6 -6
  148. package/dist/{chunk-OQ5PRDDS.js → chunk-ERZ2R42X.js} +6 -6
  149. package/dist/{chunk-U7GW7NE7.js → chunk-FIK3CQNA.js} +10 -10
  150. package/dist/{chunk-D3J5SLQK.js → chunk-FR27HBBA.js} +81 -20
  151. package/dist/chunk-FR27HBBA.js.map +1 -0
  152. package/dist/{chunk-E6PNLPGJ.js → chunk-FUCYDRE5.js} +838 -480
  153. package/dist/chunk-FUCYDRE5.js.map +1 -0
  154. package/dist/{chunk-HZFHQ4AQ.js → chunk-G7A5HLUS.js} +23 -17
  155. package/dist/chunk-G7A5HLUS.js.map +1 -0
  156. package/dist/{chunk-33PLLLL7.js → chunk-GFCVUY6G.js} +6 -6
  157. package/dist/{chunk-HREE4JHI.js → chunk-GODSPTOT.js} +477 -278
  158. package/dist/chunk-GODSPTOT.js.map +1 -0
  159. package/dist/{chunk-S2NCTZGJ.js → chunk-GRUYA45P.js} +15 -15
  160. package/dist/chunk-GRUYA45P.js.map +1 -0
  161. package/dist/{chunk-VUPTKTDV.js → chunk-GUAL4PQH.js} +3 -3
  162. package/dist/{chunk-CINZGPSJ.js → chunk-GUMZC2BO.js} +2 -2
  163. package/dist/{chunk-H24WNPA2.js → chunk-GWFSVJ4P.js} +3 -3
  164. package/dist/{chunk-7XC2HX75.js → chunk-GYPQL6XN.js} +157 -16
  165. package/dist/chunk-GYPQL6XN.js.map +1 -0
  166. package/dist/{chunk-TSH56VPU.js → chunk-HAYSYUAB.js} +2 -2
  167. package/dist/{chunk-PDLBLTOK.js → chunk-HC3PBX23.js} +9 -9
  168. package/dist/{chunk-TDHTVMPG.js → chunk-HFPASSFV.js} +7 -2
  169. package/dist/chunk-HFPASSFV.js.map +1 -0
  170. package/dist/chunk-J2WC5LF4.js +395 -0
  171. package/dist/chunk-J2WC5LF4.js.map +1 -0
  172. package/dist/{chunk-KXB4VXHY.js → chunk-JIYDRBVZ.js} +2 -2
  173. package/dist/chunk-JV3C2MNQ.js +74 -0
  174. package/dist/chunk-JV3C2MNQ.js.map +1 -0
  175. package/dist/{chunk-HLPD7B7P.js → chunk-JZH4LWHB.js} +2 -2
  176. package/dist/{chunk-AV5ZEH4M.js → chunk-KVJRXN2E.js} +2 -2
  177. package/dist/{chunk-WFTIGIIS.js → chunk-L6CQ7WIW.js} +5 -5
  178. package/dist/{chunk-227UFSEQ.js → chunk-LEPOP46W.js} +4 -4
  179. package/dist/{chunk-EJUEXZHX.js → chunk-LLJMAULE.js} +2 -2
  180. package/dist/{chunk-N5Z4EVOR.js → chunk-LNEWDF2A.js} +36 -11
  181. package/dist/chunk-LNEWDF2A.js.map +1 -0
  182. package/dist/{chunk-QN25OCUF.js → chunk-LPYDOLSM.js} +5 -5
  183. package/dist/{chunk-AS7YMSL6.js → chunk-M23RF3LJ.js} +4 -4
  184. package/dist/{chunk-OAEQLRCY.js → chunk-MO4HSXHZ.js} +5 -5
  185. package/dist/{chunk-ECK75GDJ.js → chunk-N3LL5NEU.js} +43 -24
  186. package/dist/chunk-N3LL5NEU.js.map +1 -0
  187. package/dist/chunk-NEF7LR5J.js +29 -0
  188. package/dist/chunk-NEF7LR5J.js.map +1 -0
  189. package/dist/{chunk-3F2LKUMU.js → chunk-NIS256NW.js} +2 -2
  190. package/dist/{chunk-YIAA2X3D.js → chunk-NK5RGJ65.js} +3 -3
  191. package/dist/chunk-NLDVVWCL.js +84 -0
  192. package/dist/chunk-NLDVVWCL.js.map +1 -0
  193. package/dist/{chunk-4J7G5SY4.js → chunk-NZBZ7IS2.js} +72 -24
  194. package/dist/chunk-NZBZ7IS2.js.map +1 -0
  195. package/dist/{chunk-3TBLDMJA.js → chunk-O4KMGRXE.js} +5 -2
  196. package/dist/chunk-O4KMGRXE.js.map +1 -0
  197. package/dist/{chunk-7TWUCYER.js → chunk-PNRA7FAD.js} +7 -7
  198. package/dist/{chunk-5I4M26Q7.js → chunk-QBSFOKY6.js} +4 -4
  199. package/dist/{chunk-E53DSZEN.js → chunk-QR6G5KF4.js} +3 -3
  200. package/dist/{chunk-CJ2ZR7UA.js → chunk-QUENPGWZ.js} +261 -211
  201. package/dist/chunk-QUENPGWZ.js.map +1 -0
  202. package/dist/{chunk-4UH4BTGK.js → chunk-QVJPH7SH.js} +84 -84
  203. package/dist/{chunk-UYLMNVY6.js → chunk-R3KHKU7M.js} +16 -9
  204. package/dist/chunk-R3KHKU7M.js.map +1 -0
  205. package/dist/{chunk-JBPKEARU.js → chunk-RKNJBZ55.js} +4 -4
  206. package/dist/{chunk-WDISJRMG.js → chunk-RMMVQQA6.js} +2 -2
  207. package/dist/{chunk-JVLCVFQ4.js → chunk-RNHVVMFN.js} +3 -3
  208. package/dist/{chunk-QJAQNXWI.js → chunk-RVO6TCTU.js} +81 -84
  209. package/dist/chunk-RVO6TCTU.js.map +1 -0
  210. package/dist/chunk-S2HLHAZ4.js +16 -0
  211. package/dist/chunk-S2HLHAZ4.js.map +1 -0
  212. package/dist/{chunk-KWMXR7XS.js → chunk-S2V7RUCL.js} +8 -1
  213. package/dist/{chunk-KWMXR7XS.js.map → chunk-S2V7RUCL.js.map} +1 -1
  214. package/dist/{chunk-5SM35XZR.js → chunk-S5NZBKKQ.js} +2 -2
  215. package/dist/{chunk-VNA7W7QF.js → chunk-SVH57F5Z.js} +12 -4
  216. package/dist/chunk-SVH57F5Z.js.map +1 -0
  217. package/dist/{chunk-WIPEXG6R.js → chunk-SXIMQLGV.js} +2 -2
  218. package/dist/{chunk-RVLJEII5.js → chunk-SYUBB3WM.js} +256 -187
  219. package/dist/chunk-SYUBB3WM.js.map +1 -0
  220. package/dist/{chunk-VCD4PSK2.js → chunk-TQZ4DVBC.js} +7 -4
  221. package/dist/chunk-TQZ4DVBC.js.map +1 -0
  222. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  223. package/dist/{chunk-YV32N67O.js → chunk-URS5GSM7.js} +1 -1
  224. package/dist/chunk-URS5GSM7.js.map +1 -0
  225. package/dist/{chunk-4B77XSG5.js → chunk-UV72DEZD.js} +5 -5
  226. package/dist/{chunk-BJKPPZ6Z.js → chunk-UW66OZTD.js} +2 -2
  227. package/dist/{chunk-XYTOI63Z.js → chunk-V2TNYF6Q.js} +19 -11
  228. package/dist/chunk-V2TNYF6Q.js.map +1 -0
  229. package/dist/{chunk-S2BBISHU.js → chunk-VANZKHTN.js} +3 -3
  230. package/dist/chunk-VHFXP27N.js +250 -0
  231. package/dist/chunk-VHFXP27N.js.map +1 -0
  232. package/dist/chunk-VL35ZFSZ.js +102 -0
  233. package/dist/chunk-VL35ZFSZ.js.map +1 -0
  234. package/dist/{chunk-3Y224NYC.js → chunk-VYISFWVX.js} +2 -2
  235. package/dist/{chunk-JE7EK33X.js → chunk-W2V7UESE.js} +2 -2
  236. package/dist/{chunk-TIHMZFIV.js → chunk-W3IC7QOY.js} +3 -3
  237. package/dist/{chunk-NRV4Y3PM.js → chunk-W4FBGYGK.js} +1 -1
  238. package/dist/{chunk-P2BM76KT.js → chunk-WAS4HV46.js} +174 -43
  239. package/dist/chunk-WAS4HV46.js.map +1 -0
  240. package/dist/{chunk-57QKLRBV.js → chunk-WB7JSQCP.js} +2 -1
  241. package/dist/chunk-WB7JSQCP.js.map +1 -0
  242. package/dist/{chunk-A5OJCXZL.js → chunk-WZ3TOIDW.js} +15 -4
  243. package/dist/chunk-WZ3TOIDW.js.map +1 -0
  244. package/dist/{chunk-MU7ZHSZE.js → chunk-WZFAPHIK.js} +2 -2
  245. package/dist/{chunk-T2TTP3KU.js → chunk-X4IDNPOS.js} +2 -2
  246. package/dist/{chunk-UVIKWC7M.js → chunk-XAGYS7X6.js} +17 -17
  247. package/dist/{chunk-BLAKS3CP.js → chunk-XL3TATMJ.js} +3 -3
  248. package/dist/{chunk-W4XJFLAL.js → chunk-XPRJSHNI.js} +2 -2
  249. package/dist/{chunk-5TFP4CUL.js → chunk-XQ3HXAQH.js} +14 -11
  250. package/dist/chunk-XQ3HXAQH.js.map +1 -0
  251. package/dist/{chunk-E6EE5B67.js → chunk-YK6BDDHP.js} +4 -4
  252. package/dist/{chunk-ES36HTSC.js → chunk-YLHM5BQQ.js} +3 -3
  253. package/dist/{chunk-ULARSG5Z.js → chunk-YN6ASZUG.js} +10 -8
  254. package/dist/{chunk-ULARSG5Z.js.map → chunk-YN6ASZUG.js.map} +1 -1
  255. package/dist/{chunk-VOUOLGIP.js → chunk-YRFAYOFQ.js} +11 -13
  256. package/dist/chunk-YRFAYOFQ.js.map +1 -0
  257. package/dist/{chunk-IKKWIPYN.js → chunk-YYQAKIDJ.js} +37 -1
  258. package/dist/chunk-YYQAKIDJ.js.map +1 -0
  259. package/dist/{chunk-GF22HWS2.js → chunk-Z54EM5YZ.js} +4 -4
  260. package/dist/{chunk-64UDOIMI.js → chunk-ZLQ37WJX.js} +2 -2
  261. package/dist/{cli-BUGN3d6_.d.ts → cli-BHBswmUa.d.ts} +5 -5
  262. package/dist/cli.d.ts +16 -12
  263. package/dist/cli.js +138 -123
  264. package/dist/compounding/engine.d.ts +3 -2
  265. package/dist/compounding/engine.js +25 -23
  266. package/dist/compounding/preference-consolidator.d.ts +2 -1
  267. package/dist/compression-optimizer.d.ts +2 -1
  268. package/dist/config.d.ts +2 -1
  269. package/dist/config.js +10 -8
  270. package/dist/connectors/codex-materialize-runner.d.ts +2 -1
  271. package/dist/connectors/codex-materialize-runner.js +24 -22
  272. package/dist/connectors/codex-materialize.d.ts +2 -1
  273. package/dist/connectors/index.d.ts +2 -1
  274. package/dist/connectors/index.js +27 -25
  275. package/dist/consolidation-provenance-check.d.ts +3 -2
  276. package/dist/consolidation-provenance-check.js +4 -4
  277. package/dist/consolidation-undo.d.ts +3 -2
  278. package/dist/consolidation-undo.js +10 -7
  279. package/dist/consolidation-undo.js.map +1 -1
  280. package/dist/contradiction/index.d.ts +3 -2
  281. package/dist/converge-config.d.ts +2 -1
  282. package/dist/convergence-refresh.d.ts +4 -3
  283. package/dist/convergence-refresh.js +28 -26
  284. package/dist/conversation-index/backend.d.ts +2 -1
  285. package/dist/conversation-index/backend.js +2 -2
  286. package/dist/conversation-index/chunker.d.ts +2 -1
  287. package/dist/conversation-index/faiss-adapter.d.ts +2 -1
  288. package/dist/conversation-index/indexer.d.ts +2 -1
  289. package/dist/conversation-index/search.d.ts +2 -1
  290. package/dist/corpus-watermark.d.ts +2 -1
  291. package/dist/corpus-watermark.js +43 -41
  292. package/dist/day-summary.d.ts +2 -1
  293. package/dist/delinearize.d.ts +2 -1
  294. package/dist/direct-answer-wiring.d.ts +2 -1
  295. package/dist/direct-answer-wiring.js +2 -2
  296. package/dist/direct-answer.d.ts +2 -1
  297. package/dist/embedding-fallback.d.ts +2 -1
  298. package/dist/embedding-fallback.js +2 -2
  299. package/dist/enrichment/index.d.ts +2 -1
  300. package/dist/entity-retrieval-boundaries.js +1 -1
  301. package/dist/entity-retrieval.d.ts +3 -2
  302. package/dist/entity-retrieval.js +25 -23
  303. package/dist/entity-schema.d.ts +2 -1
  304. package/dist/explicit-capture.d.ts +9 -8
  305. package/dist/explicit-capture.js +11 -9
  306. package/dist/external-wiki-access.d.ts +127 -0
  307. package/dist/external-wiki-access.js +187 -0
  308. package/dist/external-wiki-access.js.map +1 -0
  309. package/dist/external-wiki-cli.d.ts +13 -0
  310. package/dist/external-wiki-cli.js +10 -0
  311. package/dist/external-wiki-cli.js.map +1 -0
  312. package/dist/external-wiki-collection-registration.d.ts +39 -0
  313. package/dist/external-wiki-collection-registration.js +79 -0
  314. package/dist/external-wiki-collection-registration.js.map +1 -0
  315. package/dist/external-wiki-collection.d.ts +50 -0
  316. package/dist/external-wiki-collection.js +387 -0
  317. package/dist/external-wiki-collection.js.map +1 -0
  318. package/dist/external-wiki-config.d.ts +13 -0
  319. package/dist/external-wiki-config.js +13 -0
  320. package/dist/external-wiki-config.js.map +1 -0
  321. package/dist/external-wiki-guard.d.ts +11 -0
  322. package/dist/external-wiki-guard.js +18 -0
  323. package/dist/external-wiki-guard.js.map +1 -0
  324. package/dist/external-wiki-mcp-tools.d.ts +123 -0
  325. package/dist/external-wiki-mcp-tools.js +8 -0
  326. package/dist/external-wiki-mcp-tools.js.map +1 -0
  327. package/dist/external-wiki-search.d.ts +42 -0
  328. package/dist/external-wiki-search.js +11 -0
  329. package/dist/external-wiki-search.js.map +1 -0
  330. package/dist/external-wiki.d.ts +39 -0
  331. package/dist/external-wiki.js +14 -0
  332. package/dist/external-wiki.js.map +1 -0
  333. package/dist/extraction-error-classification.d.ts +2 -1
  334. package/dist/extraction-faithfulness.d.ts +2 -1
  335. package/dist/extraction-judge-telemetry.d.ts +2 -1
  336. package/dist/extraction-judge-training.d.ts +2 -1
  337. package/dist/extraction-judge.d.ts +2 -1
  338. package/dist/extraction-liveness.d.ts +2 -1
  339. package/dist/extraction-source-grounding-helpers.d.ts +5 -3
  340. package/dist/extraction-source-grounding-helpers.js +1 -1
  341. package/dist/extraction-source-grounding-rules.d.ts +2 -1
  342. package/dist/extraction-source-grounding-rules.js +2 -2
  343. package/dist/extraction-source-grounding.d.ts +2 -1
  344. package/dist/extraction-source-grounding.js +5 -5
  345. package/dist/extraction.d.ts +2 -1
  346. package/dist/extraction.js +46 -43
  347. package/dist/fallback-llm.d.ts +2 -1
  348. package/dist/{first-start-migration-F2QJD66E.js → first-start-migration-ZSHEFEI3.js} +10 -12
  349. package/dist/{first-start-migration-F2QJD66E.js.map → first-start-migration-ZSHEFEI3.js.map} +1 -1
  350. package/dist/graph-dashboard-diff.d.ts +2 -1
  351. package/dist/graph-dashboard-key.d.ts +2 -1
  352. package/dist/graph-dashboard-parser.d.ts +2 -1
  353. package/dist/graph-edge-reinforcement.d.ts +2 -1
  354. package/dist/graph-snapshot.d.ts +2 -1
  355. package/dist/graph.d.ts +2 -1
  356. package/dist/harmonic-retrieval.js +2 -2
  357. package/dist/importance.d.ts +2 -1
  358. package/dist/importers/index.d.ts +2 -1
  359. package/dist/in-flight-reads.d.ts +2 -1
  360. package/dist/index.d.ts +443 -430
  361. package/dist/index.js +304 -269
  362. package/dist/intent.d.ts +2 -1
  363. package/dist/lcm/engine.d.ts +2 -1
  364. package/dist/lcm/engine.js +2 -2
  365. package/dist/lcm/index.d.ts +2 -1
  366. package/dist/lcm/index.js +7 -7
  367. package/dist/lcm/tools.d.ts +2 -1
  368. package/dist/lifecycle.d.ts +2 -1
  369. package/dist/live-connectors-runner.d.ts +2 -1
  370. package/dist/local-llm.d.ts +2 -1
  371. package/dist/local-llm.js +2 -2
  372. package/dist/local-model-endpoint.d.ts +2 -1
  373. package/dist/maintenance/memory-governance.d.ts +2 -1
  374. package/dist/maintenance/memory-governance.js +25 -23
  375. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +3 -2
  376. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +25 -23
  377. package/dist/maintenance/rebuild-memory-projection.d.ts +3 -2
  378. package/dist/maintenance/rebuild-memory-projection.js +27 -25
  379. package/dist/{maintenance-LbuS2rUA.d.ts → maintenance-CoRikzIt.d.ts} +3 -3
  380. package/dist/mcp-memory-inspector-app.d.ts +14 -10
  381. package/dist/mcp-read-only-tools.js +1 -1
  382. package/dist/memory-action-policy.d.ts +2 -1
  383. package/dist/memory-cache.d.ts +2 -1
  384. package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
  385. package/dist/memory-projection-store.d.ts +2 -1
  386. package/dist/memory-provenance.d.ts +2 -1
  387. package/dist/memory-snapshot.d.ts +10 -0
  388. package/dist/memory-snapshot.js +8 -0
  389. package/dist/memory-snapshot.js.map +1 -0
  390. package/dist/memory-worth-outcomes.d.ts +3 -2
  391. package/dist/models-json.d.ts +2 -1
  392. package/dist/namespaces/migrate.d.ts +4 -3
  393. package/dist/namespaces/migrate.js +41 -39
  394. package/dist/namespaces/principal.d.ts +2 -1
  395. package/dist/namespaces/search.d.ts +2 -1
  396. package/dist/namespaces/search.js +18 -18
  397. package/dist/namespaces/storage.d.ts +4 -3
  398. package/dist/namespaces/storage.js +24 -22
  399. package/dist/native-knowledge.d.ts +2 -1
  400. package/dist/offline-sync-impression-drain.d.ts +2 -1
  401. package/dist/offline-sync-impression-drain.js +11 -9
  402. package/dist/offline-sync.d.ts +29 -3
  403. package/dist/offline-sync.js +6 -2
  404. package/dist/operator-doctor-corpus.d.ts +2 -1
  405. package/dist/operator-doctor-corpus.js +46 -44
  406. package/dist/operator-doctor-replica.d.ts +2 -1
  407. package/dist/operator-doctor-replica.js +3 -3
  408. package/dist/operator-toolkit.d.ts +4 -3
  409. package/dist/operator-toolkit.js +60 -55
  410. package/dist/orchestration/compression-guideline-coordinator.d.ts +3 -2
  411. package/dist/orchestration/maintenance.d.ts +5 -4
  412. package/dist/orchestration/maintenance.js +37 -33
  413. package/dist/{orchestrator-rHiWt32X.d.ts → orchestrator-BJeq7Pw1.d.ts} +14 -7
  414. package/dist/orchestrator.d.ts +9 -8
  415. package/dist/orchestrator.js +200 -186
  416. package/dist/page-versioning.js +3 -3
  417. package/dist/patterns-cli.d.ts +2 -1
  418. package/dist/{pipeline-W_97O8BV.d.ts → pipeline-CNjY4wk3.d.ts} +1 -1
  419. package/dist/policy-runtime.d.ts +2 -1
  420. package/dist/policy-runtime.js +1 -1
  421. package/dist/proactive-contention.d.ts +2 -1
  422. package/dist/provenance.d.ts +2 -1
  423. package/dist/provenance.js +2 -2
  424. package/dist/{qmd-LWtMofAf.d.ts → qmd-C0UDZidt.d.ts} +9 -7
  425. package/dist/qmd-preflight.d.ts +5 -4
  426. package/dist/qmd-preflight.js +2 -2
  427. package/dist/qmd-recall-cache.d.ts +2 -1
  428. package/dist/qmd.d.ts +4 -3
  429. package/dist/qmd.js +8 -8
  430. package/dist/recall-concurrency-config.d.ts +2 -1
  431. package/dist/recall-disclosure-escalation.d.ts +2 -1
  432. package/dist/recall-explain-renderer.d.ts +2 -1
  433. package/dist/recall-explain-renderer.js +3 -3
  434. package/dist/recall-memory-map.d.ts +2 -1
  435. package/dist/recall-planner-llm.d.ts +2 -1
  436. package/dist/recall-state.d.ts +2 -1
  437. package/dist/recall-tag-filter.d.ts +2 -1
  438. package/dist/recall-timings.d.ts +2 -1
  439. package/dist/recall-xray-cli.d.ts +2 -1
  440. package/dist/recall-xray-cli.js +4 -4
  441. package/dist/recall-xray-renderer.d.ts +2 -1
  442. package/dist/recall-xray-renderer.js +3 -3
  443. package/dist/recall-xray.d.ts +8 -1
  444. package/dist/recall-xray.js +2 -2
  445. package/dist/reconcile/cursor.d.ts +12 -2
  446. package/dist/reconcile/cursor.js +46 -7
  447. package/dist/reconcile/cursor.js.map +1 -1
  448. package/dist/reconcile/manifest.d.ts +9 -2
  449. package/dist/reconcile/manifest.js +15 -268
  450. package/dist/reconcile/manifest.js.map +1 -1
  451. package/dist/reconcile/plan.d.ts +4 -1
  452. package/dist/reconcile/plan.js +4 -4
  453. package/dist/replay/normalizers/chatgpt.d.ts +2 -1
  454. package/dist/replay/normalizers/claude.d.ts +2 -1
  455. package/dist/replay/normalizers/openclaw.d.ts +2 -1
  456. package/dist/replay/normalizers/shared.d.ts +2 -1
  457. package/dist/replay/runner.d.ts +2 -1
  458. package/dist/replay/types.d.ts +2 -1
  459. package/dist/replica-divergence.d.ts +2 -1
  460. package/dist/replica-divergence.js +2 -2
  461. package/dist/replica-peers-config.d.ts +2 -1
  462. package/dist/resolve-auth-token.d.ts +2 -1
  463. package/dist/resume-bundles.js +12 -10
  464. package/dist/retrieval-agents.d.ts +4 -3
  465. package/dist/retrieval-agents.js +2 -2
  466. package/dist/retrieval-tiers.d.ts +2 -1
  467. package/dist/routing/engine.d.ts +2 -1
  468. package/dist/routing/store.d.ts +2 -1
  469. package/dist/salvage-envelope.d.ts +2 -1
  470. package/dist/schemas.d.ts +54 -54
  471. package/dist/{scope-profiles-BiQKOE-p.d.ts → scope-profiles-BJzp2F5A.d.ts} +1 -1
  472. package/dist/search/embed-helper.d.ts +2 -1
  473. package/dist/search/embed-helper.js +3 -3
  474. package/dist/search/factory.d.ts +4 -2
  475. package/dist/search/factory.js +20 -18
  476. package/dist/search/index.d.ts +2 -1
  477. package/dist/search/index.js +20 -20
  478. package/dist/search/lancedb-backend.d.ts +2 -1
  479. package/dist/search/lancedb-backend.js +4 -4
  480. package/dist/search/meilisearch-backend.d.ts +2 -1
  481. package/dist/search/meilisearch-backend.js +4 -4
  482. package/dist/search/noop-backend.d.ts +2 -1
  483. package/dist/search/orama-backend.d.ts +2 -1
  484. package/dist/search/orama-backend.js +4 -4
  485. package/dist/search/port.d.ts +18 -1
  486. package/dist/search/port.js +1 -1
  487. package/dist/search/remote-backend.d.ts +2 -1
  488. package/dist/search/remote-backend.js +2 -2
  489. package/dist/secure-store/index.js +2 -2
  490. package/dist/{semantic-consolidation-dHYCyqgh.d.ts → semantic-consolidation-D4KAZO2G.d.ts} +1 -1
  491. package/dist/semantic-consolidation.d.ts +3 -2
  492. package/dist/semantic-consolidation.js +26 -24
  493. package/dist/semantic-rule-promotion.js +24 -22
  494. package/dist/semantic-rule-verifier.d.ts +2 -1
  495. package/dist/semantic-rule-verifier.js +25 -23
  496. package/dist/{service-DJG3KCQ4.d.ts → service-DWC4tq7p.d.ts} +2 -2
  497. package/dist/session-observer-bands.d.ts +2 -1
  498. package/dist/session-observer-state.d.ts +2 -1
  499. package/dist/shared-context/manager.d.ts +10 -9
  500. package/dist/shared-context/manager.js +2 -2
  501. package/dist/signal.d.ts +2 -1
  502. package/dist/source-agent-qualifier.d.ts +2 -1
  503. package/dist/source-agent-qualifier.js +43 -40
  504. package/dist/{storage-F9FVh-w9.d.ts → storage-DPGjB-8e.d.ts} +28 -13
  505. package/dist/storage.d.ts +3 -2
  506. package/dist/storage.js +26 -24
  507. package/dist/summarizer.d.ts +2 -1
  508. package/dist/summarizer.js +5 -5
  509. package/dist/summary-snapshot.d.ts +2 -1
  510. package/dist/temporal-supersession.d.ts +3 -2
  511. package/dist/temporal-timeline-recall.d.ts +2 -1
  512. package/dist/temporal-validity.d.ts +2 -1
  513. package/dist/threading.d.ts +2 -1
  514. package/dist/tier-migration.d.ts +3 -2
  515. package/dist/tier-migration.js +1 -1
  516. package/dist/tier-routing.d.ts +2 -1
  517. package/dist/tool-scoped-memory.d.ts +5 -1
  518. package/dist/tool-scoped-memory.js +3 -1
  519. package/dist/topics.d.ts +2 -1
  520. package/dist/transcript.d.ts +2 -1
  521. package/dist/transfer/capsule-import.js +4 -4
  522. package/dist/transfer/types.d.ts +66 -66
  523. package/dist/trust-score-stage.d.ts +2 -1
  524. package/dist/trust-score.d.ts +2 -1
  525. package/dist/{types-rEwubvim.d.ts → types-yX_FwERf.d.ts} +8 -1
  526. package/dist/types.d.ts +2 -1
  527. package/dist/types.js +1 -1
  528. package/dist/utility-runtime.d.ts +2 -1
  529. package/dist/verified-recall.js +25 -23
  530. package/dist/write-envelope.d.ts +2 -1
  531. package/package.json +2 -2
  532. package/src/abort-error.ts +17 -0
  533. package/src/access-admin-ops-surface.ts +1 -0
  534. package/src/access-boundary.ts +1 -0
  535. package/src/access-coding-context-resolution.ts +42 -0
  536. package/src/access-extraction-force-flush.ts +38 -2
  537. package/src/access-http-lcm-compaction.ts +5 -2
  538. package/src/access-http-offline-stream.ts +80 -0
  539. package/src/access-http.test.ts +310 -3
  540. package/src/access-http.ts +84 -77
  541. package/src/access-mcp-output-schemas.ts +36 -0
  542. package/src/access-mcp.test.ts +95 -1
  543. package/src/access-mcp.ts +7 -9
  544. package/src/access-observe-helpers.ts +64 -22
  545. package/src/access-observe-write-surface.ts +8 -0
  546. package/src/access-offline-manifest.ts +54 -0
  547. package/src/access-operations-batch.ts +3 -3
  548. package/src/access-operations.ts +13 -7
  549. package/src/access-recall-concurrency.ts +3 -27
  550. package/src/access-recall-surface.ts +3 -0
  551. package/src/access-service-health.test.ts +32 -7
  552. package/src/access-service-namespace.test.ts +55 -0
  553. package/src/access-service-observe-idempotency.test.ts +34 -2
  554. package/src/access-service-observe-lcm-parity.test.ts +183 -23
  555. package/src/access-service-observe-scope.test.ts +160 -1
  556. package/src/access-service-offline-file-content.test.ts +345 -1
  557. package/src/access-service.ts +88 -62
  558. package/src/access-surface-catalog.ts +4 -0
  559. package/src/admin/admin-surfaces.ts +2 -0
  560. package/src/binary-lifecycle/pipeline.test.ts +106 -1
  561. package/src/binary-lifecycle/pipeline.ts +3 -0
  562. package/src/coding/git-context.test.ts +47 -0
  563. package/src/coding/git-context.ts +129 -27
  564. package/src/config.test.ts +24 -0
  565. package/src/config.ts +9 -12
  566. package/src/connector-provenance.test.ts +101 -0
  567. package/src/consolidation-undo.ts +3 -0
  568. package/src/convergence-refresh.ts +14 -2
  569. package/src/correction/correction-access-wiring.ts +9 -7
  570. package/src/correction/correction-executor.test.ts +206 -2
  571. package/src/correction/correction-executor.ts +29 -20
  572. package/src/correction/correction-planner.test.ts +36 -0
  573. package/src/correction/correction-planner.ts +9 -15
  574. package/src/correction/correction-service.ts +3 -1
  575. package/src/correction/correction-storage-integration.test.ts +77 -0
  576. package/src/correction/correction-surfaces.test.ts +41 -28
  577. package/src/correction/passive-capture.test.ts +59 -0
  578. package/src/correction/passive-capture.ts +4 -1
  579. package/src/entity-retrieval-boundaries.ts +17 -4
  580. package/src/entity-retrieval.ts +27 -6
  581. package/src/external-wiki-access.test.ts +65 -0
  582. package/src/external-wiki-access.ts +31 -0
  583. package/src/external-wiki-cli.ts +100 -0
  584. package/src/external-wiki-collection-registration.test.ts +163 -0
  585. package/src/external-wiki-collection-registration.ts +101 -0
  586. package/src/external-wiki-collection.test.ts +502 -0
  587. package/src/external-wiki-collection.ts +503 -0
  588. package/src/external-wiki-config.test.ts +135 -0
  589. package/src/external-wiki-config.ts +100 -0
  590. package/src/external-wiki-guard.ts +83 -0
  591. package/src/external-wiki-mcp-tools.ts +23 -0
  592. package/src/external-wiki-search.test.ts +367 -0
  593. package/src/external-wiki-search.ts +362 -0
  594. package/src/external-wiki.test.ts +240 -0
  595. package/src/external-wiki.ts +427 -0
  596. package/src/extraction-scope-source-agent.test.ts +21 -0
  597. package/src/extraction-source-grounding-helpers.ts +243 -53
  598. package/src/extraction-source-grounding-rules.ts +133 -39
  599. package/src/extraction-source-grounding.test.ts +363 -33
  600. package/src/extraction-timeout.test.ts +1 -0
  601. package/src/extraction-watermark.test.ts +150 -7
  602. package/src/extraction.ts +8 -1
  603. package/src/index.ts +9 -5
  604. package/src/maintenance/first-start-migration.ts +11 -11
  605. package/src/mcp-read-only-tools.ts +1 -0
  606. package/src/memory-snapshot.ts +15 -0
  607. package/src/offline-sync.test.ts +194 -0
  608. package/src/offline-sync.ts +217 -13
  609. package/src/orchestration/external-wiki-recall-guard.test.ts +94 -0
  610. package/src/orchestration/extraction-persist.ts +19 -2
  611. package/src/orchestration/extraction-run-helpers.ts +37 -19
  612. package/src/orchestration/extraction-run.test.ts +171 -2
  613. package/src/orchestration/extraction-run.ts +11 -13
  614. package/src/orchestration/extraction-watermark.ts +106 -17
  615. package/src/orchestration/generic-recall-paths.ts +14 -0
  616. package/src/orchestration/orchestrator-helpers.ts +2 -0
  617. package/src/orchestration/orchestrator-init.ts +9 -0
  618. package/src/orchestration/recall-internal-deps.ts +6 -0
  619. package/src/orchestration/recall-internal.ts +154 -33
  620. package/src/orchestration/recall-rerank-coordinator.ts +60 -25
  621. package/src/orchestration/recall-search-pipeline.test.ts +75 -1
  622. package/src/orchestration/recall-search-pipeline.ts +50 -10
  623. package/src/orchestrator-convergence-refresh.test.ts +36 -2
  624. package/src/orchestrator.ts +13 -3
  625. package/src/page-versioning.ts +5 -19
  626. package/src/procedural/procedure-recall.ts +5 -1
  627. package/src/provenance-surfaces.test.ts +3 -0
  628. package/src/qmd-client.test.ts +78 -17
  629. package/src/qmd.test.ts +24 -0
  630. package/src/qmd.ts +224 -315
  631. package/src/recall-explain-renderer.ts +3 -0
  632. package/src/recall-rerank-coordinator.test.ts +61 -0
  633. package/src/recall-xray-renderer.test.ts +6 -0
  634. package/src/recall-xray.test.ts +88 -1
  635. package/src/recall-xray.ts +15 -0
  636. package/src/reconcile/cursor.test.ts +48 -0
  637. package/src/reconcile/cursor.ts +58 -11
  638. package/src/reconcile/manifest.test.ts +4 -0
  639. package/src/reconcile/manifest.ts +41 -51
  640. package/src/reconcile/plan.test.ts +4 -0
  641. package/src/reconcile/plan.ts +28 -16
  642. package/src/search/factory.ts +6 -6
  643. package/src/search/port.ts +25 -9
  644. package/src/secure-store/secure-fs.ts +20 -12
  645. package/src/secure-store/secure-store.test.ts +41 -2
  646. package/src/spaces/index.test.ts +61 -2
  647. package/src/spaces/index.ts +44 -18
  648. package/src/storage/entity-alias-config.ts +97 -0
  649. package/src/storage/entity-canonical-id-lock.ts +53 -23
  650. package/src/storage/entity-canonical-id-migration.ts +53 -22
  651. package/src/storage/entity-canonical-id-references.ts +3 -0
  652. package/src/storage/entity-id-safety.ts +7 -0
  653. package/src/storage/entity-store.ts +6 -2
  654. package/src/storage/memory-frontmatter-metadata.ts +4 -9
  655. package/src/storage/memory-migration-serialization.ts +10 -15
  656. package/src/storage/tombstone-blocked-capture-mutation.ts +52 -64
  657. package/src/storage/tombstone-blocked-capture-sync.ts +244 -199
  658. package/src/storage-contract/cache-coherence.test.ts +99 -0
  659. package/src/storage-deletion-revisions.test.ts +91 -0
  660. package/src/storage-fact-hash-index-defer.test.ts +460 -170
  661. package/src/storage.ts +572 -284
  662. package/src/testing/subjects/first-start-tier-migration.test.ts +75 -0
  663. package/src/tier-migration.ts +10 -12
  664. package/src/tool-scoped-memory.ts +10 -0
  665. package/src/transfer/capsule-import.ts +13 -0
  666. package/src/transfer/capsule-merge.ts +13 -0
  667. package/src/trust-score-recall-paths.test.ts +75 -1
  668. package/src/types.ts +7 -3
  669. package/dist/capsule-merge-IDWJPCWK.js.map +0 -1
  670. package/dist/chunk-3CE77VAP.js.map +0 -1
  671. package/dist/chunk-3TBLDMJA.js.map +0 -1
  672. package/dist/chunk-4J7G5SY4.js.map +0 -1
  673. package/dist/chunk-57QKLRBV.js.map +0 -1
  674. package/dist/chunk-5TFP4CUL.js.map +0 -1
  675. package/dist/chunk-7XC2HX75.js.map +0 -1
  676. package/dist/chunk-A5OJCXZL.js.map +0 -1
  677. package/dist/chunk-BUE5E2HL.js.map +0 -1
  678. package/dist/chunk-CJ2ZR7UA.js.map +0 -1
  679. package/dist/chunk-CUM2BBPN.js.map +0 -1
  680. package/dist/chunk-D3J5SLQK.js.map +0 -1
  681. package/dist/chunk-DL7ZD3JH.js.map +0 -1
  682. package/dist/chunk-DLVPUX7U.js.map +0 -1
  683. package/dist/chunk-E6PNLPGJ.js.map +0 -1
  684. package/dist/chunk-ECK75GDJ.js.map +0 -1
  685. package/dist/chunk-HREE4JHI.js.map +0 -1
  686. package/dist/chunk-HZFHQ4AQ.js.map +0 -1
  687. package/dist/chunk-IKKWIPYN.js.map +0 -1
  688. package/dist/chunk-J7VGGECD.js.map +0 -1
  689. package/dist/chunk-N5Z4EVOR.js.map +0 -1
  690. package/dist/chunk-NVRYW264.js.map +0 -1
  691. package/dist/chunk-P2BM76KT.js.map +0 -1
  692. package/dist/chunk-PVGDJXVK.js +0 -21
  693. package/dist/chunk-QJAQNXWI.js.map +0 -1
  694. package/dist/chunk-RN7DY3FC.js.map +0 -1
  695. package/dist/chunk-RVLJEII5.js.map +0 -1
  696. package/dist/chunk-S2NCTZGJ.js.map +0 -1
  697. package/dist/chunk-TDHTVMPG.js.map +0 -1
  698. package/dist/chunk-UYLMNVY6.js.map +0 -1
  699. package/dist/chunk-VCD4PSK2.js.map +0 -1
  700. package/dist/chunk-VNA7W7QF.js.map +0 -1
  701. package/dist/chunk-VOUOLGIP.js.map +0 -1
  702. package/dist/chunk-VWAXN2BN.js.map +0 -1
  703. package/dist/chunk-WOCNN776.js.map +0 -1
  704. package/dist/chunk-XYTOI63Z.js.map +0 -1
  705. package/dist/chunk-YV32N67O.js.map +0 -1
  706. /package/dist/{auto-sync-5OE5QOZB.js.map → auto-sync-UPTUVE4X.js.map} +0 -0
  707. /package/dist/{chunk-E5UK4VPE.js.map → chunk-2FSTB6BJ.js.map} +0 -0
  708. /package/dist/{chunk-5ZE7QHTK.js.map → chunk-2X2T2UVE.js.map} +0 -0
  709. /package/dist/{chunk-P4DRWEYC.js.map → chunk-3COYXTGM.js.map} +0 -0
  710. /package/dist/{chunk-5IVLTFOV.js.map → chunk-44N6ESJ4.js.map} +0 -0
  711. /package/dist/{chunk-HO3QBJEY.js.map → chunk-5546W5SI.js.map} +0 -0
  712. /package/dist/{chunk-AAIUERNB.js.map → chunk-5QJQHBLE.js.map} +0 -0
  713. /package/dist/{chunk-6CZPDBJS.js.map → chunk-5U7ID3EZ.js.map} +0 -0
  714. /package/dist/{chunk-DNWXFTLD.js.map → chunk-A4IJCD2Z.js.map} +0 -0
  715. /package/dist/{chunk-PKNLM44P.js.map → chunk-AC5OWJLV.js.map} +0 -0
  716. /package/dist/{chunk-LZ4LDKHZ.js.map → chunk-AMAUBUKY.js.map} +0 -0
  717. /package/dist/{chunk-S5SLVSVY.js.map → chunk-BQIFZ2MP.js.map} +0 -0
  718. /package/dist/{chunk-Q6IP2ARR.js.map → chunk-CSOYVTRX.js.map} +0 -0
  719. /package/dist/{chunk-XOQSEF7X.js.map → chunk-CVILPI77.js.map} +0 -0
  720. /package/dist/{chunk-4LMA77JH.js.map → chunk-E5XQIWAL.js.map} +0 -0
  721. /package/dist/{chunk-WUNIWKY4.js.map → chunk-ELIL2A37.js.map} +0 -0
  722. /package/dist/{chunk-OQ5PRDDS.js.map → chunk-ERZ2R42X.js.map} +0 -0
  723. /package/dist/{chunk-U7GW7NE7.js.map → chunk-FIK3CQNA.js.map} +0 -0
  724. /package/dist/{chunk-33PLLLL7.js.map → chunk-GFCVUY6G.js.map} +0 -0
  725. /package/dist/{chunk-VUPTKTDV.js.map → chunk-GUAL4PQH.js.map} +0 -0
  726. /package/dist/{chunk-CINZGPSJ.js.map → chunk-GUMZC2BO.js.map} +0 -0
  727. /package/dist/{chunk-H24WNPA2.js.map → chunk-GWFSVJ4P.js.map} +0 -0
  728. /package/dist/{chunk-TSH56VPU.js.map → chunk-HAYSYUAB.js.map} +0 -0
  729. /package/dist/{chunk-PDLBLTOK.js.map → chunk-HC3PBX23.js.map} +0 -0
  730. /package/dist/{chunk-KXB4VXHY.js.map → chunk-JIYDRBVZ.js.map} +0 -0
  731. /package/dist/{chunk-HLPD7B7P.js.map → chunk-JZH4LWHB.js.map} +0 -0
  732. /package/dist/{chunk-AV5ZEH4M.js.map → chunk-KVJRXN2E.js.map} +0 -0
  733. /package/dist/{chunk-WFTIGIIS.js.map → chunk-L6CQ7WIW.js.map} +0 -0
  734. /package/dist/{chunk-227UFSEQ.js.map → chunk-LEPOP46W.js.map} +0 -0
  735. /package/dist/{chunk-EJUEXZHX.js.map → chunk-LLJMAULE.js.map} +0 -0
  736. /package/dist/{chunk-QN25OCUF.js.map → chunk-LPYDOLSM.js.map} +0 -0
  737. /package/dist/{chunk-AS7YMSL6.js.map → chunk-M23RF3LJ.js.map} +0 -0
  738. /package/dist/{chunk-OAEQLRCY.js.map → chunk-MO4HSXHZ.js.map} +0 -0
  739. /package/dist/{chunk-3F2LKUMU.js.map → chunk-NIS256NW.js.map} +0 -0
  740. /package/dist/{chunk-YIAA2X3D.js.map → chunk-NK5RGJ65.js.map} +0 -0
  741. /package/dist/{chunk-7TWUCYER.js.map → chunk-PNRA7FAD.js.map} +0 -0
  742. /package/dist/{chunk-5I4M26Q7.js.map → chunk-QBSFOKY6.js.map} +0 -0
  743. /package/dist/{chunk-E53DSZEN.js.map → chunk-QR6G5KF4.js.map} +0 -0
  744. /package/dist/{chunk-4UH4BTGK.js.map → chunk-QVJPH7SH.js.map} +0 -0
  745. /package/dist/{chunk-JBPKEARU.js.map → chunk-RKNJBZ55.js.map} +0 -0
  746. /package/dist/{chunk-WDISJRMG.js.map → chunk-RMMVQQA6.js.map} +0 -0
  747. /package/dist/{chunk-JVLCVFQ4.js.map → chunk-RNHVVMFN.js.map} +0 -0
  748. /package/dist/{chunk-5SM35XZR.js.map → chunk-S5NZBKKQ.js.map} +0 -0
  749. /package/dist/{chunk-WIPEXG6R.js.map → chunk-SXIMQLGV.js.map} +0 -0
  750. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  751. /package/dist/{chunk-4B77XSG5.js.map → chunk-UV72DEZD.js.map} +0 -0
  752. /package/dist/{chunk-BJKPPZ6Z.js.map → chunk-UW66OZTD.js.map} +0 -0
  753. /package/dist/{chunk-S2BBISHU.js.map → chunk-VANZKHTN.js.map} +0 -0
  754. /package/dist/{chunk-3Y224NYC.js.map → chunk-VYISFWVX.js.map} +0 -0
  755. /package/dist/{chunk-JE7EK33X.js.map → chunk-W2V7UESE.js.map} +0 -0
  756. /package/dist/{chunk-TIHMZFIV.js.map → chunk-W3IC7QOY.js.map} +0 -0
  757. /package/dist/{chunk-NRV4Y3PM.js.map → chunk-W4FBGYGK.js.map} +0 -0
  758. /package/dist/{chunk-MU7ZHSZE.js.map → chunk-WZFAPHIK.js.map} +0 -0
  759. /package/dist/{chunk-T2TTP3KU.js.map → chunk-X4IDNPOS.js.map} +0 -0
  760. /package/dist/{chunk-UVIKWC7M.js.map → chunk-XAGYS7X6.js.map} +0 -0
  761. /package/dist/{chunk-BLAKS3CP.js.map → chunk-XL3TATMJ.js.map} +0 -0
  762. /package/dist/{chunk-W4XJFLAL.js.map → chunk-XPRJSHNI.js.map} +0 -0
  763. /package/dist/{chunk-E6EE5B67.js.map → chunk-YK6BDDHP.js.map} +0 -0
  764. /package/dist/{chunk-ES36HTSC.js.map → chunk-YLHM5BQQ.js.map} +0 -0
  765. /package/dist/{chunk-GF22HWS2.js.map → chunk-Z54EM5YZ.js.map} +0 -0
  766. /package/dist/{chunk-64UDOIMI.js.map → chunk-ZLQ37WJX.js.map} +0 -0
@@ -15,6 +15,9 @@ import {
15
15
  buildRetiredFactTombstoneInputs,
16
16
  collectRetiredMemoriesForRebuild
17
17
  } from "./chunk-ENTCVTQR.js";
18
+ import {
19
+ withholdToolScopedFromSharedNamespace
20
+ } from "./chunk-S2V7RUCL.js";
18
21
  import {
19
22
  DEFAULT_CITATION_FORMAT,
20
23
  hasCitation,
@@ -23,28 +26,10 @@ import {
23
26
  import {
24
27
  SPECULATIVE_TTL_DAYS,
25
28
  confidenceTier
26
- } from "./chunk-J7VGGECD.js";
27
- import {
28
- ProjectionLedgerLagManager,
29
- appendLifecycleEventsSerialized,
30
- drainPendingLifecycleLedgerForSync,
31
- drainPendingLifecycleLedgerIfAny,
32
- formatProjectionAge,
33
- readAllLifecycleEventsFromLedger,
34
- readAllLifecycleEventsFromLedgerBuffer,
35
- readBoundedLifecycleEventsFromLedger,
36
- readMaybeEncryptedLines,
37
- readMemoryActionEventRowsFromLines,
38
- readProjectionRebuiltAt,
39
- serializeLifecycleAppendPayload
40
- } from "./chunk-WUNIWKY4.js";
41
- import {
42
- namespaceIdentityFromToken
43
- } from "./chunk-EGGE52UU.js";
29
+ } from "./chunk-DZPFMQZ7.js";
44
30
  import {
45
- assertMemoryFrontmatterId,
46
- warnProjectionFallback
47
- } from "./chunk-ZA53AZND.js";
31
+ createMemorySnapshot
32
+ } from "./chunk-S2HLHAZ4.js";
48
33
  import {
49
34
  normalizeProjectionPreview,
50
35
  normalizeProjectionTags
@@ -53,15 +38,6 @@ import {
53
38
  rewriteProjectedEntityReferences,
54
39
  rewriteProjectedMemoryEntityReference
55
40
  } from "./chunk-WRJVB3C2.js";
56
- import {
57
- assertPathInsideRoot,
58
- pathIsInside
59
- } from "./chunk-GCASGYIO.js";
60
- import {
61
- inferMemoryStatus,
62
- isArchivedMemoryPath,
63
- toMemoryPathRel
64
- } from "./chunk-7RJUVTVF.js";
65
41
  import {
66
42
  rotateMarkdownFileToArchive
67
43
  } from "./chunk-DM2T26WE.js";
@@ -80,14 +56,12 @@ import {
80
56
  } from "./chunk-JYIJNNN3.js";
81
57
  import {
82
58
  TombstoneBlockedCaptureIndexHost,
59
+ buildCapturePathLockIdentity,
83
60
  buildExplicitCaptureDedupKey,
84
- parseTombstoneBlockedOfflineSyncMemory
85
- } from "./chunk-RVLJEII5.js";
86
- import {
87
- CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS,
88
- ContentHashIndex,
89
- FactHashIndexNotAuthoritativeError
90
- } from "./chunk-S5SLVSVY.js";
61
+ isQueuedReviewMemory,
62
+ parseTombstoneBlockedOfflineSyncMemory,
63
+ tombstoneBlocked
64
+ } from "./chunk-SYUBB3WM.js";
91
65
  import {
92
66
  composeMemoryEnvelope,
93
67
  isSealedMemoryEnvelope,
@@ -97,14 +71,6 @@ import {
97
71
  assemblePersistedBody,
98
72
  stripAttributesSuffix
99
73
  } from "./chunk-R3DJVOSM.js";
100
- import {
101
- markProjectedMemoryPathInvalid,
102
- readProjectedGovernanceRecord,
103
- readProjectedMemoryBrowse,
104
- readProjectedMemoryState,
105
- readProjectedMemoryTimeline,
106
- updateProjectedMemoryPath
107
- } from "./chunk-3CSX3ETE.js";
108
74
  import {
109
75
  normalizeEntityName
110
76
  } from "./chunk-YXZG5TVN.js";
@@ -114,7 +80,7 @@ import {
114
80
  } from "./chunk-G7D6GZ5J.js";
115
81
  import {
116
82
  createVersion
117
- } from "./chunk-DLVPUX7U.js";
83
+ } from "./chunk-7YKVM5H3.js";
118
84
  import {
119
85
  clearInFlightReads,
120
86
  deleteInFlightRead,
@@ -128,21 +94,20 @@ import {
128
94
  ENTITY_CANONICAL_ID_RECONCILE_MARKER,
129
95
  HistoricalEntityCanonicalIdCache,
130
96
  appendCanonicalizedTombstone,
97
+ assertSafeEntityId,
98
+ canonicalizeEntityRefFrontmatter,
131
99
  canonicalizeEntityRefOption,
132
100
  reconcileIfJournalMovedSync,
133
101
  repairEntityRefAfterJournalMove,
134
102
  requestEntityCanonicalIdReconcileSync,
135
103
  resolveHistoricalEntityCanonicalId,
136
104
  withEntityCanonicalMutationLock
137
- } from "./chunk-4J7G5SY4.js";
105
+ } from "./chunk-NZBZ7IS2.js";
138
106
  import {
139
107
  computeSupersessionKey,
140
108
  normalizeSupersessionKey,
141
109
  supersessionKeysForFact
142
110
  } from "./chunk-DNHVPZOD.js";
143
- import {
144
- withHeldFileLock
145
- } from "./chunk-FFAZ2XFU.js";
146
111
  import {
147
112
  clearMemoryCache,
148
113
  getCachedEntities,
@@ -161,15 +126,61 @@ import {
161
126
  parseProvenanceTag,
162
127
  reconcileProvenanceRead,
163
128
  serializeProvenanceFields
164
- } from "./chunk-5I4M26Q7.js";
129
+ } from "./chunk-QBSFOKY6.js";
130
+ import {
131
+ sanitizeMemoryContent
132
+ } from "./chunk-5GKPFL3S.js";
165
133
  import {
166
134
  matchEntitySchemaSection,
167
135
  normalizeEntityStructuredSection,
168
136
  sortStructuredSectionsBySchema
169
137
  } from "./chunk-ZIKENA2C.js";
170
138
  import {
171
- sanitizeMemoryContent
172
- } from "./chunk-5GKPFL3S.js";
139
+ ProjectionLedgerLagManager,
140
+ appendLifecycleEventsSerialized,
141
+ drainPendingLifecycleLedgerForSync,
142
+ drainPendingLifecycleLedgerIfAny,
143
+ formatProjectionAge,
144
+ readAllLifecycleEventsFromLedger,
145
+ readAllLifecycleEventsFromLedgerBuffer,
146
+ readBoundedLifecycleEventsFromLedger,
147
+ readMaybeEncryptedLines,
148
+ readMemoryActionEventRowsFromLines,
149
+ readProjectionRebuiltAt,
150
+ serializeLifecycleAppendPayload
151
+ } from "./chunk-ELIL2A37.js";
152
+ import {
153
+ namespaceIdentityFromToken
154
+ } from "./chunk-EGGE52UU.js";
155
+ import {
156
+ assertMemoryFrontmatterId,
157
+ warnProjectionFallback
158
+ } from "./chunk-ZA53AZND.js";
159
+ import {
160
+ inferMemoryStatus,
161
+ isArchivedMemoryPath,
162
+ toMemoryPathRel
163
+ } from "./chunk-7RJUVTVF.js";
164
+ import {
165
+ assertPathInsideRoot,
166
+ pathIsInside
167
+ } from "./chunk-GCASGYIO.js";
168
+ import {
169
+ CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS,
170
+ ContentHashIndex,
171
+ FactHashIndexNotAuthoritativeError
172
+ } from "./chunk-BQIFZ2MP.js";
173
+ import {
174
+ markProjectedMemoryPathInvalid,
175
+ readProjectedGovernanceRecord,
176
+ readProjectedMemoryBrowse,
177
+ readProjectedMemoryState,
178
+ readProjectedMemoryTimeline,
179
+ updateProjectedMemoryPath
180
+ } from "./chunk-3CSX3ETE.js";
181
+ import {
182
+ withHeldFileLock
183
+ } from "./chunk-FFAZ2XFU.js";
173
184
  import {
174
185
  parseFlexibleIsoTimestamp
175
186
  } from "./chunk-P7FMDTKL.js";
@@ -187,7 +198,7 @@ import {
187
198
  readMaybeEncryptedFile,
188
199
  readMaybeEncryptedFileBuffer,
189
200
  writeMaybeEncryptedFile
190
- } from "./chunk-5TFP4CUL.js";
201
+ } from "./chunk-XQ3HXAQH.js";
191
202
  import {
192
203
  isErrnoCode
193
204
  } from "./chunk-5UZXUTVO.js";
@@ -206,6 +217,7 @@ import {
206
217
  readdir as readdir5,
207
218
  readFile as readFile2,
208
219
  realpath as realpath3,
220
+ rename as rename2,
209
221
  stat as stat2,
210
222
  writeFile as writeFile2,
211
223
  mkdir,
@@ -213,26 +225,22 @@ import {
213
225
  appendFile,
214
226
  open
215
227
  } from "fs/promises";
216
- import { appendFileSync, createReadStream, mkdirSync, readFileSync, statSync } from "fs";
217
- import { createHash as createHash5 } from "crypto";
218
- import path8 from "path";
228
+ import { appendFileSync, createReadStream, mkdirSync, statSync } from "fs";
229
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
230
+ import path9 from "path";
219
231
 
220
232
  // src/storage/memory-read-store.ts
221
233
  import { lstat, readdir, realpath, stat } from "fs/promises";
222
234
  import path from "path";
223
235
 
224
236
  // src/storage/memory-frontmatter-metadata.ts
225
- var rawFrontmatterByMemory = /* @__PURE__ */ new WeakMap();
226
- function extractRawFrontmatter(raw) {
227
- return raw.match(/^---\n([\s\S]*?)\n---\n?/)?.[1] ?? null;
228
- }
237
+ var rawDocumentByMemory = /* @__PURE__ */ new WeakMap();
229
238
  function rememberRawFrontmatter(owner, raw) {
230
- const frontmatter = extractRawFrontmatter(raw);
231
- if (frontmatter !== null) rawFrontmatterByMemory.set(owner, frontmatter);
239
+ if (/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.test(raw)) rawDocumentByMemory.set(owner, raw);
232
240
  return owner;
233
241
  }
234
- function readRawFrontmatter(owner) {
235
- return rawFrontmatterByMemory.get(owner);
242
+ function readRawMemoryDocument(owner) {
243
+ return rawDocumentByMemory.get(owner);
236
244
  }
237
245
 
238
246
  // src/storage/memory-read-store.ts
@@ -1718,8 +1726,11 @@ var EntityStore = class {
1718
1726
  */
1719
1727
  async readAllEntityFiles() {
1720
1728
  const currentVersion = this.deps.getMemoryStatusVersion();
1721
- const schemaCacheKey = buildEntitySchemaCacheKey(this.deps.entitySchemas);
1722
- const cacheKey = `${this.deps.getEntityCacheSecureStoreKey()}\0${schemaCacheKey}`;
1729
+ const cacheKey = [
1730
+ this.deps.getEntityCacheSecureStoreKey(),
1731
+ buildEntitySchemaCacheKey(this.deps.entitySchemas),
1732
+ this.deps.getEntityMutationVersion()
1733
+ ].join("\0");
1723
1734
  const cached = getCachedEntities(this.deps.baseDir, currentVersion, cacheKey);
1724
1735
  if (cached) return cached;
1725
1736
  try {
@@ -2161,7 +2172,7 @@ var IdentityContinuityStore = class {
2161
2172
  };
2162
2173
 
2163
2174
  // src/storage/entity-canonical-id-migration.ts
2164
- import { randomUUID } from "crypto";
2175
+ import { createHash, randomUUID } from "crypto";
2165
2176
  import {
2166
2177
  access,
2167
2178
  lstat as lstat2,
@@ -2204,16 +2215,50 @@ async function fingerprintPath(filePath) {
2204
2215
  }
2205
2216
  return fileStat ? `${fileStat.dev}:${fileStat.ino}:${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}` : "missing";
2206
2217
  }
2218
+ async function fingerprintEntityEntries(entitiesDir) {
2219
+ let names;
2220
+ try {
2221
+ names = (await readdir4(entitiesDir)).filter((name) => path4.extname(name) === ".md").sort();
2222
+ } catch (error) {
2223
+ if (isErrnoCode(error, "ENOENT")) return "missing";
2224
+ throw error;
2225
+ }
2226
+ const hash = createHash("sha256");
2227
+ for (const name of names) {
2228
+ hash.update(`${name.length}:${name}:`);
2229
+ try {
2230
+ const entry = await lstat2(path4.join(entitiesDir, name), { bigint: true });
2231
+ hash.update(`${entry.dev}:${entry.ino}:${entry.size}:${entry.mtimeNs}:${entry.ctimeNs}`);
2232
+ } catch (error) {
2233
+ if (!isErrnoCode(error, "ENOENT")) throw error;
2234
+ hash.update("missing");
2235
+ }
2236
+ hash.update("\n");
2237
+ }
2238
+ return hash.digest("hex");
2239
+ }
2207
2240
  async function getFingerprint(baseDir, entitiesDir, getEntityMutationVersion) {
2208
- const [entityFingerprint, aliasFingerprint, reconcileFingerprint, consumingFingerprint] = await Promise.all([
2241
+ const [
2242
+ entityDirectoryFingerprint,
2243
+ entityEntriesFingerprint,
2244
+ aliasFingerprint,
2245
+ reconcileFingerprint,
2246
+ consumingFingerprint
2247
+ ] = await Promise.all([
2209
2248
  fingerprintPath(entitiesDir),
2249
+ fingerprintEntityEntries(entitiesDir),
2210
2250
  fingerprintPath(path4.join(baseDir, "config", "aliases.json")),
2211
2251
  fingerprintPath(path4.join(baseDir, "state", ENTITY_CANONICAL_ID_RECONCILE_MARKER)),
2212
- // A `.consuming` generation stranded by a crashed PEER process must also
2213
- // re-invoke a live runner whose cached fingerprint predates it.
2214
2252
  fingerprintPath(path4.join(baseDir, "state", ENTITY_CANONICAL_ID_RECONCILE_CONSUMING_MARKER))
2215
2253
  ]);
2216
- return [entityFingerprint, aliasFingerprint, reconcileFingerprint, consumingFingerprint, getEntityMutationVersion()].join(":");
2254
+ return [
2255
+ entityDirectoryFingerprint,
2256
+ entityEntriesFingerprint,
2257
+ aliasFingerprint,
2258
+ reconcileFingerprint,
2259
+ consumingFingerprint,
2260
+ getEntityMutationVersion()
2261
+ ].join(":");
2217
2262
  }
2218
2263
  async function validateRoots(baseDir, entitiesDir, stateDir, archiveDir) {
2219
2264
  let baseStat;
@@ -2311,6 +2356,12 @@ async function readState(deps) {
2311
2356
  }
2312
2357
  const result = EntityCanonicalIdMigrationStateSchema.safeParse(parsed);
2313
2358
  if (!result.success) throw new Error("Invalid entity canonical-id migration state.");
2359
+ for (const mappings of [result.data.mappings, result.data.blocked ?? {}]) {
2360
+ for (const [legacyId, canonicalId] of Object.entries(mappings)) {
2361
+ assertSafeEntityId(legacyId);
2362
+ assertSafeEntityId(canonicalId);
2363
+ }
2364
+ }
2314
2365
  return result.data;
2315
2366
  }
2316
2367
  async function writeState(deps, state) {
@@ -2347,11 +2398,6 @@ async function sameFileIdentity(leftPath, rightPath) {
2347
2398
  throw error;
2348
2399
  }
2349
2400
  }
2350
- function assertSafeEntityId(entityId) {
2351
- if (/[\/\\\0]/.test(entityId)) {
2352
- throw new Error(`Refusing entity canonical-id migration through unsafe entity id: ${entityId}.`);
2353
- }
2354
- }
2355
2401
  async function assertNotSymlink(filePath, label) {
2356
2402
  let stat3;
2357
2403
  try {
@@ -3137,25 +3183,14 @@ var EntityCanonicalIdMigrationRunner = class {
3137
3183
 
3138
3184
  // src/storage/memory-migration-serialization.ts
3139
3185
  function serializeMemoryWithEntityRef(memory, entityRef, fallback) {
3140
- const rawFrontmatter = readRawFrontmatter(memory);
3141
- if (rawFrontmatter === void 0) return fallback(memory, entityRef);
3142
- const lines = rawFrontmatter.split("\n");
3143
- let entityRefLine = -1;
3144
- for (let index = 0; index < lines.length; index += 1) {
3145
- if (/^\s*entityRef\s*:/.test(lines[index] ?? "")) entityRefLine = index;
3146
- }
3147
- if (entityRefLine >= 0) {
3148
- const indent = lines[entityRefLine].match(/^\s*/)?.[0] ?? "";
3149
- lines[entityRefLine] = `${indent}entityRef: ${entityRef}`;
3150
- } else {
3151
- lines.push(`entityRef: ${entityRef}`);
3152
- }
3153
- return `---
3154
- ${lines.join("\n")}
3155
- ---
3156
-
3157
- ${memory.content}
3158
- `;
3186
+ const rawDocument = readRawMemoryDocument(memory);
3187
+ if (rawDocument === void 0) return fallback(memory, entityRef);
3188
+ const currentEntityRef = memory.frontmatter.entityRef;
3189
+ if (currentEntityRef === void 0) return fallback(memory, entityRef);
3190
+ if (currentEntityRef === entityRef) return rawDocument;
3191
+ const rewritten = canonicalizeEntityRefFrontmatter(rawDocument, { [currentEntityRef]: entityRef });
3192
+ if (rewritten !== rawDocument) return rewritten;
3193
+ return fallback(memory, entityRef);
3159
3194
  }
3160
3195
  function createMemoryEntityRefSerializer(serializeFrontmatter2) {
3161
3196
  return (memory, entityRef) => serializeMemoryWithEntityRef(
@@ -3168,6 +3203,90 @@ ${fallbackMemory.content}
3168
3203
  );
3169
3204
  }
3170
3205
 
3206
+ // src/storage/entity-alias-config.ts
3207
+ import {
3208
+ closeSync,
3209
+ constants,
3210
+ fstatSync,
3211
+ lstatSync,
3212
+ openSync,
3213
+ readFileSync,
3214
+ realpathSync
3215
+ } from "fs";
3216
+ import path5 from "path";
3217
+ function resolveSafeAliasRoots(baseDir, configDir) {
3218
+ let baseStat;
3219
+ try {
3220
+ baseStat = lstatSync(baseDir);
3221
+ } catch (error) {
3222
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3223
+ throw error;
3224
+ }
3225
+ if (baseStat.isSymbolicLink() || !baseStat.isDirectory()) {
3226
+ throw new Error(`Refusing unsafe entity alias memory root: ${baseDir}.`);
3227
+ }
3228
+ let configStat;
3229
+ try {
3230
+ configStat = lstatSync(configDir);
3231
+ } catch (error) {
3232
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3233
+ throw error;
3234
+ }
3235
+ if (configStat.isSymbolicLink() || !configStat.isDirectory()) {
3236
+ throw new Error(`Refusing unsafe entity alias config root: ${configDir}.`);
3237
+ }
3238
+ const memoryRoot = realpathSync(baseDir);
3239
+ assertPathInsideRoot(memoryRoot, realpathSync(configDir), configDir);
3240
+ return memoryRoot;
3241
+ }
3242
+ function readEntityAliasConfigSync(baseDir) {
3243
+ const configDir = path5.join(baseDir, "config");
3244
+ const aliasPath = path5.join(configDir, "aliases.json");
3245
+ let memoryRoot = resolveSafeAliasRoots(baseDir, configDir);
3246
+ if (memoryRoot === void 0) return void 0;
3247
+ let aliasPreflight;
3248
+ try {
3249
+ aliasPreflight = lstatSync(aliasPath);
3250
+ } catch (error) {
3251
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3252
+ throw error;
3253
+ }
3254
+ if (aliasPreflight.isSymbolicLink() || !aliasPreflight.isFile()) {
3255
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3256
+ }
3257
+ let fd;
3258
+ try {
3259
+ fd = openSync(
3260
+ aliasPath,
3261
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
3262
+ );
3263
+ } catch (error) {
3264
+ if (isErrnoCode(error, "ENOENT")) {
3265
+ resolveSafeAliasRoots(baseDir, configDir);
3266
+ return void 0;
3267
+ }
3268
+ if (isErrnoCode(error, "ELOOP")) {
3269
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3270
+ }
3271
+ throw error;
3272
+ }
3273
+ try {
3274
+ const opened = fstatSync(fd);
3275
+ memoryRoot = resolveSafeAliasRoots(baseDir, configDir);
3276
+ if (memoryRoot === void 0) {
3277
+ throw new Error(`Refusing unsafe entity alias config root: ${configDir}.`);
3278
+ }
3279
+ const aliasStat = lstatSync(aliasPath);
3280
+ if (!opened.isFile() || aliasStat.isSymbolicLink() || !aliasStat.isFile() || aliasStat.dev !== opened.dev || aliasStat.ino !== opened.ino) {
3281
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3282
+ }
3283
+ assertPathInsideRoot(memoryRoot, realpathSync(aliasPath), aliasPath);
3284
+ return readFileSync(fd, "utf-8");
3285
+ } finally {
3286
+ closeSync(fd);
3287
+ }
3288
+ }
3289
+
3171
3290
  // src/utils/yaml-scalar.ts
3172
3291
  function decodeYamlScalar(value) {
3173
3292
  const trimmed = value.trim();
@@ -3183,9 +3302,9 @@ function decodeYamlScalar(value) {
3183
3302
  }
3184
3303
 
3185
3304
  // src/orchestration/qmd-result-resolver.ts
3186
- import path5 from "path";
3305
+ import path6 from "path";
3187
3306
  function qmdCollectionPathParts(resultPath) {
3188
- if (!resultPath || path5.isAbsolute(resultPath)) return null;
3307
+ if (!resultPath || path6.isAbsolute(resultPath)) return null;
3189
3308
  const normalized = resultPath.replace(/\\/g, "/").replace(/^\/+/, "");
3190
3309
  const slashIndex = normalized.indexOf("/");
3191
3310
  if (slashIndex <= 0 || slashIndex >= normalized.length - 1) return null;
@@ -3198,9 +3317,9 @@ function qmdCollectionPathParts(resultPath) {
3198
3317
  }
3199
3318
  function qmdResultPathCandidates(storageDir, resultPath) {
3200
3319
  const candidates = /* @__PURE__ */ new Set();
3201
- const storageRoot = path5.resolve(storageDir);
3320
+ const storageRoot = path6.resolve(storageDir);
3202
3321
  const addCandidate = (candidate) => {
3203
- const resolved = path5.resolve(candidate);
3322
+ const resolved = path6.resolve(candidate);
3204
3323
  if (isPathInsideStorageRoot(storageRoot, resolved)) {
3205
3324
  candidates.add(resolved);
3206
3325
  }
@@ -3208,18 +3327,18 @@ function qmdResultPathCandidates(storageDir, resultPath) {
3208
3327
  const addRelativeCandidates = (relativePath) => {
3209
3328
  const normalized = relativePath.replace(/\\/g, "/").replace(/^\/+/, "");
3210
3329
  if (!normalized) return;
3211
- addCandidate(path5.join(storageRoot, normalized));
3330
+ addCandidate(path6.join(storageRoot, normalized));
3212
3331
  if (/^\d{4}-\d{2}-\d{2}\//.test(normalized)) {
3213
- addCandidate(path5.join(storageRoot, "facts", normalized));
3332
+ addCandidate(path6.join(storageRoot, "facts", normalized));
3214
3333
  }
3215
3334
  };
3216
- if (path5.isAbsolute(resultPath)) {
3335
+ if (path6.isAbsolute(resultPath)) {
3217
3336
  addCandidate(resultPath);
3218
- const relative2 = path5.relative(storageRoot, path5.resolve(resultPath));
3219
- if (relative2 && !relative2.startsWith("..") && !path5.isAbsolute(relative2)) {
3220
- const normalized = relative2.split(path5.sep).join("/");
3337
+ const relative2 = path6.relative(storageRoot, path6.resolve(resultPath));
3338
+ if (relative2 && !relative2.startsWith("..") && !path6.isAbsolute(relative2)) {
3339
+ const normalized = relative2.split(path6.sep).join("/");
3221
3340
  if (/^\d{4}-\d{2}-\d{2}\//.test(normalized)) {
3222
- addCandidate(path5.join(storageRoot, "facts", normalized));
3341
+ addCandidate(path6.join(storageRoot, "facts", normalized));
3223
3342
  }
3224
3343
  }
3225
3344
  } else {
@@ -3254,7 +3373,7 @@ var QmdResultResolver = class {
3254
3373
  const seenStorageDirs = /* @__PURE__ */ new Set();
3255
3374
  const addStorage = (storage) => {
3256
3375
  const storageDir = storageDirOrNull(storage);
3257
- const storageKey = storageDir ? path5.resolve(storageDir) : `storage-without-dir-${storages.length}`;
3376
+ const storageKey = storageDir ? path6.resolve(storageDir) : `storage-without-dir-${storages.length}`;
3258
3377
  if (seenStorageDirs.has(storageKey)) return;
3259
3378
  seenStorageDirs.add(storageKey);
3260
3379
  storages.push(storage);
@@ -3284,7 +3403,7 @@ var QmdResultResolver = class {
3284
3403
  continue;
3285
3404
  }
3286
3405
  try {
3287
- const coldRoot = path5.join(storageDir, "cold");
3406
+ const coldRoot = path6.join(storageDir, "cold");
3288
3407
  for (const candidate of qmdResultPathCandidates(
3289
3408
  coldRoot,
3290
3409
  parts.relativePath
@@ -3343,9 +3462,9 @@ var QmdResultResolver = class {
3343
3462
  error: err.message
3344
3463
  });
3345
3464
  }
3346
- if (!path5.isAbsolute(resultPath)) return null;
3465
+ if (!path6.isAbsolute(resultPath)) return null;
3347
3466
  }
3348
- if (path5.isAbsolute(resultPath)) {
3467
+ if (path6.isAbsolute(resultPath)) {
3349
3468
  if (!fallbackStorageDir) {
3350
3469
  return await fallbackStorage.readMemoryByPath(resultPath);
3351
3470
  }
@@ -3385,7 +3504,7 @@ var QmdResultResolver = class {
3385
3504
  );
3386
3505
  if (!memory) return null;
3387
3506
  let ownerNamespace = null;
3388
- if (path5.isAbsolute(memory.path)) {
3507
+ if (path6.isAbsolute(memory.path)) {
3389
3508
  const ownerStorage = await this.storageForAbsoluteQmdResultPath(
3390
3509
  memory.path,
3391
3510
  fallbackStorage,
@@ -3409,17 +3528,17 @@ var QmdResultResolver = class {
3409
3528
  };
3410
3529
  }
3411
3530
  async storageForAbsoluteQmdResultPath(resultPath, fallbackStorage, recallNamespaces = []) {
3412
- const resolvedPath = path5.resolve(resultPath);
3531
+ const resolvedPath = path6.resolve(resultPath);
3413
3532
  const config = this.getConfig();
3414
- const memoryRoot = path5.resolve(config.memoryDir);
3415
- const namespacesRoot = path5.join(memoryRoot, "namespaces");
3533
+ const memoryRoot = path6.resolve(config.memoryDir);
3534
+ const namespacesRoot = path6.join(memoryRoot, "namespaces");
3416
3535
  const fallbackStorageDir = storageDirOrNull(fallbackStorage);
3417
3536
  const matches = [];
3418
3537
  const seenDirs = /* @__PURE__ */ new Set();
3419
3538
  const maybeAddStorage = (storage, namespace) => {
3420
3539
  const storageDir = storageDirOrNull(storage);
3421
3540
  if (!storageDir) return;
3422
- const candidateRoot = path5.resolve(storageDir);
3541
+ const candidateRoot = path6.resolve(storageDir);
3423
3542
  if (seenDirs.has(candidateRoot)) return;
3424
3543
  if (!isPathInsideStorageRoot(candidateRoot, resolvedPath)) return;
3425
3544
  if (candidateRoot === memoryRoot && isPathInsideStorageRoot(namespacesRoot, resolvedPath)) {
@@ -3437,7 +3556,7 @@ var QmdResultResolver = class {
3437
3556
  candidateNamespaces.add(ns);
3438
3557
  }
3439
3558
  if (isPathInsideStorageRoot(namespacesRoot, resolvedPath)) {
3440
- const relativeToNamespaces = path5.relative(namespacesRoot, resolvedPath);
3559
+ const relativeToNamespaces = path6.relative(namespacesRoot, resolvedPath);
3441
3560
  const [namespaceSegment] = relativeToNamespaces.split(/[\\/]/);
3442
3561
  if (namespaceSegment) {
3443
3562
  candidateNamespaces.add(
@@ -3981,7 +4100,7 @@ function collectSpeakers(tagged) {
3981
4100
  }
3982
4101
 
3983
4102
  // src/wearables/fusion/fuse.ts
3984
- import { createHash } from "crypto";
4103
+ import { createHash as createHash2 } from "crypto";
3985
4104
  var FUSION_ID_PREFIX = "fusion";
3986
4105
  var FUSION_ALGO_VERSION = "2026-07-12-1";
3987
4106
  function canonicalInputsKey(date, inputs) {
@@ -4010,7 +4129,7 @@ function canonicalInputsKey(date, inputs) {
4010
4129
  ])
4011
4130
  ])
4012
4131
  ];
4013
- return createHash("sha256").update(JSON.stringify(record), "utf-8").digest("hex");
4132
+ return createHash2("sha256").update(JSON.stringify(record), "utf-8").digest("hex");
4014
4133
  }
4015
4134
  function configFingerprint(options, sources) {
4016
4135
  const proximityGapMs = options.proximityGapMs ?? DEFAULT_PROXIMITY_GAP_MS;
@@ -4025,7 +4144,7 @@ function canonicalDayKey(date, inputs, options, algoVersion = FUSION_ALGO_VERSIO
4025
4144
  options,
4026
4145
  inputs.map((conv) => conv.source)
4027
4146
  );
4028
- return createHash("sha256").update(inputsKey).update("\n").update(fingerprint).update("\n").update(algoVersion).digest("hex");
4147
+ return createHash2("sha256").update(inputsKey).update("\n").update(fingerprint).update("\n").update(algoVersion).digest("hex");
4029
4148
  }
4030
4149
  function buildProvenance(cluster, proximityGapMs, windowToleranceMs) {
4031
4150
  return {
@@ -4085,11 +4204,11 @@ function fuseDay(date, inputs, options = {}) {
4085
4204
  }
4086
4205
 
4087
4206
  // src/wearables/fusion/store.ts
4088
- import { createHash as createHash2 } from "crypto";
4089
- import * as path6 from "path";
4207
+ import { createHash as createHash3 } from "crypto";
4208
+ import * as path7 from "path";
4090
4209
  var FUSION_KIND = "wearable-fusion";
4091
4210
  function hashFusionBody(conversations) {
4092
- return createHash2("sha256").update(JSON.stringify(conversations), "utf-8").digest("hex");
4211
+ return createHash3("sha256").update(JSON.stringify(conversations), "utf-8").digest("hex");
4093
4212
  }
4094
4213
  function composeFusionDayMeta(date, conversations, sources, contentHash, fusedAt) {
4095
4214
  return {
@@ -4273,7 +4392,7 @@ var FusionArtifactStore = class {
4273
4392
  `invalid wearable fusion date '${String(date)}' \u2014 expected YYYY-MM-DD`
4274
4393
  );
4275
4394
  }
4276
- return path6.join(this.wearablesDir, FUSION_DIR_NAME, `${date}.md`);
4395
+ return path7.join(this.wearablesDir, FUSION_DIR_NAME, `${date}.md`);
4277
4396
  }
4278
4397
  async writeFusedDay(date, serialized) {
4279
4398
  const filePath = this.fusedDayPath(date);
@@ -4310,7 +4429,7 @@ var FusionArtifactStore = class {
4310
4429
  }
4311
4430
  /** List dates with stored fused artifacts, newest first. */
4312
4431
  async listFusedDays() {
4313
- const fusionDir = path6.join(this.wearablesDir, FUSION_DIR_NAME);
4432
+ const fusionDir = path7.join(this.wearablesDir, FUSION_DIR_NAME);
4314
4433
  await this.assertPathContained(fusionDir);
4315
4434
  let entries;
4316
4435
  try {
@@ -4354,10 +4473,10 @@ var FusionArtifactStore = class {
4354
4473
  try {
4355
4474
  rootReal = await this.io.realpath(this.memoryDir);
4356
4475
  } catch {
4357
- rootReal = path6.resolve(this.memoryDir);
4476
+ rootReal = path7.resolve(this.memoryDir);
4358
4477
  }
4359
4478
  await this.assertNoEscape(rootReal, this.wearablesDir);
4360
- await this.assertNoEscape(rootReal, path6.dirname(targetPath));
4479
+ await this.assertNoEscape(rootReal, path7.dirname(targetPath));
4361
4480
  await this.assertNoEscape(rootReal, targetPath);
4362
4481
  await this.assertFusionDirNotSymlinked();
4363
4482
  }
@@ -4371,7 +4490,7 @@ var FusionArtifactStore = class {
4371
4490
  * (a fresh write creates a real directory lexically under the root).
4372
4491
  */
4373
4492
  async assertFusionDirNotSymlinked() {
4374
- const fusionDir = path6.join(this.wearablesDir, FUSION_DIR_NAME);
4493
+ const fusionDir = path7.join(this.wearablesDir, FUSION_DIR_NAME);
4375
4494
  let stat3;
4376
4495
  try {
4377
4496
  stat3 = await this.io.lstat(fusionDir);
@@ -4506,8 +4625,8 @@ function reconstructFusionInputs(date, dayTranscripts) {
4506
4625
  }
4507
4626
 
4508
4627
  // src/meetings/store.ts
4509
- import { createHash as createHash3 } from "crypto";
4510
- import * as path7 from "path";
4628
+ import { createHash as createHash4 } from "crypto";
4629
+ import * as path8 from "path";
4511
4630
  var MEETINGS_DIR_NAME = "meetings";
4512
4631
  var MEETING_KIND = "meeting";
4513
4632
  var MEETING_FORMAT_VERSION = 1;
@@ -4537,7 +4656,7 @@ function canonicalContent(base, fused) {
4537
4656
  });
4538
4657
  }
4539
4658
  function composeMeetingRecord(base, fused) {
4540
- const contentHash = createHash3("sha256").update(canonicalContent(base, fused), "utf-8").digest("hex");
4659
+ const contentHash = createHash4("sha256").update(canonicalContent(base, fused), "utf-8").digest("hex");
4541
4660
  return {
4542
4661
  ...base,
4543
4662
  ...fused,
@@ -4676,7 +4795,7 @@ var MeetingRecordStore = class {
4676
4795
  constructor(memoryDir, io) {
4677
4796
  this.memoryDir = memoryDir;
4678
4797
  this.io = io;
4679
- this.meetingsDir = path7.join(memoryDir, MEETINGS_DIR_NAME);
4798
+ this.meetingsDir = path8.join(memoryDir, MEETINGS_DIR_NAME);
4680
4799
  }
4681
4800
  memoryDir;
4682
4801
  io;
@@ -4692,7 +4811,7 @@ var MeetingRecordStore = class {
4692
4811
  if (idDate !== date) {
4693
4812
  throw new Error(`meeting id '${id}' does not belong to date '${date}'`);
4694
4813
  }
4695
- return path7.join(this.meetingsDir, date, `${id}.md`);
4814
+ return path8.join(this.meetingsDir, date, `${id}.md`);
4696
4815
  }
4697
4816
  /** Idempotently persist a record: skip the write when contentHash is unchanged. */
4698
4817
  async saveMeetingRecord(record) {
@@ -4723,7 +4842,7 @@ var MeetingRecordStore = class {
4723
4842
  if (!isValidTranscriptDate(date)) {
4724
4843
  throw new Error(`invalid meeting date '${String(date)}' \u2014 expected YYYY-MM-DD`);
4725
4844
  }
4726
- const dayDir = path7.join(this.meetingsDir, date);
4845
+ const dayDir = path8.join(this.meetingsDir, date);
4727
4846
  await this.assertPathContained(dayDir);
4728
4847
  let entries;
4729
4848
  try {
@@ -4791,10 +4910,10 @@ var MeetingRecordStore = class {
4791
4910
  try {
4792
4911
  rootReal = await this.io.realpath(this.memoryDir);
4793
4912
  } catch {
4794
- rootReal = path7.resolve(this.memoryDir);
4913
+ rootReal = path8.resolve(this.memoryDir);
4795
4914
  }
4796
4915
  await this.assertNoEscape(rootReal, this.meetingsDir);
4797
- await this.assertNoEscape(rootReal, path7.dirname(targetPath));
4916
+ await this.assertNoEscape(rootReal, path8.dirname(targetPath));
4798
4917
  await this.assertNoEscape(rootReal, targetPath);
4799
4918
  await this.assertNotSymlink(this.meetingsDir, "directory");
4800
4919
  const dayDir = this.dayDirWithin(targetPath);
@@ -4804,11 +4923,11 @@ var MeetingRecordStore = class {
4804
4923
  /** The `<meetings>/<date>` directory on the path to `targetPath`, or null when
4805
4924
  * `targetPath` is the meetings root itself. */
4806
4925
  dayDirWithin(targetPath) {
4807
- const rel = path7.relative(this.meetingsDir, targetPath);
4808
- if (rel === "" || rel.startsWith("..") || path7.isAbsolute(rel)) return null;
4809
- const first = rel.split(path7.sep)[0];
4926
+ const rel = path8.relative(this.meetingsDir, targetPath);
4927
+ if (rel === "" || rel.startsWith("..") || path8.isAbsolute(rel)) return null;
4928
+ const first = rel.split(path8.sep)[0];
4810
4929
  if (first === void 0 || first.length === 0) return null;
4811
- return path7.join(this.meetingsDir, first);
4930
+ return path8.join(this.meetingsDir, first);
4812
4931
  }
4813
4932
  async assertNotSymlink(target, kind) {
4814
4933
  let stat3;
@@ -4819,7 +4938,7 @@ var MeetingRecordStore = class {
4819
4938
  throw err;
4820
4939
  }
4821
4940
  if (stat3.isSymbolicLink) {
4822
- const label = path7.relative(this.memoryDir, target) || MEETINGS_DIR_NAME;
4941
+ const label = path8.relative(this.memoryDir, target) || MEETINGS_DIR_NAME;
4823
4942
  throw new Error(
4824
4943
  `meetings ${kind} '${label}' is a symbolic link \u2014 refusing to follow it even when it resolves inside the memory dir (AGENTS.md pattern #3)`
4825
4944
  );
@@ -4923,7 +5042,7 @@ function stripCitationMarkersForHashRemoval(value, template) {
4923
5042
  }
4924
5043
 
4925
5044
  // src/storage/entity-timeline.ts
4926
- import { createHash as createHash4 } from "crypto";
5045
+ import { createHash as createHash5 } from "crypto";
4927
5046
  function parseEntityTimelineBullet(bullet, fallbackTimestamp) {
4928
5047
  const trimmed = bullet.trim();
4929
5048
  if (!trimmed) return null;
@@ -5295,7 +5414,7 @@ function fingerprintEntityStructuredFacts(entity) {
5295
5414
  (left, right) => left.key.localeCompare(right.key) || left.title.localeCompare(right.title) || left.facts.join("\n").localeCompare(right.facts.join("\n"))
5296
5415
  );
5297
5416
  if (normalizedSections.length === 0) return void 0;
5298
- return createHash4("sha256").update(JSON.stringify(normalizedSections)).digest("hex");
5417
+ return createHash5("sha256").update(JSON.stringify(normalizedSections)).digest("hex");
5299
5418
  }
5300
5419
  function isEntitySynthesisStale(entity) {
5301
5420
  const structuredFactCount = countEntityStructuredFacts(entity);
@@ -5346,6 +5465,15 @@ var ARTIFACT_SEARCH_STOPWORDS = /* @__PURE__ */ new Set([
5346
5465
  "were",
5347
5466
  "with"
5348
5467
  ]);
5468
+ var DELETION_REVISION_MAX_MTIME_MS = 864e13;
5469
+ var DELETION_REVISION_LOCK_STALE_MS = 6e4;
5470
+ var DELETION_REVISION_LOCK_MAX_WAIT_MS = 12e4;
5471
+ function isValidDeletionRevisionPath(value) {
5472
+ return typeof value === "string" && value.length > 0 && !value.includes("\\") && !value.includes("\0") && !path9.posix.isAbsolute(value) && path9.posix.normalize(value) === value && value !== "." && value !== ".." && !value.startsWith("../");
5473
+ }
5474
+ function deletionRevisionPathIdentity(value) {
5475
+ return value.normalize("NFC").toUpperCase().toLowerCase().replace(/\u00df/g, "ss");
5476
+ }
5349
5477
  function tokenizeArtifactSearchText(input) {
5350
5478
  return input.toLowerCase().split(/[^a-z0-9]+/i).map((t) => t.trim()).filter((t) => t.length >= 2).filter((t) => !ARTIFACT_SEARCH_STOPWORDS.has(t));
5351
5479
  }
@@ -5390,6 +5518,7 @@ function serializeFrontmatter(fm) {
5390
5518
  const safe = /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(fm.sourceConnector);
5391
5519
  lines.push(`sourceConnector: ${safe ? fm.sourceConnector : JSON.stringify(fm.sourceConnector)}`);
5392
5520
  }
5521
+ if (fm.toolScoped === true) lines.push("toolScoped: true");
5393
5522
  if (fm.supersedes) lines.push(`supersedes: ${fm.supersedes}`);
5394
5523
  if (fm.expiresAt) lines.push(`expiresAt: ${fm.expiresAt}`);
5395
5524
  if (fm.lineage && fm.lineage.length > 0) {
@@ -5599,7 +5728,7 @@ function parseReinforcementCountField(raw) {
5599
5728
  return n;
5600
5729
  }
5601
5730
  function parseFrontmatter(raw) {
5602
- const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
5731
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/);
5603
5732
  if (!match) return null;
5604
5733
  const fmBlock = match[1];
5605
5734
  const content = match[2].trim();
@@ -5773,6 +5902,7 @@ function parseFrontmatter(raw) {
5773
5902
  tags,
5774
5903
  entityRef: fm.entityRef || void 0,
5775
5904
  sourceConnector: fm.sourceConnector ? decodeYamlScalar(fm.sourceConnector) || void 0 : void 0,
5905
+ toolScoped: fm.toolScoped === "true" ? true : void 0,
5776
5906
  supersedes: fm.supersedes || void 0,
5777
5907
  expiresAt: fm.expiresAt || void 0,
5778
5908
  lineage: lineage && lineage.length > 0 ? lineage : void 0,
@@ -5861,17 +5991,17 @@ function inferEntityTypeFromContent(content) {
5861
5991
  }
5862
5992
  var KNOWN_ENTITY_FILENAME_PREFIXES = /* @__PURE__ */ new Set(["company", "other", "person", "place", "project", "tool", "topic"]);
5863
5993
  function inferEntityTypeFromFilename(pathRel) {
5864
- const basename = path8.basename(pathRel, ".md").toLowerCase();
5994
+ const basename = path9.basename(pathRel, ".md").toLowerCase();
5865
5995
  const separator = basename.indexOf("-");
5866
5996
  if (separator <= 0) return void 0;
5867
5997
  const candidate = basename.slice(0, separator);
5868
5998
  return KNOWN_ENTITY_FILENAME_PREFIXES.has(candidate) ? candidate : void 0;
5869
5999
  }
5870
6000
  function normalizeFrontmatterForPath(frontmatter, pathRel, content = "") {
5871
- const normalizedPath = pathRel.split(path8.sep).join("/");
6001
+ const normalizedPath = pathRel.split(path9.sep).join("/");
5872
6002
  let normalizedFrontmatter = frontmatter;
5873
6003
  if (normalizedPath === "entities" || normalizedPath.startsWith("entities/") || normalizedPath.includes("/entities/")) {
5874
- const basename = path8.basename(pathRel, ".md");
6004
+ const basename = path9.basename(pathRel, ".md");
5875
6005
  const inferredType = inferEntityTypeFromContent(content) || inferEntityTypeFromFilename(pathRel) || "entity";
5876
6006
  const existingTags = Array.isArray(frontmatter.tags) ? frontmatter.tags : [];
5877
6007
  normalizedFrontmatter = {
@@ -6344,6 +6474,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6344
6474
  knowledgeIndexCache = null;
6345
6475
  artifactIndexCache = null;
6346
6476
  projectionLedgerLagManager = new ProjectionLedgerLagManager();
6477
+ static loadedMemorySnapshots = /* @__PURE__ */ new WeakMap();
6347
6478
  static KNOWLEDGE_INDEX_CACHE_TTL_MS = 6e5;
6348
6479
  // 10 minutes (entity mutations invalidate)
6349
6480
  /** Read by storage/memory-read-store.ts (decomposition). */
@@ -6519,8 +6650,8 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6519
6650
  }
6520
6651
  /** Whether `filePath` resolves to `stateDir` itself or a path contained in it. */
6521
6652
  isStateFilePath(filePath) {
6522
- const rel = path8.relative(this.stateDir, path8.resolve(filePath));
6523
- return rel === "" || !rel.startsWith("..") && !path8.isAbsolute(rel);
6653
+ const rel = path9.relative(this.stateDir, path9.resolve(filePath));
6654
+ return rel === "" || !rel.startsWith("..") && !path9.isAbsolute(rel);
6524
6655
  }
6525
6656
  // ── Tombstone store (issue #1579) ───────────────────────────────────────
6526
6657
  // Instance-scoped (rule 11) + namespace-scoped (rule 42) tombstone index.
@@ -6572,9 +6703,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6572
6703
  setSecureStoreKey(key, encryptOnWrite = true) {
6573
6704
  if (!this.applySecureStoreKey(key, encryptOnWrite) || key === null) return;
6574
6705
  void this.entityCanonicalIdMigration.triggerAfterUnlock().catch((error) => {
6575
- log.warn(
6576
- `secure-store unlock migration failed: ${error instanceof Error ? error.message : String(error)}`
6577
- );
6706
+ log.warn(`secure-store unlock migration failed: ${error instanceof Error ? error.message : String(error)}`);
6578
6707
  });
6579
6708
  }
6580
6709
  async setSecureStoreKeyAndWait(key, encryptOnWrite = true) {
@@ -6637,8 +6766,8 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6637
6766
  * /srv/cold/remnic), skipping the patch and stranding a stale hot entry.
6638
6767
  */
6639
6768
  isColdOrArchiveTierPath(p) {
6640
- const rel = path8.relative(this.baseDir, p);
6641
- return rel === "cold" || rel === "archive" || rel.startsWith(`cold${path8.sep}`) || rel.startsWith(`archive${path8.sep}`);
6769
+ const rel = path9.relative(this.baseDir, p);
6770
+ return rel === "cold" || rel === "archive" || rel.startsWith(`cold${path9.sep}`) || rel.startsWith(`archive${path9.sep}`);
6642
6771
  }
6643
6772
  /**
6644
6773
  * Mark the secure-store as required for this storage instance.
@@ -6725,7 +6854,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6725
6854
  void 0,
6726
6855
  this.baseDir
6727
6856
  );
6728
- const rel = path8.relative(this.baseDir, filePath).split(path8.sep).join("/");
6857
+ const rel = path9.relative(this.baseDir, filePath).split(path9.sep).join("/");
6729
6858
  return `${rel}:${version.versionId}`;
6730
6859
  } catch (err) {
6731
6860
  log.warn(
@@ -6805,12 +6934,12 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6805
6934
  }
6806
6935
  identityFilePath(workspaceDir, namespace) {
6807
6936
  const rawNamespace = typeof namespace === "string" ? namespace.trim() : "";
6808
- if (!rawNamespace) return path8.join(workspaceDir, "IDENTITY.md");
6937
+ if (!rawNamespace) return path9.join(workspaceDir, "IDENTITY.md");
6809
6938
  const safeNamespace = rawNamespace.replace(/[^a-zA-Z0-9._-]/g, "-");
6810
- return path8.join(workspaceDir, `IDENTITY.${safeNamespace}.md`);
6939
+ return path9.join(workspaceDir, `IDENTITY.${safeNamespace}.md`);
6811
6940
  }
6812
6941
  versionFilePath(kind) {
6813
- return path8.join(this.stateDir, `.${kind}-version.log`);
6942
+ return path9.join(this.stateDir, `.${kind}-version.log`);
6814
6943
  }
6815
6944
  bumpSharedVersion(kind, fallbackMap) {
6816
6945
  const filePath = this.versionFilePath(kind);
@@ -6843,14 +6972,13 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6843
6972
  return this.readSharedVersion("memory-status", _StorageManager.memoryStatusVersionByDir);
6844
6973
  }
6845
6974
  /**
6846
- * Entity-mutation sentinel: advanced only by entity-store content writes.
6847
- * The migration fingerprint keys on this instead of memory-status, so
6848
- * supersede/archive/delete no longer re-trigger discovery scans (#2213).
6975
+ * Entity content revision used by migration discovery and entity-page cache coherence.
6849
6976
  */
6850
6977
  getEntityMutationVersion() {
6851
6978
  return this.readSharedVersion("entity-mutation", _StorageManager.entityMutationVersionByDir);
6852
6979
  }
6853
6980
  bumpEntityMutationVersion() {
6981
+ invalidateForScope(this.baseDir, "entity-write");
6854
6982
  this.bumpSharedVersion("entity-mutation", _StorageManager.entityMutationVersionByDir);
6855
6983
  }
6856
6984
  /**
@@ -6908,7 +7036,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6908
7036
  // memories.
6909
7037
  // -------------------------------------------------------------------------
6910
7038
  get wearablesDir() {
6911
- return path8.join(this.baseDir, WEARABLES_DIR_NAME);
7039
+ return path9.join(this.baseDir, WEARABLES_DIR_NAME);
6912
7040
  }
6913
7041
  /**
6914
7042
  * Resolve the on-disk path for a source/day transcript. Throws on
@@ -6924,7 +7052,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6924
7052
  if (!isValidTranscriptDate(date)) {
6925
7053
  throw new Error(`invalid wearable transcript date '${String(date)}' \u2014 expected YYYY-MM-DD`);
6926
7054
  }
6927
- return path8.join(this.wearablesDir, sourceId, `${date}.md`);
7055
+ return path9.join(this.wearablesDir, sourceId, `${date}.md`);
6928
7056
  }
6929
7057
  async writeWearableDayTranscript(sourceId, date, serialized) {
6930
7058
  const targetPath = this.wearableTranscriptPath(sourceId, date);
@@ -7040,25 +7168,25 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7040
7168
  });
7041
7169
  }
7042
7170
  get factsDir() {
7043
- return path8.join(this.baseDir, "facts");
7171
+ return path9.join(this.baseDir, "facts");
7044
7172
  }
7045
7173
  get correctionsDir() {
7046
- return path8.join(this.baseDir, "corrections");
7174
+ return path9.join(this.baseDir, "corrections");
7047
7175
  }
7048
7176
  get proceduresDir() {
7049
- return path8.join(this.baseDir, "procedures");
7177
+ return path9.join(this.baseDir, "procedures");
7050
7178
  }
7051
7179
  get reasoningTracesDir() {
7052
- return path8.join(this.baseDir, "reasoning-traces");
7180
+ return path9.join(this.baseDir, "reasoning-traces");
7053
7181
  }
7054
7182
  get entitiesDir() {
7055
- return path8.join(this.baseDir, "entities");
7183
+ return path9.join(this.baseDir, "entities");
7056
7184
  }
7057
7185
  resolveEntityFilePath(name) {
7058
7186
  if (typeof name !== "string") return null;
7059
- const filePath = path8.resolve(this.entitiesDir, `${name}.md`);
7060
- const relative2 = path8.relative(this.entitiesDir, filePath);
7061
- if (relative2 === "" || relative2.startsWith("..") || path8.isAbsolute(relative2)) {
7187
+ const filePath = path9.resolve(this.entitiesDir, `${name}.md`);
7188
+ const relative2 = path9.relative(this.entitiesDir, filePath);
7189
+ if (relative2 === "" || relative2.startsWith("..") || path9.isAbsolute(relative2)) {
7062
7190
  return null;
7063
7191
  }
7064
7192
  return filePath;
@@ -7073,14 +7201,186 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7073
7201
  });
7074
7202
  }
7075
7203
  assertManagedStoragePath(filePath, method) {
7076
- const resolved = path8.resolve(filePath);
7077
- const base = path8.resolve(this.baseDir);
7078
- const rel = path8.relative(base, resolved);
7079
- if (rel === "" || rel === ".." || rel.startsWith(`..${path8.sep}`) || path8.isAbsolute(rel)) {
7204
+ const resolved = path9.resolve(filePath);
7205
+ const base = path9.resolve(this.baseDir);
7206
+ const rel = path9.relative(base, resolved);
7207
+ if (rel === "" || rel === ".." || rel.startsWith(`..${path9.sep}`) || path9.isAbsolute(rel)) {
7080
7208
  throw new Error(`${method}: file path escapes memory dir`);
7081
7209
  }
7082
7210
  return resolved;
7083
7211
  }
7212
+ parseDeletionRevisionMetadata(raw) {
7213
+ let parsed;
7214
+ try {
7215
+ parsed = JSON.parse(raw);
7216
+ } catch {
7217
+ throw new Error("Deletion revision metadata is invalid.");
7218
+ }
7219
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
7220
+ throw new Error("Deletion revision metadata is invalid.");
7221
+ }
7222
+ const root = parsed;
7223
+ if (Object.keys(root).sort().join(",") !== "deletions,version" || root.version !== 1 || !Array.isArray(root.deletions)) {
7224
+ throw new Error("Deletion revision metadata is invalid.");
7225
+ }
7226
+ const revisions = /* @__PURE__ */ new Map();
7227
+ const pathByIdentity = /* @__PURE__ */ new Map();
7228
+ for (const rawEntry of root.deletions) {
7229
+ if (!rawEntry || typeof rawEntry !== "object" || Array.isArray(rawEntry)) {
7230
+ throw new Error("Deletion revision metadata is invalid.");
7231
+ }
7232
+ const entry = rawEntry;
7233
+ if (Object.keys(entry).sort().join(",") !== "mtimeMs,path" || !isValidDeletionRevisionPath(entry.path) || typeof entry.mtimeMs !== "number" || !Number.isFinite(entry.mtimeMs) || entry.mtimeMs < 0 || entry.mtimeMs > DELETION_REVISION_MAX_MTIME_MS || revisions.has(entry.path)) {
7234
+ throw new Error("Deletion revision metadata is invalid.");
7235
+ }
7236
+ const identity = deletionRevisionPathIdentity(entry.path);
7237
+ if (pathByIdentity.has(identity)) {
7238
+ throw new Error("Deletion revision metadata is invalid.");
7239
+ }
7240
+ pathByIdentity.set(identity, entry.path);
7241
+ revisions.set(entry.path, entry.mtimeMs);
7242
+ }
7243
+ return new Map([...revisions.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
7244
+ }
7245
+ async readDeletionRevisionMetadata() {
7246
+ let raw;
7247
+ try {
7248
+ raw = await readFile2(this.deletionRevisionMetadataPath, "utf8");
7249
+ } catch (error) {
7250
+ if (isErrnoCode(error, "ENOENT")) return /* @__PURE__ */ new Map();
7251
+ throw new Error("Deletion revision metadata is unavailable.");
7252
+ }
7253
+ return this.parseDeletionRevisionMetadata(raw);
7254
+ }
7255
+ async writeDeletionRevisionMetadata(revisions, lock) {
7256
+ const deletions = [...revisions.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([entryPath, mtimeMs]) => ({ path: entryPath, mtimeMs }));
7257
+ const metadata = { version: 1, deletions };
7258
+ const temporaryPath = `${this.deletionRevisionMetadataPath}.${process.pid}.${randomUUID2()}.tmp`;
7259
+ let handle = null;
7260
+ try {
7261
+ handle = await open(temporaryPath, "wx", 384);
7262
+ await handle.writeFile(`${JSON.stringify(metadata)}
7263
+ `, "utf8");
7264
+ await handle.sync();
7265
+ await handle.close();
7266
+ handle = null;
7267
+ if (!await lock.refresh()) {
7268
+ throw new Error("Deletion revision metadata lock was lost.");
7269
+ }
7270
+ await rename2(temporaryPath, this.deletionRevisionMetadataPath);
7271
+ } finally {
7272
+ if (handle !== null) await handle.close().catch(() => void 0);
7273
+ await unlink4(temporaryPath).catch((error) => {
7274
+ if (!isErrnoCode(error, "ENOENT")) throw error;
7275
+ });
7276
+ }
7277
+ }
7278
+ async withDeletionRevisionLock(task) {
7279
+ return withHeldFileLock(
7280
+ this.deletionRevisionLockPath,
7281
+ {
7282
+ staleMs: DELETION_REVISION_LOCK_STALE_MS,
7283
+ maxWaitMs: DELETION_REVISION_LOCK_MAX_WAIT_MS
7284
+ },
7285
+ async (acquired, lock) => {
7286
+ if (!acquired) throw new Error("Deletion revision metadata lock is unavailable.");
7287
+ return task(lock);
7288
+ }
7289
+ );
7290
+ }
7291
+ async readDeletionRevisions() {
7292
+ return this.withDeletionRevisionLock(async () => this.readDeletionRevisionMetadata());
7293
+ }
7294
+ async recordReplicatedDeletionRevision(filePath, mtimeMs) {
7295
+ const target = this.assertManagedStoragePath(filePath, "storage.recordReplicatedDeletionRevision");
7296
+ if (typeof mtimeMs !== "number" || !Number.isFinite(mtimeMs) || mtimeMs < 0 || mtimeMs > DELETION_REVISION_MAX_MTIME_MS) {
7297
+ throw new Error("Deletion revision timestamp is invalid.");
7298
+ }
7299
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7300
+ if (!isValidDeletionRevisionPath(relativePath)) {
7301
+ throw new Error("Deletion revision path is invalid.");
7302
+ }
7303
+ await this.withDeletionRevisionLock(async (lock) => {
7304
+ const revisions = await this.readDeletionRevisionMetadata();
7305
+ const identity = deletionRevisionPathIdentity(relativePath);
7306
+ let existingPath;
7307
+ for (const candidatePath of revisions.keys()) {
7308
+ if (deletionRevisionPathIdentity(candidatePath) === identity) {
7309
+ existingPath = candidatePath;
7310
+ break;
7311
+ }
7312
+ }
7313
+ const existingMtimeMs = existingPath === void 0 ? void 0 : revisions.get(existingPath);
7314
+ if (existingMtimeMs !== void 0 && existingMtimeMs >= mtimeMs) return;
7315
+ const updated = new Map(revisions);
7316
+ if (existingPath !== void 0) updated.delete(existingPath);
7317
+ updated.set(relativePath, mtimeMs);
7318
+ await this.writeDeletionRevisionMetadata(updated, lock);
7319
+ });
7320
+ }
7321
+ async writeManagedStorageFile(filePath, write) {
7322
+ const target = this.assertManagedStoragePath(filePath, "storage.writeManagedStorageFile");
7323
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7324
+ if (!isValidDeletionRevisionPath(relativePath)) {
7325
+ throw new Error("Deletion revision path is invalid.");
7326
+ }
7327
+ await this.withDeletionRevisionLock(async (lock) => {
7328
+ const before = await this.readDeletionRevisionMetadata();
7329
+ const identity = deletionRevisionPathIdentity(relativePath);
7330
+ const existingPath = [...before.keys()].find(
7331
+ (candidatePath) => deletionRevisionPathIdentity(candidatePath) === identity
7332
+ );
7333
+ await write();
7334
+ if (existingPath === void 0) return;
7335
+ const updated = new Map(before);
7336
+ updated.delete(existingPath);
7337
+ await this.writeDeletionRevisionMetadata(updated, lock);
7338
+ });
7339
+ }
7340
+ async deleteManagedStorageFile(filePath, deletionMtimeMs) {
7341
+ const target = this.assertManagedStoragePath(filePath, "storage.deleteManagedStorageFile");
7342
+ if (deletionMtimeMs !== void 0 && deletionMtimeMs !== null && (typeof deletionMtimeMs !== "number" || !Number.isFinite(deletionMtimeMs) || deletionMtimeMs < 0 || deletionMtimeMs > DELETION_REVISION_MAX_MTIME_MS)) {
7343
+ throw new Error("Deletion revision timestamp is invalid.");
7344
+ }
7345
+ return this.withDeletionRevisionLock(async (lock) => {
7346
+ try {
7347
+ await lstat3(target);
7348
+ } catch (error) {
7349
+ if (isErrnoCode(error, "ENOENT")) return false;
7350
+ throw error;
7351
+ }
7352
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7353
+ if (!isValidDeletionRevisionPath(relativePath)) {
7354
+ throw new Error("Deletion revision path is invalid.");
7355
+ }
7356
+ const revision = deletionMtimeMs === null ? void 0 : deletionMtimeMs ?? Date.now();
7357
+ const before = await this.readDeletionRevisionMetadata();
7358
+ const identity = deletionRevisionPathIdentity(relativePath);
7359
+ let existingPath;
7360
+ for (const candidatePath of before.keys()) {
7361
+ if (deletionRevisionPathIdentity(candidatePath) === identity) {
7362
+ existingPath = candidatePath;
7363
+ break;
7364
+ }
7365
+ }
7366
+ const existing = existingPath === void 0 ? void 0 : before.get(existingPath);
7367
+ const changed = existingPath !== void 0 && existingPath !== relativePath || (revision === void 0 ? existing !== void 0 : existing !== revision);
7368
+ if (changed) {
7369
+ const updated = new Map(before);
7370
+ if (existingPath !== void 0) updated.delete(existingPath);
7371
+ if (revision !== void 0) updated.set(relativePath, revision);
7372
+ await this.writeDeletionRevisionMetadata(updated, lock);
7373
+ }
7374
+ try {
7375
+ await unlink4(target);
7376
+ return true;
7377
+ } catch (error) {
7378
+ if (changed) await this.writeDeletionRevisionMetadata(before, lock);
7379
+ if (isErrnoCode(error, "ENOENT")) return false;
7380
+ throw error;
7381
+ }
7382
+ });
7383
+ }
7084
7384
  async readOfflineSyncFile(filePath) {
7085
7385
  const target = this.assertManagedStoragePath(filePath, "storage.readOfflineSyncFile");
7086
7386
  return readMaybeEncryptedFileBuffer(target, this._secureStoreKey, this.baseDir);
@@ -7088,7 +7388,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7088
7388
  async digestOfflineSyncFile(filePath) {
7089
7389
  const target = this.assertManagedStoragePath(filePath, "storage.digestOfflineSyncFile");
7090
7390
  const st = await stat2(target);
7091
- const relPath = path8.relative(this.baseDir, target).split(path8.sep).join("/");
7391
+ const relPath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7092
7392
  const cache = await this.loadOfflineSyncDigestCache();
7093
7393
  const cached = cache.get(relPath);
7094
7394
  if (cached && cached.statBytes === st.size && cached.mtimeMs === st.mtimeMs && cached.ctimeMs === st.ctimeMs && !cached.encrypted) {
@@ -7102,11 +7402,11 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7102
7402
  if (encrypted) {
7103
7403
  const content = await readMaybeEncryptedFileBuffer(target, this._secureStoreKey, this.baseDir);
7104
7404
  digest = {
7105
- sha256: createHash5("sha256").update(content).digest("hex"),
7405
+ sha256: createHash6("sha256").update(content).digest("hex"),
7106
7406
  bytes: content.byteLength
7107
7407
  };
7108
7408
  } else {
7109
- const hash = createHash5("sha256");
7409
+ const hash = createHash6("sha256");
7110
7410
  let bytes = 0;
7111
7411
  for await (const rawChunk of createReadStream(target)) {
7112
7412
  const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
@@ -7149,7 +7449,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7149
7449
  const bytes = typeof record.bytes === "number" ? record.bytes : NaN;
7150
7450
  const sha256 = typeof record.sha256 === "string" ? record.sha256 : "";
7151
7451
  const encrypted = record.encrypted === true;
7152
- if (cachePath.length === 0 || cachePath === ".." || cachePath.startsWith("../") || path8.isAbsolute(cachePath) || !Number.isFinite(statBytes) || !Number.isFinite(mtimeMs) || !Number.isFinite(ctimeMs) || !Number.isFinite(bytes) || !/^[a-f0-9]{64}$/i.test(sha256)) {
7452
+ if (cachePath.length === 0 || cachePath === ".." || cachePath.startsWith("../") || path9.isAbsolute(cachePath) || !Number.isFinite(statBytes) || !Number.isFinite(mtimeMs) || !Number.isFinite(ctimeMs) || !Number.isFinite(bytes) || !/^[a-f0-9]{64}$/i.test(sha256)) {
7153
7453
  continue;
7154
7454
  }
7155
7455
  cache.set(cachePath, { statBytes, mtimeMs, ctimeMs, encrypted, sha256, bytes });
@@ -7191,7 +7491,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7191
7491
  const cache = this.offlineSyncDigestCache;
7192
7492
  if (!cache) return;
7193
7493
  const entries = [...cache.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([entryPath, entry]) => ({ path: entryPath, ...entry }));
7194
- await mkdir(path8.dirname(this.offlineSyncDigestCachePath), { recursive: true });
7494
+ await mkdir(path9.dirname(this.offlineSyncDigestCachePath), { recursive: true });
7195
7495
  await writeFile2(this.offlineSyncDigestCachePath, `${JSON.stringify({ version: 1, entries })}
7196
7496
  `, "utf-8");
7197
7497
  }).catch((err) => {
@@ -7280,7 +7580,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7280
7580
  }
7281
7581
  async appendStorageSecureFileUnlocked(filePath, content) {
7282
7582
  const writeKey = this.resolveWriteKey();
7283
- await mkdir(path8.dirname(filePath), { recursive: true });
7583
+ await mkdir(path9.dirname(filePath), { recursive: true });
7284
7584
  if (writeKey === null) {
7285
7585
  try {
7286
7586
  if (await this.isEncryptedFileHeader(filePath)) {
@@ -7306,13 +7606,19 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7306
7606
  this.notifyCatalogWriteForPath(filePath);
7307
7607
  }
7308
7608
  get stateDir() {
7309
- return path8.join(this.baseDir, "state");
7609
+ return path9.join(this.baseDir, "state");
7310
7610
  }
7311
7611
  get offlineSyncDigestCachePath() {
7312
- return path8.join(this.baseDir, ".offline-sync", "digest-cache.v1.json");
7612
+ return path9.join(this.baseDir, ".offline-sync", "digest-cache.v1.json");
7613
+ }
7614
+ get deletionRevisionMetadataPath() {
7615
+ return path9.join(this.baseDir, ".offline-sync", "deletion-revisions.v1.json");
7616
+ }
7617
+ get deletionRevisionLockPath() {
7618
+ return `${this.deletionRevisionMetadataPath}.lock`;
7313
7619
  }
7314
7620
  get entitySynthesisQueuePath() {
7315
- return path8.join(this.stateDir, "entity-synthesis-queue.json");
7621
+ return path9.join(this.stateDir, "entity-synthesis-queue.json");
7316
7622
  }
7317
7623
  // ── Tombstone store access (issue #1579) ─────────────────────────────────
7318
7624
  /**
@@ -7322,7 +7628,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7322
7628
  * helpers are injected into the store).
7323
7629
  */
7324
7630
  get tombstonesPath() {
7325
- return path8.join(this.stateDir, "tombstones.jsonl");
7631
+ return path9.join(this.stateDir, "tombstones.jsonl");
7326
7632
  }
7327
7633
  /**
7328
7634
  * Configure the tombstone invariant for this storage instance. Installed
@@ -7619,55 +7925,55 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7619
7925
  return null;
7620
7926
  }
7621
7927
  get questionsDir() {
7622
- return path8.join(this.baseDir, "questions");
7928
+ return path9.join(this.baseDir, "questions");
7623
7929
  }
7624
7930
  get artifactsDir() {
7625
- return path8.join(this.baseDir, "artifacts");
7931
+ return path9.join(this.baseDir, "artifacts");
7626
7932
  }
7627
7933
  get identityDir() {
7628
- return path8.join(this.baseDir, "identity");
7934
+ return path9.join(this.baseDir, "identity");
7629
7935
  }
7630
7936
  get identityAnchorPath() {
7631
- return path8.join(this.identityDir, "identity-anchor.md");
7937
+ return path9.join(this.identityDir, "identity-anchor.md");
7632
7938
  }
7633
7939
  get identityIncidentsDir() {
7634
- return path8.join(this.identityDir, "incidents");
7940
+ return path9.join(this.identityDir, "incidents");
7635
7941
  }
7636
7942
  get identityAuditsWeeklyDir() {
7637
- return path8.join(this.identityDir, "audits", "weekly");
7943
+ return path9.join(this.identityDir, "audits", "weekly");
7638
7944
  }
7639
7945
  get identityAuditsMonthlyDir() {
7640
- return path8.join(this.identityDir, "audits", "monthly");
7946
+ return path9.join(this.identityDir, "audits", "monthly");
7641
7947
  }
7642
7948
  get identityImprovementLoopsPath() {
7643
- return path8.join(this.identityDir, "improvement-loops.md");
7949
+ return path9.join(this.identityDir, "improvement-loops.md");
7644
7950
  }
7645
7951
  get identityReflectionsPath() {
7646
- return path8.join(this.identityDir, "reflections.md");
7952
+ return path9.join(this.identityDir, "reflections.md");
7647
7953
  }
7648
7954
  get profilePath() {
7649
- return path8.join(this.baseDir, "profile.md");
7955
+ return path9.join(this.baseDir, "profile.md");
7650
7956
  }
7651
7957
  get memoryActionsPath() {
7652
- return path8.join(this.stateDir, "memory-actions.jsonl");
7958
+ return path9.join(this.stateDir, "memory-actions.jsonl");
7653
7959
  }
7654
7960
  get memoryLifecycleLedgerPath() {
7655
- return path8.join(this.stateDir, "memory-lifecycle-ledger.jsonl");
7961
+ return path9.join(this.stateDir, "memory-lifecycle-ledger.jsonl");
7656
7962
  }
7657
7963
  get compressionGuidelinesPath() {
7658
- return path8.join(this.stateDir, "compression-guidelines.md");
7964
+ return path9.join(this.stateDir, "compression-guidelines.md");
7659
7965
  }
7660
7966
  get compressionGuidelineDraftPath() {
7661
- return path8.join(this.stateDir, "compression-guidelines.draft.md");
7967
+ return path9.join(this.stateDir, "compression-guidelines.draft.md");
7662
7968
  }
7663
7969
  get compressionGuidelineStatePath() {
7664
- return path8.join(this.stateDir, "compression-guideline-state.json");
7970
+ return path9.join(this.stateDir, "compression-guideline-state.json");
7665
7971
  }
7666
7972
  get compressionGuidelineDraftStatePath() {
7667
- return path8.join(this.stateDir, "compression-guideline-draft-state.json");
7973
+ return path9.join(this.stateDir, "compression-guideline-draft-state.json");
7668
7974
  }
7669
7975
  get behaviorSignalsPath() {
7670
- return path8.join(this.stateDir, "behavior-signals.jsonl");
7976
+ return path9.join(this.stateDir, "behavior-signals.jsonl");
7671
7977
  }
7672
7978
  /**
7673
7979
  * In-memory dedup key set for behavior-signals appends (issue #1909),
@@ -7699,7 +8005,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7699
8005
  * governance sweeps can treat it uniformly.
7700
8006
  */
7701
8007
  get bufferSurpriseLedgerPath() {
7702
- return path8.join(this.stateDir, "buffer-surprise-ledger.jsonl");
8008
+ return path9.join(this.stateDir, "buffer-surprise-ledger.jsonl");
7703
8009
  }
7704
8010
  /**
7705
8011
  * Entity alias table loaded from THIS store's config/aliases.json.
@@ -7760,25 +8066,29 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7760
8066
  this.loadAliasesSync();
7761
8067
  }
7762
8068
  loadAliasesSync() {
7763
- const aliasPath = path8.join(this.baseDir, "config", "aliases.json");
8069
+ const aliasPath = path9.join(this.baseDir, "config", "aliases.json");
7764
8070
  this.userAliases = {};
8071
+ const raw = readEntityAliasConfigSync(this.baseDir);
8072
+ if (raw === void 0) return;
8073
+ let parsed;
7765
8074
  try {
7766
- const raw = readFileSync(aliasPath, "utf-8");
7767
- const parsed = JSON.parse(raw);
7768
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
7769
- const cleaned = {};
7770
- for (const [key, value] of Object.entries(parsed)) {
7771
- if (typeof value === "string" && value.trim().length > 0) {
7772
- cleaned[key] = value;
7773
- }
8075
+ parsed = JSON.parse(raw);
8076
+ } catch {
8077
+ log.debug("invalid config/aliases.json \u2014 using built-in aliases only");
8078
+ return;
8079
+ }
8080
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
8081
+ const cleaned = {};
8082
+ for (const [key, value] of Object.entries(parsed)) {
8083
+ if (typeof value === "string" && value.trim().length > 0) {
8084
+ assertSafeEntityId(value);
8085
+ cleaned[key] = value;
7774
8086
  }
7775
- this.userAliases = cleaned;
7776
- log.debug(`loaded ${Object.keys(cleaned).length} entity aliases from ${aliasPath}`);
7777
- } else {
7778
- log.warn(`ignoring ${aliasPath}: payload must be a JSON object mapping variant \u2192 canonical strings`);
7779
8087
  }
7780
- } catch {
7781
- log.debug("no config/aliases.json found \u2014 using built-in aliases only");
8088
+ this.userAliases = cleaned;
8089
+ log.debug(`loaded ${Object.keys(cleaned).length} entity aliases from ${aliasPath}`);
8090
+ } else {
8091
+ log.warn(`ignoring ${aliasPath}: payload must be a JSON object mapping variant \u2192 canonical strings`);
7782
8092
  }
7783
8093
  }
7784
8094
  async runLegacyEntityCanonicalIdMigration() {
@@ -7794,9 +8104,9 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7794
8104
  await mkdir(this.baseDir, { recursive: true });
7795
8105
  await validateRoots(this.baseDir, this.entitiesDir, this.stateDir, this.archiveDir);
7796
8106
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
7797
- await mkdir(path8.join(this.factsDir, today), { recursive: true });
7798
- await mkdir(path8.join(this.proceduresDir, today), { recursive: true });
7799
- await mkdir(path8.join(this.reasoningTracesDir, today), { recursive: true });
8107
+ await mkdir(path9.join(this.factsDir, today), { recursive: true });
8108
+ await mkdir(path9.join(this.proceduresDir, today), { recursive: true });
8109
+ await mkdir(path9.join(this.reasoningTracesDir, today), { recursive: true });
7800
8110
  await mkdir(this.correctionsDir, { recursive: true });
7801
8111
  await mkdir(this.entitiesDir, { recursive: true });
7802
8112
  await mkdir(this.stateDir, { recursive: true });
@@ -7806,7 +8116,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7806
8116
  await mkdir(this.identityIncidentsDir, { recursive: true });
7807
8117
  await mkdir(this.identityAuditsWeeklyDir, { recursive: true });
7808
8118
  await mkdir(this.identityAuditsMonthlyDir, { recursive: true });
7809
- await mkdir(path8.join(this.baseDir, "config"), { recursive: true });
8119
+ await mkdir(path9.join(this.baseDir, "config"), { recursive: true });
7810
8120
  await this.entityCanonicalIdMigration.ensure();
7811
8121
  if (this.hotMemoriesCacheEnabled && this.getMemoryCorpusVersion() === 0) {
7812
8122
  this.bumpMemoryCorpusVersion();
@@ -7828,11 +8138,11 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7828
8138
  async resolveCategoryWritePath(category, id, today) {
7829
8139
  if (category === "correction") {
7830
8140
  await mkdir(this.correctionsDir, { recursive: true });
7831
- return path8.join(this.correctionsDir, `${id}.md`);
8141
+ return path9.join(this.correctionsDir, `${id}.md`);
7832
8142
  }
7833
- const datedDir = path8.join(getCategoryDir(this.baseDir, category), today);
8143
+ const datedDir = path9.join(getCategoryDir(this.baseDir, category), today);
7834
8144
  await mkdir(datedDir, { recursive: true });
7835
- return path8.join(datedDir, `${id}.md`);
8145
+ return path9.join(datedDir, `${id}.md`);
7836
8146
  }
7837
8147
  async findExistingTombstoneBlockedMemory(content, category, sourceConnector) {
7838
8148
  const identity = buildExplicitCaptureDedupKey(content, category, sourceConnector);
@@ -7918,6 +8228,12 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7918
8228
  if (!sanitized.clean) {
7919
8229
  log.warn(`memory content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
7920
8230
  }
8231
+ if (options.toolScoped || withholdToolScopedFromSharedNamespace({
8232
+ content: sanitized.text,
8233
+ sourceConnector: options.sourceConnector
8234
+ })) {
8235
+ fm.toolScoped = true;
8236
+ }
7921
8237
  let factHashSourceForTombstone = null;
7922
8238
  if (category === "fact") {
7923
8239
  const hashSource = options.contentHashSource !== void 0 && options.contentHashSource.length > 0 ? sanitizeMemoryContent(options.contentHashSource).text : sanitized.text;
@@ -7928,13 +8244,13 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7928
8244
  refIds = this.currentHistoricalIds();
7929
8245
  fm.entityRef = resolveHistoricalEntityCanonicalId(rawEntityRef, refIds);
7930
8246
  }
7931
- let tombstoneBlocked = false;
8247
+ let tombstoneBlocked2 = false;
7932
8248
  let gateRef;
7933
8249
  let statusBeforeBlock;
7934
8250
  const applyTombstoneGate = async () => {
7935
- if (tombstoneBlocked) {
8251
+ if (tombstoneBlocked2) {
7936
8252
  if (fm.entityRef === gateRef) return;
7937
- tombstoneBlocked = false;
8253
+ tombstoneBlocked2 = false;
7938
8254
  fm.status = statusBeforeBlock;
7939
8255
  delete fm.blockedBy;
7940
8256
  delete fm.tombstoneBlockTier;
@@ -7945,7 +8261,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7945
8261
  if (match) {
7946
8262
  gateRef = fm.entityRef;
7947
8263
  statusBeforeBlock = statusBefore;
7948
- tombstoneBlocked = true;
8264
+ tombstoneBlocked2 = true;
7949
8265
  }
7950
8266
  };
7951
8267
  await applyTombstoneGate();
@@ -7955,7 +8271,7 @@ ${sanitized.text}
7955
8271
  `;
7956
8272
  const filePath = await this.resolveCategoryWritePath(category, id, today);
7957
8273
  const persistFile = async () => {
7958
- if (tombstoneBlocked) {
8274
+ if (tombstoneBlocked2) {
7959
8275
  const duplicate = await this.findExistingTombstoneBlockedMemory(sanitized.text, category, fm.sourceConnector);
7960
8276
  if (duplicate) return duplicate;
7961
8277
  }
@@ -7963,12 +8279,44 @@ ${sanitized.text}
7963
8279
  await this.writeTombstoneBlockedMemory(filePath, fileContent, fm, sanitized.text, async () => {
7964
8280
  this.invalidateAllMemoriesCache();
7965
8281
  });
8282
+ if (refIds && typeof rawEntityRef === "string") {
8283
+ const refBeforeRepair = fm.entityRef;
8284
+ try {
8285
+ await repairEntityRefAfterJournalMove({
8286
+ stateDir: this.stateDir,
8287
+ currentIds: () => this.currentHistoricalIds(),
8288
+ idsAtResolve: refIds,
8289
+ rawRef: rawEntityRef,
8290
+ frontmatter: fm,
8291
+ rewrite: async () => {
8292
+ await applyTombstoneGate();
8293
+ await this.writeTombstoneBlockedMemory(
8294
+ filePath,
8295
+ `${serializeFrontmatter(fm)}
8296
+
8297
+ ${sanitized.text}
8298
+ `,
8299
+ fm,
8300
+ sanitized.text,
8301
+ async () => this.invalidateAllMemoriesCache()
8302
+ );
8303
+ this.invalidateAllMemoriesCache();
8304
+ }
8305
+ });
8306
+ } catch (err) {
8307
+ await unlink4(filePath).catch(() => void 0);
8308
+ this.invalidateAllMemoriesCache();
8309
+ await this.rebuildTombstoneBlockedCaptureAfterInvalidationForPath(filePath);
8310
+ throw err;
8311
+ }
8312
+ await this.entityRefRepair.syncProjection(id, refBeforeRepair, fm.entityRef);
8313
+ }
7966
8314
  return null;
7967
8315
  };
7968
- const duplicateBlocked = tombstoneBlocked ? await this.withTombstoneBlockedCaptureWriteLock(
7969
- persistFile,
8316
+ const duplicateBlocked = await this.withTombstoneBlockedCaptureWriteLock(persistFile, [
8317
+ buildCapturePathLockIdentity(filePath),
7970
8318
  buildExplicitCaptureDedupKey(sanitized.text, category, fm.sourceConnector)
7971
- ) : await persistFile();
8319
+ ]);
7972
8320
  if (duplicateBlocked) {
7973
8321
  return {
7974
8322
  id: duplicateBlocked.frontmatter.id,
@@ -7977,37 +8325,6 @@ ${sanitized.text}
7977
8325
  duplicateOf: duplicateBlocked.frontmatter.id
7978
8326
  };
7979
8327
  }
7980
- if (refIds && typeof rawEntityRef === "string") {
7981
- const refBeforeRepair = fm.entityRef;
7982
- try {
7983
- await repairEntityRefAfterJournalMove({
7984
- stateDir: this.stateDir,
7985
- currentIds: () => this.currentHistoricalIds(),
7986
- idsAtResolve: refIds,
7987
- rawRef: rawEntityRef,
7988
- frontmatter: fm,
7989
- rewrite: async () => {
7990
- await applyTombstoneGate();
7991
- await this.writeTombstoneBlockedMemory(
7992
- filePath,
7993
- `${serializeFrontmatter(fm)}
7994
-
7995
- ${sanitized.text}
7996
- `,
7997
- fm,
7998
- sanitized.text,
7999
- async () => this.invalidateAllMemoriesCache()
8000
- );
8001
- this.invalidateAllMemoriesCache();
8002
- }
8003
- });
8004
- } catch (err) {
8005
- await unlink4(filePath).catch(() => void 0);
8006
- this.invalidateAllMemoriesCache();
8007
- throw err;
8008
- }
8009
- await this.entityRefRepair.syncProjection(id, refBeforeRepair, fm.entityRef);
8010
- }
8011
8328
  await this.patchHotMemoriesCache({ addedPath: filePath }, "memory-create");
8012
8329
  this.notifyMemoryWrite(filePath);
8013
8330
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.writeMemory", {
@@ -8021,7 +8338,7 @@ ${sanitized.text}
8021
8338
  ...(options.lineage ?? []).filter(Boolean)
8022
8339
  ]
8023
8340
  });
8024
- if (category === "fact" && !tombstoneBlocked) {
8341
+ if (category === "fact" && !tombstoneBlocked2) {
8025
8342
  try {
8026
8343
  const factHashIndex = await this.getFactHashIndex();
8027
8344
  const hashText = options.contentHashSource !== void 0 && options.contentHashSource.length > 0 ? sanitizeMemoryContent(options.contentHashSource).text : sanitized.text;
@@ -8036,7 +8353,7 @@ ${sanitized.text}
8036
8353
  }
8037
8354
  }
8038
8355
  log.debug(`wrote memory ${id} to ${filePath}`);
8039
- return { id, tombstoneBlocked, ...fm.blockedBy ? { blockedBy: fm.blockedBy } : {} };
8356
+ return { id, tombstoneBlocked: tombstoneBlocked2, ...fm.blockedBy ? { blockedBy: fm.blockedBy } : {} };
8040
8357
  }
8041
8358
  /**
8042
8359
  * Sealed-envelope write entry point (issue #1989 PR2).
@@ -8192,7 +8509,7 @@ ${sanitized.text}
8192
8509
  await this.ensureDirectories();
8193
8510
  const now = /* @__PURE__ */ new Date();
8194
8511
  const day = now.toISOString().slice(0, 10);
8195
- const dir = path8.join(this.artifactsDir, day);
8512
+ const dir = path9.join(this.artifactsDir, day);
8196
8513
  await mkdir(dir, { recursive: true });
8197
8514
  const id = `artifact-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
8198
8515
  const fm = {
@@ -8210,14 +8527,15 @@ ${sanitized.text}
8210
8527
  intentGoal: options.intentGoal,
8211
8528
  intentActionType: options.intentActionType,
8212
8529
  intentEntityTypes: options.intentEntityTypes,
8213
- ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {}
8530
+ ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {},
8531
+ ...options.toolScoped ? { toolScoped: true } : {}
8214
8532
  };
8215
8533
  const sanitized = sanitizeMemoryContent(quote);
8216
8534
  if (!sanitized.clean) {
8217
8535
  log.warn(`artifact content rejected for ${id}; violations=${sanitized.violations.join(", ")}`);
8218
8536
  return "";
8219
8537
  }
8220
- const filePath = path8.join(dir, `${id}.md`);
8538
+ const filePath = path9.join(dir, `${id}.md`);
8221
8539
  await this.writeStorageSecureFile(filePath, `${serializeFrontmatter(fm)}
8222
8540
 
8223
8541
  ${sanitized.text}
@@ -8308,12 +8626,7 @@ ${sanitized.text}
8308
8626
  });
8309
8627
  if (newBullets.length === 0) return;
8310
8628
  if (!existing) {
8311
- const content = [
8312
- "# Behavioral Profile",
8313
- "",
8314
- ...newBullets.map((b) => `- ${b}`),
8315
- ""
8316
- ].join("\n");
8629
+ const content = ["# Behavioral Profile", "", ...newBullets.map((b) => `- ${b}`), ""].join("\n");
8317
8630
  await this.writeProfile(content);
8318
8631
  } else {
8319
8632
  const withBullets = existing.trimEnd() + "\n" + newBullets.map((b) => `- ${b}`).join("\n") + "\n";
@@ -8328,6 +8641,16 @@ ${sanitized.text}
8328
8641
  const threshold = typeof triggerLines === "number" ? Math.max(0, Math.floor(triggerLines)) : _StorageManager.PROFILE_MAX_LINES;
8329
8642
  return lineCount > threshold;
8330
8643
  }
8644
+ rememberMemorySnapshot(memory) {
8645
+ if (memory !== null && !_StorageManager.loadedMemorySnapshots.has(memory)) {
8646
+ _StorageManager.loadedMemorySnapshots.set(memory, createMemorySnapshot(memory));
8647
+ }
8648
+ return memory;
8649
+ }
8650
+ rememberMemorySnapshots(memories) {
8651
+ for (const memory of memories) this.rememberMemorySnapshot(memory);
8652
+ return memories;
8653
+ }
8331
8654
  async readAllMemories() {
8332
8655
  if (this.hotMemoriesCacheEnabled) {
8333
8656
  const cached = getCachedMemories(
@@ -8336,11 +8659,11 @@ ${sanitized.text}
8336
8659
  this.hotCacheKeyId(),
8337
8660
  this.hotCacheTtlMs()
8338
8661
  );
8339
- if (cached !== null) return cached;
8662
+ if (cached !== null) return this.rememberMemorySnapshots(cached);
8340
8663
  }
8341
8664
  const keyId = this.hotCacheKeyId();
8342
8665
  const inFlight = getInFlightRead(this.baseDir, keyId);
8343
- if (inFlight) return inFlight;
8666
+ if (inFlight) return this.rememberMemorySnapshots(await inFlight);
8344
8667
  const readPromise = (async () => {
8345
8668
  const version = this.getMemoryCorpusVersion();
8346
8669
  const memories = await this._readAllMemoriesFromDisk();
@@ -8351,7 +8674,7 @@ ${sanitized.text}
8351
8674
  })();
8352
8675
  setInFlightRead(this.baseDir, keyId, readPromise);
8353
8676
  try {
8354
- return await readPromise;
8677
+ return this.rememberMemorySnapshots(await readPromise);
8355
8678
  } finally {
8356
8679
  deleteInFlightRead(this.baseDir, keyId, readPromise);
8357
8680
  }
@@ -8488,7 +8811,7 @@ ${sanitized.text}
8488
8811
  * per-process in-memory cache safe across process boundaries.
8489
8812
  */
8490
8813
  invalidateColdMemoriesCache() {
8491
- const coldRoot = path8.join(this.baseDir, "cold");
8814
+ const coldRoot = path9.join(this.baseDir, "cold");
8492
8815
  _StorageManager.coldMemoriesCache.delete(coldRoot);
8493
8816
  this.bumpColdWriteVersion();
8494
8817
  invalidateAllForDir(this.baseDir);
@@ -8548,15 +8871,18 @@ ${sanitized.text}
8548
8871
  const raw = await readMaybeEncryptedFile(fullPath, this._secureStoreKey, this.baseDir);
8549
8872
  const parsed = parseFrontmatter(raw);
8550
8873
  if (!parsed) return null;
8551
- return rememberRawFrontmatter({
8552
- path: fullPath,
8553
- frontmatter: normalizeFrontmatterForPath(
8554
- parsed.frontmatter,
8555
- toMemoryPathRel(this.baseDir, fullPath),
8556
- parsed.content
8557
- ),
8558
- content: parsed.content
8559
- }, raw);
8874
+ return rememberRawFrontmatter(
8875
+ {
8876
+ path: fullPath,
8877
+ frontmatter: normalizeFrontmatterForPath(
8878
+ parsed.frontmatter,
8879
+ toMemoryPathRel(this.baseDir, fullPath),
8880
+ parsed.content
8881
+ ),
8882
+ content: parsed.content
8883
+ },
8884
+ raw
8885
+ );
8560
8886
  } catch (err) {
8561
8887
  if (err instanceof SecureStoreLockedError) throw err;
8562
8888
  return null;
@@ -8603,7 +8929,7 @@ ${sanitized.text}
8603
8929
  const correctionPaths = [];
8604
8930
  const factPaths = [];
8605
8931
  for (const filePath of filePaths) {
8606
- if (filePath === this.correctionsDir || filePath.startsWith(`${this.correctionsDir}${path8.sep}`)) {
8932
+ if (filePath === this.correctionsDir || filePath.startsWith(`${this.correctionsDir}${path9.sep}`)) {
8607
8933
  correctionPaths.push(filePath);
8608
8934
  } else {
8609
8935
  factPaths.push(filePath);
@@ -8653,7 +8979,7 @@ ${sanitized.text}
8653
8979
  return this.readParsedMemoriesFromPaths(filePaths, 50);
8654
8980
  }
8655
8981
  async readAllColdMemories() {
8656
- return this.memoryReadStore.readAllColdMemories();
8982
+ return this.rememberMemorySnapshots(await this.memoryReadStore.readAllColdMemories());
8657
8983
  }
8658
8984
  /**
8659
8985
  * Read archived memory markdown files under archive/.
@@ -8666,7 +8992,7 @@ ${sanitized.text}
8666
8992
  try {
8667
8993
  const entries = await readdir5(dir, { withFileTypes: true });
8668
8994
  for (const entry of entries) {
8669
- const fullPath = path8.join(dir, entry.name);
8995
+ const fullPath = path9.join(dir, entry.name);
8670
8996
  if (entry.isDirectory()) {
8671
8997
  await readDir(fullPath);
8672
8998
  } else if (entry.name.endsWith(".md")) {
@@ -8674,15 +9000,20 @@ ${sanitized.text}
8674
9000
  const raw = await readMaybeEncryptedFile(fullPath, this._secureStoreKey, this.baseDir);
8675
9001
  const parsed = parseFrontmatter(raw);
8676
9002
  if (parsed) {
8677
- memories.push(rememberRawFrontmatter({
8678
- path: fullPath,
8679
- frontmatter: normalizeFrontmatterForPath(
8680
- parsed.frontmatter,
8681
- toMemoryPathRel(this.baseDir, fullPath),
8682
- parsed.content
8683
- ),
8684
- content: parsed.content
8685
- }, raw));
9003
+ memories.push(
9004
+ rememberRawFrontmatter(
9005
+ {
9006
+ path: fullPath,
9007
+ frontmatter: normalizeFrontmatterForPath(
9008
+ parsed.frontmatter,
9009
+ toMemoryPathRel(this.baseDir, fullPath),
9010
+ parsed.content
9011
+ ),
9012
+ content: parsed.content
9013
+ },
9014
+ raw
9015
+ )
9016
+ );
8686
9017
  }
8687
9018
  } catch (err) {
8688
9019
  if (err instanceof SecureStoreLockedError) throw err;
@@ -8693,13 +9024,13 @@ ${sanitized.text}
8693
9024
  }
8694
9025
  };
8695
9026
  await readDir(root);
8696
- return memories;
9027
+ return this.rememberMemorySnapshots(memories);
8697
9028
  }
8698
9029
  async readMemoryByPath(filePath) {
8699
- return this.memoryReadStore.readMemoryByPath(filePath);
9030
+ return this.rememberMemorySnapshot(await this.memoryReadStore.readMemoryByPath(filePath));
8700
9031
  }
8701
9032
  resolveTierRootDir(tier) {
8702
- return tier === "cold" ? path8.join(this.baseDir, "cold") : this.baseDir;
9033
+ return tier === "cold" ? path9.join(this.baseDir, "cold") : this.baseDir;
8703
9034
  }
8704
9035
  resolveMemoryDateDir(memory) {
8705
9036
  const preferred = memory.frontmatter.created || memory.frontmatter.updated;
@@ -8714,13 +9045,13 @@ ${sanitized.text}
8714
9045
  buildTierMemoryPath(memory, tier) {
8715
9046
  const root = this.resolveTierRootDir(tier);
8716
9047
  if (this.isArtifactMemory(memory)) {
8717
- return path8.join(root, "artifacts", this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
9048
+ return path9.join(root, "artifacts", this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
8718
9049
  }
8719
9050
  if (memory.frontmatter.category === "correction") {
8720
- return path8.join(root, "corrections", `${memory.frontmatter.id}.md`);
9051
+ return path9.join(root, "corrections", `${memory.frontmatter.id}.md`);
8721
9052
  }
8722
9053
  const dir = categoryDirName(memory.frontmatter.category);
8723
- return path8.join(root, dir, this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
9054
+ return path9.join(root, dir, this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
8724
9055
  }
8725
9056
  async writeMemoryFileAtomic(targetPath, memory) {
8726
9057
  const refIdsAtWrite = this.currentHistoricalIds();
@@ -8767,53 +9098,73 @@ ${memory.content}
8767
9098
  this.notifyCatalogWrite();
8768
9099
  }
8769
9100
  async moveMemoryToPath(memory, targetPath) {
8770
- await this.writeMemoryFileAtomic(targetPath, memory);
8771
- const sourcePath = path8.resolve(memory.path);
8772
- const destPath = path8.resolve(targetPath);
8773
- if (sourcePath !== destPath) {
8774
- try {
8775
- await unlink4(memory.path);
8776
- } catch (err) {
8777
- const message = err instanceof Error ? err.message : String(err);
8778
- if (!message.includes("ENOENT")) {
8779
- throw err;
9101
+ const changed = await this.withTombstoneBlockedMemoryPathLock(
9102
+ memory.path,
9103
+ async (current) => {
9104
+ const destination = await this.readMemoryByPath(targetPath);
9105
+ if (current?.frontmatter.id !== memory.frontmatter.id) {
9106
+ if (current === null && destination?.frontmatter.id === memory.frontmatter.id) return false;
9107
+ throw new Error(`memory ${memory.frontmatter.id} changed before its tier move`);
8780
9108
  }
8781
- }
8782
- this.invalidateAllMemoriesCache();
8783
- updateProjectedMemoryPath(this.baseDir, memory.frontmatter.id, toMemoryPathRel(this.baseDir, targetPath));
9109
+ const callerSnapshot = _StorageManager.loadedMemorySnapshots.get(memory);
9110
+ const currentSnapshot = createMemorySnapshot(current);
9111
+ if (callerSnapshot === void 0 ? current.frontmatter.updated !== memory.frontmatter.updated : currentSnapshot !== callerSnapshot) {
9112
+ throw new Error(`memory ${memory.frontmatter.id} changed before its tier move`);
9113
+ }
9114
+ const coordinate = tombstoneBlocked(current.frontmatter) || isQueuedReviewMemory(current) || destination !== null && tombstoneBlocked(destination.frontmatter) || isQueuedReviewMemory(destination);
9115
+ const index = this.getTombstoneBlockedCaptureIndex();
9116
+ const marker = coordinate ? await index.prepareWrite() : void 0;
9117
+ const projectedPath = toMemoryPathRel(this.baseDir, targetPath);
9118
+ let durable = false;
9119
+ try {
9120
+ if (destination?.frontmatter.id === current.frontmatter.id) {
9121
+ await this.deleteManagedStorageFile(current.path);
9122
+ durable = true;
9123
+ this.invalidateAllMemoriesCache();
9124
+ updateProjectedMemoryPath(this.baseDir, current.frontmatter.id, projectedPath);
9125
+ } else {
9126
+ await this.writeMemoryFileAtomic(targetPath, current);
9127
+ if (memory.frontmatter.entityRef !== current.frontmatter.entityRef) {
9128
+ memory.frontmatter.entityRef = current.frontmatter.entityRef;
9129
+ }
9130
+ durable = true;
9131
+ const sourcePath = path9.resolve(current.path);
9132
+ const destPath = path9.resolve(targetPath);
9133
+ if (sourcePath !== destPath) {
9134
+ await this.deleteManagedStorageFile(current.path);
9135
+ this.invalidateAllMemoriesCache();
9136
+ updateProjectedMemoryPath(this.baseDir, current.frontmatter.id, projectedPath);
9137
+ }
9138
+ }
9139
+ if (marker !== void 0) await this.rebuildTombstoneBlockedCaptureAfterInvalidation(marker);
9140
+ } catch (error) {
9141
+ if (marker !== void 0 && !durable) await index.discardWrite(marker).catch(() => index.markUntrusted());
9142
+ if (marker !== void 0 && durable) index.markUntrusted();
9143
+ throw error;
9144
+ }
9145
+ return true;
9146
+ },
9147
+ [targetPath]
9148
+ );
9149
+ if (this.isColdOrArchiveTierPath(memory.path) || this.isColdOrArchiveTierPath(targetPath)) {
9150
+ this.invalidateColdMemoriesCache();
8784
9151
  }
9152
+ return changed;
8785
9153
  }
8786
9154
  async migrateMemoryToTier(memory, targetTier) {
8787
9155
  const targetPath = this.buildTierMemoryPath(memory, targetTier);
8788
- const sourcePath = path8.resolve(memory.path);
8789
- const destPath = path8.resolve(targetPath);
9156
+ const sourcePath = path9.resolve(memory.path);
9157
+ const destPath = path9.resolve(targetPath);
8790
9158
  if (sourcePath === destPath) {
8791
9159
  return { changed: false, targetPath };
8792
9160
  }
8793
- const existing = await this.readMemoryByPath(targetPath);
8794
- if (existing?.frontmatter.id === memory.frontmatter.id) {
8795
- try {
8796
- await unlink4(memory.path);
8797
- } catch (err) {
8798
- const message = err instanceof Error ? err.message : String(err);
8799
- if (!message.includes("ENOENT")) {
8800
- throw err;
8801
- }
8802
- }
8803
- updateProjectedMemoryPath(this.baseDir, memory.frontmatter.id, toMemoryPathRel(this.baseDir, targetPath));
8804
- this.bumpMemoryStatusVersion();
8805
- return { changed: false, targetPath };
8806
- }
8807
- await this.moveMemoryToPath(memory, targetPath);
8808
- this.invalidateAllMemoriesCache();
8809
- if (targetTier === "cold") {
8810
- this.invalidateColdMemoriesCache();
8811
- }
9161
+ const changed = await this.moveMemoryToPath(memory, targetPath);
9162
+ if (!changed) return { changed: false, targetPath };
8812
9163
  this.bumpMemoryStatusVersion();
8813
- return { changed: true, targetPath };
9164
+ return { changed, targetPath };
8814
9165
  }
8815
9166
  get archiveDir() {
8816
- return path8.join(this.baseDir, "archive");
9167
+ return path9.join(this.baseDir, "archive");
8817
9168
  }
8818
9169
  /**
8819
9170
  * Archive a memory by moving it from facts/ to archive/YYYY-MM-DD/.
@@ -8825,7 +9176,7 @@ ${memory.content}
8825
9176
  try {
8826
9177
  const now = lifecycle?.at ?? /* @__PURE__ */ new Date();
8827
9178
  const today = now.toISOString().slice(0, 10);
8828
- const destDir = path8.join(this.archiveDir, today);
9179
+ const destDir = path9.join(this.archiveDir, today);
8829
9180
  await mkdir(destDir, { recursive: true });
8830
9181
  const refIdsAtWrite = this.currentHistoricalIds();
8831
9182
  const updatedFm = canonicalizeEntityRefOption(
@@ -8841,7 +9192,7 @@ ${memory.content}
8841
9192
 
8842
9193
  ${current.content}
8843
9194
  `;
8844
- const destPath = path8.join(destDir, path8.basename(current.path));
9195
+ const destPath = path9.join(destDir, path9.basename(current.path));
8845
9196
  const priorDest = await this.readStorageSecureFile(destPath).catch(() => null);
8846
9197
  await this.writeStorageSecureFile(destPath, fileContent);
8847
9198
  if (typeof current.frontmatter.entityRef === "string") {
@@ -8862,7 +9213,7 @@ ${current.content}
8862
9213
  throw err;
8863
9214
  }
8864
9215
  }
8865
- await unlink4(current.path);
9216
+ if (!await this.deleteManagedStorageFile(current.path)) return null;
8866
9217
  markDurable();
8867
9218
  markProjectedMemoryPathInvalid(this.baseDir, current.frontmatter.id);
8868
9219
  this.invalidateAllMemoriesCache();
@@ -8940,19 +9291,16 @@ ${current.content}
8940
9291
  const memories = await this.readAllMemories();
8941
9292
  const memory = memories.find((candidate) => candidate.frontmatter.id === id);
8942
9293
  if (!memory) return false;
8943
- return await this.runTombstoneBlockedInvalidation(
8944
- memory,
8945
- async (current, rebuildMarker, markDurable) => {
8946
- await unlink4(current.path);
8947
- markDurable();
8948
- markProjectedMemoryPathInvalid(this.baseDir, id);
8949
- this.invalidateAllMemoriesCache();
8950
- await this.rebuildTombstoneBlockedCaptureAfterInvalidation(rebuildMarker);
8951
- this.bumpMemoryStatusVersion();
8952
- log.debug(`invalidated memory ${id}`);
8953
- return true;
8954
- }
8955
- );
9294
+ return await this.runTombstoneBlockedInvalidation(memory, async (current, rebuildMarker, markDurable) => {
9295
+ if (!await this.deleteManagedStorageFile(current.path)) return false;
9296
+ markDurable();
9297
+ markProjectedMemoryPathInvalid(this.baseDir, id);
9298
+ this.invalidateAllMemoriesCache();
9299
+ await this.rebuildTombstoneBlockedCaptureAfterInvalidation(rebuildMarker);
9300
+ this.bumpMemoryStatusVersion();
9301
+ log.debug(`invalidated memory ${id}`);
9302
+ return true;
9303
+ });
8956
9304
  }
8957
9305
  async updateMemory(id, newContent, options) {
8958
9306
  const memories = await this.readAllMemories();
@@ -9028,23 +9376,18 @@ ${memory.content}
9028
9376
  `;
9029
9377
  await this.writeTombstoneBlockedFrontmatter(memory, fileContent, updated, async () => {
9030
9378
  this.invalidateAllMemoriesCache();
9031
- if (memory.path.includes(`${path8.sep}cold${path8.sep}`)) {
9379
+ if (memory.path.includes(`${path9.sep}cold${path9.sep}`)) {
9032
9380
  this.invalidateColdMemoriesCache();
9033
9381
  }
9034
9382
  });
9035
9383
  const rawMergedRef = typeof patch.entityRef === "string" ? patch.entityRef : memory.frontmatter.entityRef;
9036
9384
  if (refIds && typeof rawMergedRef === "string") {
9037
- await this.entityRefRepair.repair(
9038
- memory.path,
9039
- updated,
9040
- rawMergedRef,
9041
- refIds,
9042
- memory.content,
9043
- { onFailRestore: memory }
9044
- );
9385
+ await this.entityRefRepair.repair(memory.path, updated, rawMergedRef, refIds, memory.content, {
9386
+ onFailRestore: memory
9387
+ });
9045
9388
  }
9046
9389
  await this.patchHotMemoriesCache({ addedPath: memory.path });
9047
- if (memory.path.includes(`${path8.sep}cold${path8.sep}`)) {
9390
+ if (memory.path.includes(`${path9.sep}cold${path9.sep}`)) {
9048
9391
  this.invalidateColdMemoriesCache();
9049
9392
  }
9050
9393
  try {
@@ -9114,7 +9457,7 @@ ${memory.content}
9114
9457
  return deleted;
9115
9458
  }
9116
9459
  async loadBuffer() {
9117
- const bufferPath = path8.join(this.stateDir, "buffer.json");
9460
+ const bufferPath = path9.join(this.stateDir, "buffer.json");
9118
9461
  try {
9119
9462
  const raw = await this.readStorageSecureFile(bufferPath);
9120
9463
  return JSON.parse(raw);
@@ -9126,11 +9469,11 @@ ${memory.content}
9126
9469
  }
9127
9470
  async saveBuffer(state) {
9128
9471
  await this.ensureDirectories();
9129
- const bufferPath = path8.join(this.stateDir, "buffer.json");
9472
+ const bufferPath = path9.join(this.stateDir, "buffer.json");
9130
9473
  await this.writeStorageSecureFile(bufferPath, JSON.stringify(state, null, 2));
9131
9474
  }
9132
9475
  async loadMeta() {
9133
- const metaPath = path8.join(this.stateDir, "meta.json");
9476
+ const metaPath = path9.join(this.stateDir, "meta.json");
9134
9477
  try {
9135
9478
  const raw = await this.readStorageSecureFile(metaPath);
9136
9479
  const parsed = JSON.parse(raw);
@@ -9163,7 +9506,7 @@ ${memory.content}
9163
9506
  }
9164
9507
  async saveMeta(state) {
9165
9508
  await this.ensureDirectories();
9166
- const metaPath = path8.join(this.stateDir, "meta.json");
9509
+ const metaPath = path9.join(this.stateDir, "meta.json");
9167
9510
  await this.writeStorageSecureFile(metaPath, JSON.stringify(state, null, 2));
9168
9511
  }
9169
9512
  async appendMemoryActionEvents(events) {
@@ -9227,7 +9570,7 @@ ${memory.content}
9227
9570
  },
9228
9571
  (payload) => this.appendStorageSecureFile(target, payload),
9229
9572
  async () => {
9230
- await mkdir(path8.dirname(target), { recursive: true });
9573
+ await mkdir(path9.dirname(target), { recursive: true });
9231
9574
  }
9232
9575
  );
9233
9576
  }
@@ -9325,7 +9668,7 @@ ${memory.content}
9325
9668
  async appendReextractJobs(events) {
9326
9669
  if (events.length === 0) return 0;
9327
9670
  await this.ensureDirectories();
9328
- const filePath = path8.join(this.stateDir, "reextract-jobs.jsonl");
9671
+ const filePath = path9.join(this.stateDir, "reextract-jobs.jsonl");
9329
9672
  const lines = events.map((event) => JSON.stringify(event)).join("\n") + "\n";
9330
9673
  try {
9331
9674
  await this.appendStorageSecureFile(filePath, lines);
@@ -9338,7 +9681,7 @@ ${memory.content}
9338
9681
  }
9339
9682
  async readReextractJobs(limit = 200) {
9340
9683
  const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.min(1e3, Math.floor(limit))) : 200;
9341
- const filePath = path8.join(this.stateDir, "reextract-jobs.jsonl");
9684
+ const filePath = path9.join(this.stateDir, "reextract-jobs.jsonl");
9342
9685
  try {
9343
9686
  const raw = await this.readStorageSecureFile(filePath);
9344
9687
  const lines = raw.split("\n").filter((line) => line.trim().length > 0);
@@ -9487,7 +9830,7 @@ ${memory.content}
9487
9830
  return false;
9488
9831
  }
9489
9832
  if (draftState.contentHash) {
9490
- const contentHash = createHash5("sha256").update(draftContent).digest("hex");
9833
+ const contentHash = createHash6("sha256").update(draftContent).digest("hex");
9491
9834
  if (contentHash !== draftState.contentHash) return false;
9492
9835
  }
9493
9836
  await this.writeCompressionGuidelines(draftContent);
@@ -9565,7 +9908,7 @@ ${question}
9565
9908
 
9566
9909
  **Context:** ${context}
9567
9910
  `;
9568
- const filePath = path8.join(this.questionsDir, `${id}.md`);
9911
+ const filePath = path9.join(this.questionsDir, `${id}.md`);
9569
9912
  await this.writeStorageSecureFile(filePath, content);
9570
9913
  log.debug(`wrote question ${id} to ${filePath}`);
9571
9914
  this.invalidateQuestionsCache();
@@ -9583,7 +9926,7 @@ ${question}
9583
9926
  if (!match) return null;
9584
9927
  const frontmatterStr = match[1];
9585
9928
  const body = match[2].trim();
9586
- const id = this.extractFrontmatterValue(frontmatterStr, "id") ?? path8.basename(filePath, ".md");
9929
+ const id = this.extractFrontmatterValue(frontmatterStr, "id") ?? path9.basename(filePath, ".md");
9587
9930
  const created = this.extractFrontmatterValue(frontmatterStr, "created") ?? "";
9588
9931
  const priority = parseFloat(this.extractFrontmatterValue(frontmatterStr, "priority") ?? "0.5");
9589
9932
  const resolved = this.extractFrontmatterValue(frontmatterStr, "resolved") === "true";
@@ -9639,11 +9982,11 @@ ${question}
9639
9982
  } catch {
9640
9983
  }
9641
9984
  const hygiene = opts?.hygiene;
9642
- const rotateEnabled = hygiene?.enabled === true && hygiene.rotateEnabled === true && Array.isArray(hygiene.rotatePaths) && hygiene.rotatePaths.includes(path8.basename(identityPath));
9985
+ const rotateEnabled = hygiene?.enabled === true && hygiene.rotateEnabled === true && Array.isArray(hygiene.rotatePaths) && hygiene.rotatePaths.includes(path9.basename(identityPath));
9643
9986
  if (rotateEnabled) {
9644
9987
  const maxBytes = hygiene.rotateMaxBytes;
9645
9988
  if (existing.length > maxBytes) {
9646
- const archiveDir = path8.join(workspaceDir, hygiene.archiveDir);
9989
+ const archiveDir = path9.join(workspaceDir, hygiene.archiveDir);
9647
9990
  const { newContent } = await rotateMarkdownFileToArchive({
9648
9991
  filePath: identityPath,
9649
9992
  archiveDir,
@@ -9903,40 +10246,45 @@ ${reflection}
9903
10246
  if (entries.length === 0) return 0;
9904
10247
  const memories = await this.readAllMemories();
9905
10248
  const memoryMap = new Map(memories.map((m) => [m.frontmatter.id, m]));
9906
- const memoryPathMap = new Map(memories.map((m) => [path8.resolve(m.path), m]));
10249
+ const memoryPathMap = new Map(memories.map((m) => [path9.resolve(m.path), m]));
9907
10250
  let updated = 0;
9908
10251
  const prevVersion = this.getMemoryCorpusVersion();
9909
10252
  const keyId = this.hotCacheKeyId();
9910
10253
  const warm = this.hotMemoriesCacheEnabled && getCachedMemories(this.baseDir, prevVersion, keyId, this.hotCacheTtlMs()) !== null;
9911
10254
  const appliedPatches = /* @__PURE__ */ new Map();
9912
10255
  for (const entry of entries) {
9913
- const memory = entry.memoryPath ? memoryPathMap.get(path8.resolve(entry.memoryPath)) : memoryMap.get(entry.memoryId);
10256
+ const memory = entry.memoryPath ? memoryPathMap.get(path9.resolve(entry.memoryPath)) : memoryMap.get(entry.memoryId);
9914
10257
  if (!memory) continue;
9915
- const rowIds = this.currentHistoricalIds();
9916
- const newFm = canonicalizeEntityRefOption(
9917
- { ...memory.frontmatter, accessCount: entry.newCount, lastAccessed: entry.lastAccessed },
9918
- rowIds
9919
- );
9920
10258
  try {
9921
- const fileContent = `${serializeFrontmatter(newFm)}
10259
+ const applied = await this.withTombstoneBlockedMemoryPathLock(memory.path, async (current) => {
10260
+ if (current?.frontmatter.id !== entry.memoryId) return null;
10261
+ const rowIds = this.currentHistoricalIds();
10262
+ const newFm = canonicalizeEntityRefOption(
10263
+ { ...current.frontmatter, accessCount: entry.newCount, lastAccessed: entry.lastAccessed },
10264
+ rowIds
10265
+ );
10266
+ const fileContent = `${serializeFrontmatter(newFm)}
9922
10267
 
9923
- ${memory.content}
10268
+ ${current.content}
9924
10269
  `;
9925
- await this.writeStorageSecureFile(memory.path, fileContent);
9926
- if (typeof memory.frontmatter.entityRef === "string") {
9927
- await this.entityRefRepair.repair(
9928
- memory.path,
9929
- newFm,
9930
- memory.frontmatter.entityRef,
9931
- rowIds,
9932
- memory.content,
9933
- { onFailRestore: memory }
9934
- );
9935
- }
10270
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, newFm);
10271
+ if (typeof current.frontmatter.entityRef === "string") {
10272
+ await this.entityRefRepair.repair(
10273
+ current.path,
10274
+ newFm,
10275
+ current.frontmatter.entityRef,
10276
+ rowIds,
10277
+ current.content,
10278
+ { onFailRestore: current }
10279
+ );
10280
+ }
10281
+ return { current, newFm };
10282
+ });
10283
+ if (applied === null) continue;
9936
10284
  if (warm) {
9937
- updateCacheOnWrite(this.baseDir, { ...memory, frontmatter: newFm }, keyId);
10285
+ updateCacheOnWrite(this.baseDir, { ...applied.current, frontmatter: applied.newFm }, keyId);
9938
10286
  }
9939
- appliedPatches.set(path8.resolve(memory.path), {
10287
+ appliedPatches.set(path9.resolve(memory.path), {
9940
10288
  accessCount: entry.newCount,
9941
10289
  lastAccessed: entry.lastAccessed
9942
10290
  });
@@ -9952,7 +10300,7 @@ ${memory.content}
9952
10300
  const cur = getCachedMemories(this.baseDir, prevVersion, keyId);
9953
10301
  if (cur) {
9954
10302
  const reapplied = cur.map((m) => {
9955
- const patch = appliedPatches.get(path8.resolve(m.path));
10303
+ const patch = appliedPatches.get(path9.resolve(m.path));
9956
10304
  return patch ? {
9957
10305
  ...m,
9958
10306
  frontmatter: { ...m.frontmatter, accessCount: patch.accessCount, lastAccessed: patch.lastAccessed }
@@ -9987,7 +10335,7 @@ ${memory.content}
9987
10335
  const pathsById = /* @__PURE__ */ new Map();
9988
10336
  const filePathsById = /* @__PURE__ */ new Map();
9989
10337
  for (const filePath of filePaths) {
9990
- const memoryId = path8.basename(filePath, ".md");
10338
+ const memoryId = path9.basename(filePath, ".md");
9991
10339
  if (!wantedIds.has(memoryId)) continue;
9992
10340
  const paths = filePathsById.get(memoryId) ?? [];
9993
10341
  paths.push(filePath);
@@ -9999,7 +10347,7 @@ ${memory.content}
9999
10347
  const preferredMatches = [];
10000
10348
  for (const preferredPath of preferred) {
10001
10349
  const directCandidates = new Set(qmdResultPathCandidates(this.baseDir, preferredPath));
10002
- const directMatch = existingPaths.find((filePath) => directCandidates.has(path8.resolve(filePath)));
10350
+ const directMatch = existingPaths.find((filePath) => directCandidates.has(path9.resolve(filePath)));
10003
10351
  if (directMatch) {
10004
10352
  preferredMatches.push(directMatch);
10005
10353
  continue;
@@ -10011,7 +10359,7 @@ ${memory.content}
10011
10359
  candidates.add(candidate);
10012
10360
  }
10013
10361
  }
10014
- const match = existingPaths.find((filePath) => candidates.has(path8.resolve(filePath)));
10362
+ const match = existingPaths.find((filePath) => candidates.has(path9.resolve(filePath)));
10015
10363
  if (match) preferredMatches.push(match);
10016
10364
  }
10017
10365
  if (preferredMatches.length > 0) {
@@ -10102,6 +10450,10 @@ ${memory.content}
10102
10450
  const validAt = normalizeMemoryWriteTimestamp("validAt", options.validAt);
10103
10451
  const chunkInvalidAt = normalizeMemoryWriteTimestamp("invalidAt", options.invalidAt);
10104
10452
  const chunkObservedAt = normalizeMemoryWriteTimestamp("observedAt", options.observedAt);
10453
+ const sanitized = sanitizeMemoryContent(content);
10454
+ if (!sanitized.clean) {
10455
+ log.warn(`chunk content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
10456
+ }
10105
10457
  const fm = {
10106
10458
  id,
10107
10459
  category,
@@ -10129,44 +10481,34 @@ ${memory.content}
10129
10481
  ...options.faithfulness ? { faithfulness: options.faithfulness } : {},
10130
10482
  ...options.sources ? { sources: options.sources } : {},
10131
10483
  ...options.provenance ? { provenance: options.provenance } : {},
10132
- ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {}
10484
+ ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {},
10485
+ ...options.toolScoped || withholdToolScopedFromSharedNamespace({
10486
+ content: sanitized.text,
10487
+ sourceConnector: options.sourceConnector
10488
+ }) ? { toolScoped: true } : {}
10133
10489
  };
10134
- const sanitized = sanitizeMemoryContent(content);
10135
- if (!sanitized.clean) {
10136
- log.warn(`chunk content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
10137
- }
10138
10490
  const filePath = await this.resolveCategoryWritePath(category, id, today);
10139
10491
  const fileContent = `${serializeFrontmatter(fm)}
10140
10492
 
10141
10493
  ${sanitized.text}
10142
10494
  `;
10143
- let priorChunk = null;
10144
- try {
10145
- const priorRaw = await readMaybeEncryptedFile(filePath, this._secureStoreKey, this.baseDir);
10146
- const parsedPrior = parseFrontmatter(priorRaw);
10147
- if (parsedPrior) {
10148
- priorChunk = { path: filePath, frontmatter: parsedPrior.frontmatter, content: parsedPrior.content };
10149
- }
10150
- } catch {
10151
- priorChunk = null;
10152
- }
10153
10495
  const written = await this.writeTombstoneBlockedChunk(
10154
10496
  filePath,
10155
10497
  fileContent,
10156
10498
  fm,
10157
10499
  sanitized.text,
10158
10500
  () => this.findExistingTombstoneBlockedMemory(sanitized.text, category, fm.sourceConnector),
10159
- async () => {
10501
+ async (priorChunk) => {
10502
+ if (refIds && typeof rawEntityRef === "string") {
10503
+ await this.entityRefRepair.repair(filePath, fm, rawEntityRef, refIds, sanitized.text, {
10504
+ regateFact: true,
10505
+ ...priorChunk ? { onFailRestore: priorChunk } : { onFailRemove: filePath }
10506
+ });
10507
+ }
10160
10508
  await this.patchHotMemoriesCache({ addedPath: filePath }, "memory-create");
10161
10509
  log.debug(`wrote chunk ${id} (${chunkIndex + 1}/${chunkTotal}) to ${filePath}`);
10162
10510
  }
10163
10511
  );
10164
- if (written === id && refIds && typeof rawEntityRef === "string") {
10165
- await this.entityRefRepair.repair(filePath, fm, rawEntityRef, refIds, sanitized.text, {
10166
- regateFact: true,
10167
- ...priorChunk ? { onFailRestore: priorChunk } : { onFailRemove: filePath }
10168
- });
10169
- }
10170
10512
  return written;
10171
10513
  }
10172
10514
  /**
@@ -10189,27 +10531,35 @@ ${sanitized.text}
10189
10531
  const oldMemory = memories.find((m) => m.frontmatter.id === oldMemoryId);
10190
10532
  if (!oldMemory) return false;
10191
10533
  const now = (/* @__PURE__ */ new Date()).toISOString();
10192
- const refIdsAtWrite = this.currentHistoricalIds();
10193
- const updatedFm = canonicalizeEntityRefOption(
10194
- { ...oldMemory.frontmatter, status: "superseded", supersededBy: newMemoryId, supersededAt: now, updated: now },
10195
- refIdsAtWrite
10196
- );
10197
- const fileContent = `${serializeFrontmatter(updatedFm)}
10198
-
10199
- ${oldMemory.content}
10200
- `;
10534
+ let currentBefore = oldMemory;
10535
+ let updatedFm = oldMemory.frontmatter;
10201
10536
  try {
10202
- await this.writeStorageSecureFile(oldMemory.path, fileContent);
10203
- if (typeof oldMemory.frontmatter.entityRef === "string") {
10204
- await this.entityRefRepair.repair(
10205
- oldMemory.path,
10206
- updatedFm,
10207
- oldMemory.frontmatter.entityRef,
10208
- refIdsAtWrite,
10209
- oldMemory.content,
10210
- { onFailRestore: oldMemory }
10537
+ const written = await this.withTombstoneBlockedMemoryPathLock(oldMemory.path, async (current) => {
10538
+ if (current?.frontmatter.id !== oldMemoryId) return false;
10539
+ currentBefore = current;
10540
+ const refIdsAtWrite = this.currentHistoricalIds();
10541
+ updatedFm = canonicalizeEntityRefOption(
10542
+ { ...current.frontmatter, status: "superseded", supersededBy: newMemoryId, supersededAt: now, updated: now },
10543
+ refIdsAtWrite
10211
10544
  );
10212
- }
10545
+ const fileContent = `${serializeFrontmatter(updatedFm)}
10546
+
10547
+ ${current.content}
10548
+ `;
10549
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, updatedFm);
10550
+ if (typeof current.frontmatter.entityRef === "string") {
10551
+ await this.entityRefRepair.repair(
10552
+ current.path,
10553
+ updatedFm,
10554
+ current.frontmatter.entityRef,
10555
+ refIdsAtWrite,
10556
+ current.content,
10557
+ { onFailRestore: current }
10558
+ );
10559
+ }
10560
+ return true;
10561
+ });
10562
+ if (!written) return false;
10213
10563
  this.bumpMemoryCorpusVersion();
10214
10564
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.supersedeMemory", {
10215
10565
  memoryId: oldMemoryId,
@@ -10217,20 +10567,20 @@ ${oldMemory.content}
10217
10567
  timestamp: now,
10218
10568
  actor: "storage.supersedeMemory",
10219
10569
  reasonCode: reason,
10220
- before: this.summarizeLifecycleState(oldMemory.frontmatter, oldMemory.path),
10221
- after: this.summarizeLifecycleState(updatedFm, oldMemory.path),
10570
+ before: this.summarizeLifecycleState(currentBefore.frontmatter, currentBefore.path),
10571
+ after: this.summarizeLifecycleState(updatedFm, currentBefore.path),
10222
10572
  relatedMemoryIds: [newMemoryId]
10223
10573
  });
10224
10574
  this.bumpMemoryStatusVersion();
10225
10575
  log.debug(`superseded memory ${oldMemoryId} by ${newMemoryId}: ${reason}`);
10226
- if (oldMemory.frontmatter.category === "fact") {
10576
+ if (currentBefore.frontmatter.category === "fact") {
10227
10577
  for (const input of buildRetiredFactTombstoneInputs(
10228
10578
  {
10229
10579
  id: oldMemoryId,
10230
- content: stripCitationForTemplate(oldMemory.content, this.citationTemplate),
10231
- contentHash: oldMemory.frontmatter.contentHash,
10580
+ content: stripCitationForTemplate(currentBefore.content, this.citationTemplate),
10581
+ contentHash: currentBefore.frontmatter.contentHash,
10232
10582
  entityRef: updatedFm.entityRef,
10233
- structuredAttributes: oldMemory.frontmatter.structuredAttributes
10583
+ structuredAttributes: currentBefore.frontmatter.structuredAttributes
10234
10584
  },
10235
10585
  {
10236
10586
  reason: "contradiction_resolution",
@@ -10242,7 +10592,7 @@ ${oldMemory.content}
10242
10592
  await this.appendTombstone(input);
10243
10593
  }
10244
10594
  }
10245
- const auditBody = `Superseded: ${oldMemory.content}
10595
+ const auditBody = `Superseded: ${currentBefore.content}
10246
10596
 
10247
10597
  Reason: ${reason}`;
10248
10598
  const auditInput = {
@@ -10263,14 +10613,14 @@ Reason: ${reason}`;
10263
10613
  // Memory Summarization (Phase 4A)
10264
10614
  // ---------------------------------------------------------------------------
10265
10615
  get summariesDir() {
10266
- return path8.join(this.baseDir, "summaries");
10616
+ return path9.join(this.baseDir, "summaries");
10267
10617
  }
10268
10618
  /**
10269
10619
  * Write a memory summary.
10270
10620
  */
10271
10621
  async writeSummary(summary) {
10272
10622
  await mkdir(this.summariesDir, { recursive: true });
10273
- const filePath = path8.join(this.summariesDir, `${summary.id}.json`);
10623
+ const filePath = path9.join(this.summariesDir, `${summary.id}.json`);
10274
10624
  await this.writeStorageSecureFile(filePath, JSON.stringify(summary, null, 2));
10275
10625
  log.debug(`wrote summary ${summary.id}`);
10276
10626
  }
@@ -10283,7 +10633,7 @@ Reason: ${reason}`;
10283
10633
  const summaries = [];
10284
10634
  for (const file of files) {
10285
10635
  if (!file.endsWith(".json")) continue;
10286
- const filePath = path8.join(this.summariesDir, file);
10636
+ const filePath = path9.join(this.summariesDir, file);
10287
10637
  const raw = await this.readStorageSecureFile(filePath);
10288
10638
  summaries.push(JSON.parse(raw));
10289
10639
  }
@@ -10305,27 +10655,35 @@ Reason: ${reason}`;
10305
10655
  const memory = memoryMap.get(id);
10306
10656
  if (!memory) continue;
10307
10657
  const now = (/* @__PURE__ */ new Date()).toISOString();
10308
- const rowIds = this.currentHistoricalIds();
10309
- const updatedFm = canonicalizeEntityRefOption(
10310
- { ...memory.frontmatter, status: "archived", archivedAt: now, updated: now },
10311
- rowIds
10312
- );
10658
+ let currentBefore = memory;
10659
+ let updatedFm = memory.frontmatter;
10313
10660
  try {
10314
- const fileContent = `${serializeFrontmatter(updatedFm)}
10661
+ const written = await this.withTombstoneBlockedMemoryPathLock(memory.path, async (current) => {
10662
+ if (current?.frontmatter.id !== id) return false;
10663
+ currentBefore = current;
10664
+ const rowIds = this.currentHistoricalIds();
10665
+ updatedFm = canonicalizeEntityRefOption(
10666
+ { ...current.frontmatter, status: "archived", archivedAt: now, updated: now },
10667
+ rowIds
10668
+ );
10669
+ const fileContent = `${serializeFrontmatter(updatedFm)}
10315
10670
 
10316
- ${memory.content}
10671
+ ${current.content}
10317
10672
  `;
10318
- await this.writeStorageSecureFile(memory.path, fileContent);
10319
- if (typeof memory.frontmatter.entityRef === "string") {
10320
- await this.entityRefRepair.repair(
10321
- memory.path,
10322
- updatedFm,
10323
- memory.frontmatter.entityRef,
10324
- rowIds,
10325
- memory.content,
10326
- { onFailRestore: memory }
10327
- );
10328
- }
10673
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, updatedFm);
10674
+ if (typeof current.frontmatter.entityRef === "string") {
10675
+ await this.entityRefRepair.repair(
10676
+ current.path,
10677
+ updatedFm,
10678
+ current.frontmatter.entityRef,
10679
+ rowIds,
10680
+ current.content,
10681
+ { onFailRestore: current }
10682
+ );
10683
+ }
10684
+ return true;
10685
+ });
10686
+ if (!written) continue;
10329
10687
  this.bumpMemoryCorpusVersion();
10330
10688
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.archiveMemories", {
10331
10689
  memoryId: id,
@@ -10333,8 +10691,8 @@ ${memory.content}
10333
10691
  timestamp: updatedFm.archivedAt ?? updatedFm.updated,
10334
10692
  actor: "storage.archiveMemories",
10335
10693
  reasonCode: `summary:${summaryId}`,
10336
- before: this.summarizeLifecycleState(memory.frontmatter, memory.path),
10337
- after: this.summarizeLifecycleState(updatedFm, memory.path),
10694
+ before: this.summarizeLifecycleState(currentBefore.frontmatter, currentBefore.path),
10695
+ after: this.summarizeLifecycleState(updatedFm, currentBefore.path),
10338
10696
  relatedMemoryIds: [summaryId]
10339
10697
  });
10340
10698
  archived++;
@@ -10354,7 +10712,7 @@ ${memory.content}
10354
10712
  * Save topic scores to meta.json.
10355
10713
  */
10356
10714
  async saveTopics(topics) {
10357
- const metaPath = path8.join(this.stateDir, "topics.json");
10715
+ const metaPath = path9.join(this.stateDir, "topics.json");
10358
10716
  await mkdir(this.stateDir, { recursive: true });
10359
10717
  await this.writeStorageSecureFile(
10360
10718
  metaPath,
@@ -10366,7 +10724,7 @@ ${memory.content}
10366
10724
  * Load topic scores from meta.json.
10367
10725
  */
10368
10726
  async loadTopics() {
10369
- const metaPath = path8.join(this.stateDir, "topics.json");
10727
+ const metaPath = path9.join(this.stateDir, "topics.json");
10370
10728
  try {
10371
10729
  const raw = await this.readStorageSecureFile(metaPath);
10372
10730
  return JSON.parse(raw);
@@ -10484,4 +10842,4 @@ export {
10484
10842
  isValidBufferSurpriseEvent,
10485
10843
  StorageManager3 as StorageManager
10486
10844
  };
10487
- //# sourceMappingURL=chunk-E6PNLPGJ.js.map
10845
+ //# sourceMappingURL=chunk-FUCYDRE5.js.map