@remnic/core 9.45.3 → 9.45.4

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 (747) 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 -76
  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 -77
  8. package/dist/access-boundary.d.ts +15 -11
  9. package/dist/access-boundary.js +84 -76
  10. package/dist/access-citation-namespace.js +2 -2
  11. package/dist/access-cli.js +193 -181
  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 -76
  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 -76
  27. package/dist/access-http.d.ts +15 -10
  28. package/dist/access-http.js +105 -92
  29. package/dist/access-identity-continuity-surface.d.ts +9 -8
  30. package/dist/access-identity-continuity-surface.js +84 -76
  31. package/dist/access-lcm-surface.d.ts +14 -10
  32. package/dist/access-lcm-surface.js +84 -76
  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 -83
  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 -76
  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 -76
  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 -78
  48. package/dist/access-operations.d.ts +15 -11
  49. package/dist/access-operations.js +91 -80
  50. package/dist/access-recall-concurrency.d.ts +16 -26
  51. package/dist/access-recall-concurrency.js +86 -77
  52. package/dist/access-recall-response.d.ts +18 -14
  53. package/dist/access-recall-response.js +84 -76
  54. package/dist/access-recall-surface.d.ts +29 -24
  55. package/dist/access-recall-surface.js +84 -76
  56. package/dist/access-schema.js +3 -3
  57. package/dist/{access-service-CiJRsgAB.d.ts → access-service-CsU-ljFD.d.ts} +25 -16
  58. package/dist/access-service-helpers.d.ts +14 -10
  59. package/dist/access-service.d.ts +14 -10
  60. package/dist/access-service.js +84 -76
  61. package/dist/access-surface-catalog.d.ts +14 -10
  62. package/dist/access-surface-catalog.js +4 -0
  63. package/dist/access-surface-catalog.js.map +1 -1
  64. package/dist/access-wearables-meetings-surface.d.ts +4 -3
  65. package/dist/action-confidence.d.ts +2 -1
  66. package/dist/active-memory-bridge.d.ts +2 -1
  67. package/dist/active-recall.d.ts +2 -1
  68. package/dist/active-recall.js +10 -8
  69. package/dist/active-recall.js.map +1 -1
  70. package/dist/adapters/index.js +7 -7
  71. package/dist/adapters/registry.js +3 -3
  72. package/dist/{auto-sync-5OE5QOZB.js → auto-sync-UPTUVE4X.js} +6 -6
  73. package/dist/behavior-learner.d.ts +2 -1
  74. package/dist/behavior-learner.js +1 -1
  75. package/dist/behavior-signals.d.ts +2 -1
  76. package/dist/bootstrap.d.ts +9 -8
  77. package/dist/briefing.d.ts +3 -2
  78. package/dist/briefing.js +23 -22
  79. package/dist/buffer-surprise-report.d.ts +2 -1
  80. package/dist/buffer-turn-helpers.d.ts +2 -1
  81. package/dist/buffer.d.ts +3 -2
  82. package/dist/buffer.js +12 -11
  83. package/dist/bulk-import/index.d.ts +4 -3
  84. package/dist/calibration.d.ts +2 -1
  85. package/dist/capabilities.d.ts +2 -1
  86. package/dist/{capsule-merge-IDWJPCWK.js → capsule-merge-Q6AR3XL7.js} +67 -54
  87. package/dist/capsule-merge-Q6AR3XL7.js.map +1 -0
  88. package/dist/{catalog-scBmy0sO.d.ts → catalog-bctMURhN.d.ts} +1 -1
  89. package/dist/causal-behavior.d.ts +2 -1
  90. package/dist/causal-behavior.js +2 -2
  91. package/dist/causal-chain.js +2 -2
  92. package/dist/causal-consolidation.d.ts +2 -1
  93. package/dist/causal-consolidation.js +27 -26
  94. package/dist/causal-consolidation.js.map +1 -1
  95. package/dist/causal-retrieval.js +2 -2
  96. package/dist/causal-trajectory-graph.d.ts +2 -1
  97. package/dist/causal-trajectory.js +1 -1
  98. package/dist/{chunk-VUPTKTDV.js → chunk-2MRHJNWL.js} +3 -3
  99. package/dist/{chunk-JBPKEARU.js → chunk-2QSZNTDO.js} +7 -7
  100. package/dist/{chunk-5IVLTFOV.js → chunk-44N6ESJ4.js} +2 -2
  101. package/dist/{chunk-WOCNN776.js → chunk-4POAMKV6.js} +100 -41
  102. package/dist/chunk-4POAMKV6.js.map +1 -0
  103. package/dist/{chunk-HO3QBJEY.js → chunk-5546W5SI.js} +2 -2
  104. package/dist/{chunk-U7GW7NE7.js → chunk-5CEECY6P.js} +10 -10
  105. package/dist/{chunk-4UH4BTGK.js → chunk-5SNZSWWR.js} +82 -82
  106. package/dist/{chunk-6CZPDBJS.js → chunk-5U7ID3EZ.js} +3 -3
  107. package/dist/{chunk-GF22HWS2.js → chunk-6NNNURLK.js} +7 -7
  108. package/dist/chunk-773TRRGT.js +36 -0
  109. package/dist/chunk-773TRRGT.js.map +1 -0
  110. package/dist/chunk-7CITSYSH.js +242 -0
  111. package/dist/chunk-7CITSYSH.js.map +1 -0
  112. package/dist/{chunk-227UFSEQ.js → chunk-7RZJWZ46.js} +5 -5
  113. package/dist/{chunk-E5UK4VPE.js → chunk-7SHJHPTY.js} +5 -5
  114. package/dist/{chunk-UVIKWC7M.js → chunk-7YERSTN7.js} +17 -17
  115. package/dist/{chunk-DLVPUX7U.js → chunk-7YKVM5H3.js} +8 -6
  116. package/dist/chunk-7YKVM5H3.js.map +1 -0
  117. package/dist/{chunk-3CE77VAP.js → chunk-A4JMGKCD.js} +87 -74
  118. package/dist/chunk-A4JMGKCD.js.map +1 -0
  119. package/dist/chunk-A5KNZSNA.js +26 -0
  120. package/dist/chunk-A5KNZSNA.js.map +1 -0
  121. package/dist/{chunk-S2NCTZGJ.js → chunk-AJQ57VV3.js} +15 -15
  122. package/dist/chunk-AJQ57VV3.js.map +1 -0
  123. package/dist/{chunk-CUM2BBPN.js → chunk-AUMWZSE7.js} +19 -10
  124. package/dist/chunk-AUMWZSE7.js.map +1 -0
  125. package/dist/{chunk-XYTOI63Z.js → chunk-BGHFOD5A.js} +19 -11
  126. package/dist/chunk-BGHFOD5A.js.map +1 -0
  127. package/dist/{chunk-BUE5E2HL.js → chunk-BGLY7EEM.js} +5 -314
  128. package/dist/chunk-BGLY7EEM.js.map +1 -0
  129. package/dist/chunk-BIPBQQFI.js +44 -0
  130. package/dist/chunk-BIPBQQFI.js.map +1 -0
  131. package/dist/{chunk-S5SLVSVY.js → chunk-BQIFZ2MP.js} +5 -5
  132. package/dist/chunk-BTTPKDIL.js +34 -0
  133. package/dist/{chunk-PVGDJXVK.js.map → chunk-BTTPKDIL.js.map} +1 -1
  134. package/dist/{chunk-E53DSZEN.js → chunk-C26TE27X.js} +3 -3
  135. package/dist/{chunk-LZ4LDKHZ.js → chunk-CLB32OHM.js} +6 -6
  136. package/dist/{chunk-Q6IP2ARR.js → chunk-CSOYVTRX.js} +2 -2
  137. package/dist/{chunk-XOQSEF7X.js → chunk-CVILPI77.js} +6 -6
  138. package/dist/chunk-D3I2MCN7.js +29 -0
  139. package/dist/chunk-D3I2MCN7.js.map +1 -0
  140. package/dist/{chunk-A5OJCXZL.js → chunk-DSUAAZZX.js} +15 -4
  141. package/dist/chunk-DSUAAZZX.js.map +1 -0
  142. package/dist/{chunk-HREE4JHI.js → chunk-DYVMXPCF.js} +486 -287
  143. package/dist/chunk-DYVMXPCF.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-PDLBLTOK.js → chunk-EITZHSX6.js} +9 -9
  147. package/dist/{chunk-D3J5SLQK.js → chunk-EJHEWCGQ.js} +81 -20
  148. package/dist/chunk-EJHEWCGQ.js.map +1 -0
  149. package/dist/{chunk-WUNIWKY4.js → chunk-ELIL2A37.js} +6 -6
  150. package/dist/{chunk-E6PNLPGJ.js → chunk-FZP32336.js} +806 -470
  151. package/dist/chunk-FZP32336.js.map +1 -0
  152. package/dist/{chunk-HZFHQ4AQ.js → chunk-G7A5HLUS.js} +23 -17
  153. package/dist/chunk-G7A5HLUS.js.map +1 -0
  154. package/dist/{chunk-CINZGPSJ.js → chunk-GUMZC2BO.js} +2 -2
  155. package/dist/{chunk-H24WNPA2.js → chunk-GWFSVJ4P.js} +3 -3
  156. package/dist/{chunk-7XC2HX75.js → chunk-GYPQL6XN.js} +157 -16
  157. package/dist/chunk-GYPQL6XN.js.map +1 -0
  158. package/dist/{chunk-TSH56VPU.js → chunk-HAYSYUAB.js} +2 -2
  159. package/dist/{chunk-TDHTVMPG.js → chunk-HFPASSFV.js} +7 -2
  160. package/dist/chunk-HFPASSFV.js.map +1 -0
  161. package/dist/chunk-J2WC5LF4.js +395 -0
  162. package/dist/chunk-J2WC5LF4.js.map +1 -0
  163. package/dist/{chunk-PKNLM44P.js → chunk-JH6BPLOP.js} +9 -9
  164. package/dist/{chunk-KXB4VXHY.js → chunk-JIYDRBVZ.js} +2 -2
  165. package/dist/chunk-JV3C2MNQ.js +74 -0
  166. package/dist/chunk-JV3C2MNQ.js.map +1 -0
  167. package/dist/{chunk-AV5ZEH4M.js → chunk-KVJRXN2E.js} +2 -2
  168. package/dist/{chunk-JVLCVFQ4.js → chunk-KXEFRMCF.js} +3 -3
  169. package/dist/{chunk-WFTIGIIS.js → chunk-L6CQ7WIW.js} +5 -5
  170. package/dist/{chunk-EJUEXZHX.js → chunk-LLJMAULE.js} +2 -2
  171. package/dist/{chunk-N5Z4EVOR.js → chunk-LNEWDF2A.js} +36 -11
  172. package/dist/chunk-LNEWDF2A.js.map +1 -0
  173. package/dist/{chunk-AS7YMSL6.js → chunk-M23RF3LJ.js} +4 -4
  174. package/dist/{chunk-UYLMNVY6.js → chunk-MDISBSYA.js} +16 -9
  175. package/dist/chunk-MDISBSYA.js.map +1 -0
  176. package/dist/{chunk-3F2LKUMU.js → chunk-NIS256NW.js} +2 -2
  177. package/dist/{chunk-YIAA2X3D.js → chunk-NK5RGJ65.js} +3 -3
  178. package/dist/chunk-NLDVVWCL.js +84 -0
  179. package/dist/chunk-NLDVVWCL.js.map +1 -0
  180. package/dist/{chunk-OQ5PRDDS.js → chunk-NTOIP2E6.js} +6 -6
  181. package/dist/{chunk-HLPD7B7P.js → chunk-NUEQKLNB.js} +2 -2
  182. package/dist/{chunk-4J7G5SY4.js → chunk-NZBZ7IS2.js} +72 -24
  183. package/dist/chunk-NZBZ7IS2.js.map +1 -0
  184. package/dist/{chunk-3TBLDMJA.js → chunk-O4KMGRXE.js} +5 -2
  185. package/dist/chunk-O4KMGRXE.js.map +1 -0
  186. package/dist/{chunk-33PLLLL7.js → chunk-P7NGM24P.js} +6 -6
  187. package/dist/{chunk-7TWUCYER.js → chunk-PNRA7FAD.js} +7 -7
  188. package/dist/{chunk-5I4M26Q7.js → chunk-QBSFOKY6.js} +4 -4
  189. package/dist/{chunk-QJAQNXWI.js → chunk-QCECHYZL.js} +76 -79
  190. package/dist/chunk-QCECHYZL.js.map +1 -0
  191. package/dist/{chunk-P4DRWEYC.js → chunk-QVSBTCVP.js} +2 -2
  192. package/dist/{chunk-AAIUERNB.js → chunk-R5RFK3CB.js} +6 -6
  193. package/dist/{chunk-WDISJRMG.js → chunk-RMMVQQA6.js} +2 -2
  194. package/dist/{chunk-KWMXR7XS.js → chunk-S2V7RUCL.js} +8 -1
  195. package/dist/{chunk-KWMXR7XS.js.map → chunk-S2V7RUCL.js.map} +1 -1
  196. package/dist/{chunk-5SM35XZR.js → chunk-S5NZBKKQ.js} +2 -2
  197. package/dist/{chunk-VNA7W7QF.js → chunk-SVH57F5Z.js} +12 -4
  198. package/dist/chunk-SVH57F5Z.js.map +1 -0
  199. package/dist/{chunk-WIPEXG6R.js → chunk-SXIMQLGV.js} +2 -2
  200. package/dist/{chunk-RVLJEII5.js → chunk-SYUBB3WM.js} +256 -187
  201. package/dist/chunk-SYUBB3WM.js.map +1 -0
  202. package/dist/{chunk-OAEQLRCY.js → chunk-TN76AKO3.js} +5 -5
  203. package/dist/{chunk-QN25OCUF.js → chunk-TQ4GD737.js} +5 -5
  204. package/dist/{chunk-VCD4PSK2.js → chunk-TQZ4DVBC.js} +7 -4
  205. package/dist/chunk-TQZ4DVBC.js.map +1 -0
  206. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  207. package/dist/{chunk-DNWXFTLD.js → chunk-TYISDI6B.js} +2 -2
  208. package/dist/{chunk-4LMA77JH.js → chunk-U2VLVBBH.js} +3 -3
  209. package/dist/{chunk-5ZE7QHTK.js → chunk-ULVR5KG7.js} +5 -5
  210. package/dist/{chunk-NVRYW264.js → chunk-UQWIKLQK.js} +18 -15
  211. package/dist/chunk-UQWIKLQK.js.map +1 -0
  212. package/dist/{chunk-YV32N67O.js → chunk-URS5GSM7.js} +1 -1
  213. package/dist/chunk-URS5GSM7.js.map +1 -0
  214. package/dist/{chunk-4B77XSG5.js → chunk-UV72DEZD.js} +5 -5
  215. package/dist/{chunk-S2BBISHU.js → chunk-VANZKHTN.js} +3 -3
  216. package/dist/chunk-VHFXP27N.js +250 -0
  217. package/dist/chunk-VHFXP27N.js.map +1 -0
  218. package/dist/{chunk-3Y224NYC.js → chunk-VYISFWVX.js} +2 -2
  219. package/dist/{chunk-TIHMZFIV.js → chunk-W3IC7QOY.js} +3 -3
  220. package/dist/{chunk-NRV4Y3PM.js → chunk-W4FBGYGK.js} +1 -1
  221. package/dist/{chunk-P2BM76KT.js → chunk-WAS4HV46.js} +174 -43
  222. package/dist/chunk-WAS4HV46.js.map +1 -0
  223. package/dist/{chunk-57QKLRBV.js → chunk-WB7JSQCP.js} +2 -1
  224. package/dist/chunk-WB7JSQCP.js.map +1 -0
  225. package/dist/chunk-WGP57SR3.js +68 -0
  226. package/dist/chunk-WGP57SR3.js.map +1 -0
  227. package/dist/{chunk-ECK75GDJ.js → chunk-WQIHRA5F.js} +43 -24
  228. package/dist/chunk-WQIHRA5F.js.map +1 -0
  229. package/dist/{chunk-MU7ZHSZE.js → chunk-WZFAPHIK.js} +2 -2
  230. package/dist/{chunk-T2TTP3KU.js → chunk-X4IDNPOS.js} +2 -2
  231. package/dist/{chunk-BLAKS3CP.js → chunk-XL3TATMJ.js} +3 -3
  232. package/dist/{chunk-W4XJFLAL.js → chunk-XPRJSHNI.js} +2 -2
  233. package/dist/{chunk-5TFP4CUL.js → chunk-XQ3HXAQH.js} +14 -11
  234. package/dist/chunk-XQ3HXAQH.js.map +1 -0
  235. package/dist/{chunk-VWAXN2BN.js → chunk-XSFHWBQO.js} +93 -31
  236. package/dist/chunk-XSFHWBQO.js.map +1 -0
  237. package/dist/{chunk-DL7ZD3JH.js → chunk-XTAUXTDO.js} +14 -9
  238. package/dist/chunk-XTAUXTDO.js.map +1 -0
  239. package/dist/{chunk-JE7EK33X.js → chunk-Y7HRYCNW.js} +2 -2
  240. package/dist/{chunk-E6EE5B67.js → chunk-YK6BDDHP.js} +4 -4
  241. package/dist/{chunk-ES36HTSC.js → chunk-YLHM5BQQ.js} +3 -3
  242. package/dist/{chunk-RN7DY3FC.js → chunk-YMAQDHQM.js} +31 -12
  243. package/dist/chunk-YMAQDHQM.js.map +1 -0
  244. package/dist/{chunk-ULARSG5Z.js → chunk-YN6ASZUG.js} +10 -8
  245. package/dist/{chunk-ULARSG5Z.js.map → chunk-YN6ASZUG.js.map} +1 -1
  246. package/dist/{chunk-IKKWIPYN.js → chunk-YYQAKIDJ.js} +37 -1
  247. package/dist/chunk-YYQAKIDJ.js.map +1 -0
  248. package/dist/{chunk-BJKPPZ6Z.js → chunk-ZFGZ6PZ2.js} +2 -2
  249. package/dist/{chunk-CJ2ZR7UA.js → chunk-ZI32MKDW.js} +267 -214
  250. package/dist/chunk-ZI32MKDW.js.map +1 -0
  251. package/dist/{chunk-64UDOIMI.js → chunk-ZLQ37WJX.js} +2 -2
  252. package/dist/chunk-ZMAYKGPN.js +351 -0
  253. package/dist/chunk-ZMAYKGPN.js.map +1 -0
  254. package/dist/{cli-BUGN3d6_.d.ts → cli-BBHDtG36.d.ts} +5 -5
  255. package/dist/cli.d.ts +16 -12
  256. package/dist/cli.js +138 -124
  257. package/dist/compounding/engine.d.ts +3 -2
  258. package/dist/compounding/engine.js +24 -23
  259. package/dist/compounding/preference-consolidator.d.ts +2 -1
  260. package/dist/compression-optimizer.d.ts +2 -1
  261. package/dist/config.d.ts +2 -1
  262. package/dist/config.js +10 -8
  263. package/dist/connectors/codex-materialize-runner.d.ts +2 -1
  264. package/dist/connectors/codex-materialize-runner.js +23 -22
  265. package/dist/connectors/codex-materialize.d.ts +2 -1
  266. package/dist/connectors/index.d.ts +2 -1
  267. package/dist/connectors/index.js +26 -25
  268. package/dist/consolidation-provenance-check.d.ts +3 -2
  269. package/dist/consolidation-provenance-check.js +4 -4
  270. package/dist/consolidation-undo.d.ts +3 -2
  271. package/dist/consolidation-undo.js +10 -7
  272. package/dist/consolidation-undo.js.map +1 -1
  273. package/dist/contradiction/index.d.ts +3 -2
  274. package/dist/converge-config.d.ts +2 -1
  275. package/dist/convergence-refresh.d.ts +4 -3
  276. package/dist/convergence-refresh.js +27 -26
  277. package/dist/conversation-index/backend.d.ts +2 -1
  278. package/dist/conversation-index/backend.js +2 -2
  279. package/dist/conversation-index/chunker.d.ts +2 -1
  280. package/dist/conversation-index/faiss-adapter.d.ts +2 -1
  281. package/dist/conversation-index/indexer.d.ts +2 -1
  282. package/dist/conversation-index/search.d.ts +2 -1
  283. package/dist/corpus-watermark.d.ts +2 -1
  284. package/dist/corpus-watermark.js +42 -41
  285. package/dist/day-summary.d.ts +2 -1
  286. package/dist/delinearize.d.ts +2 -1
  287. package/dist/direct-answer-wiring.d.ts +2 -1
  288. package/dist/direct-answer-wiring.js +2 -2
  289. package/dist/direct-answer.d.ts +2 -1
  290. package/dist/embedding-fallback.d.ts +2 -1
  291. package/dist/embedding-fallback.js +2 -2
  292. package/dist/enrichment/index.d.ts +2 -1
  293. package/dist/entity-retrieval-boundaries.js +1 -1
  294. package/dist/entity-retrieval.d.ts +3 -2
  295. package/dist/entity-retrieval.js +24 -23
  296. package/dist/entity-schema.d.ts +2 -1
  297. package/dist/explicit-capture.d.ts +9 -8
  298. package/dist/explicit-capture.js +11 -9
  299. package/dist/external-wiki-access.d.ts +127 -0
  300. package/dist/external-wiki-access.js +186 -0
  301. package/dist/external-wiki-access.js.map +1 -0
  302. package/dist/external-wiki-cli.d.ts +13 -0
  303. package/dist/external-wiki-cli.js +96 -0
  304. package/dist/external-wiki-cli.js.map +1 -0
  305. package/dist/external-wiki-collection-registration.d.ts +39 -0
  306. package/dist/external-wiki-collection-registration.js +79 -0
  307. package/dist/external-wiki-collection-registration.js.map +1 -0
  308. package/dist/external-wiki-collection.d.ts +50 -0
  309. package/dist/external-wiki-collection.js +387 -0
  310. package/dist/external-wiki-collection.js.map +1 -0
  311. package/dist/external-wiki-config.d.ts +13 -0
  312. package/dist/external-wiki-config.js +13 -0
  313. package/dist/external-wiki-config.js.map +1 -0
  314. package/dist/external-wiki-guard.d.ts +11 -0
  315. package/dist/external-wiki-guard.js +18 -0
  316. package/dist/external-wiki-guard.js.map +1 -0
  317. package/dist/external-wiki-mcp-tools.d.ts +123 -0
  318. package/dist/external-wiki-mcp-tools.js +8 -0
  319. package/dist/external-wiki-mcp-tools.js.map +1 -0
  320. package/dist/external-wiki-search.d.ts +42 -0
  321. package/dist/external-wiki-search.js +11 -0
  322. package/dist/external-wiki-search.js.map +1 -0
  323. package/dist/external-wiki.d.ts +43 -0
  324. package/dist/external-wiki.js +16 -0
  325. package/dist/external-wiki.js.map +1 -0
  326. package/dist/extraction-error-classification.d.ts +2 -1
  327. package/dist/extraction-faithfulness.d.ts +2 -1
  328. package/dist/extraction-judge-telemetry.d.ts +2 -1
  329. package/dist/extraction-judge-training.d.ts +2 -1
  330. package/dist/extraction-judge.d.ts +2 -1
  331. package/dist/extraction-liveness.d.ts +2 -1
  332. package/dist/extraction-source-grounding-helpers.d.ts +5 -3
  333. package/dist/extraction-source-grounding-helpers.js +1 -1
  334. package/dist/extraction-source-grounding-rules.d.ts +2 -1
  335. package/dist/extraction-source-grounding-rules.js +2 -2
  336. package/dist/extraction-source-grounding.d.ts +2 -1
  337. package/dist/extraction-source-grounding.js +5 -5
  338. package/dist/extraction.d.ts +2 -1
  339. package/dist/extraction.js +45 -43
  340. package/dist/fallback-llm.d.ts +2 -1
  341. package/dist/graph-dashboard-diff.d.ts +2 -1
  342. package/dist/graph-dashboard-key.d.ts +2 -1
  343. package/dist/graph-dashboard-parser.d.ts +2 -1
  344. package/dist/graph-edge-reinforcement.d.ts +2 -1
  345. package/dist/graph-snapshot.d.ts +2 -1
  346. package/dist/graph.d.ts +2 -1
  347. package/dist/harmonic-retrieval.js +2 -2
  348. package/dist/importance.d.ts +2 -1
  349. package/dist/importers/index.d.ts +2 -1
  350. package/dist/in-flight-reads.d.ts +2 -1
  351. package/dist/index.d.ts +362 -350
  352. package/dist/index.js +291 -259
  353. package/dist/intent.d.ts +2 -1
  354. package/dist/lcm/engine.d.ts +2 -1
  355. package/dist/lcm/engine.js +3 -3
  356. package/dist/lcm/index.d.ts +2 -1
  357. package/dist/lcm/index.js +8 -8
  358. package/dist/lcm/tools.d.ts +2 -1
  359. package/dist/lifecycle.d.ts +2 -1
  360. package/dist/live-connectors-runner.d.ts +2 -1
  361. package/dist/local-llm.d.ts +2 -1
  362. package/dist/local-llm.js +2 -2
  363. package/dist/local-model-endpoint.d.ts +2 -1
  364. package/dist/maintenance/memory-governance.d.ts +2 -1
  365. package/dist/maintenance/memory-governance.js +24 -23
  366. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +3 -2
  367. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +24 -23
  368. package/dist/maintenance/rebuild-memory-projection.d.ts +3 -2
  369. package/dist/maintenance/rebuild-memory-projection.js +26 -25
  370. package/dist/{maintenance-LbuS2rUA.d.ts → maintenance-D2mveyCd.d.ts} +3 -3
  371. package/dist/mcp-memory-inspector-app.d.ts +14 -10
  372. package/dist/mcp-read-only-tools.js +1 -1
  373. package/dist/memory-action-policy.d.ts +2 -1
  374. package/dist/memory-cache.d.ts +2 -1
  375. package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
  376. package/dist/memory-projection-store.d.ts +2 -1
  377. package/dist/memory-provenance.d.ts +2 -1
  378. package/dist/memory-worth-outcomes.d.ts +3 -2
  379. package/dist/models-json.d.ts +2 -1
  380. package/dist/namespaces/migrate.d.ts +4 -3
  381. package/dist/namespaces/migrate.js +40 -39
  382. package/dist/namespaces/principal.d.ts +2 -1
  383. package/dist/namespaces/search.d.ts +2 -1
  384. package/dist/namespaces/search.js +18 -18
  385. package/dist/namespaces/storage.d.ts +4 -3
  386. package/dist/namespaces/storage.js +23 -22
  387. package/dist/native-knowledge.d.ts +2 -1
  388. package/dist/offline-sync-impression-drain.d.ts +2 -1
  389. package/dist/offline-sync-impression-drain.js +11 -9
  390. package/dist/offline-sync.d.ts +29 -3
  391. package/dist/offline-sync.js +6 -2
  392. package/dist/operator-doctor-corpus.d.ts +2 -1
  393. package/dist/operator-doctor-corpus.js +45 -44
  394. package/dist/operator-doctor-replica.d.ts +2 -1
  395. package/dist/operator-doctor-replica.js +3 -3
  396. package/dist/operator-toolkit.d.ts +4 -3
  397. package/dist/operator-toolkit.js +59 -55
  398. package/dist/orchestration/compression-guideline-coordinator.d.ts +3 -2
  399. package/dist/orchestration/maintenance.d.ts +5 -4
  400. package/dist/orchestration/maintenance.js +36 -33
  401. package/dist/{orchestrator-rHiWt32X.d.ts → orchestrator-DJYlwiUv.d.ts} +14 -7
  402. package/dist/orchestrator.d.ts +9 -8
  403. package/dist/orchestrator.js +201 -189
  404. package/dist/page-versioning.js +3 -3
  405. package/dist/patterns-cli.d.ts +2 -1
  406. package/dist/{pipeline-W_97O8BV.d.ts → pipeline-CNjY4wk3.d.ts} +1 -1
  407. package/dist/policy-runtime.d.ts +2 -1
  408. package/dist/policy-runtime.js +1 -1
  409. package/dist/proactive-contention.d.ts +2 -1
  410. package/dist/provenance.d.ts +2 -1
  411. package/dist/provenance.js +2 -2
  412. package/dist/{qmd-LWtMofAf.d.ts → qmd-C0UDZidt.d.ts} +9 -7
  413. package/dist/qmd-preflight.d.ts +5 -4
  414. package/dist/qmd-preflight.js +2 -2
  415. package/dist/qmd-recall-cache.d.ts +2 -1
  416. package/dist/qmd.d.ts +4 -3
  417. package/dist/qmd.js +5 -5
  418. package/dist/recall-concurrency-config.d.ts +2 -1
  419. package/dist/recall-disclosure-escalation.d.ts +2 -1
  420. package/dist/recall-explain-renderer.d.ts +2 -1
  421. package/dist/recall-explain-renderer.js +3 -3
  422. package/dist/recall-memory-map.d.ts +2 -1
  423. package/dist/recall-planner-llm.d.ts +2 -1
  424. package/dist/recall-state.d.ts +2 -1
  425. package/dist/recall-tag-filter.d.ts +2 -1
  426. package/dist/recall-timings.d.ts +2 -1
  427. package/dist/recall-xray-cli.d.ts +2 -1
  428. package/dist/recall-xray-cli.js +4 -4
  429. package/dist/recall-xray-renderer.d.ts +2 -1
  430. package/dist/recall-xray-renderer.js +3 -3
  431. package/dist/recall-xray.d.ts +8 -1
  432. package/dist/recall-xray.js +2 -2
  433. package/dist/reconcile/cursor.d.ts +12 -2
  434. package/dist/reconcile/cursor.js +46 -7
  435. package/dist/reconcile/cursor.js.map +1 -1
  436. package/dist/reconcile/manifest.d.ts +9 -2
  437. package/dist/reconcile/manifest.js +15 -268
  438. package/dist/reconcile/manifest.js.map +1 -1
  439. package/dist/reconcile/plan.d.ts +4 -1
  440. package/dist/reconcile/plan.js +4 -4
  441. package/dist/replay/normalizers/chatgpt.d.ts +2 -1
  442. package/dist/replay/normalizers/claude.d.ts +2 -1
  443. package/dist/replay/normalizers/openclaw.d.ts +2 -1
  444. package/dist/replay/normalizers/shared.d.ts +2 -1
  445. package/dist/replay/runner.d.ts +2 -1
  446. package/dist/replay/types.d.ts +2 -1
  447. package/dist/replica-divergence.d.ts +2 -1
  448. package/dist/replica-divergence.js +2 -2
  449. package/dist/replica-peers-config.d.ts +2 -1
  450. package/dist/resolve-auth-token.d.ts +2 -1
  451. package/dist/resume-bundles.js +12 -10
  452. package/dist/retrieval-agents.d.ts +4 -3
  453. package/dist/retrieval-agents.js +2 -2
  454. package/dist/retrieval-tiers.d.ts +2 -1
  455. package/dist/routing/engine.d.ts +2 -1
  456. package/dist/routing/store.d.ts +2 -1
  457. package/dist/salvage-envelope.d.ts +2 -1
  458. package/dist/schemas.d.ts +32 -32
  459. package/dist/{scope-profiles-BiQKOE-p.d.ts → scope-profiles-BJzp2F5A.d.ts} +1 -1
  460. package/dist/search/embed-helper.d.ts +2 -1
  461. package/dist/search/embed-helper.js +3 -3
  462. package/dist/search/factory.d.ts +4 -2
  463. package/dist/search/factory.js +20 -18
  464. package/dist/search/index.d.ts +2 -1
  465. package/dist/search/index.js +22 -22
  466. package/dist/search/lancedb-backend.d.ts +2 -1
  467. package/dist/search/lancedb-backend.js +4 -4
  468. package/dist/search/meilisearch-backend.d.ts +2 -1
  469. package/dist/search/meilisearch-backend.js +4 -4
  470. package/dist/search/noop-backend.d.ts +2 -1
  471. package/dist/search/orama-backend.d.ts +2 -1
  472. package/dist/search/orama-backend.js +4 -4
  473. package/dist/search/port.d.ts +18 -1
  474. package/dist/search/port.js +1 -1
  475. package/dist/search/remote-backend.d.ts +2 -1
  476. package/dist/search/remote-backend.js +2 -2
  477. package/dist/secure-store/index.js +2 -2
  478. package/dist/{semantic-consolidation-dHYCyqgh.d.ts → semantic-consolidation-D4KAZO2G.d.ts} +1 -1
  479. package/dist/semantic-consolidation.d.ts +3 -2
  480. package/dist/semantic-consolidation.js +25 -24
  481. package/dist/semantic-rule-promotion.js +23 -22
  482. package/dist/semantic-rule-verifier.d.ts +2 -1
  483. package/dist/semantic-rule-verifier.js +24 -23
  484. package/dist/{service-DJG3KCQ4.d.ts → service-BeDxSqE-.d.ts} +2 -2
  485. package/dist/session-observer-bands.d.ts +2 -1
  486. package/dist/session-observer-state.d.ts +2 -1
  487. package/dist/shared-context/manager.d.ts +2 -1
  488. package/dist/shared-context/manager.js +2 -2
  489. package/dist/signal.d.ts +2 -1
  490. package/dist/source-agent-qualifier.d.ts +2 -1
  491. package/dist/source-agent-qualifier.js +42 -40
  492. package/dist/{storage-F9FVh-w9.d.ts → storage-DfjxusTE.d.ts} +24 -12
  493. package/dist/storage.d.ts +3 -2
  494. package/dist/storage.js +25 -24
  495. package/dist/summarizer.d.ts +2 -1
  496. package/dist/summarizer.js +5 -5
  497. package/dist/summary-snapshot.d.ts +2 -1
  498. package/dist/temporal-supersession.d.ts +3 -2
  499. package/dist/temporal-timeline-recall.d.ts +2 -1
  500. package/dist/temporal-validity.d.ts +2 -1
  501. package/dist/threading.d.ts +2 -1
  502. package/dist/tier-migration.d.ts +3 -2
  503. package/dist/tier-routing.d.ts +2 -1
  504. package/dist/tool-scoped-memory.d.ts +5 -1
  505. package/dist/tool-scoped-memory.js +3 -1
  506. package/dist/topics.d.ts +2 -1
  507. package/dist/transcript.d.ts +2 -1
  508. package/dist/transfer/capsule-import.js +4 -4
  509. package/dist/transfer/types.d.ts +12 -12
  510. package/dist/trust-score-stage.d.ts +2 -1
  511. package/dist/trust-score.d.ts +2 -1
  512. package/dist/{types-rEwubvim.d.ts → types-yX_FwERf.d.ts} +8 -1
  513. package/dist/types.d.ts +2 -1
  514. package/dist/types.js +1 -1
  515. package/dist/utility-runtime.d.ts +2 -1
  516. package/dist/verified-recall.js +24 -23
  517. package/dist/write-envelope.d.ts +2 -1
  518. package/package.json +2 -2
  519. package/src/abort-error.ts +17 -0
  520. package/src/access-admin-ops-surface.ts +1 -0
  521. package/src/access-boundary.ts +1 -0
  522. package/src/access-coding-context-resolution.ts +42 -0
  523. package/src/access-extraction-force-flush.ts +38 -2
  524. package/src/access-http-lcm-compaction.ts +5 -2
  525. package/src/access-http-offline-stream.ts +79 -0
  526. package/src/access-http.test.ts +310 -3
  527. package/src/access-http.ts +85 -21
  528. package/src/access-mcp-output-schemas.ts +36 -0
  529. package/src/access-mcp.test.ts +95 -1
  530. package/src/access-mcp.ts +7 -9
  531. package/src/access-observe-helpers.ts +64 -22
  532. package/src/access-observe-write-surface.ts +8 -0
  533. package/src/access-offline-manifest.ts +54 -0
  534. package/src/access-operations-batch.ts +3 -3
  535. package/src/access-operations.ts +13 -7
  536. package/src/access-recall-concurrency.ts +3 -27
  537. package/src/access-recall-surface.ts +3 -0
  538. package/src/access-service-health.test.ts +32 -7
  539. package/src/access-service-namespace.test.ts +55 -0
  540. package/src/access-service-observe-idempotency.test.ts +34 -2
  541. package/src/access-service-observe-lcm-parity.test.ts +138 -3
  542. package/src/access-service-observe-scope.test.ts +160 -1
  543. package/src/access-service-offline-file-content.test.ts +345 -1
  544. package/src/access-service.ts +86 -59
  545. package/src/access-surface-catalog.ts +4 -0
  546. package/src/admin/admin-surfaces.ts +2 -0
  547. package/src/binary-lifecycle/pipeline.test.ts +106 -1
  548. package/src/binary-lifecycle/pipeline.ts +3 -0
  549. package/src/coding/git-context.test.ts +47 -0
  550. package/src/coding/git-context.ts +129 -27
  551. package/src/config.test.ts +24 -0
  552. package/src/config.ts +9 -12
  553. package/src/connector-provenance.test.ts +101 -0
  554. package/src/consolidation-undo.ts +3 -0
  555. package/src/convergence-refresh.ts +14 -2
  556. package/src/correction/correction-access-wiring.ts +9 -7
  557. package/src/correction/correction-executor.test.ts +206 -2
  558. package/src/correction/correction-executor.ts +29 -20
  559. package/src/correction/correction-planner.test.ts +36 -0
  560. package/src/correction/correction-planner.ts +9 -15
  561. package/src/correction/correction-service.ts +3 -1
  562. package/src/correction/correction-storage-integration.test.ts +77 -0
  563. package/src/correction/correction-surfaces.test.ts +41 -28
  564. package/src/correction/passive-capture.test.ts +59 -0
  565. package/src/correction/passive-capture.ts +4 -1
  566. package/src/entity-retrieval-boundaries.ts +17 -4
  567. package/src/entity-retrieval.ts +27 -6
  568. package/src/external-wiki-access.test.ts +65 -0
  569. package/src/external-wiki-access.ts +31 -0
  570. package/src/external-wiki-cli.ts +92 -0
  571. package/src/external-wiki-collection-registration.test.ts +163 -0
  572. package/src/external-wiki-collection-registration.ts +101 -0
  573. package/src/external-wiki-collection.test.ts +502 -0
  574. package/src/external-wiki-collection.ts +503 -0
  575. package/src/external-wiki-config.test.ts +135 -0
  576. package/src/external-wiki-config.ts +100 -0
  577. package/src/external-wiki-guard.ts +83 -0
  578. package/src/external-wiki-mcp-tools.ts +23 -0
  579. package/src/external-wiki-search.test.ts +301 -0
  580. package/src/external-wiki-search.ts +362 -0
  581. package/src/external-wiki.test.ts +240 -0
  582. package/src/external-wiki.ts +453 -0
  583. package/src/extraction-scope-source-agent.test.ts +21 -0
  584. package/src/extraction-source-grounding-helpers.ts +243 -53
  585. package/src/extraction-source-grounding-rules.ts +133 -39
  586. package/src/extraction-source-grounding.test.ts +363 -33
  587. package/src/extraction-timeout.test.ts +1 -0
  588. package/src/extraction-watermark.test.ts +150 -7
  589. package/src/extraction.ts +8 -1
  590. package/src/index.ts +8 -0
  591. package/src/mcp-read-only-tools.ts +1 -0
  592. package/src/offline-sync.test.ts +194 -0
  593. package/src/offline-sync.ts +217 -13
  594. package/src/orchestration/external-wiki-recall-guard.test.ts +94 -0
  595. package/src/orchestration/extraction-persist.ts +19 -2
  596. package/src/orchestration/extraction-run-helpers.ts +37 -19
  597. package/src/orchestration/extraction-run.test.ts +171 -2
  598. package/src/orchestration/extraction-run.ts +11 -13
  599. package/src/orchestration/extraction-watermark.ts +106 -17
  600. package/src/orchestration/generic-recall-paths.ts +14 -0
  601. package/src/orchestration/orchestrator-helpers.ts +2 -0
  602. package/src/orchestration/orchestrator-init.ts +9 -0
  603. package/src/orchestration/recall-internal-deps.ts +6 -0
  604. package/src/orchestration/recall-internal.ts +154 -33
  605. package/src/orchestration/recall-rerank-coordinator.ts +60 -25
  606. package/src/orchestration/recall-search-pipeline.test.ts +75 -1
  607. package/src/orchestration/recall-search-pipeline.ts +50 -10
  608. package/src/orchestrator-convergence-refresh.test.ts +36 -2
  609. package/src/orchestrator.ts +13 -3
  610. package/src/page-versioning.ts +5 -19
  611. package/src/procedural/procedure-recall.ts +5 -1
  612. package/src/provenance-surfaces.test.ts +3 -0
  613. package/src/qmd-client.test.ts +78 -17
  614. package/src/qmd.test.ts +24 -0
  615. package/src/qmd.ts +224 -315
  616. package/src/recall-explain-renderer.ts +3 -0
  617. package/src/recall-rerank-coordinator.test.ts +61 -0
  618. package/src/recall-xray-renderer.test.ts +6 -0
  619. package/src/recall-xray.test.ts +88 -1
  620. package/src/recall-xray.ts +15 -0
  621. package/src/reconcile/cursor.test.ts +48 -0
  622. package/src/reconcile/cursor.ts +58 -11
  623. package/src/reconcile/manifest.test.ts +4 -0
  624. package/src/reconcile/manifest.ts +41 -51
  625. package/src/reconcile/plan.test.ts +4 -0
  626. package/src/reconcile/plan.ts +28 -16
  627. package/src/search/factory.ts +6 -6
  628. package/src/search/port.ts +25 -9
  629. package/src/secure-store/secure-fs.ts +20 -12
  630. package/src/secure-store/secure-store.test.ts +41 -2
  631. package/src/spaces/index.test.ts +61 -2
  632. package/src/spaces/index.ts +44 -18
  633. package/src/storage/entity-alias-config.ts +97 -0
  634. package/src/storage/entity-canonical-id-lock.ts +53 -23
  635. package/src/storage/entity-canonical-id-migration.ts +53 -22
  636. package/src/storage/entity-canonical-id-references.ts +3 -0
  637. package/src/storage/entity-id-safety.ts +7 -0
  638. package/src/storage/entity-store.ts +6 -2
  639. package/src/storage/memory-frontmatter-metadata.ts +4 -9
  640. package/src/storage/memory-migration-serialization.ts +10 -15
  641. package/src/storage/tombstone-blocked-capture-mutation.ts +52 -64
  642. package/src/storage/tombstone-blocked-capture-sync.ts +244 -199
  643. package/src/storage-deletion-revisions.test.ts +91 -0
  644. package/src/storage-fact-hash-index-defer.test.ts +446 -163
  645. package/src/storage.ts +534 -245
  646. package/src/tool-scoped-memory.ts +10 -0
  647. package/src/transfer/capsule-import.ts +13 -0
  648. package/src/transfer/capsule-merge.ts +13 -0
  649. package/src/trust-score-recall-paths.test.ts +75 -1
  650. package/src/types.ts +7 -3
  651. package/dist/capsule-merge-IDWJPCWK.js.map +0 -1
  652. package/dist/chunk-3CE77VAP.js.map +0 -1
  653. package/dist/chunk-3TBLDMJA.js.map +0 -1
  654. package/dist/chunk-4J7G5SY4.js.map +0 -1
  655. package/dist/chunk-57QKLRBV.js.map +0 -1
  656. package/dist/chunk-5TFP4CUL.js.map +0 -1
  657. package/dist/chunk-7XC2HX75.js.map +0 -1
  658. package/dist/chunk-A5OJCXZL.js.map +0 -1
  659. package/dist/chunk-BUE5E2HL.js.map +0 -1
  660. package/dist/chunk-CJ2ZR7UA.js.map +0 -1
  661. package/dist/chunk-CUM2BBPN.js.map +0 -1
  662. package/dist/chunk-D3J5SLQK.js.map +0 -1
  663. package/dist/chunk-DL7ZD3JH.js.map +0 -1
  664. package/dist/chunk-DLVPUX7U.js.map +0 -1
  665. package/dist/chunk-E6PNLPGJ.js.map +0 -1
  666. package/dist/chunk-ECK75GDJ.js.map +0 -1
  667. package/dist/chunk-HREE4JHI.js.map +0 -1
  668. package/dist/chunk-HZFHQ4AQ.js.map +0 -1
  669. package/dist/chunk-IKKWIPYN.js.map +0 -1
  670. package/dist/chunk-J7VGGECD.js.map +0 -1
  671. package/dist/chunk-N5Z4EVOR.js.map +0 -1
  672. package/dist/chunk-NVRYW264.js.map +0 -1
  673. package/dist/chunk-P2BM76KT.js.map +0 -1
  674. package/dist/chunk-PVGDJXVK.js +0 -21
  675. package/dist/chunk-QJAQNXWI.js.map +0 -1
  676. package/dist/chunk-RN7DY3FC.js.map +0 -1
  677. package/dist/chunk-RVLJEII5.js.map +0 -1
  678. package/dist/chunk-S2NCTZGJ.js.map +0 -1
  679. package/dist/chunk-TDHTVMPG.js.map +0 -1
  680. package/dist/chunk-UYLMNVY6.js.map +0 -1
  681. package/dist/chunk-VCD4PSK2.js.map +0 -1
  682. package/dist/chunk-VNA7W7QF.js.map +0 -1
  683. package/dist/chunk-VWAXN2BN.js.map +0 -1
  684. package/dist/chunk-WOCNN776.js.map +0 -1
  685. package/dist/chunk-XYTOI63Z.js.map +0 -1
  686. package/dist/chunk-YV32N67O.js.map +0 -1
  687. /package/dist/{auto-sync-5OE5QOZB.js.map → auto-sync-UPTUVE4X.js.map} +0 -0
  688. /package/dist/{chunk-VUPTKTDV.js.map → chunk-2MRHJNWL.js.map} +0 -0
  689. /package/dist/{chunk-JBPKEARU.js.map → chunk-2QSZNTDO.js.map} +0 -0
  690. /package/dist/{chunk-5IVLTFOV.js.map → chunk-44N6ESJ4.js.map} +0 -0
  691. /package/dist/{chunk-HO3QBJEY.js.map → chunk-5546W5SI.js.map} +0 -0
  692. /package/dist/{chunk-U7GW7NE7.js.map → chunk-5CEECY6P.js.map} +0 -0
  693. /package/dist/{chunk-4UH4BTGK.js.map → chunk-5SNZSWWR.js.map} +0 -0
  694. /package/dist/{chunk-6CZPDBJS.js.map → chunk-5U7ID3EZ.js.map} +0 -0
  695. /package/dist/{chunk-GF22HWS2.js.map → chunk-6NNNURLK.js.map} +0 -0
  696. /package/dist/{chunk-227UFSEQ.js.map → chunk-7RZJWZ46.js.map} +0 -0
  697. /package/dist/{chunk-E5UK4VPE.js.map → chunk-7SHJHPTY.js.map} +0 -0
  698. /package/dist/{chunk-UVIKWC7M.js.map → chunk-7YERSTN7.js.map} +0 -0
  699. /package/dist/{chunk-S5SLVSVY.js.map → chunk-BQIFZ2MP.js.map} +0 -0
  700. /package/dist/{chunk-E53DSZEN.js.map → chunk-C26TE27X.js.map} +0 -0
  701. /package/dist/{chunk-LZ4LDKHZ.js.map → chunk-CLB32OHM.js.map} +0 -0
  702. /package/dist/{chunk-Q6IP2ARR.js.map → chunk-CSOYVTRX.js.map} +0 -0
  703. /package/dist/{chunk-XOQSEF7X.js.map → chunk-CVILPI77.js.map} +0 -0
  704. /package/dist/{chunk-PDLBLTOK.js.map → chunk-EITZHSX6.js.map} +0 -0
  705. /package/dist/{chunk-WUNIWKY4.js.map → chunk-ELIL2A37.js.map} +0 -0
  706. /package/dist/{chunk-CINZGPSJ.js.map → chunk-GUMZC2BO.js.map} +0 -0
  707. /package/dist/{chunk-H24WNPA2.js.map → chunk-GWFSVJ4P.js.map} +0 -0
  708. /package/dist/{chunk-TSH56VPU.js.map → chunk-HAYSYUAB.js.map} +0 -0
  709. /package/dist/{chunk-PKNLM44P.js.map → chunk-JH6BPLOP.js.map} +0 -0
  710. /package/dist/{chunk-KXB4VXHY.js.map → chunk-JIYDRBVZ.js.map} +0 -0
  711. /package/dist/{chunk-AV5ZEH4M.js.map → chunk-KVJRXN2E.js.map} +0 -0
  712. /package/dist/{chunk-JVLCVFQ4.js.map → chunk-KXEFRMCF.js.map} +0 -0
  713. /package/dist/{chunk-WFTIGIIS.js.map → chunk-L6CQ7WIW.js.map} +0 -0
  714. /package/dist/{chunk-EJUEXZHX.js.map → chunk-LLJMAULE.js.map} +0 -0
  715. /package/dist/{chunk-AS7YMSL6.js.map → chunk-M23RF3LJ.js.map} +0 -0
  716. /package/dist/{chunk-3F2LKUMU.js.map → chunk-NIS256NW.js.map} +0 -0
  717. /package/dist/{chunk-YIAA2X3D.js.map → chunk-NK5RGJ65.js.map} +0 -0
  718. /package/dist/{chunk-OQ5PRDDS.js.map → chunk-NTOIP2E6.js.map} +0 -0
  719. /package/dist/{chunk-HLPD7B7P.js.map → chunk-NUEQKLNB.js.map} +0 -0
  720. /package/dist/{chunk-33PLLLL7.js.map → chunk-P7NGM24P.js.map} +0 -0
  721. /package/dist/{chunk-7TWUCYER.js.map → chunk-PNRA7FAD.js.map} +0 -0
  722. /package/dist/{chunk-5I4M26Q7.js.map → chunk-QBSFOKY6.js.map} +0 -0
  723. /package/dist/{chunk-P4DRWEYC.js.map → chunk-QVSBTCVP.js.map} +0 -0
  724. /package/dist/{chunk-AAIUERNB.js.map → chunk-R5RFK3CB.js.map} +0 -0
  725. /package/dist/{chunk-WDISJRMG.js.map → chunk-RMMVQQA6.js.map} +0 -0
  726. /package/dist/{chunk-5SM35XZR.js.map → chunk-S5NZBKKQ.js.map} +0 -0
  727. /package/dist/{chunk-WIPEXG6R.js.map → chunk-SXIMQLGV.js.map} +0 -0
  728. /package/dist/{chunk-OAEQLRCY.js.map → chunk-TN76AKO3.js.map} +0 -0
  729. /package/dist/{chunk-QN25OCUF.js.map → chunk-TQ4GD737.js.map} +0 -0
  730. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  731. /package/dist/{chunk-DNWXFTLD.js.map → chunk-TYISDI6B.js.map} +0 -0
  732. /package/dist/{chunk-4LMA77JH.js.map → chunk-U2VLVBBH.js.map} +0 -0
  733. /package/dist/{chunk-5ZE7QHTK.js.map → chunk-ULVR5KG7.js.map} +0 -0
  734. /package/dist/{chunk-4B77XSG5.js.map → chunk-UV72DEZD.js.map} +0 -0
  735. /package/dist/{chunk-S2BBISHU.js.map → chunk-VANZKHTN.js.map} +0 -0
  736. /package/dist/{chunk-3Y224NYC.js.map → chunk-VYISFWVX.js.map} +0 -0
  737. /package/dist/{chunk-TIHMZFIV.js.map → chunk-W3IC7QOY.js.map} +0 -0
  738. /package/dist/{chunk-NRV4Y3PM.js.map → chunk-W4FBGYGK.js.map} +0 -0
  739. /package/dist/{chunk-MU7ZHSZE.js.map → chunk-WZFAPHIK.js.map} +0 -0
  740. /package/dist/{chunk-T2TTP3KU.js.map → chunk-X4IDNPOS.js.map} +0 -0
  741. /package/dist/{chunk-BLAKS3CP.js.map → chunk-XL3TATMJ.js.map} +0 -0
  742. /package/dist/{chunk-W4XJFLAL.js.map → chunk-XPRJSHNI.js.map} +0 -0
  743. /package/dist/{chunk-JE7EK33X.js.map → chunk-Y7HRYCNW.js.map} +0 -0
  744. /package/dist/{chunk-E6EE5B67.js.map → chunk-YK6BDDHP.js.map} +0 -0
  745. /package/dist/{chunk-ES36HTSC.js.map → chunk-YLHM5BQQ.js.map} +0 -0
  746. /package/dist/{chunk-BJKPPZ6Z.js.map → chunk-ZFGZ6PZ2.js.map} +0 -0
  747. /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,7 @@ 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";
44
- import {
45
- assertMemoryFrontmatterId,
46
- warnProjectionFallback
47
- } from "./chunk-ZA53AZND.js";
29
+ } from "./chunk-DZPFMQZ7.js";
48
30
  import {
49
31
  normalizeProjectionPreview,
50
32
  normalizeProjectionTags
@@ -53,15 +35,6 @@ import {
53
35
  rewriteProjectedEntityReferences,
54
36
  rewriteProjectedMemoryEntityReference
55
37
  } 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
38
  import {
66
39
  rotateMarkdownFileToArchive
67
40
  } from "./chunk-DM2T26WE.js";
@@ -80,14 +53,12 @@ import {
80
53
  } from "./chunk-JYIJNNN3.js";
81
54
  import {
82
55
  TombstoneBlockedCaptureIndexHost,
56
+ buildCapturePathLockIdentity,
83
57
  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";
58
+ isQueuedReviewMemory,
59
+ parseTombstoneBlockedOfflineSyncMemory,
60
+ tombstoneBlocked
61
+ } from "./chunk-SYUBB3WM.js";
91
62
  import {
92
63
  composeMemoryEnvelope,
93
64
  isSealedMemoryEnvelope,
@@ -97,14 +68,6 @@ import {
97
68
  assemblePersistedBody,
98
69
  stripAttributesSuffix
99
70
  } from "./chunk-R3DJVOSM.js";
100
- import {
101
- markProjectedMemoryPathInvalid,
102
- readProjectedGovernanceRecord,
103
- readProjectedMemoryBrowse,
104
- readProjectedMemoryState,
105
- readProjectedMemoryTimeline,
106
- updateProjectedMemoryPath
107
- } from "./chunk-3CSX3ETE.js";
108
71
  import {
109
72
  normalizeEntityName
110
73
  } from "./chunk-YXZG5TVN.js";
@@ -114,7 +77,7 @@ import {
114
77
  } from "./chunk-G7D6GZ5J.js";
115
78
  import {
116
79
  createVersion
117
- } from "./chunk-DLVPUX7U.js";
80
+ } from "./chunk-7YKVM5H3.js";
118
81
  import {
119
82
  clearInFlightReads,
120
83
  deleteInFlightRead,
@@ -128,21 +91,20 @@ import {
128
91
  ENTITY_CANONICAL_ID_RECONCILE_MARKER,
129
92
  HistoricalEntityCanonicalIdCache,
130
93
  appendCanonicalizedTombstone,
94
+ assertSafeEntityId,
95
+ canonicalizeEntityRefFrontmatter,
131
96
  canonicalizeEntityRefOption,
132
97
  reconcileIfJournalMovedSync,
133
98
  repairEntityRefAfterJournalMove,
134
99
  requestEntityCanonicalIdReconcileSync,
135
100
  resolveHistoricalEntityCanonicalId,
136
101
  withEntityCanonicalMutationLock
137
- } from "./chunk-4J7G5SY4.js";
102
+ } from "./chunk-NZBZ7IS2.js";
138
103
  import {
139
104
  computeSupersessionKey,
140
105
  normalizeSupersessionKey,
141
106
  supersessionKeysForFact
142
107
  } from "./chunk-DNHVPZOD.js";
143
- import {
144
- withHeldFileLock
145
- } from "./chunk-FFAZ2XFU.js";
146
108
  import {
147
109
  clearMemoryCache,
148
110
  getCachedEntities,
@@ -161,15 +123,61 @@ import {
161
123
  parseProvenanceTag,
162
124
  reconcileProvenanceRead,
163
125
  serializeProvenanceFields
164
- } from "./chunk-5I4M26Q7.js";
126
+ } from "./chunk-QBSFOKY6.js";
127
+ import {
128
+ sanitizeMemoryContent
129
+ } from "./chunk-5GKPFL3S.js";
165
130
  import {
166
131
  matchEntitySchemaSection,
167
132
  normalizeEntityStructuredSection,
168
133
  sortStructuredSectionsBySchema
169
134
  } from "./chunk-ZIKENA2C.js";
170
135
  import {
171
- sanitizeMemoryContent
172
- } from "./chunk-5GKPFL3S.js";
136
+ ProjectionLedgerLagManager,
137
+ appendLifecycleEventsSerialized,
138
+ drainPendingLifecycleLedgerForSync,
139
+ drainPendingLifecycleLedgerIfAny,
140
+ formatProjectionAge,
141
+ readAllLifecycleEventsFromLedger,
142
+ readAllLifecycleEventsFromLedgerBuffer,
143
+ readBoundedLifecycleEventsFromLedger,
144
+ readMaybeEncryptedLines,
145
+ readMemoryActionEventRowsFromLines,
146
+ readProjectionRebuiltAt,
147
+ serializeLifecycleAppendPayload
148
+ } from "./chunk-ELIL2A37.js";
149
+ import {
150
+ namespaceIdentityFromToken
151
+ } from "./chunk-EGGE52UU.js";
152
+ import {
153
+ assertMemoryFrontmatterId,
154
+ warnProjectionFallback
155
+ } from "./chunk-ZA53AZND.js";
156
+ import {
157
+ inferMemoryStatus,
158
+ isArchivedMemoryPath,
159
+ toMemoryPathRel
160
+ } from "./chunk-7RJUVTVF.js";
161
+ import {
162
+ assertPathInsideRoot,
163
+ pathIsInside
164
+ } from "./chunk-GCASGYIO.js";
165
+ import {
166
+ CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS,
167
+ ContentHashIndex,
168
+ FactHashIndexNotAuthoritativeError
169
+ } from "./chunk-BQIFZ2MP.js";
170
+ import {
171
+ markProjectedMemoryPathInvalid,
172
+ readProjectedGovernanceRecord,
173
+ readProjectedMemoryBrowse,
174
+ readProjectedMemoryState,
175
+ readProjectedMemoryTimeline,
176
+ updateProjectedMemoryPath
177
+ } from "./chunk-3CSX3ETE.js";
178
+ import {
179
+ withHeldFileLock
180
+ } from "./chunk-FFAZ2XFU.js";
173
181
  import {
174
182
  parseFlexibleIsoTimestamp
175
183
  } from "./chunk-P7FMDTKL.js";
@@ -187,7 +195,7 @@ import {
187
195
  readMaybeEncryptedFile,
188
196
  readMaybeEncryptedFileBuffer,
189
197
  writeMaybeEncryptedFile
190
- } from "./chunk-5TFP4CUL.js";
198
+ } from "./chunk-XQ3HXAQH.js";
191
199
  import {
192
200
  isErrnoCode
193
201
  } from "./chunk-5UZXUTVO.js";
@@ -206,6 +214,7 @@ import {
206
214
  readdir as readdir5,
207
215
  readFile as readFile2,
208
216
  realpath as realpath3,
217
+ rename as rename2,
209
218
  stat as stat2,
210
219
  writeFile as writeFile2,
211
220
  mkdir,
@@ -213,26 +222,22 @@ import {
213
222
  appendFile,
214
223
  open
215
224
  } from "fs/promises";
216
- import { appendFileSync, createReadStream, mkdirSync, readFileSync, statSync } from "fs";
217
- import { createHash as createHash5 } from "crypto";
218
- import path8 from "path";
225
+ import { appendFileSync, createReadStream, mkdirSync, statSync } from "fs";
226
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
227
+ import path9 from "path";
219
228
 
220
229
  // src/storage/memory-read-store.ts
221
230
  import { lstat, readdir, realpath, stat } from "fs/promises";
222
231
  import path from "path";
223
232
 
224
233
  // 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
- }
234
+ var rawDocumentByMemory = /* @__PURE__ */ new WeakMap();
229
235
  function rememberRawFrontmatter(owner, raw) {
230
- const frontmatter = extractRawFrontmatter(raw);
231
- if (frontmatter !== null) rawFrontmatterByMemory.set(owner, frontmatter);
236
+ if (/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.test(raw)) rawDocumentByMemory.set(owner, raw);
232
237
  return owner;
233
238
  }
234
- function readRawFrontmatter(owner) {
235
- return rawFrontmatterByMemory.get(owner);
239
+ function readRawMemoryDocument(owner) {
240
+ return rawDocumentByMemory.get(owner);
236
241
  }
237
242
 
238
243
  // src/storage/memory-read-store.ts
@@ -1718,8 +1723,11 @@ var EntityStore = class {
1718
1723
  */
1719
1724
  async readAllEntityFiles() {
1720
1725
  const currentVersion = this.deps.getMemoryStatusVersion();
1721
- const schemaCacheKey = buildEntitySchemaCacheKey(this.deps.entitySchemas);
1722
- const cacheKey = `${this.deps.getEntityCacheSecureStoreKey()}\0${schemaCacheKey}`;
1726
+ const cacheKey = [
1727
+ this.deps.getEntityCacheSecureStoreKey(),
1728
+ buildEntitySchemaCacheKey(this.deps.entitySchemas),
1729
+ this.deps.getEntityMutationVersion()
1730
+ ].join("\0");
1723
1731
  const cached = getCachedEntities(this.deps.baseDir, currentVersion, cacheKey);
1724
1732
  if (cached) return cached;
1725
1733
  try {
@@ -2161,7 +2169,7 @@ var IdentityContinuityStore = class {
2161
2169
  };
2162
2170
 
2163
2171
  // src/storage/entity-canonical-id-migration.ts
2164
- import { randomUUID } from "crypto";
2172
+ import { createHash, randomUUID } from "crypto";
2165
2173
  import {
2166
2174
  access,
2167
2175
  lstat as lstat2,
@@ -2204,16 +2212,50 @@ async function fingerprintPath(filePath) {
2204
2212
  }
2205
2213
  return fileStat ? `${fileStat.dev}:${fileStat.ino}:${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}` : "missing";
2206
2214
  }
2215
+ async function fingerprintEntityEntries(entitiesDir) {
2216
+ let names;
2217
+ try {
2218
+ names = (await readdir4(entitiesDir)).filter((name) => path4.extname(name) === ".md").sort();
2219
+ } catch (error) {
2220
+ if (isErrnoCode(error, "ENOENT")) return "missing";
2221
+ throw error;
2222
+ }
2223
+ const hash = createHash("sha256");
2224
+ for (const name of names) {
2225
+ hash.update(`${name.length}:${name}:`);
2226
+ try {
2227
+ const entry = await lstat2(path4.join(entitiesDir, name), { bigint: true });
2228
+ hash.update(`${entry.dev}:${entry.ino}:${entry.size}:${entry.mtimeNs}:${entry.ctimeNs}`);
2229
+ } catch (error) {
2230
+ if (!isErrnoCode(error, "ENOENT")) throw error;
2231
+ hash.update("missing");
2232
+ }
2233
+ hash.update("\n");
2234
+ }
2235
+ return hash.digest("hex");
2236
+ }
2207
2237
  async function getFingerprint(baseDir, entitiesDir, getEntityMutationVersion) {
2208
- const [entityFingerprint, aliasFingerprint, reconcileFingerprint, consumingFingerprint] = await Promise.all([
2238
+ const [
2239
+ entityDirectoryFingerprint,
2240
+ entityEntriesFingerprint,
2241
+ aliasFingerprint,
2242
+ reconcileFingerprint,
2243
+ consumingFingerprint
2244
+ ] = await Promise.all([
2209
2245
  fingerprintPath(entitiesDir),
2246
+ fingerprintEntityEntries(entitiesDir),
2210
2247
  fingerprintPath(path4.join(baseDir, "config", "aliases.json")),
2211
2248
  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
2249
  fingerprintPath(path4.join(baseDir, "state", ENTITY_CANONICAL_ID_RECONCILE_CONSUMING_MARKER))
2215
2250
  ]);
2216
- return [entityFingerprint, aliasFingerprint, reconcileFingerprint, consumingFingerprint, getEntityMutationVersion()].join(":");
2251
+ return [
2252
+ entityDirectoryFingerprint,
2253
+ entityEntriesFingerprint,
2254
+ aliasFingerprint,
2255
+ reconcileFingerprint,
2256
+ consumingFingerprint,
2257
+ getEntityMutationVersion()
2258
+ ].join(":");
2217
2259
  }
2218
2260
  async function validateRoots(baseDir, entitiesDir, stateDir, archiveDir) {
2219
2261
  let baseStat;
@@ -2311,6 +2353,12 @@ async function readState(deps) {
2311
2353
  }
2312
2354
  const result = EntityCanonicalIdMigrationStateSchema.safeParse(parsed);
2313
2355
  if (!result.success) throw new Error("Invalid entity canonical-id migration state.");
2356
+ for (const mappings of [result.data.mappings, result.data.blocked ?? {}]) {
2357
+ for (const [legacyId, canonicalId] of Object.entries(mappings)) {
2358
+ assertSafeEntityId(legacyId);
2359
+ assertSafeEntityId(canonicalId);
2360
+ }
2361
+ }
2314
2362
  return result.data;
2315
2363
  }
2316
2364
  async function writeState(deps, state) {
@@ -2347,11 +2395,6 @@ async function sameFileIdentity(leftPath, rightPath) {
2347
2395
  throw error;
2348
2396
  }
2349
2397
  }
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
2398
  async function assertNotSymlink(filePath, label) {
2356
2399
  let stat3;
2357
2400
  try {
@@ -3137,25 +3180,14 @@ var EntityCanonicalIdMigrationRunner = class {
3137
3180
 
3138
3181
  // src/storage/memory-migration-serialization.ts
3139
3182
  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
- `;
3183
+ const rawDocument = readRawMemoryDocument(memory);
3184
+ if (rawDocument === void 0) return fallback(memory, entityRef);
3185
+ const currentEntityRef = memory.frontmatter.entityRef;
3186
+ if (currentEntityRef === void 0) return fallback(memory, entityRef);
3187
+ if (currentEntityRef === entityRef) return rawDocument;
3188
+ const rewritten = canonicalizeEntityRefFrontmatter(rawDocument, { [currentEntityRef]: entityRef });
3189
+ if (rewritten !== rawDocument) return rewritten;
3190
+ return fallback(memory, entityRef);
3159
3191
  }
3160
3192
  function createMemoryEntityRefSerializer(serializeFrontmatter2) {
3161
3193
  return (memory, entityRef) => serializeMemoryWithEntityRef(
@@ -3168,6 +3200,90 @@ ${fallbackMemory.content}
3168
3200
  );
3169
3201
  }
3170
3202
 
3203
+ // src/storage/entity-alias-config.ts
3204
+ import {
3205
+ closeSync,
3206
+ constants,
3207
+ fstatSync,
3208
+ lstatSync,
3209
+ openSync,
3210
+ readFileSync,
3211
+ realpathSync
3212
+ } from "fs";
3213
+ import path5 from "path";
3214
+ function resolveSafeAliasRoots(baseDir, configDir) {
3215
+ let baseStat;
3216
+ try {
3217
+ baseStat = lstatSync(baseDir);
3218
+ } catch (error) {
3219
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3220
+ throw error;
3221
+ }
3222
+ if (baseStat.isSymbolicLink() || !baseStat.isDirectory()) {
3223
+ throw new Error(`Refusing unsafe entity alias memory root: ${baseDir}.`);
3224
+ }
3225
+ let configStat;
3226
+ try {
3227
+ configStat = lstatSync(configDir);
3228
+ } catch (error) {
3229
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3230
+ throw error;
3231
+ }
3232
+ if (configStat.isSymbolicLink() || !configStat.isDirectory()) {
3233
+ throw new Error(`Refusing unsafe entity alias config root: ${configDir}.`);
3234
+ }
3235
+ const memoryRoot = realpathSync(baseDir);
3236
+ assertPathInsideRoot(memoryRoot, realpathSync(configDir), configDir);
3237
+ return memoryRoot;
3238
+ }
3239
+ function readEntityAliasConfigSync(baseDir) {
3240
+ const configDir = path5.join(baseDir, "config");
3241
+ const aliasPath = path5.join(configDir, "aliases.json");
3242
+ let memoryRoot = resolveSafeAliasRoots(baseDir, configDir);
3243
+ if (memoryRoot === void 0) return void 0;
3244
+ let aliasPreflight;
3245
+ try {
3246
+ aliasPreflight = lstatSync(aliasPath);
3247
+ } catch (error) {
3248
+ if (isErrnoCode(error, "ENOENT")) return void 0;
3249
+ throw error;
3250
+ }
3251
+ if (aliasPreflight.isSymbolicLink() || !aliasPreflight.isFile()) {
3252
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3253
+ }
3254
+ let fd;
3255
+ try {
3256
+ fd = openSync(
3257
+ aliasPath,
3258
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
3259
+ );
3260
+ } catch (error) {
3261
+ if (isErrnoCode(error, "ENOENT")) {
3262
+ resolveSafeAliasRoots(baseDir, configDir);
3263
+ return void 0;
3264
+ }
3265
+ if (isErrnoCode(error, "ELOOP")) {
3266
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3267
+ }
3268
+ throw error;
3269
+ }
3270
+ try {
3271
+ const opened = fstatSync(fd);
3272
+ memoryRoot = resolveSafeAliasRoots(baseDir, configDir);
3273
+ if (memoryRoot === void 0) {
3274
+ throw new Error(`Refusing unsafe entity alias config root: ${configDir}.`);
3275
+ }
3276
+ const aliasStat = lstatSync(aliasPath);
3277
+ if (!opened.isFile() || aliasStat.isSymbolicLink() || !aliasStat.isFile() || aliasStat.dev !== opened.dev || aliasStat.ino !== opened.ino) {
3278
+ throw new Error(`Refusing unsafe entity alias config file: ${aliasPath}.`);
3279
+ }
3280
+ assertPathInsideRoot(memoryRoot, realpathSync(aliasPath), aliasPath);
3281
+ return readFileSync(fd, "utf-8");
3282
+ } finally {
3283
+ closeSync(fd);
3284
+ }
3285
+ }
3286
+
3171
3287
  // src/utils/yaml-scalar.ts
3172
3288
  function decodeYamlScalar(value) {
3173
3289
  const trimmed = value.trim();
@@ -3183,9 +3299,9 @@ function decodeYamlScalar(value) {
3183
3299
  }
3184
3300
 
3185
3301
  // src/orchestration/qmd-result-resolver.ts
3186
- import path5 from "path";
3302
+ import path6 from "path";
3187
3303
  function qmdCollectionPathParts(resultPath) {
3188
- if (!resultPath || path5.isAbsolute(resultPath)) return null;
3304
+ if (!resultPath || path6.isAbsolute(resultPath)) return null;
3189
3305
  const normalized = resultPath.replace(/\\/g, "/").replace(/^\/+/, "");
3190
3306
  const slashIndex = normalized.indexOf("/");
3191
3307
  if (slashIndex <= 0 || slashIndex >= normalized.length - 1) return null;
@@ -3198,9 +3314,9 @@ function qmdCollectionPathParts(resultPath) {
3198
3314
  }
3199
3315
  function qmdResultPathCandidates(storageDir, resultPath) {
3200
3316
  const candidates = /* @__PURE__ */ new Set();
3201
- const storageRoot = path5.resolve(storageDir);
3317
+ const storageRoot = path6.resolve(storageDir);
3202
3318
  const addCandidate = (candidate) => {
3203
- const resolved = path5.resolve(candidate);
3319
+ const resolved = path6.resolve(candidate);
3204
3320
  if (isPathInsideStorageRoot(storageRoot, resolved)) {
3205
3321
  candidates.add(resolved);
3206
3322
  }
@@ -3208,18 +3324,18 @@ function qmdResultPathCandidates(storageDir, resultPath) {
3208
3324
  const addRelativeCandidates = (relativePath) => {
3209
3325
  const normalized = relativePath.replace(/\\/g, "/").replace(/^\/+/, "");
3210
3326
  if (!normalized) return;
3211
- addCandidate(path5.join(storageRoot, normalized));
3327
+ addCandidate(path6.join(storageRoot, normalized));
3212
3328
  if (/^\d{4}-\d{2}-\d{2}\//.test(normalized)) {
3213
- addCandidate(path5.join(storageRoot, "facts", normalized));
3329
+ addCandidate(path6.join(storageRoot, "facts", normalized));
3214
3330
  }
3215
3331
  };
3216
- if (path5.isAbsolute(resultPath)) {
3332
+ if (path6.isAbsolute(resultPath)) {
3217
3333
  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("/");
3334
+ const relative2 = path6.relative(storageRoot, path6.resolve(resultPath));
3335
+ if (relative2 && !relative2.startsWith("..") && !path6.isAbsolute(relative2)) {
3336
+ const normalized = relative2.split(path6.sep).join("/");
3221
3337
  if (/^\d{4}-\d{2}-\d{2}\//.test(normalized)) {
3222
- addCandidate(path5.join(storageRoot, "facts", normalized));
3338
+ addCandidate(path6.join(storageRoot, "facts", normalized));
3223
3339
  }
3224
3340
  }
3225
3341
  } else {
@@ -3254,7 +3370,7 @@ var QmdResultResolver = class {
3254
3370
  const seenStorageDirs = /* @__PURE__ */ new Set();
3255
3371
  const addStorage = (storage) => {
3256
3372
  const storageDir = storageDirOrNull(storage);
3257
- const storageKey = storageDir ? path5.resolve(storageDir) : `storage-without-dir-${storages.length}`;
3373
+ const storageKey = storageDir ? path6.resolve(storageDir) : `storage-without-dir-${storages.length}`;
3258
3374
  if (seenStorageDirs.has(storageKey)) return;
3259
3375
  seenStorageDirs.add(storageKey);
3260
3376
  storages.push(storage);
@@ -3284,7 +3400,7 @@ var QmdResultResolver = class {
3284
3400
  continue;
3285
3401
  }
3286
3402
  try {
3287
- const coldRoot = path5.join(storageDir, "cold");
3403
+ const coldRoot = path6.join(storageDir, "cold");
3288
3404
  for (const candidate of qmdResultPathCandidates(
3289
3405
  coldRoot,
3290
3406
  parts.relativePath
@@ -3343,9 +3459,9 @@ var QmdResultResolver = class {
3343
3459
  error: err.message
3344
3460
  });
3345
3461
  }
3346
- if (!path5.isAbsolute(resultPath)) return null;
3462
+ if (!path6.isAbsolute(resultPath)) return null;
3347
3463
  }
3348
- if (path5.isAbsolute(resultPath)) {
3464
+ if (path6.isAbsolute(resultPath)) {
3349
3465
  if (!fallbackStorageDir) {
3350
3466
  return await fallbackStorage.readMemoryByPath(resultPath);
3351
3467
  }
@@ -3385,7 +3501,7 @@ var QmdResultResolver = class {
3385
3501
  );
3386
3502
  if (!memory) return null;
3387
3503
  let ownerNamespace = null;
3388
- if (path5.isAbsolute(memory.path)) {
3504
+ if (path6.isAbsolute(memory.path)) {
3389
3505
  const ownerStorage = await this.storageForAbsoluteQmdResultPath(
3390
3506
  memory.path,
3391
3507
  fallbackStorage,
@@ -3409,17 +3525,17 @@ var QmdResultResolver = class {
3409
3525
  };
3410
3526
  }
3411
3527
  async storageForAbsoluteQmdResultPath(resultPath, fallbackStorage, recallNamespaces = []) {
3412
- const resolvedPath = path5.resolve(resultPath);
3528
+ const resolvedPath = path6.resolve(resultPath);
3413
3529
  const config = this.getConfig();
3414
- const memoryRoot = path5.resolve(config.memoryDir);
3415
- const namespacesRoot = path5.join(memoryRoot, "namespaces");
3530
+ const memoryRoot = path6.resolve(config.memoryDir);
3531
+ const namespacesRoot = path6.join(memoryRoot, "namespaces");
3416
3532
  const fallbackStorageDir = storageDirOrNull(fallbackStorage);
3417
3533
  const matches = [];
3418
3534
  const seenDirs = /* @__PURE__ */ new Set();
3419
3535
  const maybeAddStorage = (storage, namespace) => {
3420
3536
  const storageDir = storageDirOrNull(storage);
3421
3537
  if (!storageDir) return;
3422
- const candidateRoot = path5.resolve(storageDir);
3538
+ const candidateRoot = path6.resolve(storageDir);
3423
3539
  if (seenDirs.has(candidateRoot)) return;
3424
3540
  if (!isPathInsideStorageRoot(candidateRoot, resolvedPath)) return;
3425
3541
  if (candidateRoot === memoryRoot && isPathInsideStorageRoot(namespacesRoot, resolvedPath)) {
@@ -3437,7 +3553,7 @@ var QmdResultResolver = class {
3437
3553
  candidateNamespaces.add(ns);
3438
3554
  }
3439
3555
  if (isPathInsideStorageRoot(namespacesRoot, resolvedPath)) {
3440
- const relativeToNamespaces = path5.relative(namespacesRoot, resolvedPath);
3556
+ const relativeToNamespaces = path6.relative(namespacesRoot, resolvedPath);
3441
3557
  const [namespaceSegment] = relativeToNamespaces.split(/[\\/]/);
3442
3558
  if (namespaceSegment) {
3443
3559
  candidateNamespaces.add(
@@ -3981,7 +4097,7 @@ function collectSpeakers(tagged) {
3981
4097
  }
3982
4098
 
3983
4099
  // src/wearables/fusion/fuse.ts
3984
- import { createHash } from "crypto";
4100
+ import { createHash as createHash2 } from "crypto";
3985
4101
  var FUSION_ID_PREFIX = "fusion";
3986
4102
  var FUSION_ALGO_VERSION = "2026-07-12-1";
3987
4103
  function canonicalInputsKey(date, inputs) {
@@ -4010,7 +4126,7 @@ function canonicalInputsKey(date, inputs) {
4010
4126
  ])
4011
4127
  ])
4012
4128
  ];
4013
- return createHash("sha256").update(JSON.stringify(record), "utf-8").digest("hex");
4129
+ return createHash2("sha256").update(JSON.stringify(record), "utf-8").digest("hex");
4014
4130
  }
4015
4131
  function configFingerprint(options, sources) {
4016
4132
  const proximityGapMs = options.proximityGapMs ?? DEFAULT_PROXIMITY_GAP_MS;
@@ -4025,7 +4141,7 @@ function canonicalDayKey(date, inputs, options, algoVersion = FUSION_ALGO_VERSIO
4025
4141
  options,
4026
4142
  inputs.map((conv) => conv.source)
4027
4143
  );
4028
- return createHash("sha256").update(inputsKey).update("\n").update(fingerprint).update("\n").update(algoVersion).digest("hex");
4144
+ return createHash2("sha256").update(inputsKey).update("\n").update(fingerprint).update("\n").update(algoVersion).digest("hex");
4029
4145
  }
4030
4146
  function buildProvenance(cluster, proximityGapMs, windowToleranceMs) {
4031
4147
  return {
@@ -4085,11 +4201,11 @@ function fuseDay(date, inputs, options = {}) {
4085
4201
  }
4086
4202
 
4087
4203
  // src/wearables/fusion/store.ts
4088
- import { createHash as createHash2 } from "crypto";
4089
- import * as path6 from "path";
4204
+ import { createHash as createHash3 } from "crypto";
4205
+ import * as path7 from "path";
4090
4206
  var FUSION_KIND = "wearable-fusion";
4091
4207
  function hashFusionBody(conversations) {
4092
- return createHash2("sha256").update(JSON.stringify(conversations), "utf-8").digest("hex");
4208
+ return createHash3("sha256").update(JSON.stringify(conversations), "utf-8").digest("hex");
4093
4209
  }
4094
4210
  function composeFusionDayMeta(date, conversations, sources, contentHash, fusedAt) {
4095
4211
  return {
@@ -4273,7 +4389,7 @@ var FusionArtifactStore = class {
4273
4389
  `invalid wearable fusion date '${String(date)}' \u2014 expected YYYY-MM-DD`
4274
4390
  );
4275
4391
  }
4276
- return path6.join(this.wearablesDir, FUSION_DIR_NAME, `${date}.md`);
4392
+ return path7.join(this.wearablesDir, FUSION_DIR_NAME, `${date}.md`);
4277
4393
  }
4278
4394
  async writeFusedDay(date, serialized) {
4279
4395
  const filePath = this.fusedDayPath(date);
@@ -4310,7 +4426,7 @@ var FusionArtifactStore = class {
4310
4426
  }
4311
4427
  /** List dates with stored fused artifacts, newest first. */
4312
4428
  async listFusedDays() {
4313
- const fusionDir = path6.join(this.wearablesDir, FUSION_DIR_NAME);
4429
+ const fusionDir = path7.join(this.wearablesDir, FUSION_DIR_NAME);
4314
4430
  await this.assertPathContained(fusionDir);
4315
4431
  let entries;
4316
4432
  try {
@@ -4354,10 +4470,10 @@ var FusionArtifactStore = class {
4354
4470
  try {
4355
4471
  rootReal = await this.io.realpath(this.memoryDir);
4356
4472
  } catch {
4357
- rootReal = path6.resolve(this.memoryDir);
4473
+ rootReal = path7.resolve(this.memoryDir);
4358
4474
  }
4359
4475
  await this.assertNoEscape(rootReal, this.wearablesDir);
4360
- await this.assertNoEscape(rootReal, path6.dirname(targetPath));
4476
+ await this.assertNoEscape(rootReal, path7.dirname(targetPath));
4361
4477
  await this.assertNoEscape(rootReal, targetPath);
4362
4478
  await this.assertFusionDirNotSymlinked();
4363
4479
  }
@@ -4371,7 +4487,7 @@ var FusionArtifactStore = class {
4371
4487
  * (a fresh write creates a real directory lexically under the root).
4372
4488
  */
4373
4489
  async assertFusionDirNotSymlinked() {
4374
- const fusionDir = path6.join(this.wearablesDir, FUSION_DIR_NAME);
4490
+ const fusionDir = path7.join(this.wearablesDir, FUSION_DIR_NAME);
4375
4491
  let stat3;
4376
4492
  try {
4377
4493
  stat3 = await this.io.lstat(fusionDir);
@@ -4506,8 +4622,8 @@ function reconstructFusionInputs(date, dayTranscripts) {
4506
4622
  }
4507
4623
 
4508
4624
  // src/meetings/store.ts
4509
- import { createHash as createHash3 } from "crypto";
4510
- import * as path7 from "path";
4625
+ import { createHash as createHash4 } from "crypto";
4626
+ import * as path8 from "path";
4511
4627
  var MEETINGS_DIR_NAME = "meetings";
4512
4628
  var MEETING_KIND = "meeting";
4513
4629
  var MEETING_FORMAT_VERSION = 1;
@@ -4537,7 +4653,7 @@ function canonicalContent(base, fused) {
4537
4653
  });
4538
4654
  }
4539
4655
  function composeMeetingRecord(base, fused) {
4540
- const contentHash = createHash3("sha256").update(canonicalContent(base, fused), "utf-8").digest("hex");
4656
+ const contentHash = createHash4("sha256").update(canonicalContent(base, fused), "utf-8").digest("hex");
4541
4657
  return {
4542
4658
  ...base,
4543
4659
  ...fused,
@@ -4676,7 +4792,7 @@ var MeetingRecordStore = class {
4676
4792
  constructor(memoryDir, io) {
4677
4793
  this.memoryDir = memoryDir;
4678
4794
  this.io = io;
4679
- this.meetingsDir = path7.join(memoryDir, MEETINGS_DIR_NAME);
4795
+ this.meetingsDir = path8.join(memoryDir, MEETINGS_DIR_NAME);
4680
4796
  }
4681
4797
  memoryDir;
4682
4798
  io;
@@ -4692,7 +4808,7 @@ var MeetingRecordStore = class {
4692
4808
  if (idDate !== date) {
4693
4809
  throw new Error(`meeting id '${id}' does not belong to date '${date}'`);
4694
4810
  }
4695
- return path7.join(this.meetingsDir, date, `${id}.md`);
4811
+ return path8.join(this.meetingsDir, date, `${id}.md`);
4696
4812
  }
4697
4813
  /** Idempotently persist a record: skip the write when contentHash is unchanged. */
4698
4814
  async saveMeetingRecord(record) {
@@ -4723,7 +4839,7 @@ var MeetingRecordStore = class {
4723
4839
  if (!isValidTranscriptDate(date)) {
4724
4840
  throw new Error(`invalid meeting date '${String(date)}' \u2014 expected YYYY-MM-DD`);
4725
4841
  }
4726
- const dayDir = path7.join(this.meetingsDir, date);
4842
+ const dayDir = path8.join(this.meetingsDir, date);
4727
4843
  await this.assertPathContained(dayDir);
4728
4844
  let entries;
4729
4845
  try {
@@ -4791,10 +4907,10 @@ var MeetingRecordStore = class {
4791
4907
  try {
4792
4908
  rootReal = await this.io.realpath(this.memoryDir);
4793
4909
  } catch {
4794
- rootReal = path7.resolve(this.memoryDir);
4910
+ rootReal = path8.resolve(this.memoryDir);
4795
4911
  }
4796
4912
  await this.assertNoEscape(rootReal, this.meetingsDir);
4797
- await this.assertNoEscape(rootReal, path7.dirname(targetPath));
4913
+ await this.assertNoEscape(rootReal, path8.dirname(targetPath));
4798
4914
  await this.assertNoEscape(rootReal, targetPath);
4799
4915
  await this.assertNotSymlink(this.meetingsDir, "directory");
4800
4916
  const dayDir = this.dayDirWithin(targetPath);
@@ -4804,11 +4920,11 @@ var MeetingRecordStore = class {
4804
4920
  /** The `<meetings>/<date>` directory on the path to `targetPath`, or null when
4805
4921
  * `targetPath` is the meetings root itself. */
4806
4922
  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];
4923
+ const rel = path8.relative(this.meetingsDir, targetPath);
4924
+ if (rel === "" || rel.startsWith("..") || path8.isAbsolute(rel)) return null;
4925
+ const first = rel.split(path8.sep)[0];
4810
4926
  if (first === void 0 || first.length === 0) return null;
4811
- return path7.join(this.meetingsDir, first);
4927
+ return path8.join(this.meetingsDir, first);
4812
4928
  }
4813
4929
  async assertNotSymlink(target, kind) {
4814
4930
  let stat3;
@@ -4819,7 +4935,7 @@ var MeetingRecordStore = class {
4819
4935
  throw err;
4820
4936
  }
4821
4937
  if (stat3.isSymbolicLink) {
4822
- const label = path7.relative(this.memoryDir, target) || MEETINGS_DIR_NAME;
4938
+ const label = path8.relative(this.memoryDir, target) || MEETINGS_DIR_NAME;
4823
4939
  throw new Error(
4824
4940
  `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
4941
  );
@@ -4923,7 +5039,7 @@ function stripCitationMarkersForHashRemoval(value, template) {
4923
5039
  }
4924
5040
 
4925
5041
  // src/storage/entity-timeline.ts
4926
- import { createHash as createHash4 } from "crypto";
5042
+ import { createHash as createHash5 } from "crypto";
4927
5043
  function parseEntityTimelineBullet(bullet, fallbackTimestamp) {
4928
5044
  const trimmed = bullet.trim();
4929
5045
  if (!trimmed) return null;
@@ -5295,7 +5411,7 @@ function fingerprintEntityStructuredFacts(entity) {
5295
5411
  (left, right) => left.key.localeCompare(right.key) || left.title.localeCompare(right.title) || left.facts.join("\n").localeCompare(right.facts.join("\n"))
5296
5412
  );
5297
5413
  if (normalizedSections.length === 0) return void 0;
5298
- return createHash4("sha256").update(JSON.stringify(normalizedSections)).digest("hex");
5414
+ return createHash5("sha256").update(JSON.stringify(normalizedSections)).digest("hex");
5299
5415
  }
5300
5416
  function isEntitySynthesisStale(entity) {
5301
5417
  const structuredFactCount = countEntityStructuredFacts(entity);
@@ -5346,6 +5462,15 @@ var ARTIFACT_SEARCH_STOPWORDS = /* @__PURE__ */ new Set([
5346
5462
  "were",
5347
5463
  "with"
5348
5464
  ]);
5465
+ var DELETION_REVISION_MAX_MTIME_MS = 864e13;
5466
+ var DELETION_REVISION_LOCK_STALE_MS = 6e4;
5467
+ var DELETION_REVISION_LOCK_MAX_WAIT_MS = 12e4;
5468
+ function isValidDeletionRevisionPath(value) {
5469
+ 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("../");
5470
+ }
5471
+ function deletionRevisionPathIdentity(value) {
5472
+ return value.normalize("NFC").toUpperCase().toLowerCase().replace(/\u00df/g, "ss");
5473
+ }
5349
5474
  function tokenizeArtifactSearchText(input) {
5350
5475
  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
5476
  }
@@ -5390,6 +5515,7 @@ function serializeFrontmatter(fm) {
5390
5515
  const safe = /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(fm.sourceConnector);
5391
5516
  lines.push(`sourceConnector: ${safe ? fm.sourceConnector : JSON.stringify(fm.sourceConnector)}`);
5392
5517
  }
5518
+ if (fm.toolScoped === true) lines.push("toolScoped: true");
5393
5519
  if (fm.supersedes) lines.push(`supersedes: ${fm.supersedes}`);
5394
5520
  if (fm.expiresAt) lines.push(`expiresAt: ${fm.expiresAt}`);
5395
5521
  if (fm.lineage && fm.lineage.length > 0) {
@@ -5599,7 +5725,7 @@ function parseReinforcementCountField(raw) {
5599
5725
  return n;
5600
5726
  }
5601
5727
  function parseFrontmatter(raw) {
5602
- const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
5728
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/);
5603
5729
  if (!match) return null;
5604
5730
  const fmBlock = match[1];
5605
5731
  const content = match[2].trim();
@@ -5773,6 +5899,7 @@ function parseFrontmatter(raw) {
5773
5899
  tags,
5774
5900
  entityRef: fm.entityRef || void 0,
5775
5901
  sourceConnector: fm.sourceConnector ? decodeYamlScalar(fm.sourceConnector) || void 0 : void 0,
5902
+ toolScoped: fm.toolScoped === "true" ? true : void 0,
5776
5903
  supersedes: fm.supersedes || void 0,
5777
5904
  expiresAt: fm.expiresAt || void 0,
5778
5905
  lineage: lineage && lineage.length > 0 ? lineage : void 0,
@@ -5861,17 +5988,17 @@ function inferEntityTypeFromContent(content) {
5861
5988
  }
5862
5989
  var KNOWN_ENTITY_FILENAME_PREFIXES = /* @__PURE__ */ new Set(["company", "other", "person", "place", "project", "tool", "topic"]);
5863
5990
  function inferEntityTypeFromFilename(pathRel) {
5864
- const basename = path8.basename(pathRel, ".md").toLowerCase();
5991
+ const basename = path9.basename(pathRel, ".md").toLowerCase();
5865
5992
  const separator = basename.indexOf("-");
5866
5993
  if (separator <= 0) return void 0;
5867
5994
  const candidate = basename.slice(0, separator);
5868
5995
  return KNOWN_ENTITY_FILENAME_PREFIXES.has(candidate) ? candidate : void 0;
5869
5996
  }
5870
5997
  function normalizeFrontmatterForPath(frontmatter, pathRel, content = "") {
5871
- const normalizedPath = pathRel.split(path8.sep).join("/");
5998
+ const normalizedPath = pathRel.split(path9.sep).join("/");
5872
5999
  let normalizedFrontmatter = frontmatter;
5873
6000
  if (normalizedPath === "entities" || normalizedPath.startsWith("entities/") || normalizedPath.includes("/entities/")) {
5874
- const basename = path8.basename(pathRel, ".md");
6001
+ const basename = path9.basename(pathRel, ".md");
5875
6002
  const inferredType = inferEntityTypeFromContent(content) || inferEntityTypeFromFilename(pathRel) || "entity";
5876
6003
  const existingTags = Array.isArray(frontmatter.tags) ? frontmatter.tags : [];
5877
6004
  normalizedFrontmatter = {
@@ -6519,8 +6646,8 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6519
6646
  }
6520
6647
  /** Whether `filePath` resolves to `stateDir` itself or a path contained in it. */
6521
6648
  isStateFilePath(filePath) {
6522
- const rel = path8.relative(this.stateDir, path8.resolve(filePath));
6523
- return rel === "" || !rel.startsWith("..") && !path8.isAbsolute(rel);
6649
+ const rel = path9.relative(this.stateDir, path9.resolve(filePath));
6650
+ return rel === "" || !rel.startsWith("..") && !path9.isAbsolute(rel);
6524
6651
  }
6525
6652
  // ── Tombstone store (issue #1579) ───────────────────────────────────────
6526
6653
  // Instance-scoped (rule 11) + namespace-scoped (rule 42) tombstone index.
@@ -6572,9 +6699,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6572
6699
  setSecureStoreKey(key, encryptOnWrite = true) {
6573
6700
  if (!this.applySecureStoreKey(key, encryptOnWrite) || key === null) return;
6574
6701
  void this.entityCanonicalIdMigration.triggerAfterUnlock().catch((error) => {
6575
- log.warn(
6576
- `secure-store unlock migration failed: ${error instanceof Error ? error.message : String(error)}`
6577
- );
6702
+ log.warn(`secure-store unlock migration failed: ${error instanceof Error ? error.message : String(error)}`);
6578
6703
  });
6579
6704
  }
6580
6705
  async setSecureStoreKeyAndWait(key, encryptOnWrite = true) {
@@ -6637,8 +6762,8 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6637
6762
  * /srv/cold/remnic), skipping the patch and stranding a stale hot entry.
6638
6763
  */
6639
6764
  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}`);
6765
+ const rel = path9.relative(this.baseDir, p);
6766
+ return rel === "cold" || rel === "archive" || rel.startsWith(`cold${path9.sep}`) || rel.startsWith(`archive${path9.sep}`);
6642
6767
  }
6643
6768
  /**
6644
6769
  * Mark the secure-store as required for this storage instance.
@@ -6725,7 +6850,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6725
6850
  void 0,
6726
6851
  this.baseDir
6727
6852
  );
6728
- const rel = path8.relative(this.baseDir, filePath).split(path8.sep).join("/");
6853
+ const rel = path9.relative(this.baseDir, filePath).split(path9.sep).join("/");
6729
6854
  return `${rel}:${version.versionId}`;
6730
6855
  } catch (err) {
6731
6856
  log.warn(
@@ -6805,12 +6930,12 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6805
6930
  }
6806
6931
  identityFilePath(workspaceDir, namespace) {
6807
6932
  const rawNamespace = typeof namespace === "string" ? namespace.trim() : "";
6808
- if (!rawNamespace) return path8.join(workspaceDir, "IDENTITY.md");
6933
+ if (!rawNamespace) return path9.join(workspaceDir, "IDENTITY.md");
6809
6934
  const safeNamespace = rawNamespace.replace(/[^a-zA-Z0-9._-]/g, "-");
6810
- return path8.join(workspaceDir, `IDENTITY.${safeNamespace}.md`);
6935
+ return path9.join(workspaceDir, `IDENTITY.${safeNamespace}.md`);
6811
6936
  }
6812
6937
  versionFilePath(kind) {
6813
- return path8.join(this.stateDir, `.${kind}-version.log`);
6938
+ return path9.join(this.stateDir, `.${kind}-version.log`);
6814
6939
  }
6815
6940
  bumpSharedVersion(kind, fallbackMap) {
6816
6941
  const filePath = this.versionFilePath(kind);
@@ -6843,14 +6968,13 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6843
6968
  return this.readSharedVersion("memory-status", _StorageManager.memoryStatusVersionByDir);
6844
6969
  }
6845
6970
  /**
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).
6971
+ * Entity content revision used by migration discovery and entity-page cache coherence.
6849
6972
  */
6850
6973
  getEntityMutationVersion() {
6851
6974
  return this.readSharedVersion("entity-mutation", _StorageManager.entityMutationVersionByDir);
6852
6975
  }
6853
6976
  bumpEntityMutationVersion() {
6977
+ invalidateForScope(this.baseDir, "entity-write");
6854
6978
  this.bumpSharedVersion("entity-mutation", _StorageManager.entityMutationVersionByDir);
6855
6979
  }
6856
6980
  /**
@@ -6908,7 +7032,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6908
7032
  // memories.
6909
7033
  // -------------------------------------------------------------------------
6910
7034
  get wearablesDir() {
6911
- return path8.join(this.baseDir, WEARABLES_DIR_NAME);
7035
+ return path9.join(this.baseDir, WEARABLES_DIR_NAME);
6912
7036
  }
6913
7037
  /**
6914
7038
  * Resolve the on-disk path for a source/day transcript. Throws on
@@ -6924,7 +7048,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
6924
7048
  if (!isValidTranscriptDate(date)) {
6925
7049
  throw new Error(`invalid wearable transcript date '${String(date)}' \u2014 expected YYYY-MM-DD`);
6926
7050
  }
6927
- return path8.join(this.wearablesDir, sourceId, `${date}.md`);
7051
+ return path9.join(this.wearablesDir, sourceId, `${date}.md`);
6928
7052
  }
6929
7053
  async writeWearableDayTranscript(sourceId, date, serialized) {
6930
7054
  const targetPath = this.wearableTranscriptPath(sourceId, date);
@@ -7040,25 +7164,25 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7040
7164
  });
7041
7165
  }
7042
7166
  get factsDir() {
7043
- return path8.join(this.baseDir, "facts");
7167
+ return path9.join(this.baseDir, "facts");
7044
7168
  }
7045
7169
  get correctionsDir() {
7046
- return path8.join(this.baseDir, "corrections");
7170
+ return path9.join(this.baseDir, "corrections");
7047
7171
  }
7048
7172
  get proceduresDir() {
7049
- return path8.join(this.baseDir, "procedures");
7173
+ return path9.join(this.baseDir, "procedures");
7050
7174
  }
7051
7175
  get reasoningTracesDir() {
7052
- return path8.join(this.baseDir, "reasoning-traces");
7176
+ return path9.join(this.baseDir, "reasoning-traces");
7053
7177
  }
7054
7178
  get entitiesDir() {
7055
- return path8.join(this.baseDir, "entities");
7179
+ return path9.join(this.baseDir, "entities");
7056
7180
  }
7057
7181
  resolveEntityFilePath(name) {
7058
7182
  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)) {
7183
+ const filePath = path9.resolve(this.entitiesDir, `${name}.md`);
7184
+ const relative2 = path9.relative(this.entitiesDir, filePath);
7185
+ if (relative2 === "" || relative2.startsWith("..") || path9.isAbsolute(relative2)) {
7062
7186
  return null;
7063
7187
  }
7064
7188
  return filePath;
@@ -7073,14 +7197,186 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7073
7197
  });
7074
7198
  }
7075
7199
  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)) {
7200
+ const resolved = path9.resolve(filePath);
7201
+ const base = path9.resolve(this.baseDir);
7202
+ const rel = path9.relative(base, resolved);
7203
+ if (rel === "" || rel === ".." || rel.startsWith(`..${path9.sep}`) || path9.isAbsolute(rel)) {
7080
7204
  throw new Error(`${method}: file path escapes memory dir`);
7081
7205
  }
7082
7206
  return resolved;
7083
7207
  }
7208
+ parseDeletionRevisionMetadata(raw) {
7209
+ let parsed;
7210
+ try {
7211
+ parsed = JSON.parse(raw);
7212
+ } catch {
7213
+ throw new Error("Deletion revision metadata is invalid.");
7214
+ }
7215
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
7216
+ throw new Error("Deletion revision metadata is invalid.");
7217
+ }
7218
+ const root = parsed;
7219
+ if (Object.keys(root).sort().join(",") !== "deletions,version" || root.version !== 1 || !Array.isArray(root.deletions)) {
7220
+ throw new Error("Deletion revision metadata is invalid.");
7221
+ }
7222
+ const revisions = /* @__PURE__ */ new Map();
7223
+ const pathByIdentity = /* @__PURE__ */ new Map();
7224
+ for (const rawEntry of root.deletions) {
7225
+ if (!rawEntry || typeof rawEntry !== "object" || Array.isArray(rawEntry)) {
7226
+ throw new Error("Deletion revision metadata is invalid.");
7227
+ }
7228
+ const entry = rawEntry;
7229
+ 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)) {
7230
+ throw new Error("Deletion revision metadata is invalid.");
7231
+ }
7232
+ const identity = deletionRevisionPathIdentity(entry.path);
7233
+ if (pathByIdentity.has(identity)) {
7234
+ throw new Error("Deletion revision metadata is invalid.");
7235
+ }
7236
+ pathByIdentity.set(identity, entry.path);
7237
+ revisions.set(entry.path, entry.mtimeMs);
7238
+ }
7239
+ return new Map([...revisions.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
7240
+ }
7241
+ async readDeletionRevisionMetadata() {
7242
+ let raw;
7243
+ try {
7244
+ raw = await readFile2(this.deletionRevisionMetadataPath, "utf8");
7245
+ } catch (error) {
7246
+ if (isErrnoCode(error, "ENOENT")) return /* @__PURE__ */ new Map();
7247
+ throw new Error("Deletion revision metadata is unavailable.");
7248
+ }
7249
+ return this.parseDeletionRevisionMetadata(raw);
7250
+ }
7251
+ async writeDeletionRevisionMetadata(revisions, lock) {
7252
+ const deletions = [...revisions.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([entryPath, mtimeMs]) => ({ path: entryPath, mtimeMs }));
7253
+ const metadata = { version: 1, deletions };
7254
+ const temporaryPath = `${this.deletionRevisionMetadataPath}.${process.pid}.${randomUUID2()}.tmp`;
7255
+ let handle = null;
7256
+ try {
7257
+ handle = await open(temporaryPath, "wx", 384);
7258
+ await handle.writeFile(`${JSON.stringify(metadata)}
7259
+ `, "utf8");
7260
+ await handle.sync();
7261
+ await handle.close();
7262
+ handle = null;
7263
+ if (!await lock.refresh()) {
7264
+ throw new Error("Deletion revision metadata lock was lost.");
7265
+ }
7266
+ await rename2(temporaryPath, this.deletionRevisionMetadataPath);
7267
+ } finally {
7268
+ if (handle !== null) await handle.close().catch(() => void 0);
7269
+ await unlink4(temporaryPath).catch((error) => {
7270
+ if (!isErrnoCode(error, "ENOENT")) throw error;
7271
+ });
7272
+ }
7273
+ }
7274
+ async withDeletionRevisionLock(task) {
7275
+ return withHeldFileLock(
7276
+ this.deletionRevisionLockPath,
7277
+ {
7278
+ staleMs: DELETION_REVISION_LOCK_STALE_MS,
7279
+ maxWaitMs: DELETION_REVISION_LOCK_MAX_WAIT_MS
7280
+ },
7281
+ async (acquired, lock) => {
7282
+ if (!acquired) throw new Error("Deletion revision metadata lock is unavailable.");
7283
+ return task(lock);
7284
+ }
7285
+ );
7286
+ }
7287
+ async readDeletionRevisions() {
7288
+ return this.withDeletionRevisionLock(async () => this.readDeletionRevisionMetadata());
7289
+ }
7290
+ async recordReplicatedDeletionRevision(filePath, mtimeMs) {
7291
+ const target = this.assertManagedStoragePath(filePath, "storage.recordReplicatedDeletionRevision");
7292
+ if (typeof mtimeMs !== "number" || !Number.isFinite(mtimeMs) || mtimeMs < 0 || mtimeMs > DELETION_REVISION_MAX_MTIME_MS) {
7293
+ throw new Error("Deletion revision timestamp is invalid.");
7294
+ }
7295
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7296
+ if (!isValidDeletionRevisionPath(relativePath)) {
7297
+ throw new Error("Deletion revision path is invalid.");
7298
+ }
7299
+ await this.withDeletionRevisionLock(async (lock) => {
7300
+ const revisions = await this.readDeletionRevisionMetadata();
7301
+ const identity = deletionRevisionPathIdentity(relativePath);
7302
+ let existingPath;
7303
+ for (const candidatePath of revisions.keys()) {
7304
+ if (deletionRevisionPathIdentity(candidatePath) === identity) {
7305
+ existingPath = candidatePath;
7306
+ break;
7307
+ }
7308
+ }
7309
+ const existingMtimeMs = existingPath === void 0 ? void 0 : revisions.get(existingPath);
7310
+ if (existingMtimeMs !== void 0 && existingMtimeMs >= mtimeMs) return;
7311
+ const updated = new Map(revisions);
7312
+ if (existingPath !== void 0) updated.delete(existingPath);
7313
+ updated.set(relativePath, mtimeMs);
7314
+ await this.writeDeletionRevisionMetadata(updated, lock);
7315
+ });
7316
+ }
7317
+ async writeManagedStorageFile(filePath, write) {
7318
+ const target = this.assertManagedStoragePath(filePath, "storage.writeManagedStorageFile");
7319
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7320
+ if (!isValidDeletionRevisionPath(relativePath)) {
7321
+ throw new Error("Deletion revision path is invalid.");
7322
+ }
7323
+ await this.withDeletionRevisionLock(async (lock) => {
7324
+ const before = await this.readDeletionRevisionMetadata();
7325
+ const identity = deletionRevisionPathIdentity(relativePath);
7326
+ const existingPath = [...before.keys()].find(
7327
+ (candidatePath) => deletionRevisionPathIdentity(candidatePath) === identity
7328
+ );
7329
+ await write();
7330
+ if (existingPath === void 0) return;
7331
+ const updated = new Map(before);
7332
+ updated.delete(existingPath);
7333
+ await this.writeDeletionRevisionMetadata(updated, lock);
7334
+ });
7335
+ }
7336
+ async deleteManagedStorageFile(filePath, deletionMtimeMs) {
7337
+ const target = this.assertManagedStoragePath(filePath, "storage.deleteManagedStorageFile");
7338
+ if (deletionMtimeMs !== void 0 && deletionMtimeMs !== null && (typeof deletionMtimeMs !== "number" || !Number.isFinite(deletionMtimeMs) || deletionMtimeMs < 0 || deletionMtimeMs > DELETION_REVISION_MAX_MTIME_MS)) {
7339
+ throw new Error("Deletion revision timestamp is invalid.");
7340
+ }
7341
+ return this.withDeletionRevisionLock(async (lock) => {
7342
+ try {
7343
+ await lstat3(target);
7344
+ } catch (error) {
7345
+ if (isErrnoCode(error, "ENOENT")) return false;
7346
+ throw error;
7347
+ }
7348
+ const relativePath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7349
+ if (!isValidDeletionRevisionPath(relativePath)) {
7350
+ throw new Error("Deletion revision path is invalid.");
7351
+ }
7352
+ const revision = deletionMtimeMs === null ? void 0 : deletionMtimeMs ?? Date.now();
7353
+ const before = await this.readDeletionRevisionMetadata();
7354
+ const identity = deletionRevisionPathIdentity(relativePath);
7355
+ let existingPath;
7356
+ for (const candidatePath of before.keys()) {
7357
+ if (deletionRevisionPathIdentity(candidatePath) === identity) {
7358
+ existingPath = candidatePath;
7359
+ break;
7360
+ }
7361
+ }
7362
+ const existing = existingPath === void 0 ? void 0 : before.get(existingPath);
7363
+ const changed = existingPath !== void 0 && existingPath !== relativePath || (revision === void 0 ? existing !== void 0 : existing !== revision);
7364
+ if (changed) {
7365
+ const updated = new Map(before);
7366
+ if (existingPath !== void 0) updated.delete(existingPath);
7367
+ if (revision !== void 0) updated.set(relativePath, revision);
7368
+ await this.writeDeletionRevisionMetadata(updated, lock);
7369
+ }
7370
+ try {
7371
+ await unlink4(target);
7372
+ return true;
7373
+ } catch (error) {
7374
+ if (changed) await this.writeDeletionRevisionMetadata(before, lock);
7375
+ if (isErrnoCode(error, "ENOENT")) return false;
7376
+ throw error;
7377
+ }
7378
+ });
7379
+ }
7084
7380
  async readOfflineSyncFile(filePath) {
7085
7381
  const target = this.assertManagedStoragePath(filePath, "storage.readOfflineSyncFile");
7086
7382
  return readMaybeEncryptedFileBuffer(target, this._secureStoreKey, this.baseDir);
@@ -7088,7 +7384,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7088
7384
  async digestOfflineSyncFile(filePath) {
7089
7385
  const target = this.assertManagedStoragePath(filePath, "storage.digestOfflineSyncFile");
7090
7386
  const st = await stat2(target);
7091
- const relPath = path8.relative(this.baseDir, target).split(path8.sep).join("/");
7387
+ const relPath = path9.relative(this.baseDir, target).split(path9.sep).join("/");
7092
7388
  const cache = await this.loadOfflineSyncDigestCache();
7093
7389
  const cached = cache.get(relPath);
7094
7390
  if (cached && cached.statBytes === st.size && cached.mtimeMs === st.mtimeMs && cached.ctimeMs === st.ctimeMs && !cached.encrypted) {
@@ -7102,11 +7398,11 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7102
7398
  if (encrypted) {
7103
7399
  const content = await readMaybeEncryptedFileBuffer(target, this._secureStoreKey, this.baseDir);
7104
7400
  digest = {
7105
- sha256: createHash5("sha256").update(content).digest("hex"),
7401
+ sha256: createHash6("sha256").update(content).digest("hex"),
7106
7402
  bytes: content.byteLength
7107
7403
  };
7108
7404
  } else {
7109
- const hash = createHash5("sha256");
7405
+ const hash = createHash6("sha256");
7110
7406
  let bytes = 0;
7111
7407
  for await (const rawChunk of createReadStream(target)) {
7112
7408
  const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
@@ -7149,7 +7445,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7149
7445
  const bytes = typeof record.bytes === "number" ? record.bytes : NaN;
7150
7446
  const sha256 = typeof record.sha256 === "string" ? record.sha256 : "";
7151
7447
  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)) {
7448
+ 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
7449
  continue;
7154
7450
  }
7155
7451
  cache.set(cachePath, { statBytes, mtimeMs, ctimeMs, encrypted, sha256, bytes });
@@ -7191,7 +7487,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7191
7487
  const cache = this.offlineSyncDigestCache;
7192
7488
  if (!cache) return;
7193
7489
  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 });
7490
+ await mkdir(path9.dirname(this.offlineSyncDigestCachePath), { recursive: true });
7195
7491
  await writeFile2(this.offlineSyncDigestCachePath, `${JSON.stringify({ version: 1, entries })}
7196
7492
  `, "utf-8");
7197
7493
  }).catch((err) => {
@@ -7280,7 +7576,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7280
7576
  }
7281
7577
  async appendStorageSecureFileUnlocked(filePath, content) {
7282
7578
  const writeKey = this.resolveWriteKey();
7283
- await mkdir(path8.dirname(filePath), { recursive: true });
7579
+ await mkdir(path9.dirname(filePath), { recursive: true });
7284
7580
  if (writeKey === null) {
7285
7581
  try {
7286
7582
  if (await this.isEncryptedFileHeader(filePath)) {
@@ -7306,13 +7602,19 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7306
7602
  this.notifyCatalogWriteForPath(filePath);
7307
7603
  }
7308
7604
  get stateDir() {
7309
- return path8.join(this.baseDir, "state");
7605
+ return path9.join(this.baseDir, "state");
7310
7606
  }
7311
7607
  get offlineSyncDigestCachePath() {
7312
- return path8.join(this.baseDir, ".offline-sync", "digest-cache.v1.json");
7608
+ return path9.join(this.baseDir, ".offline-sync", "digest-cache.v1.json");
7609
+ }
7610
+ get deletionRevisionMetadataPath() {
7611
+ return path9.join(this.baseDir, ".offline-sync", "deletion-revisions.v1.json");
7612
+ }
7613
+ get deletionRevisionLockPath() {
7614
+ return `${this.deletionRevisionMetadataPath}.lock`;
7313
7615
  }
7314
7616
  get entitySynthesisQueuePath() {
7315
- return path8.join(this.stateDir, "entity-synthesis-queue.json");
7617
+ return path9.join(this.stateDir, "entity-synthesis-queue.json");
7316
7618
  }
7317
7619
  // ── Tombstone store access (issue #1579) ─────────────────────────────────
7318
7620
  /**
@@ -7322,7 +7624,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7322
7624
  * helpers are injected into the store).
7323
7625
  */
7324
7626
  get tombstonesPath() {
7325
- return path8.join(this.stateDir, "tombstones.jsonl");
7627
+ return path9.join(this.stateDir, "tombstones.jsonl");
7326
7628
  }
7327
7629
  /**
7328
7630
  * Configure the tombstone invariant for this storage instance. Installed
@@ -7619,55 +7921,55 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7619
7921
  return null;
7620
7922
  }
7621
7923
  get questionsDir() {
7622
- return path8.join(this.baseDir, "questions");
7924
+ return path9.join(this.baseDir, "questions");
7623
7925
  }
7624
7926
  get artifactsDir() {
7625
- return path8.join(this.baseDir, "artifacts");
7927
+ return path9.join(this.baseDir, "artifacts");
7626
7928
  }
7627
7929
  get identityDir() {
7628
- return path8.join(this.baseDir, "identity");
7930
+ return path9.join(this.baseDir, "identity");
7629
7931
  }
7630
7932
  get identityAnchorPath() {
7631
- return path8.join(this.identityDir, "identity-anchor.md");
7933
+ return path9.join(this.identityDir, "identity-anchor.md");
7632
7934
  }
7633
7935
  get identityIncidentsDir() {
7634
- return path8.join(this.identityDir, "incidents");
7936
+ return path9.join(this.identityDir, "incidents");
7635
7937
  }
7636
7938
  get identityAuditsWeeklyDir() {
7637
- return path8.join(this.identityDir, "audits", "weekly");
7939
+ return path9.join(this.identityDir, "audits", "weekly");
7638
7940
  }
7639
7941
  get identityAuditsMonthlyDir() {
7640
- return path8.join(this.identityDir, "audits", "monthly");
7942
+ return path9.join(this.identityDir, "audits", "monthly");
7641
7943
  }
7642
7944
  get identityImprovementLoopsPath() {
7643
- return path8.join(this.identityDir, "improvement-loops.md");
7945
+ return path9.join(this.identityDir, "improvement-loops.md");
7644
7946
  }
7645
7947
  get identityReflectionsPath() {
7646
- return path8.join(this.identityDir, "reflections.md");
7948
+ return path9.join(this.identityDir, "reflections.md");
7647
7949
  }
7648
7950
  get profilePath() {
7649
- return path8.join(this.baseDir, "profile.md");
7951
+ return path9.join(this.baseDir, "profile.md");
7650
7952
  }
7651
7953
  get memoryActionsPath() {
7652
- return path8.join(this.stateDir, "memory-actions.jsonl");
7954
+ return path9.join(this.stateDir, "memory-actions.jsonl");
7653
7955
  }
7654
7956
  get memoryLifecycleLedgerPath() {
7655
- return path8.join(this.stateDir, "memory-lifecycle-ledger.jsonl");
7957
+ return path9.join(this.stateDir, "memory-lifecycle-ledger.jsonl");
7656
7958
  }
7657
7959
  get compressionGuidelinesPath() {
7658
- return path8.join(this.stateDir, "compression-guidelines.md");
7960
+ return path9.join(this.stateDir, "compression-guidelines.md");
7659
7961
  }
7660
7962
  get compressionGuidelineDraftPath() {
7661
- return path8.join(this.stateDir, "compression-guidelines.draft.md");
7963
+ return path9.join(this.stateDir, "compression-guidelines.draft.md");
7662
7964
  }
7663
7965
  get compressionGuidelineStatePath() {
7664
- return path8.join(this.stateDir, "compression-guideline-state.json");
7966
+ return path9.join(this.stateDir, "compression-guideline-state.json");
7665
7967
  }
7666
7968
  get compressionGuidelineDraftStatePath() {
7667
- return path8.join(this.stateDir, "compression-guideline-draft-state.json");
7969
+ return path9.join(this.stateDir, "compression-guideline-draft-state.json");
7668
7970
  }
7669
7971
  get behaviorSignalsPath() {
7670
- return path8.join(this.stateDir, "behavior-signals.jsonl");
7972
+ return path9.join(this.stateDir, "behavior-signals.jsonl");
7671
7973
  }
7672
7974
  /**
7673
7975
  * In-memory dedup key set for behavior-signals appends (issue #1909),
@@ -7699,7 +8001,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7699
8001
  * governance sweeps can treat it uniformly.
7700
8002
  */
7701
8003
  get bufferSurpriseLedgerPath() {
7702
- return path8.join(this.stateDir, "buffer-surprise-ledger.jsonl");
8004
+ return path9.join(this.stateDir, "buffer-surprise-ledger.jsonl");
7703
8005
  }
7704
8006
  /**
7705
8007
  * Entity alias table loaded from THIS store's config/aliases.json.
@@ -7760,25 +8062,29 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7760
8062
  this.loadAliasesSync();
7761
8063
  }
7762
8064
  loadAliasesSync() {
7763
- const aliasPath = path8.join(this.baseDir, "config", "aliases.json");
8065
+ const aliasPath = path9.join(this.baseDir, "config", "aliases.json");
7764
8066
  this.userAliases = {};
8067
+ const raw = readEntityAliasConfigSync(this.baseDir);
8068
+ if (raw === void 0) return;
8069
+ let parsed;
7765
8070
  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
- }
8071
+ parsed = JSON.parse(raw);
8072
+ } catch {
8073
+ log.debug("invalid config/aliases.json \u2014 using built-in aliases only");
8074
+ return;
8075
+ }
8076
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
8077
+ const cleaned = {};
8078
+ for (const [key, value] of Object.entries(parsed)) {
8079
+ if (typeof value === "string" && value.trim().length > 0) {
8080
+ assertSafeEntityId(value);
8081
+ cleaned[key] = value;
7774
8082
  }
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
8083
  }
7780
- } catch {
7781
- log.debug("no config/aliases.json found \u2014 using built-in aliases only");
8084
+ this.userAliases = cleaned;
8085
+ log.debug(`loaded ${Object.keys(cleaned).length} entity aliases from ${aliasPath}`);
8086
+ } else {
8087
+ log.warn(`ignoring ${aliasPath}: payload must be a JSON object mapping variant \u2192 canonical strings`);
7782
8088
  }
7783
8089
  }
7784
8090
  async runLegacyEntityCanonicalIdMigration() {
@@ -7794,9 +8100,9 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7794
8100
  await mkdir(this.baseDir, { recursive: true });
7795
8101
  await validateRoots(this.baseDir, this.entitiesDir, this.stateDir, this.archiveDir);
7796
8102
  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 });
8103
+ await mkdir(path9.join(this.factsDir, today), { recursive: true });
8104
+ await mkdir(path9.join(this.proceduresDir, today), { recursive: true });
8105
+ await mkdir(path9.join(this.reasoningTracesDir, today), { recursive: true });
7800
8106
  await mkdir(this.correctionsDir, { recursive: true });
7801
8107
  await mkdir(this.entitiesDir, { recursive: true });
7802
8108
  await mkdir(this.stateDir, { recursive: true });
@@ -7806,7 +8112,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7806
8112
  await mkdir(this.identityIncidentsDir, { recursive: true });
7807
8113
  await mkdir(this.identityAuditsWeeklyDir, { recursive: true });
7808
8114
  await mkdir(this.identityAuditsMonthlyDir, { recursive: true });
7809
- await mkdir(path8.join(this.baseDir, "config"), { recursive: true });
8115
+ await mkdir(path9.join(this.baseDir, "config"), { recursive: true });
7810
8116
  await this.entityCanonicalIdMigration.ensure();
7811
8117
  if (this.hotMemoriesCacheEnabled && this.getMemoryCorpusVersion() === 0) {
7812
8118
  this.bumpMemoryCorpusVersion();
@@ -7828,11 +8134,11 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7828
8134
  async resolveCategoryWritePath(category, id, today) {
7829
8135
  if (category === "correction") {
7830
8136
  await mkdir(this.correctionsDir, { recursive: true });
7831
- return path8.join(this.correctionsDir, `${id}.md`);
8137
+ return path9.join(this.correctionsDir, `${id}.md`);
7832
8138
  }
7833
- const datedDir = path8.join(getCategoryDir(this.baseDir, category), today);
8139
+ const datedDir = path9.join(getCategoryDir(this.baseDir, category), today);
7834
8140
  await mkdir(datedDir, { recursive: true });
7835
- return path8.join(datedDir, `${id}.md`);
8141
+ return path9.join(datedDir, `${id}.md`);
7836
8142
  }
7837
8143
  async findExistingTombstoneBlockedMemory(content, category, sourceConnector) {
7838
8144
  const identity = buildExplicitCaptureDedupKey(content, category, sourceConnector);
@@ -7918,6 +8224,12 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7918
8224
  if (!sanitized.clean) {
7919
8225
  log.warn(`memory content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
7920
8226
  }
8227
+ if (options.toolScoped || withholdToolScopedFromSharedNamespace({
8228
+ content: sanitized.text,
8229
+ sourceConnector: options.sourceConnector
8230
+ })) {
8231
+ fm.toolScoped = true;
8232
+ }
7921
8233
  let factHashSourceForTombstone = null;
7922
8234
  if (category === "fact") {
7923
8235
  const hashSource = options.contentHashSource !== void 0 && options.contentHashSource.length > 0 ? sanitizeMemoryContent(options.contentHashSource).text : sanitized.text;
@@ -7928,13 +8240,13 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7928
8240
  refIds = this.currentHistoricalIds();
7929
8241
  fm.entityRef = resolveHistoricalEntityCanonicalId(rawEntityRef, refIds);
7930
8242
  }
7931
- let tombstoneBlocked = false;
8243
+ let tombstoneBlocked2 = false;
7932
8244
  let gateRef;
7933
8245
  let statusBeforeBlock;
7934
8246
  const applyTombstoneGate = async () => {
7935
- if (tombstoneBlocked) {
8247
+ if (tombstoneBlocked2) {
7936
8248
  if (fm.entityRef === gateRef) return;
7937
- tombstoneBlocked = false;
8249
+ tombstoneBlocked2 = false;
7938
8250
  fm.status = statusBeforeBlock;
7939
8251
  delete fm.blockedBy;
7940
8252
  delete fm.tombstoneBlockTier;
@@ -7945,7 +8257,7 @@ var StorageManager3 = class _StorageManager extends TombstoneBlockedCaptureIndex
7945
8257
  if (match) {
7946
8258
  gateRef = fm.entityRef;
7947
8259
  statusBeforeBlock = statusBefore;
7948
- tombstoneBlocked = true;
8260
+ tombstoneBlocked2 = true;
7949
8261
  }
7950
8262
  };
7951
8263
  await applyTombstoneGate();
@@ -7955,7 +8267,7 @@ ${sanitized.text}
7955
8267
  `;
7956
8268
  const filePath = await this.resolveCategoryWritePath(category, id, today);
7957
8269
  const persistFile = async () => {
7958
- if (tombstoneBlocked) {
8270
+ if (tombstoneBlocked2) {
7959
8271
  const duplicate = await this.findExistingTombstoneBlockedMemory(sanitized.text, category, fm.sourceConnector);
7960
8272
  if (duplicate) return duplicate;
7961
8273
  }
@@ -7963,12 +8275,44 @@ ${sanitized.text}
7963
8275
  await this.writeTombstoneBlockedMemory(filePath, fileContent, fm, sanitized.text, async () => {
7964
8276
  this.invalidateAllMemoriesCache();
7965
8277
  });
8278
+ if (refIds && typeof rawEntityRef === "string") {
8279
+ const refBeforeRepair = fm.entityRef;
8280
+ try {
8281
+ await repairEntityRefAfterJournalMove({
8282
+ stateDir: this.stateDir,
8283
+ currentIds: () => this.currentHistoricalIds(),
8284
+ idsAtResolve: refIds,
8285
+ rawRef: rawEntityRef,
8286
+ frontmatter: fm,
8287
+ rewrite: async () => {
8288
+ await applyTombstoneGate();
8289
+ await this.writeTombstoneBlockedMemory(
8290
+ filePath,
8291
+ `${serializeFrontmatter(fm)}
8292
+
8293
+ ${sanitized.text}
8294
+ `,
8295
+ fm,
8296
+ sanitized.text,
8297
+ async () => this.invalidateAllMemoriesCache()
8298
+ );
8299
+ this.invalidateAllMemoriesCache();
8300
+ }
8301
+ });
8302
+ } catch (err) {
8303
+ await unlink4(filePath).catch(() => void 0);
8304
+ this.invalidateAllMemoriesCache();
8305
+ await this.rebuildTombstoneBlockedCaptureAfterInvalidationForPath(filePath);
8306
+ throw err;
8307
+ }
8308
+ await this.entityRefRepair.syncProjection(id, refBeforeRepair, fm.entityRef);
8309
+ }
7966
8310
  return null;
7967
8311
  };
7968
- const duplicateBlocked = tombstoneBlocked ? await this.withTombstoneBlockedCaptureWriteLock(
7969
- persistFile,
8312
+ const duplicateBlocked = await this.withTombstoneBlockedCaptureWriteLock(persistFile, [
8313
+ buildCapturePathLockIdentity(filePath),
7970
8314
  buildExplicitCaptureDedupKey(sanitized.text, category, fm.sourceConnector)
7971
- ) : await persistFile();
8315
+ ]);
7972
8316
  if (duplicateBlocked) {
7973
8317
  return {
7974
8318
  id: duplicateBlocked.frontmatter.id,
@@ -7977,37 +8321,6 @@ ${sanitized.text}
7977
8321
  duplicateOf: duplicateBlocked.frontmatter.id
7978
8322
  };
7979
8323
  }
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
8324
  await this.patchHotMemoriesCache({ addedPath: filePath }, "memory-create");
8012
8325
  this.notifyMemoryWrite(filePath);
8013
8326
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.writeMemory", {
@@ -8021,7 +8334,7 @@ ${sanitized.text}
8021
8334
  ...(options.lineage ?? []).filter(Boolean)
8022
8335
  ]
8023
8336
  });
8024
- if (category === "fact" && !tombstoneBlocked) {
8337
+ if (category === "fact" && !tombstoneBlocked2) {
8025
8338
  try {
8026
8339
  const factHashIndex = await this.getFactHashIndex();
8027
8340
  const hashText = options.contentHashSource !== void 0 && options.contentHashSource.length > 0 ? sanitizeMemoryContent(options.contentHashSource).text : sanitized.text;
@@ -8036,7 +8349,7 @@ ${sanitized.text}
8036
8349
  }
8037
8350
  }
8038
8351
  log.debug(`wrote memory ${id} to ${filePath}`);
8039
- return { id, tombstoneBlocked, ...fm.blockedBy ? { blockedBy: fm.blockedBy } : {} };
8352
+ return { id, tombstoneBlocked: tombstoneBlocked2, ...fm.blockedBy ? { blockedBy: fm.blockedBy } : {} };
8040
8353
  }
8041
8354
  /**
8042
8355
  * Sealed-envelope write entry point (issue #1989 PR2).
@@ -8192,7 +8505,7 @@ ${sanitized.text}
8192
8505
  await this.ensureDirectories();
8193
8506
  const now = /* @__PURE__ */ new Date();
8194
8507
  const day = now.toISOString().slice(0, 10);
8195
- const dir = path8.join(this.artifactsDir, day);
8508
+ const dir = path9.join(this.artifactsDir, day);
8196
8509
  await mkdir(dir, { recursive: true });
8197
8510
  const id = `artifact-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
8198
8511
  const fm = {
@@ -8210,14 +8523,15 @@ ${sanitized.text}
8210
8523
  intentGoal: options.intentGoal,
8211
8524
  intentActionType: options.intentActionType,
8212
8525
  intentEntityTypes: options.intentEntityTypes,
8213
- ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {}
8526
+ ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {},
8527
+ ...options.toolScoped ? { toolScoped: true } : {}
8214
8528
  };
8215
8529
  const sanitized = sanitizeMemoryContent(quote);
8216
8530
  if (!sanitized.clean) {
8217
8531
  log.warn(`artifact content rejected for ${id}; violations=${sanitized.violations.join(", ")}`);
8218
8532
  return "";
8219
8533
  }
8220
- const filePath = path8.join(dir, `${id}.md`);
8534
+ const filePath = path9.join(dir, `${id}.md`);
8221
8535
  await this.writeStorageSecureFile(filePath, `${serializeFrontmatter(fm)}
8222
8536
 
8223
8537
  ${sanitized.text}
@@ -8308,12 +8622,7 @@ ${sanitized.text}
8308
8622
  });
8309
8623
  if (newBullets.length === 0) return;
8310
8624
  if (!existing) {
8311
- const content = [
8312
- "# Behavioral Profile",
8313
- "",
8314
- ...newBullets.map((b) => `- ${b}`),
8315
- ""
8316
- ].join("\n");
8625
+ const content = ["# Behavioral Profile", "", ...newBullets.map((b) => `- ${b}`), ""].join("\n");
8317
8626
  await this.writeProfile(content);
8318
8627
  } else {
8319
8628
  const withBullets = existing.trimEnd() + "\n" + newBullets.map((b) => `- ${b}`).join("\n") + "\n";
@@ -8488,7 +8797,7 @@ ${sanitized.text}
8488
8797
  * per-process in-memory cache safe across process boundaries.
8489
8798
  */
8490
8799
  invalidateColdMemoriesCache() {
8491
- const coldRoot = path8.join(this.baseDir, "cold");
8800
+ const coldRoot = path9.join(this.baseDir, "cold");
8492
8801
  _StorageManager.coldMemoriesCache.delete(coldRoot);
8493
8802
  this.bumpColdWriteVersion();
8494
8803
  invalidateAllForDir(this.baseDir);
@@ -8548,15 +8857,18 @@ ${sanitized.text}
8548
8857
  const raw = await readMaybeEncryptedFile(fullPath, this._secureStoreKey, this.baseDir);
8549
8858
  const parsed = parseFrontmatter(raw);
8550
8859
  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);
8860
+ return rememberRawFrontmatter(
8861
+ {
8862
+ path: fullPath,
8863
+ frontmatter: normalizeFrontmatterForPath(
8864
+ parsed.frontmatter,
8865
+ toMemoryPathRel(this.baseDir, fullPath),
8866
+ parsed.content
8867
+ ),
8868
+ content: parsed.content
8869
+ },
8870
+ raw
8871
+ );
8560
8872
  } catch (err) {
8561
8873
  if (err instanceof SecureStoreLockedError) throw err;
8562
8874
  return null;
@@ -8603,7 +8915,7 @@ ${sanitized.text}
8603
8915
  const correctionPaths = [];
8604
8916
  const factPaths = [];
8605
8917
  for (const filePath of filePaths) {
8606
- if (filePath === this.correctionsDir || filePath.startsWith(`${this.correctionsDir}${path8.sep}`)) {
8918
+ if (filePath === this.correctionsDir || filePath.startsWith(`${this.correctionsDir}${path9.sep}`)) {
8607
8919
  correctionPaths.push(filePath);
8608
8920
  } else {
8609
8921
  factPaths.push(filePath);
@@ -8666,7 +8978,7 @@ ${sanitized.text}
8666
8978
  try {
8667
8979
  const entries = await readdir5(dir, { withFileTypes: true });
8668
8980
  for (const entry of entries) {
8669
- const fullPath = path8.join(dir, entry.name);
8981
+ const fullPath = path9.join(dir, entry.name);
8670
8982
  if (entry.isDirectory()) {
8671
8983
  await readDir(fullPath);
8672
8984
  } else if (entry.name.endsWith(".md")) {
@@ -8674,15 +8986,20 @@ ${sanitized.text}
8674
8986
  const raw = await readMaybeEncryptedFile(fullPath, this._secureStoreKey, this.baseDir);
8675
8987
  const parsed = parseFrontmatter(raw);
8676
8988
  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));
8989
+ memories.push(
8990
+ rememberRawFrontmatter(
8991
+ {
8992
+ path: fullPath,
8993
+ frontmatter: normalizeFrontmatterForPath(
8994
+ parsed.frontmatter,
8995
+ toMemoryPathRel(this.baseDir, fullPath),
8996
+ parsed.content
8997
+ ),
8998
+ content: parsed.content
8999
+ },
9000
+ raw
9001
+ )
9002
+ );
8686
9003
  }
8687
9004
  } catch (err) {
8688
9005
  if (err instanceof SecureStoreLockedError) throw err;
@@ -8699,7 +9016,7 @@ ${sanitized.text}
8699
9016
  return this.memoryReadStore.readMemoryByPath(filePath);
8700
9017
  }
8701
9018
  resolveTierRootDir(tier) {
8702
- return tier === "cold" ? path8.join(this.baseDir, "cold") : this.baseDir;
9019
+ return tier === "cold" ? path9.join(this.baseDir, "cold") : this.baseDir;
8703
9020
  }
8704
9021
  resolveMemoryDateDir(memory) {
8705
9022
  const preferred = memory.frontmatter.created || memory.frontmatter.updated;
@@ -8714,13 +9031,13 @@ ${sanitized.text}
8714
9031
  buildTierMemoryPath(memory, tier) {
8715
9032
  const root = this.resolveTierRootDir(tier);
8716
9033
  if (this.isArtifactMemory(memory)) {
8717
- return path8.join(root, "artifacts", this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
9034
+ return path9.join(root, "artifacts", this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
8718
9035
  }
8719
9036
  if (memory.frontmatter.category === "correction") {
8720
- return path8.join(root, "corrections", `${memory.frontmatter.id}.md`);
9037
+ return path9.join(root, "corrections", `${memory.frontmatter.id}.md`);
8721
9038
  }
8722
9039
  const dir = categoryDirName(memory.frontmatter.category);
8723
- return path8.join(root, dir, this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
9040
+ return path9.join(root, dir, this.resolveMemoryDateDir(memory), `${memory.frontmatter.id}.md`);
8724
9041
  }
8725
9042
  async writeMemoryFileAtomic(targetPath, memory) {
8726
9043
  const refIdsAtWrite = this.currentHistoricalIds();
@@ -8767,43 +9084,55 @@ ${memory.content}
8767
9084
  this.notifyCatalogWrite();
8768
9085
  }
8769
9086
  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;
9087
+ await this.withTombstoneBlockedMemoryPathLock(
9088
+ memory.path,
9089
+ async (current) => {
9090
+ if (current?.frontmatter.id !== memory.frontmatter.id) {
9091
+ throw new Error(`memory ${memory.frontmatter.id} changed before its tier move`);
8780
9092
  }
8781
- }
8782
- this.invalidateAllMemoriesCache();
8783
- updateProjectedMemoryPath(this.baseDir, memory.frontmatter.id, toMemoryPathRel(this.baseDir, targetPath));
8784
- }
9093
+ const destination = await this.readMemoryByPath(targetPath);
9094
+ const coordinate = tombstoneBlocked(current.frontmatter) || isQueuedReviewMemory(current) || destination !== null && tombstoneBlocked(destination.frontmatter) || isQueuedReviewMemory(destination);
9095
+ const index = this.getTombstoneBlockedCaptureIndex();
9096
+ const marker = coordinate ? await index.prepareWrite() : void 0;
9097
+ let durable = false;
9098
+ try {
9099
+ if (destination?.frontmatter.id === current.frontmatter.id) {
9100
+ await this.deleteManagedStorageFile(current.path);
9101
+ durable = true;
9102
+ this.invalidateAllMemoriesCache();
9103
+ updateProjectedMemoryPath(this.baseDir, current.frontmatter.id, toMemoryPathRel(this.baseDir, targetPath));
9104
+ } else {
9105
+ await this.writeMemoryFileAtomic(targetPath, current);
9106
+ durable = true;
9107
+ const sourcePath = path9.resolve(current.path);
9108
+ const destPath = path9.resolve(targetPath);
9109
+ if (sourcePath !== destPath) {
9110
+ await this.deleteManagedStorageFile(current.path);
9111
+ this.invalidateAllMemoriesCache();
9112
+ updateProjectedMemoryPath(
9113
+ this.baseDir,
9114
+ current.frontmatter.id,
9115
+ toMemoryPathRel(this.baseDir, targetPath)
9116
+ );
9117
+ }
9118
+ }
9119
+ if (marker !== void 0) await this.rebuildTombstoneBlockedCaptureAfterInvalidation(marker);
9120
+ } catch (error) {
9121
+ if (marker !== void 0 && !durable) await index.discardWrite(marker).catch(() => index.markUntrusted());
9122
+ if (marker !== void 0 && durable) index.markUntrusted();
9123
+ throw error;
9124
+ }
9125
+ },
9126
+ [targetPath]
9127
+ );
8785
9128
  }
8786
9129
  async migrateMemoryToTier(memory, targetTier) {
8787
9130
  const targetPath = this.buildTierMemoryPath(memory, targetTier);
8788
- const sourcePath = path8.resolve(memory.path);
8789
- const destPath = path8.resolve(targetPath);
9131
+ const sourcePath = path9.resolve(memory.path);
9132
+ const destPath = path9.resolve(targetPath);
8790
9133
  if (sourcePath === destPath) {
8791
9134
  return { changed: false, targetPath };
8792
9135
  }
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
9136
  await this.moveMemoryToPath(memory, targetPath);
8808
9137
  this.invalidateAllMemoriesCache();
8809
9138
  if (targetTier === "cold") {
@@ -8813,7 +9142,7 @@ ${memory.content}
8813
9142
  return { changed: true, targetPath };
8814
9143
  }
8815
9144
  get archiveDir() {
8816
- return path8.join(this.baseDir, "archive");
9145
+ return path9.join(this.baseDir, "archive");
8817
9146
  }
8818
9147
  /**
8819
9148
  * Archive a memory by moving it from facts/ to archive/YYYY-MM-DD/.
@@ -8825,7 +9154,7 @@ ${memory.content}
8825
9154
  try {
8826
9155
  const now = lifecycle?.at ?? /* @__PURE__ */ new Date();
8827
9156
  const today = now.toISOString().slice(0, 10);
8828
- const destDir = path8.join(this.archiveDir, today);
9157
+ const destDir = path9.join(this.archiveDir, today);
8829
9158
  await mkdir(destDir, { recursive: true });
8830
9159
  const refIdsAtWrite = this.currentHistoricalIds();
8831
9160
  const updatedFm = canonicalizeEntityRefOption(
@@ -8841,7 +9170,7 @@ ${memory.content}
8841
9170
 
8842
9171
  ${current.content}
8843
9172
  `;
8844
- const destPath = path8.join(destDir, path8.basename(current.path));
9173
+ const destPath = path9.join(destDir, path9.basename(current.path));
8845
9174
  const priorDest = await this.readStorageSecureFile(destPath).catch(() => null);
8846
9175
  await this.writeStorageSecureFile(destPath, fileContent);
8847
9176
  if (typeof current.frontmatter.entityRef === "string") {
@@ -8862,7 +9191,7 @@ ${current.content}
8862
9191
  throw err;
8863
9192
  }
8864
9193
  }
8865
- await unlink4(current.path);
9194
+ if (!await this.deleteManagedStorageFile(current.path)) return null;
8866
9195
  markDurable();
8867
9196
  markProjectedMemoryPathInvalid(this.baseDir, current.frontmatter.id);
8868
9197
  this.invalidateAllMemoriesCache();
@@ -8940,19 +9269,16 @@ ${current.content}
8940
9269
  const memories = await this.readAllMemories();
8941
9270
  const memory = memories.find((candidate) => candidate.frontmatter.id === id);
8942
9271
  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
- );
9272
+ return await this.runTombstoneBlockedInvalidation(memory, async (current, rebuildMarker, markDurable) => {
9273
+ if (!await this.deleteManagedStorageFile(current.path)) return false;
9274
+ markDurable();
9275
+ markProjectedMemoryPathInvalid(this.baseDir, id);
9276
+ this.invalidateAllMemoriesCache();
9277
+ await this.rebuildTombstoneBlockedCaptureAfterInvalidation(rebuildMarker);
9278
+ this.bumpMemoryStatusVersion();
9279
+ log.debug(`invalidated memory ${id}`);
9280
+ return true;
9281
+ });
8956
9282
  }
8957
9283
  async updateMemory(id, newContent, options) {
8958
9284
  const memories = await this.readAllMemories();
@@ -9028,23 +9354,18 @@ ${memory.content}
9028
9354
  `;
9029
9355
  await this.writeTombstoneBlockedFrontmatter(memory, fileContent, updated, async () => {
9030
9356
  this.invalidateAllMemoriesCache();
9031
- if (memory.path.includes(`${path8.sep}cold${path8.sep}`)) {
9357
+ if (memory.path.includes(`${path9.sep}cold${path9.sep}`)) {
9032
9358
  this.invalidateColdMemoriesCache();
9033
9359
  }
9034
9360
  });
9035
9361
  const rawMergedRef = typeof patch.entityRef === "string" ? patch.entityRef : memory.frontmatter.entityRef;
9036
9362
  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
- );
9363
+ await this.entityRefRepair.repair(memory.path, updated, rawMergedRef, refIds, memory.content, {
9364
+ onFailRestore: memory
9365
+ });
9045
9366
  }
9046
9367
  await this.patchHotMemoriesCache({ addedPath: memory.path });
9047
- if (memory.path.includes(`${path8.sep}cold${path8.sep}`)) {
9368
+ if (memory.path.includes(`${path9.sep}cold${path9.sep}`)) {
9048
9369
  this.invalidateColdMemoriesCache();
9049
9370
  }
9050
9371
  try {
@@ -9114,7 +9435,7 @@ ${memory.content}
9114
9435
  return deleted;
9115
9436
  }
9116
9437
  async loadBuffer() {
9117
- const bufferPath = path8.join(this.stateDir, "buffer.json");
9438
+ const bufferPath = path9.join(this.stateDir, "buffer.json");
9118
9439
  try {
9119
9440
  const raw = await this.readStorageSecureFile(bufferPath);
9120
9441
  return JSON.parse(raw);
@@ -9126,11 +9447,11 @@ ${memory.content}
9126
9447
  }
9127
9448
  async saveBuffer(state) {
9128
9449
  await this.ensureDirectories();
9129
- const bufferPath = path8.join(this.stateDir, "buffer.json");
9450
+ const bufferPath = path9.join(this.stateDir, "buffer.json");
9130
9451
  await this.writeStorageSecureFile(bufferPath, JSON.stringify(state, null, 2));
9131
9452
  }
9132
9453
  async loadMeta() {
9133
- const metaPath = path8.join(this.stateDir, "meta.json");
9454
+ const metaPath = path9.join(this.stateDir, "meta.json");
9134
9455
  try {
9135
9456
  const raw = await this.readStorageSecureFile(metaPath);
9136
9457
  const parsed = JSON.parse(raw);
@@ -9163,7 +9484,7 @@ ${memory.content}
9163
9484
  }
9164
9485
  async saveMeta(state) {
9165
9486
  await this.ensureDirectories();
9166
- const metaPath = path8.join(this.stateDir, "meta.json");
9487
+ const metaPath = path9.join(this.stateDir, "meta.json");
9167
9488
  await this.writeStorageSecureFile(metaPath, JSON.stringify(state, null, 2));
9168
9489
  }
9169
9490
  async appendMemoryActionEvents(events) {
@@ -9227,7 +9548,7 @@ ${memory.content}
9227
9548
  },
9228
9549
  (payload) => this.appendStorageSecureFile(target, payload),
9229
9550
  async () => {
9230
- await mkdir(path8.dirname(target), { recursive: true });
9551
+ await mkdir(path9.dirname(target), { recursive: true });
9231
9552
  }
9232
9553
  );
9233
9554
  }
@@ -9325,7 +9646,7 @@ ${memory.content}
9325
9646
  async appendReextractJobs(events) {
9326
9647
  if (events.length === 0) return 0;
9327
9648
  await this.ensureDirectories();
9328
- const filePath = path8.join(this.stateDir, "reextract-jobs.jsonl");
9649
+ const filePath = path9.join(this.stateDir, "reextract-jobs.jsonl");
9329
9650
  const lines = events.map((event) => JSON.stringify(event)).join("\n") + "\n";
9330
9651
  try {
9331
9652
  await this.appendStorageSecureFile(filePath, lines);
@@ -9338,7 +9659,7 @@ ${memory.content}
9338
9659
  }
9339
9660
  async readReextractJobs(limit = 200) {
9340
9661
  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");
9662
+ const filePath = path9.join(this.stateDir, "reextract-jobs.jsonl");
9342
9663
  try {
9343
9664
  const raw = await this.readStorageSecureFile(filePath);
9344
9665
  const lines = raw.split("\n").filter((line) => line.trim().length > 0);
@@ -9487,7 +9808,7 @@ ${memory.content}
9487
9808
  return false;
9488
9809
  }
9489
9810
  if (draftState.contentHash) {
9490
- const contentHash = createHash5("sha256").update(draftContent).digest("hex");
9811
+ const contentHash = createHash6("sha256").update(draftContent).digest("hex");
9491
9812
  if (contentHash !== draftState.contentHash) return false;
9492
9813
  }
9493
9814
  await this.writeCompressionGuidelines(draftContent);
@@ -9565,7 +9886,7 @@ ${question}
9565
9886
 
9566
9887
  **Context:** ${context}
9567
9888
  `;
9568
- const filePath = path8.join(this.questionsDir, `${id}.md`);
9889
+ const filePath = path9.join(this.questionsDir, `${id}.md`);
9569
9890
  await this.writeStorageSecureFile(filePath, content);
9570
9891
  log.debug(`wrote question ${id} to ${filePath}`);
9571
9892
  this.invalidateQuestionsCache();
@@ -9583,7 +9904,7 @@ ${question}
9583
9904
  if (!match) return null;
9584
9905
  const frontmatterStr = match[1];
9585
9906
  const body = match[2].trim();
9586
- const id = this.extractFrontmatterValue(frontmatterStr, "id") ?? path8.basename(filePath, ".md");
9907
+ const id = this.extractFrontmatterValue(frontmatterStr, "id") ?? path9.basename(filePath, ".md");
9587
9908
  const created = this.extractFrontmatterValue(frontmatterStr, "created") ?? "";
9588
9909
  const priority = parseFloat(this.extractFrontmatterValue(frontmatterStr, "priority") ?? "0.5");
9589
9910
  const resolved = this.extractFrontmatterValue(frontmatterStr, "resolved") === "true";
@@ -9639,11 +9960,11 @@ ${question}
9639
9960
  } catch {
9640
9961
  }
9641
9962
  const hygiene = opts?.hygiene;
9642
- const rotateEnabled = hygiene?.enabled === true && hygiene.rotateEnabled === true && Array.isArray(hygiene.rotatePaths) && hygiene.rotatePaths.includes(path8.basename(identityPath));
9963
+ const rotateEnabled = hygiene?.enabled === true && hygiene.rotateEnabled === true && Array.isArray(hygiene.rotatePaths) && hygiene.rotatePaths.includes(path9.basename(identityPath));
9643
9964
  if (rotateEnabled) {
9644
9965
  const maxBytes = hygiene.rotateMaxBytes;
9645
9966
  if (existing.length > maxBytes) {
9646
- const archiveDir = path8.join(workspaceDir, hygiene.archiveDir);
9967
+ const archiveDir = path9.join(workspaceDir, hygiene.archiveDir);
9647
9968
  const { newContent } = await rotateMarkdownFileToArchive({
9648
9969
  filePath: identityPath,
9649
9970
  archiveDir,
@@ -9903,40 +10224,45 @@ ${reflection}
9903
10224
  if (entries.length === 0) return 0;
9904
10225
  const memories = await this.readAllMemories();
9905
10226
  const memoryMap = new Map(memories.map((m) => [m.frontmatter.id, m]));
9906
- const memoryPathMap = new Map(memories.map((m) => [path8.resolve(m.path), m]));
10227
+ const memoryPathMap = new Map(memories.map((m) => [path9.resolve(m.path), m]));
9907
10228
  let updated = 0;
9908
10229
  const prevVersion = this.getMemoryCorpusVersion();
9909
10230
  const keyId = this.hotCacheKeyId();
9910
10231
  const warm = this.hotMemoriesCacheEnabled && getCachedMemories(this.baseDir, prevVersion, keyId, this.hotCacheTtlMs()) !== null;
9911
10232
  const appliedPatches = /* @__PURE__ */ new Map();
9912
10233
  for (const entry of entries) {
9913
- const memory = entry.memoryPath ? memoryPathMap.get(path8.resolve(entry.memoryPath)) : memoryMap.get(entry.memoryId);
10234
+ const memory = entry.memoryPath ? memoryPathMap.get(path9.resolve(entry.memoryPath)) : memoryMap.get(entry.memoryId);
9914
10235
  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
10236
  try {
9921
- const fileContent = `${serializeFrontmatter(newFm)}
10237
+ const applied = await this.withTombstoneBlockedMemoryPathLock(memory.path, async (current) => {
10238
+ if (current?.frontmatter.id !== entry.memoryId) return null;
10239
+ const rowIds = this.currentHistoricalIds();
10240
+ const newFm = canonicalizeEntityRefOption(
10241
+ { ...current.frontmatter, accessCount: entry.newCount, lastAccessed: entry.lastAccessed },
10242
+ rowIds
10243
+ );
10244
+ const fileContent = `${serializeFrontmatter(newFm)}
9922
10245
 
9923
- ${memory.content}
10246
+ ${current.content}
9924
10247
  `;
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
- }
10248
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, newFm);
10249
+ if (typeof current.frontmatter.entityRef === "string") {
10250
+ await this.entityRefRepair.repair(
10251
+ current.path,
10252
+ newFm,
10253
+ current.frontmatter.entityRef,
10254
+ rowIds,
10255
+ current.content,
10256
+ { onFailRestore: current }
10257
+ );
10258
+ }
10259
+ return { current, newFm };
10260
+ });
10261
+ if (applied === null) continue;
9936
10262
  if (warm) {
9937
- updateCacheOnWrite(this.baseDir, { ...memory, frontmatter: newFm }, keyId);
10263
+ updateCacheOnWrite(this.baseDir, { ...applied.current, frontmatter: applied.newFm }, keyId);
9938
10264
  }
9939
- appliedPatches.set(path8.resolve(memory.path), {
10265
+ appliedPatches.set(path9.resolve(memory.path), {
9940
10266
  accessCount: entry.newCount,
9941
10267
  lastAccessed: entry.lastAccessed
9942
10268
  });
@@ -9952,7 +10278,7 @@ ${memory.content}
9952
10278
  const cur = getCachedMemories(this.baseDir, prevVersion, keyId);
9953
10279
  if (cur) {
9954
10280
  const reapplied = cur.map((m) => {
9955
- const patch = appliedPatches.get(path8.resolve(m.path));
10281
+ const patch = appliedPatches.get(path9.resolve(m.path));
9956
10282
  return patch ? {
9957
10283
  ...m,
9958
10284
  frontmatter: { ...m.frontmatter, accessCount: patch.accessCount, lastAccessed: patch.lastAccessed }
@@ -9987,7 +10313,7 @@ ${memory.content}
9987
10313
  const pathsById = /* @__PURE__ */ new Map();
9988
10314
  const filePathsById = /* @__PURE__ */ new Map();
9989
10315
  for (const filePath of filePaths) {
9990
- const memoryId = path8.basename(filePath, ".md");
10316
+ const memoryId = path9.basename(filePath, ".md");
9991
10317
  if (!wantedIds.has(memoryId)) continue;
9992
10318
  const paths = filePathsById.get(memoryId) ?? [];
9993
10319
  paths.push(filePath);
@@ -9999,7 +10325,7 @@ ${memory.content}
9999
10325
  const preferredMatches = [];
10000
10326
  for (const preferredPath of preferred) {
10001
10327
  const directCandidates = new Set(qmdResultPathCandidates(this.baseDir, preferredPath));
10002
- const directMatch = existingPaths.find((filePath) => directCandidates.has(path8.resolve(filePath)));
10328
+ const directMatch = existingPaths.find((filePath) => directCandidates.has(path9.resolve(filePath)));
10003
10329
  if (directMatch) {
10004
10330
  preferredMatches.push(directMatch);
10005
10331
  continue;
@@ -10011,7 +10337,7 @@ ${memory.content}
10011
10337
  candidates.add(candidate);
10012
10338
  }
10013
10339
  }
10014
- const match = existingPaths.find((filePath) => candidates.has(path8.resolve(filePath)));
10340
+ const match = existingPaths.find((filePath) => candidates.has(path9.resolve(filePath)));
10015
10341
  if (match) preferredMatches.push(match);
10016
10342
  }
10017
10343
  if (preferredMatches.length > 0) {
@@ -10102,6 +10428,10 @@ ${memory.content}
10102
10428
  const validAt = normalizeMemoryWriteTimestamp("validAt", options.validAt);
10103
10429
  const chunkInvalidAt = normalizeMemoryWriteTimestamp("invalidAt", options.invalidAt);
10104
10430
  const chunkObservedAt = normalizeMemoryWriteTimestamp("observedAt", options.observedAt);
10431
+ const sanitized = sanitizeMemoryContent(content);
10432
+ if (!sanitized.clean) {
10433
+ log.warn(`chunk content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
10434
+ }
10105
10435
  const fm = {
10106
10436
  id,
10107
10437
  category,
@@ -10129,44 +10459,34 @@ ${memory.content}
10129
10459
  ...options.faithfulness ? { faithfulness: options.faithfulness } : {},
10130
10460
  ...options.sources ? { sources: options.sources } : {},
10131
10461
  ...options.provenance ? { provenance: options.provenance } : {},
10132
- ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {}
10462
+ ...options.sourceConnector ? { sourceConnector: options.sourceConnector } : {},
10463
+ ...options.toolScoped || withholdToolScopedFromSharedNamespace({
10464
+ content: sanitized.text,
10465
+ sourceConnector: options.sourceConnector
10466
+ }) ? { toolScoped: true } : {}
10133
10467
  };
10134
- const sanitized = sanitizeMemoryContent(content);
10135
- if (!sanitized.clean) {
10136
- log.warn(`chunk content sanitized for ${id}; violations=${sanitized.violations.join(", ")}`);
10137
- }
10138
10468
  const filePath = await this.resolveCategoryWritePath(category, id, today);
10139
10469
  const fileContent = `${serializeFrontmatter(fm)}
10140
10470
 
10141
10471
  ${sanitized.text}
10142
10472
  `;
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
10473
  const written = await this.writeTombstoneBlockedChunk(
10154
10474
  filePath,
10155
10475
  fileContent,
10156
10476
  fm,
10157
10477
  sanitized.text,
10158
10478
  () => this.findExistingTombstoneBlockedMemory(sanitized.text, category, fm.sourceConnector),
10159
- async () => {
10479
+ async (priorChunk) => {
10480
+ if (refIds && typeof rawEntityRef === "string") {
10481
+ await this.entityRefRepair.repair(filePath, fm, rawEntityRef, refIds, sanitized.text, {
10482
+ regateFact: true,
10483
+ ...priorChunk ? { onFailRestore: priorChunk } : { onFailRemove: filePath }
10484
+ });
10485
+ }
10160
10486
  await this.patchHotMemoriesCache({ addedPath: filePath }, "memory-create");
10161
10487
  log.debug(`wrote chunk ${id} (${chunkIndex + 1}/${chunkTotal}) to ${filePath}`);
10162
10488
  }
10163
10489
  );
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
10490
  return written;
10171
10491
  }
10172
10492
  /**
@@ -10189,27 +10509,35 @@ ${sanitized.text}
10189
10509
  const oldMemory = memories.find((m) => m.frontmatter.id === oldMemoryId);
10190
10510
  if (!oldMemory) return false;
10191
10511
  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
- `;
10512
+ let currentBefore = oldMemory;
10513
+ let updatedFm = oldMemory.frontmatter;
10201
10514
  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 }
10515
+ const written = await this.withTombstoneBlockedMemoryPathLock(oldMemory.path, async (current) => {
10516
+ if (current?.frontmatter.id !== oldMemoryId) return false;
10517
+ currentBefore = current;
10518
+ const refIdsAtWrite = this.currentHistoricalIds();
10519
+ updatedFm = canonicalizeEntityRefOption(
10520
+ { ...current.frontmatter, status: "superseded", supersededBy: newMemoryId, supersededAt: now, updated: now },
10521
+ refIdsAtWrite
10211
10522
  );
10212
- }
10523
+ const fileContent = `${serializeFrontmatter(updatedFm)}
10524
+
10525
+ ${current.content}
10526
+ `;
10527
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, updatedFm);
10528
+ if (typeof current.frontmatter.entityRef === "string") {
10529
+ await this.entityRefRepair.repair(
10530
+ current.path,
10531
+ updatedFm,
10532
+ current.frontmatter.entityRef,
10533
+ refIdsAtWrite,
10534
+ current.content,
10535
+ { onFailRestore: current }
10536
+ );
10537
+ }
10538
+ return true;
10539
+ });
10540
+ if (!written) return false;
10213
10541
  this.bumpMemoryCorpusVersion();
10214
10542
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.supersedeMemory", {
10215
10543
  memoryId: oldMemoryId,
@@ -10217,20 +10545,20 @@ ${oldMemory.content}
10217
10545
  timestamp: now,
10218
10546
  actor: "storage.supersedeMemory",
10219
10547
  reasonCode: reason,
10220
- before: this.summarizeLifecycleState(oldMemory.frontmatter, oldMemory.path),
10221
- after: this.summarizeLifecycleState(updatedFm, oldMemory.path),
10548
+ before: this.summarizeLifecycleState(currentBefore.frontmatter, currentBefore.path),
10549
+ after: this.summarizeLifecycleState(updatedFm, currentBefore.path),
10222
10550
  relatedMemoryIds: [newMemoryId]
10223
10551
  });
10224
10552
  this.bumpMemoryStatusVersion();
10225
10553
  log.debug(`superseded memory ${oldMemoryId} by ${newMemoryId}: ${reason}`);
10226
- if (oldMemory.frontmatter.category === "fact") {
10554
+ if (currentBefore.frontmatter.category === "fact") {
10227
10555
  for (const input of buildRetiredFactTombstoneInputs(
10228
10556
  {
10229
10557
  id: oldMemoryId,
10230
- content: stripCitationForTemplate(oldMemory.content, this.citationTemplate),
10231
- contentHash: oldMemory.frontmatter.contentHash,
10558
+ content: stripCitationForTemplate(currentBefore.content, this.citationTemplate),
10559
+ contentHash: currentBefore.frontmatter.contentHash,
10232
10560
  entityRef: updatedFm.entityRef,
10233
- structuredAttributes: oldMemory.frontmatter.structuredAttributes
10561
+ structuredAttributes: currentBefore.frontmatter.structuredAttributes
10234
10562
  },
10235
10563
  {
10236
10564
  reason: "contradiction_resolution",
@@ -10242,7 +10570,7 @@ ${oldMemory.content}
10242
10570
  await this.appendTombstone(input);
10243
10571
  }
10244
10572
  }
10245
- const auditBody = `Superseded: ${oldMemory.content}
10573
+ const auditBody = `Superseded: ${currentBefore.content}
10246
10574
 
10247
10575
  Reason: ${reason}`;
10248
10576
  const auditInput = {
@@ -10263,14 +10591,14 @@ Reason: ${reason}`;
10263
10591
  // Memory Summarization (Phase 4A)
10264
10592
  // ---------------------------------------------------------------------------
10265
10593
  get summariesDir() {
10266
- return path8.join(this.baseDir, "summaries");
10594
+ return path9.join(this.baseDir, "summaries");
10267
10595
  }
10268
10596
  /**
10269
10597
  * Write a memory summary.
10270
10598
  */
10271
10599
  async writeSummary(summary) {
10272
10600
  await mkdir(this.summariesDir, { recursive: true });
10273
- const filePath = path8.join(this.summariesDir, `${summary.id}.json`);
10601
+ const filePath = path9.join(this.summariesDir, `${summary.id}.json`);
10274
10602
  await this.writeStorageSecureFile(filePath, JSON.stringify(summary, null, 2));
10275
10603
  log.debug(`wrote summary ${summary.id}`);
10276
10604
  }
@@ -10283,7 +10611,7 @@ Reason: ${reason}`;
10283
10611
  const summaries = [];
10284
10612
  for (const file of files) {
10285
10613
  if (!file.endsWith(".json")) continue;
10286
- const filePath = path8.join(this.summariesDir, file);
10614
+ const filePath = path9.join(this.summariesDir, file);
10287
10615
  const raw = await this.readStorageSecureFile(filePath);
10288
10616
  summaries.push(JSON.parse(raw));
10289
10617
  }
@@ -10305,27 +10633,35 @@ Reason: ${reason}`;
10305
10633
  const memory = memoryMap.get(id);
10306
10634
  if (!memory) continue;
10307
10635
  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
- );
10636
+ let currentBefore = memory;
10637
+ let updatedFm = memory.frontmatter;
10313
10638
  try {
10314
- const fileContent = `${serializeFrontmatter(updatedFm)}
10639
+ const written = await this.withTombstoneBlockedMemoryPathLock(memory.path, async (current) => {
10640
+ if (current?.frontmatter.id !== id) return false;
10641
+ currentBefore = current;
10642
+ const rowIds = this.currentHistoricalIds();
10643
+ updatedFm = canonicalizeEntityRefOption(
10644
+ { ...current.frontmatter, status: "archived", archivedAt: now, updated: now },
10645
+ rowIds
10646
+ );
10647
+ const fileContent = `${serializeFrontmatter(updatedFm)}
10315
10648
 
10316
- ${memory.content}
10649
+ ${current.content}
10317
10650
  `;
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
- }
10651
+ await this.writeTombstoneBlockedFrontmatter(current, fileContent, updatedFm);
10652
+ if (typeof current.frontmatter.entityRef === "string") {
10653
+ await this.entityRefRepair.repair(
10654
+ current.path,
10655
+ updatedFm,
10656
+ current.frontmatter.entityRef,
10657
+ rowIds,
10658
+ current.content,
10659
+ { onFailRestore: current }
10660
+ );
10661
+ }
10662
+ return true;
10663
+ });
10664
+ if (!written) continue;
10329
10665
  this.bumpMemoryCorpusVersion();
10330
10666
  await this.appendGeneratedMemoryLifecycleEventFailOpen("storage.archiveMemories", {
10331
10667
  memoryId: id,
@@ -10333,8 +10669,8 @@ ${memory.content}
10333
10669
  timestamp: updatedFm.archivedAt ?? updatedFm.updated,
10334
10670
  actor: "storage.archiveMemories",
10335
10671
  reasonCode: `summary:${summaryId}`,
10336
- before: this.summarizeLifecycleState(memory.frontmatter, memory.path),
10337
- after: this.summarizeLifecycleState(updatedFm, memory.path),
10672
+ before: this.summarizeLifecycleState(currentBefore.frontmatter, currentBefore.path),
10673
+ after: this.summarizeLifecycleState(updatedFm, currentBefore.path),
10338
10674
  relatedMemoryIds: [summaryId]
10339
10675
  });
10340
10676
  archived++;
@@ -10354,7 +10690,7 @@ ${memory.content}
10354
10690
  * Save topic scores to meta.json.
10355
10691
  */
10356
10692
  async saveTopics(topics) {
10357
- const metaPath = path8.join(this.stateDir, "topics.json");
10693
+ const metaPath = path9.join(this.stateDir, "topics.json");
10358
10694
  await mkdir(this.stateDir, { recursive: true });
10359
10695
  await this.writeStorageSecureFile(
10360
10696
  metaPath,
@@ -10366,7 +10702,7 @@ ${memory.content}
10366
10702
  * Load topic scores from meta.json.
10367
10703
  */
10368
10704
  async loadTopics() {
10369
- const metaPath = path8.join(this.stateDir, "topics.json");
10705
+ const metaPath = path9.join(this.stateDir, "topics.json");
10370
10706
  try {
10371
10707
  const raw = await this.readStorageSecureFile(metaPath);
10372
10708
  return JSON.parse(raw);
@@ -10484,4 +10820,4 @@ export {
10484
10820
  isValidBufferSurpriseEvent,
10485
10821
  StorageManager3 as StorageManager
10486
10822
  };
10487
- //# sourceMappingURL=chunk-E6PNLPGJ.js.map
10823
+ //# sourceMappingURL=chunk-FZP32336.js.map