@remnic/core 9.69.23 → 9.69.25

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 (438) hide show
  1. package/dist/abstraction-nodes.js +3 -2
  2. package/dist/access-admin-ops-surface.d.ts +1 -1
  3. package/dist/access-admin-ops-surface.js +53 -53
  4. package/dist/access-authorization-probe.d.ts +1 -1
  5. package/dist/access-authorization-probe.js +54 -54
  6. package/dist/access-boundary.d.ts +1 -1
  7. package/dist/access-boundary.js +53 -53
  8. package/dist/access-citation-namespace.js +3 -3
  9. package/dist/access-cli.js +112 -112
  10. package/dist/access-extraction-force-flush.d.ts +1 -1
  11. package/dist/access-extraction-force-flush.js +53 -53
  12. package/dist/access-http-briefing.d.ts +1 -1
  13. package/dist/access-http-briefing.js +54 -54
  14. package/dist/access-http-lcm-compaction.d.ts +1 -1
  15. package/dist/access-http-lifecycle-flush.d.ts +1 -1
  16. package/dist/access-http-offline-stream.d.ts +1 -1
  17. package/dist/access-http-query.js +55 -55
  18. package/dist/access-http.d.ts +2 -2
  19. package/dist/access-http.js +72 -72
  20. package/dist/access-identity-continuity-surface.js +53 -53
  21. package/dist/access-lcm-surface.d.ts +1 -1
  22. package/dist/access-lcm-surface.js +53 -53
  23. package/dist/access-mcp.d.ts +1 -1
  24. package/dist/access-mcp.js +64 -64
  25. package/dist/access-namespace-preflight.js +53 -53
  26. package/dist/access-observe-write-surface.d.ts +1 -1
  27. package/dist/access-observe-write-surface.js +53 -53
  28. package/dist/access-offline-manifest.js +10 -10
  29. package/dist/access-operations-batch.js +58 -58
  30. package/dist/access-operations.d.ts +1 -1
  31. package/dist/access-operations.js +63 -63
  32. package/dist/access-recall-concurrency.d.ts +1 -1
  33. package/dist/access-recall-concurrency.js +53 -53
  34. package/dist/access-recall-response.d.ts +1 -1
  35. package/dist/access-recall-response.js +53 -53
  36. package/dist/access-recall-surface.d.ts +1 -1
  37. package/dist/access-recall-surface.js +53 -53
  38. package/dist/access-schema.js +6 -5
  39. package/dist/access-service-helpers.d.ts +1 -1
  40. package/dist/access-service.d.ts +1 -1
  41. package/dist/access-service.js +53 -53
  42. package/dist/access-surface-catalog.d.ts +1 -1
  43. package/dist/access-surface-catalog.js +55 -55
  44. package/dist/active-recall.js +12 -11
  45. package/dist/active-recall.js.map +1 -1
  46. package/dist/{auto-sync-TTIEWJ5X.js → auto-sync-WNGG2GC2.js} +7 -7
  47. package/dist/briefing.js +20 -20
  48. package/dist/buffer.js +9 -9
  49. package/dist/calibration.js +2 -1
  50. package/dist/calibration.js.map +1 -1
  51. package/dist/{capsule-merge-CU6QJBSV.js → capsule-merge-IPG4IOFP.js} +4 -4
  52. package/dist/causal-behavior.js +4 -3
  53. package/dist/causal-behavior.js.map +1 -1
  54. package/dist/causal-chain.js +4 -3
  55. package/dist/causal-consolidation.js +25 -25
  56. package/dist/causal-retrieval.js +4 -3
  57. package/dist/causal-retrieval.js.map +1 -1
  58. package/dist/causal-trajectory-graph.js +2 -1
  59. package/dist/causal-trajectory-graph.js.map +1 -1
  60. package/dist/causal-trajectory.js +3 -2
  61. package/dist/{chunk-5RWHODVF.js → chunk-27QVNSQ3.js} +2 -2
  62. package/dist/{chunk-2MX7RU7B.js → chunk-2EKJDQZB.js} +2 -2
  63. package/dist/{chunk-XLRM6PPI.js → chunk-2IOHTUP3.js} +4 -4
  64. package/dist/{chunk-ZGQDTD5T.js → chunk-2ITE4C2Z.js} +2 -2
  65. package/dist/{chunk-O5ZR7SXV.js → chunk-2SGLMP2E.js} +2 -2
  66. package/dist/{chunk-FYWLSFFS.js → chunk-2Z4GS5E6.js} +2 -2
  67. package/dist/{chunk-WELP4CG6.js → chunk-37KUQPX4.js} +6 -6
  68. package/dist/{chunk-DDQQY2E3.js → chunk-3BTFBQLO.js} +7 -7
  69. package/dist/chunk-3BTFBQLO.js.map +1 -0
  70. package/dist/{chunk-UR6PBX2J.js → chunk-3K7V3HE6.js} +35 -60
  71. package/dist/chunk-3K7V3HE6.js.map +1 -0
  72. package/dist/{chunk-MRSLR6TB.js → chunk-3QQTXYZ6.js} +2 -2
  73. package/dist/{chunk-DJUKBGAD.js → chunk-46EST7JO.js} +5 -5
  74. package/dist/chunk-46EST7JO.js.map +1 -0
  75. package/dist/{chunk-CI6C33EO.js → chunk-46ZPIGWI.js} +3 -3
  76. package/dist/{chunk-HTIIXNJQ.js → chunk-4FIH6MPS.js} +6 -3
  77. package/dist/chunk-4FIH6MPS.js.map +1 -0
  78. package/dist/{chunk-MCA2X4WH.js → chunk-4IHBN6WU.js} +2 -2
  79. package/dist/{chunk-W7IGLX4G.js → chunk-4O6WRBGE.js} +7 -7
  80. package/dist/chunk-4O6WRBGE.js.map +1 -0
  81. package/dist/{chunk-TOZCM7WN.js → chunk-4TKJGOCJ.js} +2 -2
  82. package/dist/{chunk-3ADRFFRO.js → chunk-54WHLA65.js} +4 -4
  83. package/dist/{chunk-Z2N2AHEM.js → chunk-56Y6EKZN.js} +2 -2
  84. package/dist/{chunk-2H2N5UQW.js → chunk-5ATKSPEQ.js} +2 -2
  85. package/dist/{chunk-MSOXFXCA.js → chunk-5FAGCOZD.js} +5 -5
  86. package/dist/chunk-5FAGCOZD.js.map +1 -0
  87. package/dist/{chunk-ZVZHG7AI.js → chunk-5UBH37SL.js} +3 -3
  88. package/dist/{chunk-YZYZ2BEU.js → chunk-66OJSCI6.js} +2 -2
  89. package/dist/{chunk-HNPE66LB.js → chunk-6CVNSDCZ.js} +4 -4
  90. package/dist/{chunk-ERVJFFTR.js → chunk-6NXSYYGP.js} +2 -2
  91. package/dist/{chunk-2HIJHXB3.js → chunk-6WHJ2EAB.js} +2 -2
  92. package/dist/{chunk-34VTBPNE.js → chunk-6XL73HQ4.js} +4 -4
  93. package/dist/{chunk-YK3UIF7X.js → chunk-AQ7SYDVO.js} +2 -2
  94. package/dist/{chunk-DSCCM66R.js → chunk-B3O3IRZN.js} +2 -2
  95. package/dist/{chunk-P77QX3ID.js → chunk-B6O2YLUR.js} +21 -20
  96. package/dist/chunk-B6O2YLUR.js.map +1 -0
  97. package/dist/{chunk-N37X5RU7.js → chunk-BD7JTBYP.js} +2 -2
  98. package/dist/{chunk-VO43BJ2F.js → chunk-BLJWYCNO.js} +5 -5
  99. package/dist/{chunk-ACPCA4NO.js → chunk-BMWN7B3Y.js} +6 -6
  100. package/dist/chunk-BMWN7B3Y.js.map +1 -0
  101. package/dist/{chunk-HSKSVY3Q.js → chunk-C553ZTLF.js} +15 -15
  102. package/dist/{chunk-GCASGYIO.js → chunk-C7HJ3NEI.js} +2 -2
  103. package/dist/{chunk-WVGXCBOC.js → chunk-D5F7TKMH.js} +2 -2
  104. package/dist/{chunk-UFT2XNBW.js → chunk-DGS34QSY.js} +2 -2
  105. package/dist/{chunk-VAOL3SOT.js → chunk-DZD3WGCD.js} +4 -4
  106. package/dist/{chunk-KHMS2FQS.js → chunk-E2P7TZTF.js} +2 -2
  107. package/dist/{chunk-6FC3IZ26.js → chunk-EBA5DA77.js} +2 -2
  108. package/dist/{chunk-E6EANYLD.js → chunk-EOQ6FSQP.js} +2 -2
  109. package/dist/{chunk-7RPPCA26.js → chunk-FVOP3NT7.js} +2 -2
  110. package/dist/{chunk-NRLELHAY.js → chunk-G7NYVKD6.js} +2 -2
  111. package/dist/{chunk-QY34X2QJ.js → chunk-GHTSNGBZ.js} +2 -2
  112. package/dist/{chunk-SLIOMMPF.js → chunk-H272ZPQ3.js} +5 -5
  113. package/dist/{chunk-ZZBQNQS6.js → chunk-H3TKENU4.js} +2 -2
  114. package/dist/{chunk-5OPNUUBX.js → chunk-H4SEGIZY.js} +2 -2
  115. package/dist/{chunk-F2HMDGLC.js → chunk-H54VWRPS.js} +13 -13
  116. package/dist/{chunk-HTP6XRUI.js → chunk-HM7RHKS4.js} +2 -2
  117. package/dist/{chunk-O7H3P2SJ.js → chunk-HWLIMQE2.js} +2 -2
  118. package/dist/{chunk-62WZDHTW.js → chunk-ICKJ52PE.js} +33 -33
  119. package/dist/chunk-ICKJ52PE.js.map +1 -0
  120. package/dist/{chunk-I3FDDCY3.js → chunk-JEC4DVM3.js} +8 -8
  121. package/dist/chunk-JEC4DVM3.js.map +1 -0
  122. package/dist/{chunk-ET2CNMLD.js → chunk-JN72EPOE.js} +2 -2
  123. package/dist/{chunk-E7UQOS4C.js → chunk-JPKK466T.js} +2 -2
  124. package/dist/{chunk-JCCWJHOP.js → chunk-JYZSRNR7.js} +2 -2
  125. package/dist/{chunk-7IUESBLV.js → chunk-K7724CH2.js} +2 -2
  126. package/dist/{chunk-UK7HXNNJ.js → chunk-KAXCYM66.js} +3 -3
  127. package/dist/{chunk-7XVP4P4O.js → chunk-KB2G2I6Q.js} +3 -3
  128. package/dist/{chunk-K7LTRJZU.js → chunk-KEF46KL2.js} +2 -2
  129. package/dist/{chunk-5UZXUTVO.js → chunk-KNA3BXXL.js} +6 -2
  130. package/dist/chunk-KNA3BXXL.js.map +1 -0
  131. package/dist/{chunk-JYYTWCPU.js → chunk-KTWG7CNY.js} +6 -6
  132. package/dist/{chunk-XTYDEO7M.js → chunk-L7Z57SID.js} +2 -2
  133. package/dist/{chunk-EYMPUXAN.js → chunk-LO4UKPKX.js} +3 -3
  134. package/dist/{chunk-LDWIPYJ6.js → chunk-LS2FHUML.js} +3 -3
  135. package/dist/{chunk-GDB4J2H3.js → chunk-MPC7TYTZ.js} +2 -2
  136. package/dist/{chunk-2GF27PGH.js → chunk-MRPOZBJC.js} +3 -3
  137. package/dist/{chunk-7OLKAQMG.js → chunk-MWN6QEI2.js} +2 -2
  138. package/dist/{chunk-J62HG52Z.js → chunk-MY5EDR46.js} +4 -4
  139. package/dist/{chunk-IZRMWPGS.js → chunk-N3ZOP7KC.js} +2 -2
  140. package/dist/{chunk-N6A2RP5S.js → chunk-NB3LRY4T.js} +3 -3
  141. package/dist/{chunk-4N5BIR2U.js → chunk-ND6IQGSZ.js} +2 -2
  142. package/dist/{chunk-NOB2T2FC.js → chunk-NHLLKEKK.js} +2 -2
  143. package/dist/{chunk-WW6B7NQJ.js → chunk-NLYVH66G.js} +6 -6
  144. package/dist/chunk-NLYVH66G.js.map +1 -0
  145. package/dist/{chunk-M5CQNOQN.js → chunk-O6ZNNVSP.js} +2 -2
  146. package/dist/{chunk-NNBZS3DY.js → chunk-OB3XMWX5.js} +2 -2
  147. package/dist/{chunk-TXJNRGMI.js → chunk-OEYZXDQI.js} +6 -6
  148. package/dist/chunk-OEYZXDQI.js.map +1 -0
  149. package/dist/{chunk-SIBVIP2Y.js → chunk-PAZY2ZKP.js} +2 -2
  150. package/dist/{chunk-LXESHEBP.js → chunk-PX4UMA5Z.js} +2 -2
  151. package/dist/{chunk-4KNRKJXQ.js → chunk-QOOBICJF.js} +5 -5
  152. package/dist/chunk-QOOBICJF.js.map +1 -0
  153. package/dist/{chunk-NNZFPYYX.js → chunk-R7QY5ZVB.js} +2 -2
  154. package/dist/{chunk-WTRTFIIN.js → chunk-R7RTXEYG.js} +2 -2
  155. package/dist/{chunk-XRBJ5R3P.js → chunk-RBCQVOVJ.js} +3 -3
  156. package/dist/{chunk-WFZNT4KB.js → chunk-RC5DXXWC.js} +2 -2
  157. package/dist/{chunk-OH7LZHGJ.js → chunk-RJYJ7KR7.js} +52 -52
  158. package/dist/{chunk-OH7LZHGJ.js.map → chunk-RJYJ7KR7.js.map} +1 -1
  159. package/dist/{chunk-5QZR2RA3.js → chunk-ROBHL3GL.js} +2 -2
  160. package/dist/{chunk-6PST2SFW.js → chunk-SCXURCVT.js} +3 -3
  161. package/dist/{chunk-AYG7ML7O.js → chunk-SJDQ5RSN.js} +3 -3
  162. package/dist/{chunk-3ZBLKIHJ.js → chunk-SMWTZLHE.js} +51 -41
  163. package/dist/{chunk-3ZBLKIHJ.js.map → chunk-SMWTZLHE.js.map} +1 -1
  164. package/dist/{chunk-IQXDSKTL.js → chunk-SVXJLDDC.js} +6 -6
  165. package/dist/{chunk-SEF4IOFE.js → chunk-SWIKABKI.js} +2 -2
  166. package/dist/{chunk-ZJABRLCZ.js → chunk-TBXAY2SS.js} +4 -4
  167. package/dist/{chunk-GIC6BASP.js → chunk-TNSCIPBQ.js} +2 -2
  168. package/dist/{chunk-ZMDMHSV2.js → chunk-TVEONGBU.js} +2 -2
  169. package/dist/{chunk-4FSEZRGK.js → chunk-TWF35IC6.js} +2 -2
  170. package/dist/{chunk-LS2SGMQE.js → chunk-U6N5IBVY.js} +2 -2
  171. package/dist/{chunk-62YW6OYI.js → chunk-UCKYTA2T.js} +3 -3
  172. package/dist/{chunk-YFCHNOGJ.js → chunk-UNNPNBR2.js} +9 -9
  173. package/dist/{chunk-Z2M7F4QM.js → chunk-VVX5PZFS.js} +3 -3
  174. package/dist/{chunk-NTYLZXDX.js → chunk-VYCOJKSX.js} +2 -2
  175. package/dist/{chunk-UICSQESY.js → chunk-W24T5YMW.js} +2 -2
  176. package/dist/{chunk-HDQUQBPW.js → chunk-W3K3HITK.js} +2 -2
  177. package/dist/{chunk-GDASG7NC.js → chunk-W4F3C7N7.js} +2 -2
  178. package/dist/{chunk-YBLZFNIQ.js → chunk-WJHGDE7X.js} +2 -2
  179. package/dist/{chunk-ZBPXG5PJ.js → chunk-WMLEPWMO.js} +9 -9
  180. package/dist/chunk-WMLEPWMO.js.map +1 -0
  181. package/dist/{chunk-4F24PHNX.js → chunk-WQZZDN5M.js} +2 -2
  182. package/dist/{chunk-CDZEUCV7.js → chunk-X5K5TAQZ.js} +4 -4
  183. package/dist/{chunk-5AUODSOQ.js → chunk-XM24CDZX.js} +3 -3
  184. package/dist/{chunk-6VML2LII.js → chunk-XOVKXJEP.js} +3 -3
  185. package/dist/{chunk-OU5TIWDQ.js → chunk-XSGUMQQQ.js} +12 -12
  186. package/dist/{chunk-7CFVBWDC.js → chunk-XUE46UYW.js} +3 -3
  187. package/dist/{chunk-DJORULH3.js → chunk-YRLHEEQT.js} +2 -2
  188. package/dist/{chunk-YRWDPE32.js → chunk-Z3O53WZR.js} +2 -2
  189. package/dist/{chunk-CSY5DA7O.js → chunk-Z6COGHHN.js} +2 -2
  190. package/dist/{chunk-OYR3IPHD.js → chunk-ZIW5JVRM.js} +2 -2
  191. package/dist/{cli-B_YwqoIr.d.ts → cli-BqMNkQn5.d.ts} +1 -1
  192. package/dist/cli.d.ts +2 -2
  193. package/dist/cli.js +94 -94
  194. package/dist/coding/export-okf-codegraph.js +21 -21
  195. package/dist/coding/pre-action-gate.js +4 -3
  196. package/dist/commitment-ledger.js +3 -2
  197. package/dist/compounding/engine.js +21 -21
  198. package/dist/config.js +12 -11
  199. package/dist/connectors/codex-materialize-runner.js +21 -21
  200. package/dist/connectors/codex-materialize.js +3 -3
  201. package/dist/connectors/index.js +21 -21
  202. package/dist/consolidation-provenance-check.js +4 -4
  203. package/dist/consolidation-undo.js +3 -3
  204. package/dist/contradiction/index.js +7 -7
  205. package/dist/convergence-refresh.js +22 -22
  206. package/dist/corpus-watermark.js +22 -22
  207. package/dist/cue-anchors.js +4 -3
  208. package/dist/deep-recall-http-glue.d.ts +1 -1
  209. package/dist/deep-recall-http-glue.js +7 -6
  210. package/dist/deep-recall-mcp-tools.d.ts +1 -1
  211. package/dist/entity-retrieval.js +20 -20
  212. package/dist/eval-trajectory-store.js +4 -3
  213. package/dist/eval-trajectory.js +4 -3
  214. package/dist/evals.js +3 -2
  215. package/dist/explicit-capture.js +8 -8
  216. package/dist/external-wiki-access.d.ts +1 -1
  217. package/dist/external-wiki-access.js +54 -54
  218. package/dist/external-wiki-mcp-tools.d.ts +1 -1
  219. package/dist/extraction.js +25 -25
  220. package/dist/{first-start-migration-KHIMCBIC.js → first-start-migration-RC345GPL.js} +6 -5
  221. package/dist/{first-start-migration-KHIMCBIC.js.map → first-start-migration-RC345GPL.js.map} +1 -1
  222. package/dist/{graph-edge-decay-CJW4OT2X.js → graph-edge-decay-MKIRZ762.js} +5 -4
  223. package/dist/graph-jsonl.js +3 -2
  224. package/dist/graph-snapshot.js +3 -2
  225. package/dist/graph.js +2 -1
  226. package/dist/harmonic-construction.js +5 -4
  227. package/dist/harmonic-retrieval.js +5 -4
  228. package/dist/index.d.ts +19 -7
  229. package/dist/index.js +114 -112
  230. package/dist/json-store.js +2 -1
  231. package/dist/live-connectors-runner.js +3 -2
  232. package/dist/location/index.js +23 -23
  233. package/dist/maintenance/memory-governance.js +20 -20
  234. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +20 -20
  235. package/dist/maintenance/rebuild-memory-projection.js +21 -21
  236. package/dist/mcp-memory-inspector-app.d.ts +1 -1
  237. package/dist/memory-projection-mutations.js +3 -3
  238. package/dist/memory-subject-cli.d.ts +1 -1
  239. package/dist/memory-subject.d.ts +1 -1
  240. package/dist/memory-subject.js +4 -4
  241. package/dist/namespaces/migrate.js +21 -21
  242. package/dist/namespaces/search.js +8 -8
  243. package/dist/namespaces/storage.js +20 -20
  244. package/dist/objective-state-writers.js +4 -3
  245. package/dist/objective-state.js +3 -2
  246. package/dist/offline-sync-file-io.js +4 -3
  247. package/dist/offline-sync-impression-drain.js +5 -5
  248. package/dist/offline-sync.js +5 -4
  249. package/dist/operator-doctor-corpus.js +23 -23
  250. package/dist/operator-toolkit.js +38 -38
  251. package/dist/orchestration/maintenance.js +29 -29
  252. package/dist/orchestrator.js +112 -112
  253. package/dist/page-versioning.js +3 -3
  254. package/dist/{public-http-D6d4W8x-.d.ts → public-http-ByX2eTla.d.ts} +1 -1
  255. package/dist/{purge-OP6BEDFY.js → purge-TZKRE6ZQ.js} +5 -5
  256. package/dist/purge-TZKRE6ZQ.js.map +1 -0
  257. package/dist/recall-state.js +3 -3
  258. package/dist/reconcile/manifest.js +4 -4
  259. package/dist/{resolution-U5O4QANY.js → resolution-VKATP2HT.js} +8 -8
  260. package/dist/resume-bundles.js +16 -15
  261. package/dist/salvage-envelope.js +6 -6
  262. package/dist/schemas.d.ts +42 -42
  263. package/dist/search/document-scanner.js +3 -3
  264. package/dist/search/factory.js +7 -7
  265. package/dist/search/index.js +7 -7
  266. package/dist/search/lancedb-backend.js +4 -4
  267. package/dist/search/meilisearch-backend.js +4 -4
  268. package/dist/search/orama-backend.js +4 -4
  269. package/dist/secure-store/index.js +3 -3
  270. package/dist/semantic-consolidation.js +22 -22
  271. package/dist/semantic-rule-promotion.js +20 -20
  272. package/dist/semantic-rule-verifier.js +20 -20
  273. package/dist/source-agent-qualifier.js +24 -24
  274. package/dist/standup/build.js +20 -20
  275. package/dist/storage.js +19 -19
  276. package/dist/subject-config.js +5 -5
  277. package/dist/support-passport/index.d.ts +4 -4
  278. package/dist/support-passport/index.js +56 -56
  279. package/dist/{tier-stats-2TOW3QNL.js → tier-stats-KA6OZX2C.js} +6 -5
  280. package/dist/{tier-stats-2TOW3QNL.js.map → tier-stats-KA6OZX2C.js.map} +1 -1
  281. package/dist/transfer/capsule-import.js +4 -4
  282. package/dist/transfer/export-okf.js +21 -21
  283. package/dist/transfer/types.d.ts +12 -12
  284. package/dist/trust-zones.js +3 -2
  285. package/dist/utility-learner.js +4 -3
  286. package/dist/utility-runtime.js +5 -4
  287. package/dist/utility-telemetry.js +3 -2
  288. package/dist/verified-recall.js +20 -20
  289. package/dist/who-knows-cli.d.ts +1 -1
  290. package/dist/who-knows-cli.js +21 -21
  291. package/dist/who-knows.d.ts +1 -1
  292. package/dist/who-knows.js +20 -20
  293. package/dist/work/board.js +3 -3
  294. package/dist/work/storage.js +2 -2
  295. package/dist/work-product-ledger.js +3 -2
  296. package/dist/write-envelope.js +5 -5
  297. package/package.json +2 -2
  298. package/src/abstraction-nodes.ts +1 -4
  299. package/src/binary-lifecycle/backend.ts +2 -1
  300. package/src/connectors/live/github.ts +10 -17
  301. package/src/connectors/live/gmail.ts +8 -19
  302. package/src/connectors/live/google-drive.ts +6 -13
  303. package/src/connectors/live/notion.ts +11 -21
  304. package/src/cue-anchors.ts +1 -6
  305. package/src/graph.ts +2 -4
  306. package/src/json-store.ts +17 -20
  307. package/src/live-connectors-runner.ts +2 -1
  308. package/src/location/store.ts +1 -4
  309. package/src/maintenance/purge.ts +2 -5
  310. package/src/maintenance/rebuild-memory-lifecycle-ledger.ts +3 -6
  311. package/src/maintenance/rebuild-memory-projection.ts +2 -5
  312. package/src/namespaces/catalog.ts +1 -9
  313. package/src/offline-sync-file-io.test.ts +39 -0
  314. package/src/offline-sync-file-io.ts +3 -7
  315. package/src/procedural/procedure-miner.ts +1 -9
  316. package/src/search/document-scanner.ts +3 -6
  317. package/src/semantic-rule-promotion.ts +1 -4
  318. package/src/utils/errno.test.ts +31 -0
  319. package/src/utils/errno.ts +5 -0
  320. package/src/wearables/index.ts +1 -0
  321. package/src/wearables/registry.ts +23 -0
  322. package/dist/chunk-4KNRKJXQ.js.map +0 -1
  323. package/dist/chunk-5UZXUTVO.js.map +0 -1
  324. package/dist/chunk-62WZDHTW.js.map +0 -1
  325. package/dist/chunk-ACPCA4NO.js.map +0 -1
  326. package/dist/chunk-DDQQY2E3.js.map +0 -1
  327. package/dist/chunk-DJUKBGAD.js.map +0 -1
  328. package/dist/chunk-HTIIXNJQ.js.map +0 -1
  329. package/dist/chunk-I3FDDCY3.js.map +0 -1
  330. package/dist/chunk-MSOXFXCA.js.map +0 -1
  331. package/dist/chunk-P77QX3ID.js.map +0 -1
  332. package/dist/chunk-TXJNRGMI.js.map +0 -1
  333. package/dist/chunk-UR6PBX2J.js.map +0 -1
  334. package/dist/chunk-W7IGLX4G.js.map +0 -1
  335. package/dist/chunk-WW6B7NQJ.js.map +0 -1
  336. package/dist/chunk-ZBPXG5PJ.js.map +0 -1
  337. package/dist/purge-OP6BEDFY.js.map +0 -1
  338. package/dist/{access-service-Cv8Rizo0.d.ts → access-service-GrdVg_-Z.d.ts} +6 -6
  339. /package/dist/{auto-sync-TTIEWJ5X.js.map → auto-sync-WNGG2GC2.js.map} +0 -0
  340. /package/dist/{capsule-merge-CU6QJBSV.js.map → capsule-merge-IPG4IOFP.js.map} +0 -0
  341. /package/dist/{chunk-5RWHODVF.js.map → chunk-27QVNSQ3.js.map} +0 -0
  342. /package/dist/{chunk-2MX7RU7B.js.map → chunk-2EKJDQZB.js.map} +0 -0
  343. /package/dist/{chunk-XLRM6PPI.js.map → chunk-2IOHTUP3.js.map} +0 -0
  344. /package/dist/{chunk-ZGQDTD5T.js.map → chunk-2ITE4C2Z.js.map} +0 -0
  345. /package/dist/{chunk-O5ZR7SXV.js.map → chunk-2SGLMP2E.js.map} +0 -0
  346. /package/dist/{chunk-FYWLSFFS.js.map → chunk-2Z4GS5E6.js.map} +0 -0
  347. /package/dist/{chunk-WELP4CG6.js.map → chunk-37KUQPX4.js.map} +0 -0
  348. /package/dist/{chunk-MRSLR6TB.js.map → chunk-3QQTXYZ6.js.map} +0 -0
  349. /package/dist/{chunk-CI6C33EO.js.map → chunk-46ZPIGWI.js.map} +0 -0
  350. /package/dist/{chunk-MCA2X4WH.js.map → chunk-4IHBN6WU.js.map} +0 -0
  351. /package/dist/{chunk-TOZCM7WN.js.map → chunk-4TKJGOCJ.js.map} +0 -0
  352. /package/dist/{chunk-3ADRFFRO.js.map → chunk-54WHLA65.js.map} +0 -0
  353. /package/dist/{chunk-Z2N2AHEM.js.map → chunk-56Y6EKZN.js.map} +0 -0
  354. /package/dist/{chunk-2H2N5UQW.js.map → chunk-5ATKSPEQ.js.map} +0 -0
  355. /package/dist/{chunk-ZVZHG7AI.js.map → chunk-5UBH37SL.js.map} +0 -0
  356. /package/dist/{chunk-YZYZ2BEU.js.map → chunk-66OJSCI6.js.map} +0 -0
  357. /package/dist/{chunk-HNPE66LB.js.map → chunk-6CVNSDCZ.js.map} +0 -0
  358. /package/dist/{chunk-ERVJFFTR.js.map → chunk-6NXSYYGP.js.map} +0 -0
  359. /package/dist/{chunk-2HIJHXB3.js.map → chunk-6WHJ2EAB.js.map} +0 -0
  360. /package/dist/{chunk-34VTBPNE.js.map → chunk-6XL73HQ4.js.map} +0 -0
  361. /package/dist/{chunk-YK3UIF7X.js.map → chunk-AQ7SYDVO.js.map} +0 -0
  362. /package/dist/{chunk-DSCCM66R.js.map → chunk-B3O3IRZN.js.map} +0 -0
  363. /package/dist/{chunk-N37X5RU7.js.map → chunk-BD7JTBYP.js.map} +0 -0
  364. /package/dist/{chunk-VO43BJ2F.js.map → chunk-BLJWYCNO.js.map} +0 -0
  365. /package/dist/{chunk-HSKSVY3Q.js.map → chunk-C553ZTLF.js.map} +0 -0
  366. /package/dist/{chunk-GCASGYIO.js.map → chunk-C7HJ3NEI.js.map} +0 -0
  367. /package/dist/{chunk-WVGXCBOC.js.map → chunk-D5F7TKMH.js.map} +0 -0
  368. /package/dist/{chunk-UFT2XNBW.js.map → chunk-DGS34QSY.js.map} +0 -0
  369. /package/dist/{chunk-VAOL3SOT.js.map → chunk-DZD3WGCD.js.map} +0 -0
  370. /package/dist/{chunk-KHMS2FQS.js.map → chunk-E2P7TZTF.js.map} +0 -0
  371. /package/dist/{chunk-6FC3IZ26.js.map → chunk-EBA5DA77.js.map} +0 -0
  372. /package/dist/{chunk-E6EANYLD.js.map → chunk-EOQ6FSQP.js.map} +0 -0
  373. /package/dist/{chunk-7RPPCA26.js.map → chunk-FVOP3NT7.js.map} +0 -0
  374. /package/dist/{chunk-NRLELHAY.js.map → chunk-G7NYVKD6.js.map} +0 -0
  375. /package/dist/{chunk-QY34X2QJ.js.map → chunk-GHTSNGBZ.js.map} +0 -0
  376. /package/dist/{chunk-SLIOMMPF.js.map → chunk-H272ZPQ3.js.map} +0 -0
  377. /package/dist/{chunk-ZZBQNQS6.js.map → chunk-H3TKENU4.js.map} +0 -0
  378. /package/dist/{chunk-5OPNUUBX.js.map → chunk-H4SEGIZY.js.map} +0 -0
  379. /package/dist/{chunk-F2HMDGLC.js.map → chunk-H54VWRPS.js.map} +0 -0
  380. /package/dist/{chunk-HTP6XRUI.js.map → chunk-HM7RHKS4.js.map} +0 -0
  381. /package/dist/{chunk-O7H3P2SJ.js.map → chunk-HWLIMQE2.js.map} +0 -0
  382. /package/dist/{chunk-ET2CNMLD.js.map → chunk-JN72EPOE.js.map} +0 -0
  383. /package/dist/{chunk-E7UQOS4C.js.map → chunk-JPKK466T.js.map} +0 -0
  384. /package/dist/{chunk-JCCWJHOP.js.map → chunk-JYZSRNR7.js.map} +0 -0
  385. /package/dist/{chunk-7IUESBLV.js.map → chunk-K7724CH2.js.map} +0 -0
  386. /package/dist/{chunk-UK7HXNNJ.js.map → chunk-KAXCYM66.js.map} +0 -0
  387. /package/dist/{chunk-7XVP4P4O.js.map → chunk-KB2G2I6Q.js.map} +0 -0
  388. /package/dist/{chunk-K7LTRJZU.js.map → chunk-KEF46KL2.js.map} +0 -0
  389. /package/dist/{chunk-JYYTWCPU.js.map → chunk-KTWG7CNY.js.map} +0 -0
  390. /package/dist/{chunk-XTYDEO7M.js.map → chunk-L7Z57SID.js.map} +0 -0
  391. /package/dist/{chunk-EYMPUXAN.js.map → chunk-LO4UKPKX.js.map} +0 -0
  392. /package/dist/{chunk-LDWIPYJ6.js.map → chunk-LS2FHUML.js.map} +0 -0
  393. /package/dist/{chunk-GDB4J2H3.js.map → chunk-MPC7TYTZ.js.map} +0 -0
  394. /package/dist/{chunk-2GF27PGH.js.map → chunk-MRPOZBJC.js.map} +0 -0
  395. /package/dist/{chunk-7OLKAQMG.js.map → chunk-MWN6QEI2.js.map} +0 -0
  396. /package/dist/{chunk-J62HG52Z.js.map → chunk-MY5EDR46.js.map} +0 -0
  397. /package/dist/{chunk-IZRMWPGS.js.map → chunk-N3ZOP7KC.js.map} +0 -0
  398. /package/dist/{chunk-N6A2RP5S.js.map → chunk-NB3LRY4T.js.map} +0 -0
  399. /package/dist/{chunk-4N5BIR2U.js.map → chunk-ND6IQGSZ.js.map} +0 -0
  400. /package/dist/{chunk-NOB2T2FC.js.map → chunk-NHLLKEKK.js.map} +0 -0
  401. /package/dist/{chunk-M5CQNOQN.js.map → chunk-O6ZNNVSP.js.map} +0 -0
  402. /package/dist/{chunk-NNBZS3DY.js.map → chunk-OB3XMWX5.js.map} +0 -0
  403. /package/dist/{chunk-SIBVIP2Y.js.map → chunk-PAZY2ZKP.js.map} +0 -0
  404. /package/dist/{chunk-LXESHEBP.js.map → chunk-PX4UMA5Z.js.map} +0 -0
  405. /package/dist/{chunk-NNZFPYYX.js.map → chunk-R7QY5ZVB.js.map} +0 -0
  406. /package/dist/{chunk-WTRTFIIN.js.map → chunk-R7RTXEYG.js.map} +0 -0
  407. /package/dist/{chunk-XRBJ5R3P.js.map → chunk-RBCQVOVJ.js.map} +0 -0
  408. /package/dist/{chunk-WFZNT4KB.js.map → chunk-RC5DXXWC.js.map} +0 -0
  409. /package/dist/{chunk-5QZR2RA3.js.map → chunk-ROBHL3GL.js.map} +0 -0
  410. /package/dist/{chunk-6PST2SFW.js.map → chunk-SCXURCVT.js.map} +0 -0
  411. /package/dist/{chunk-AYG7ML7O.js.map → chunk-SJDQ5RSN.js.map} +0 -0
  412. /package/dist/{chunk-IQXDSKTL.js.map → chunk-SVXJLDDC.js.map} +0 -0
  413. /package/dist/{chunk-SEF4IOFE.js.map → chunk-SWIKABKI.js.map} +0 -0
  414. /package/dist/{chunk-ZJABRLCZ.js.map → chunk-TBXAY2SS.js.map} +0 -0
  415. /package/dist/{chunk-GIC6BASP.js.map → chunk-TNSCIPBQ.js.map} +0 -0
  416. /package/dist/{chunk-ZMDMHSV2.js.map → chunk-TVEONGBU.js.map} +0 -0
  417. /package/dist/{chunk-4FSEZRGK.js.map → chunk-TWF35IC6.js.map} +0 -0
  418. /package/dist/{chunk-LS2SGMQE.js.map → chunk-U6N5IBVY.js.map} +0 -0
  419. /package/dist/{chunk-62YW6OYI.js.map → chunk-UCKYTA2T.js.map} +0 -0
  420. /package/dist/{chunk-YFCHNOGJ.js.map → chunk-UNNPNBR2.js.map} +0 -0
  421. /package/dist/{chunk-Z2M7F4QM.js.map → chunk-VVX5PZFS.js.map} +0 -0
  422. /package/dist/{chunk-NTYLZXDX.js.map → chunk-VYCOJKSX.js.map} +0 -0
  423. /package/dist/{chunk-UICSQESY.js.map → chunk-W24T5YMW.js.map} +0 -0
  424. /package/dist/{chunk-HDQUQBPW.js.map → chunk-W3K3HITK.js.map} +0 -0
  425. /package/dist/{chunk-GDASG7NC.js.map → chunk-W4F3C7N7.js.map} +0 -0
  426. /package/dist/{chunk-YBLZFNIQ.js.map → chunk-WJHGDE7X.js.map} +0 -0
  427. /package/dist/{chunk-4F24PHNX.js.map → chunk-WQZZDN5M.js.map} +0 -0
  428. /package/dist/{chunk-CDZEUCV7.js.map → chunk-X5K5TAQZ.js.map} +0 -0
  429. /package/dist/{chunk-5AUODSOQ.js.map → chunk-XM24CDZX.js.map} +0 -0
  430. /package/dist/{chunk-6VML2LII.js.map → chunk-XOVKXJEP.js.map} +0 -0
  431. /package/dist/{chunk-OU5TIWDQ.js.map → chunk-XSGUMQQQ.js.map} +0 -0
  432. /package/dist/{chunk-7CFVBWDC.js.map → chunk-XUE46UYW.js.map} +0 -0
  433. /package/dist/{chunk-DJORULH3.js.map → chunk-YRLHEEQT.js.map} +0 -0
  434. /package/dist/{chunk-YRWDPE32.js.map → chunk-Z3O53WZR.js.map} +0 -0
  435. /package/dist/{chunk-CSY5DA7O.js.map → chunk-Z6COGHHN.js.map} +0 -0
  436. /package/dist/{chunk-OYR3IPHD.js.map → chunk-ZIW5JVRM.js.map} +0 -0
  437. /package/dist/{graph-edge-decay-CJW4OT2X.js.map → graph-edge-decay-MKIRZ762.js.map} +0 -0
  438. /package/dist/{resolution-U5O4QANY.js.map → resolution-VKATP2HT.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/search/document-scanner.ts"],"sourcesContent":["import path from \"node:path\";\nimport { lstat, readdir, readFile, realpath } from \"node:fs/promises\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport { assertPathInsideRoot } from \"../utils/path-containment.js\";\n\nexport interface IndexableDocument {\n /** Memory ID from frontmatter or filename stem */\n docid: string;\n /** Absolute file path */\n path: string;\n /** Markdown body (no YAML frontmatter) */\n content: string;\n /** First ~200 chars for display */\n snippet: string;\n}\n\n/**\n * Parse YAML frontmatter from a markdown string.\n * Returns the frontmatter key-value pairs and body, or null if no frontmatter block.\n */\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } | null {\n // Support both LF and CRLF line endings\n const normalized = raw.replace(/\\r\\n/g, \"\\n\");\n const match = normalized.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) return null;\n\n const fmBlock = match[1];\n const body = (match[2] ?? \"\").trim();\n const data: Record<string, string> = {};\n\n for (const line of fmBlock.split(\"\\n\")) {\n const colonIdx = line.indexOf(\":\");\n if (colonIdx === -1) continue;\n const key = line.slice(0, colonIdx).trim();\n const value = line.slice(colonIdx + 1).trim();\n data[key] = value;\n }\n\n return { data, body };\n}\n\n/**\n * Recursively scan a directory for `.md` files and return IndexableDocuments.\n */\nasync function scanDir(dir: string, memoryRootReal: string): Promise<IndexableDocument[]> {\n const docs: IndexableDocument[] = [];\n try {\n const dirStat = await lstat(dir);\n if (dirStat.isSymbolicLink()) {\n throw new Error(`Refusing to scan symlinked memory category directory: ${dir}`);\n }\n if (!dirStat.isDirectory()) {\n const error = new Error(`Memory category path is not a directory: ${dir}`) as NodeJS.ErrnoException;\n error.code = \"ENOTDIR\";\n throw error;\n }\n assertPathInsideRoot(memoryRootReal, await realpath(dir), dir);\n\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue;\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n assertPathInsideRoot(memoryRootReal, await realpath(fullPath), fullPath);\n const sub = await scanDir(fullPath, memoryRootReal);\n docs.push(...sub);\n } else if (entry.name.endsWith(\".md\")) {\n try {\n assertPathInsideRoot(memoryRootReal, await realpath(fullPath), fullPath);\n const raw = await readFile(fullPath, \"utf-8\");\n const parsed = parseFrontmatter(raw);\n const body = parsed ? parsed.body : raw.trim();\n const docid = parsed?.data.id || path.basename(entry.name, \".md\");\n docs.push({\n docid,\n path: fullPath,\n content: body,\n snippet: body.slice(0, 200),\n });\n } catch {\n // Skip unreadable files\n }\n }\n }\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n // Optional category directories may not exist yet.\n return docs;\n }\n throw err;\n }\n return docs;\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\n/**\n * Scan every recall category subdir of memoryDir for indexable markdown\n * documents. The directory set is derived from `RECALL_FALLBACK_DIRS`\n * (utils/category-dir.ts → ALL_CATEGORY_DIRS minus non-recall queue dirs) —\n * the single source of truth — so adding a new category never requires\n * touching this scanner. Non-QMD backends (Orama / Meilisearch / LanceDB)\n * build their index through this helper; deriving from RECALL_FALLBACK_DIRS\n * keeps them in parity with writeMemory's category-dir routing (issue #1546)\n * and the QMD filesystem-fallback corpus. reasoning-traces/ and the other\n * category dirs are covered automatically (issue #564 PR 3 no longer needs a\n * hand-maintained list). scanDir tolerates missing dirs (ENOENT), so category\n * dirs that do not exist yet are skipped.\n */\nexport async function scanMemoryDir(memoryDir: string): Promise<IndexableDocument[]> {\n let memoryRootReal: string;\n try {\n memoryRootReal = await realpath(memoryDir);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n const perDir = await Promise.all(\n RECALL_FALLBACK_DIRS.map((dir) => scanDir(path.join(memoryDir, dir), memoryRootReal)),\n );\n return perDir.flat();\n}\n"],"mappings":";;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,OAAO,SAAS,UAAU,gBAAgB;AAmBnD,SAAS,iBAAiB,KAAoE;AAE5F,QAAM,aAAa,IAAI,QAAQ,SAAS,IAAI;AAC5C,QAAM,QAAQ,WAAW,MAAM,oCAAoC;AACnE,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,UAAU,MAAM,CAAC;AACvB,QAAM,QAAQ,MAAM,CAAC,KAAK,IAAI,KAAK;AACnC,QAAM,OAA+B,CAAC;AAEtC,aAAW,QAAQ,QAAQ,MAAM,IAAI,GAAG;AACtC,UAAM,WAAW,KAAK,QAAQ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;AAChE,eAAK,KAAK;AAAA,YACR;AAAA,YACA,MAAM;AAAA,YACN,SAAS;AAAA,YACT,SAAS,KAAK,MAAM,GAAG,GAAG;AAAA,UAC5B,CAAC;AAAA,QACH,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,YAAY,GAAG,KAAK,IAAI,SAAS,UAAU;AAE7C,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACA,SAAO;AACT;AAEA,SAAS,YAAY,KAA4C;AAC/D,SAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU;AAC9D;AAeA,eAAsB,cAAc,WAAiD;AACnF,MAAI;AACJ,MAAI;AACF,qBAAiB,MAAM,SAAS,SAAS;AAAA,EAC3C,SAAS,KAAK;AACZ,QAAI,YAAY,GAAG,KAAK,IAAI,SAAS,UAAU;AAC7C,aAAO,CAAC;AAAA,IACV;AACA,UAAM;AAAA,EACR;AACA,QAAM,SAAS,MAAM,QAAQ;AAAA,IAC3B,qBAAqB,IAAI,CAAC,QAAQ,QAAQ,KAAK,KAAK,WAAW,GAAG,GAAG,cAAc,CAAC;AAAA,EACtF;AACA,SAAO,OAAO,KAAK;AACrB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/location/intervals.ts","../src/location/matching.ts","../src/location/store.ts","../src/location/tagging.ts"],"sourcesContent":["/**\n * Location interval math (issue #2044).\n *\n * Pure, deterministic helpers over UTC ISO-8601 instants: half-open\n * [start, end) day windows (reusing the DST-correct activity day-window), IANA\n * local-day bucketing, overlap, observation→segment dwell, and dominant-place\n * selection with stable tie-breaking. No IO, no clocks, no randomness.\n */\n\nimport { activityDayWindow, isValidActivityDate } from \"../activity/digest.js\";\nimport type { LocationObservation, LocationPlace, LocationSegment } from \"./types.js\";\n\nexport function isValidLocationDate(date: string): boolean {\n return isValidActivityDate(date);\n}\n\n/** Half-open [start, end) UTC ISO bounds of a local day. */\nexport function locationDayWindow(date: string, timezone: string): { startUtc: string; endUtc: string } {\n if (!isValidActivityDate(date)) {\n throw new RangeError(`Invalid location date \"${date}\"; expected a real YYYY-MM-DD day.`);\n }\n return activityDayWindow(date, timezone);\n}\n\nfunction assertFiniteInstant(iso: string, what: string): number {\n const ms = Date.parse(iso);\n if (typeof iso !== \"string\" || !Number.isFinite(ms)) {\n throw new RangeError(`${what} must be a UTC ISO-8601 instant; got \"${String(iso)}\"`);\n }\n return ms;\n}\n\n/** The IANA local calendar day (YYYY-MM-DD) an instant falls in. */\nexport function localDayKey(instantUtc: string, timezone: string): string {\n assertFiniteInstant(instantUtc, \"instantUtc\");\n return new Intl.DateTimeFormat(\"en-CA\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n }).format(new Date(instantUtc));\n}\n\nfunction compareObservations(a: LocationObservation, b: LocationObservation): number {\n if (a.observedAtUtc !== b.observedAtUtc) {\n return a.observedAtUtc < b.observedAtUtc ? -1 : 1;\n }\n // Total comparator (§12): equal-key observations fall back to place id so\n // ordering — and therefore dwell attribution — is deterministic.\n if (a.place.id !== b.place.id) {\n return a.place.id < b.place.id ? -1 : 1;\n }\n return 0;\n}\n\n/** Bucket observations into their IANA local days, sorted within each day. */\nexport function bucketObservationsByDay(\n observations: readonly LocationObservation[],\n timezone: string,\n): Map<string, LocationObservation[]> {\n const buckets = new Map<string, LocationObservation[]>();\n for (const observation of observations) {\n assertFiniteInstant(observation.observedAtUtc, \"observation observedAtUtc\");\n const key = localDayKey(observation.observedAtUtc, timezone);\n const bucket = buckets.get(key);\n if (bucket === undefined) buckets.set(key, [observation]);\n else bucket.push(observation);\n }\n for (const bucket of buckets.values()) bucket.sort(compareObservations);\n return buckets;\n}\n\n/** Overlap in ms of two half-open intervals; 0 when disjoint. */\nexport function intervalOverlapMs(\n a: { startUtc: string; endUtc: string },\n b: { startUtc: string; endUtc: string },\n): number {\n const overlap =\n Math.min(Date.parse(a.endUtc), Date.parse(b.endUtc)) - Math.max(Date.parse(a.startUtc), Date.parse(b.startUtc));\n return Math.max(0, overlap);\n}\n\nfunction placeForSegment(place: LocationPlace, retainCoordinates: boolean): LocationPlace {\n if (retainCoordinates || place.latitude === undefined || place.longitude === undefined) {\n return place;\n }\n return {\n id: place.id,\n label: place.label,\n ...(place.kind === undefined ? {} : { kind: place.kind }),\n };\n}\n\n/**\n * Derive place-visit segments from a day's observations: each observation\n * covers [its instant, the next observation's instant ∩ window end). The last\n * observation is capped by the window end, so dwell never crosses the day\n * boundary. Out-of-window observations are a provider contract violation and\n * are rejected loudly rather than silently reshaping the day. Coordinates are\n * stripped unless `retainCoordinates` is set.\n */\nexport function observationSegments(\n observations: readonly LocationObservation[],\n window: { startUtc: string; endUtc: string },\n options: { retainCoordinates: boolean },\n): LocationSegment[] {\n const startMs = assertFiniteInstant(window.startUtc, \"window startUtc\");\n const endMs = assertFiniteInstant(window.endUtc, \"window endUtc\");\n if (startMs >= endMs) {\n throw new RangeError(\"location window must satisfy startUtc < endUtc\");\n }\n const ordered = [...observations].sort(compareObservations);\n const segments: LocationSegment[] = [];\n for (let index = 0; index < ordered.length; index += 1) {\n const current = ordered[index]!;\n const currentMs = Date.parse(current.observedAtUtc);\n if (currentMs < startMs || currentMs >= endMs) {\n throw new RangeError(\n `location observation at \"${current.observedAtUtc}\" falls outside the requested [${window.startUtc}, ${window.endUtc}) window`,\n );\n }\n const nextMs =\n index + 1 < ordered.length ? Date.parse(ordered[index + 1]!.observedAtUtc) : endMs;\n const segmentEndMs = Math.min(nextMs, endMs);\n if (currentMs >= segmentEndMs) continue;\n segments.push({\n startUtc: new Date(currentMs).toISOString(),\n endUtc: new Date(segmentEndMs).toISOString(),\n place: placeForSegment(current.place, options.retainCoordinates),\n ...(current.confidence !== undefined ? { confidence: current.confidence } : {}),\n });\n }\n return segments;\n}\n\n/** Total time a place was occupied (union of its segment intervals, ms). */\nexport interface PlaceDuration {\n place: LocationPlace;\n totalMs: number;\n /** Earliest segment start contributing to this place's total. */\n firstStartUtc: string;\n}\n\nfunction unionIntervalMs(segments: readonly LocationSegment[]): number {\n // Merge overlapping [start, end) intervals per place so two providers\n // observing the same visit do not double-count its duration.\n const bounds = segments\n .map((segment) => ({ start: Date.parse(segment.startUtc), end: Date.parse(segment.endUtc) }))\n .sort((a, b) => (a.start !== b.start ? a.start - b.start : a.end - b.end));\n let total = 0;\n let sweepStart: number | null = null;\n let sweepEnd = 0;\n for (const bound of bounds) {\n if (sweepStart === null || bound.start > sweepEnd) {\n if (sweepStart !== null) total += sweepEnd - sweepStart;\n sweepStart = bound.start;\n sweepEnd = bound.end;\n } else if (bound.end > sweepEnd) {\n sweepEnd = bound.end;\n }\n }\n if (sweepStart !== null) total += sweepEnd - sweepStart;\n return total;\n}\n\n/** Per-place totals across every segment given (multi-source safe). */\nexport function placeDurations(segments: readonly LocationSegment[]): PlaceDuration[] {\n const byPlace = new Map<string, { place: LocationPlace; segments: LocationSegment[]; firstStartUtc: string }>();\n for (const segment of segments) {\n const existing = byPlace.get(segment.place.id);\n if (existing === undefined) {\n byPlace.set(segment.place.id, { place: segment.place, segments: [segment], firstStartUtc: segment.startUtc });\n continue;\n }\n existing.segments.push(segment);\n if (segment.startUtc < existing.firstStartUtc) existing.firstStartUtc = segment.startUtc;\n // Two providers may label the same place id differently; keep the\n // lexicographically smallest label so rendering stays deterministic.\n if (segment.place.label < existing.place.label) existing.place = segment.place;\n }\n const durations: PlaceDuration[] = [...byPlace.values()].map((entry) => ({\n place: entry.place,\n totalMs: unionIntervalMs(entry.segments),\n firstStartUtc: entry.firstStartUtc,\n }));\n durations.sort((a, b) => {\n if (a.place.id !== b.place.id) return a.place.id < b.place.id ? -1 : 1;\n return 0;\n });\n return durations;\n}\n\nexport interface DominantPlaceResult {\n place: LocationPlace;\n totalMs: number;\n}\n\n/**\n * The place with the longest total occupancy. Ties are stable and\n * deterministic: earlier first start wins, then the lexicographically smaller\n * place id — never insertion order.\n */\nexport function dominantPlace(segments: readonly LocationSegment[]): DominantPlaceResult | null {\n const durations = placeDurations(segments);\n let best: PlaceDuration | null = null;\n for (const duration of durations) {\n if (best === null) {\n best = duration;\n continue;\n }\n if (duration.totalMs !== best.totalMs) {\n if (duration.totalMs > best.totalMs) best = duration;\n continue;\n }\n if (duration.firstStartUtc !== best.firstStartUtc) {\n if (duration.firstStartUtc < best.firstStartUtc) best = duration;\n continue;\n }\n if (duration.place.id < best.place.id) best = duration;\n }\n return best === null ? null : { place: best.place, totalMs: best.totalMs };\n}\n","/**\n * Core location matcher (issue #2046) — the ONE place that decides whether a\n * memory or wearable conversation gets provider location context.\n *\n * Pure and deterministic: no IO, no clocks, no randomness. Inputs are UTC\n * ISO-8601 instants and half-open [start, end) intervals everywhere.\n *\n * Rules (issue #2046 / umbrella #2043 decision D):\n * 1. A valid memory interval is required — derived ONLY from the memory's own\n * bi-temporal frontmatter (`valid_at` / `observedAt` / `invalid_at`), never\n * from wall-clock time or message order. Untimed memories stay untagged.\n * 2. Intervals longer than 24h describe long-lived facts, not events at a\n * place; they stay untagged.\n * 3. A place is tagged only when it is DOMINANT (strictly the longest overlap\n * among candidate places; ties are conflicts and leave the memory untagged)\n * and meets `minimumOverlapSeconds` and `minimumConfidence`.\n * 4. Only resolved named places participate (`kind` home/work/poi): transit\n * legs and unnamed visits never tag a memory.\n * 5. No address is ever inferred from text, coordinates, IP, or proximity —\n * only provider-supplied place metadata is echoed, and coordinates only\n * when `retainCoordinates` is enabled.\n *\n * Provider-owned metadata contract: the tag is `location:<stable-place-slug>`\n * and the opaque provider place id lives in structured attributes. Every\n * field the matcher writes is provider-owned; a memory that carries\n * location-ish metadata WITHOUT the `locationSource` marker is treated as\n * manual/user-authored and is never touched.\n */\n\nimport { TAG_LIMITS, STRUCTURED_ATTRIBUTE_LIMITS } from \"../write-envelope.js\";\nimport type { LocationPlace, LocationSegment } from \"./types.js\";\n\n/** Maximum memory span eligible for location tagging. */\nexport const LOCATION_MATCH_MAX_MEMORY_SPAN_MS = 24 * 60 * 60 * 1000;\n\n/** Prefix of provider-owned location tags. */\nexport const LOCATION_TAG_PREFIX = \"location:\";\n\n/** Structured-attribute keys owned by the tagging pipeline (never manual). */\nexport const LOCATION_ATTRIBUTE_KEYS = [\n \"locationSource\",\n \"locationPlaceId\",\n \"locationPlace\",\n \"locationConfidence\",\n \"locationVisitStart\",\n \"locationVisitEnd\",\n \"locationLatitude\",\n \"locationLongitude\",\n] as const;\n\n/** Place kinds eligible for tagging: resolved, named places only. */\nconst TAGGABLE_PLACE_KINDS: Record<string, true> = { home: true, work: true, poi: true };\n\nexport interface LocationTagPolicy {\n minimumOverlapSeconds: number;\n minimumConfidence: number;\n retainCoordinates: boolean;\n}\n\n/** The memory side of a match: a half-open interval, or a single instant. */\nexport type MemoryLocationWindow =\n | { kind: \"interval\"; startUtc: string; endUtc: string }\n | { kind: \"instant\"; atUtc: string };\n\n/** Why a window was rejected before matching. */\nexport type WindowRejectReason = \"untimed\" | \"span-too-long\";\n\nexport interface WindowResult {\n window?: MemoryLocationWindow;\n /** Local days (YYYY-MM-DD in the tag policy timezone) the window touches. */\n days?: string[];\n rejected?: WindowRejectReason;\n}\n\n/**\n * Derive the match window from a memory's own frontmatter. `validAt` (the\n * event start; assumed copies carry the ingestion anchor) opens the window;\n * `invalid_at` closes it. An end-only memory (no start bound) is untimed.\n */\nexport function memoryLocationWindow(\n frontmatter: { valid_at?: string; observedAt?: string; invalid_at?: string },\n localDay: (instantUtc: string) => string,\n): WindowResult {\n const start = frontmatter.valid_at ?? frontmatter.observedAt;\n if (start === undefined || Number.isNaN(Date.parse(start))) {\n return { rejected: \"untimed\" };\n }\n const end = frontmatter.invalid_at;\n if (end === undefined || Number.isNaN(Date.parse(end)) || Date.parse(end) <= Date.parse(start)) {\n return { window: { kind: \"instant\", atUtc: start }, days: [localDay(start)] };\n }\n if (Date.parse(end) - Date.parse(start) > LOCATION_MATCH_MAX_MEMORY_SPAN_MS) {\n return { rejected: \"span-too-long\" };\n }\n // The interval is half-open [start, end): its last instant is end-1ms, so a\n // memory ending exactly at local midnight never touches the next day.\n const lastInstant = new Date(Date.parse(end) - 1).toISOString();\n const days = [localDay(start)];\n const endDay = localDay(lastInstant);\n if (endDay !== days[0]) days.push(endDay);\n return { window: { kind: \"interval\", startUtc: start, endUtc: end }, days };\n}\n\n/** One source's segments for a day, keyed by the configured source id. */\nexport interface LocationSourceSegments {\n sourceId: string;\n segments: LocationSegment[];\n}\n\nexport interface LocationMatch {\n sourceId: string;\n place: LocationPlace;\n /** Overlap (ms) with the window — interval mode; see `visitMs` otherwise. */\n overlapMs: number;\n /** Total dwell (ms) of the dominant place inside the window's day(s). */\n visitMs: number;\n /** Minimum contributing segment confidence, when any source reported one. */\n confidence?: number;\n /** Envelope [start, end) of the segments that produced the match. */\n visitStartUtc: string;\n visitEndUtc: string;\n}\n\nexport type MatchOutcome =\n | { status: \"matched\"; match: LocationMatch }\n | { status: \"unmatched\"; reason: \"no-overlap\" | \"ambiguous\" | \"below-minimum-overlap\" | \"below-minimum-confidence\" };\n\ninterface PlaceAccumulator {\n sourceId: string;\n place: LocationPlace;\n overlapMs: number;\n visitMs: number;\n confidence: number | undefined;\n startUtc: string;\n endUtc: string;\n}\n\nfunction overlapMsOf(\n window: MemoryLocationWindow,\n segment: { startUtc: string; endUtc: string },\n): number {\n if (window.kind === \"instant\") {\n const at = Date.parse(window.atUtc);\n return at >= Date.parse(segment.startUtc) && at < Date.parse(segment.endUtc) ? 1 : 0;\n }\n return Math.max(\n 0,\n Math.min(Date.parse(window.endUtc), Date.parse(segment.endUtc)) -\n Math.max(Date.parse(window.startUtc), Date.parse(segment.startUtc)),\n );\n}\n\n/**\n * The dominant qualifying place for a window, across every source's\n * segments. Deterministic: strict overlap comparison, ties (conflicts) are\n * rejected, and equal-place contributions merge across sources.\n */\nexport function matchDominantPlace(\n window: MemoryLocationWindow,\n sources: readonly LocationSourceSegments[],\n policy: LocationTagPolicy,\n): MatchOutcome {\n const byPlace = new Map<string, PlaceAccumulator>();\n for (const source of sources) {\n for (const segment of source.segments) {\n if (TAGGABLE_PLACE_KINDS[segment.place.kind ?? \"\"] !== true) continue;\n const overlap = overlapMsOf(window, segment);\n if (overlap <= 0) continue;\n const duration = Date.parse(segment.endUtc) - Date.parse(segment.startUtc);\n const existing = byPlace.get(segment.place.id);\n if (existing === undefined) {\n byPlace.set(segment.place.id, {\n sourceId: source.sourceId,\n place: segment.place,\n overlapMs: overlap,\n visitMs: duration,\n confidence: segment.confidence,\n startUtc: segment.startUtc,\n endUtc: segment.endUtc,\n });\n continue;\n }\n // Same place from another source (or a revisit): accumulate.\n existing.overlapMs += overlap;\n existing.visitMs += duration;\n existing.confidence =\n existing.confidence === undefined\n ? segment.confidence\n : segment.confidence === undefined\n ? existing.confidence\n : Math.min(existing.confidence, segment.confidence);\n if (segment.startUtc < existing.startUtc) existing.startUtc = segment.startUtc;\n if (segment.endUtc > existing.endUtc) existing.endUtc = segment.endUtc;\n }\n }\n if (byPlace.size === 0) return { status: \"unmatched\", reason: \"no-overlap\" };\n\n let best: PlaceAccumulator | null = null;\n let tie = false;\n for (const candidate of byPlace.values()) {\n if (best === null || candidate.overlapMs > best.overlapMs) {\n best = candidate;\n tie = false;\n continue;\n }\n if (candidate.overlapMs === best.overlapMs) tie = true;\n }\n if (best === null || tie) return { status: \"unmatched\", reason: \"ambiguous\" };\n\n const overlapForThreshold = window.kind === \"instant\" ? best.visitMs : best.overlapMs;\n if (policy.minimumOverlapSeconds > 0 && overlapForThreshold < policy.minimumOverlapSeconds * 1000) {\n return { status: \"unmatched\", reason: \"below-minimum-overlap\" };\n }\n if (best.confidence !== undefined && best.confidence < policy.minimumConfidence) {\n return { status: \"unmatched\", reason: \"below-minimum-confidence\" };\n }\n return {\n status: \"matched\",\n match: {\n sourceId: best.sourceId,\n place: best.place,\n overlapMs: best.overlapMs,\n visitMs: best.visitMs,\n ...(best.confidence !== undefined ? { confidence: best.confidence } : {}),\n visitStartUtc: best.startUtc,\n visitEndUtc: best.endUtc,\n },\n };\n}\n\n/** Deterministic tag slug for a provider place id (`reitti:place:7` → `reitti-place-7`). */\nexport function locationTagSlug(placeId: string): string {\n const slug = placeId\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n // The collapse above leaves at most one dash at each edge, so single-char\n // strips are complete. The old /^-+|-+$/ alternation backtracked\n // quadratically on unsanitized dash runs (CodeQL js/polynomial-redos);\n // single-character anchors are linear.\n .replace(/^-/, \"\")\n .replace(/-$/, \"\");\n return slug.slice(0, TAG_LIMITS.maxTagLength - LOCATION_TAG_PREFIX.length);\n}\n\n/** The provider-owned tag for a matched place. */\nexport function locationTagForPlace(placeId: string): string {\n return `${LOCATION_TAG_PREFIX}${locationTagSlug(placeId)}`;\n}\n\nfunction boundedAttributeValue(value: string): string {\n return value.slice(0, STRUCTURED_ATTRIBUTE_LIMITS.maxValueLength);\n}\n\n/** Provider-owned structured attributes describing a match. */\nexport function locationAttributesForMatch(\n match: LocationMatch,\n policy: LocationTagPolicy,\n): Record<string, string> {\n const attributes: Record<string, string> = {\n locationSource: match.sourceId,\n locationPlaceId: boundedAttributeValue(match.place.id),\n locationPlace: boundedAttributeValue(match.place.label),\n ...(match.confidence !== undefined ? { locationConfidence: match.confidence.toFixed(3) } : {}),\n locationVisitStart: match.visitStartUtc,\n locationVisitEnd: match.visitEndUtc,\n };\n if (policy.retainCoordinates && match.place.latitude !== undefined && match.place.longitude !== undefined) {\n attributes.locationLatitude = String(match.place.latitude);\n attributes.locationLongitude = String(match.place.longitude);\n }\n return attributes;\n}\n\nexport interface LocationUpdatePlan {\n /** Patch for `writeMemoryFrontmatter`; absent when nothing changes. */\n patch?: { tags: string[]; structuredAttributes: Record<string, string> };\n /** Outcome for reporting. */\n outcome:\n | \"tagged\"\n | \"updated\"\n | \"removed\"\n | \"unchanged\"\n | \"manual-metadata\"\n | \"unmatched\"\n | \"untimed\"\n | \"span-too-long\";\n}\n\nfunction frontmatterHasLocationMetadata(\n frontmatter: { tags?: string[]; structuredAttributes?: Record<string, string> },\n): boolean {\n if ((frontmatter.tags ?? []).some((tag) => tag.startsWith(LOCATION_TAG_PREFIX))) return true;\n return Object.keys(frontmatter.structuredAttributes ?? {}).some((key) =>\n (LOCATION_ATTRIBUTE_KEYS as readonly string[]).includes(key),\n );\n}\n\nfunction isProviderOwned(frontmatter: { structuredAttributes?: Record<string, string> }): boolean {\n const source = frontmatter.structuredAttributes?.locationSource;\n return typeof source === \"string\" && source.length > 0;\n}\n\n/**\n * Plan the provider-owned update for one memory: a match adds/replaces ONLY\n * provider-owned fields; a lost match removes them (corrected observations);\n * manual location metadata (no `locationSource` marker) always wins and is\n * never touched. Unrelated tags and attributes survive every path.\n */\nexport function planLocationUpdate(\n frontmatter: { tags?: string[]; structuredAttributes?: Record<string, string> },\n outcome: MatchOutcome,\n policy: LocationTagPolicy,\n): LocationUpdatePlan {\n if (frontmatterHasLocationMetadata(frontmatter) && !isProviderOwned(frontmatter)) {\n return { outcome: \"manual-metadata\" };\n }\n const tags = [...(frontmatter.tags ?? [])];\n const attributes = { ...(frontmatter.structuredAttributes ?? {}) };\n const providerTagIndex = tags.findIndex((tag) => tag.startsWith(LOCATION_TAG_PREFIX));\n const stripProviderFields = (): void => {\n if (providerTagIndex >= 0) tags.splice(providerTagIndex, 1);\n for (const key of LOCATION_ATTRIBUTE_KEYS) delete attributes[key];\n };\n\n if (outcome.status !== \"matched\") {\n if (!isProviderOwned(frontmatter)) return { outcome: \"unmatched\" };\n if (providerTagIndex < 0 && !(\"locationPlaceId\" in attributes)) {\n return { outcome: \"unchanged\" };\n }\n stripProviderFields();\n return { patch: { tags, structuredAttributes: attributes }, outcome: \"removed\" };\n }\n\n const desiredTag = locationTagForPlace(outcome.match.place.id);\n const desiredAttributes = locationAttributesForMatch(outcome.match, policy);\n if (tags.length >= TAG_LIMITS.maxTags && providerTagIndex < 0) {\n // Full tag budget with no provider slot to reuse — leave the memory alone.\n return { outcome: \"unchanged\" };\n }\n const alreadyCurrent =\n providerTagIndex >= 0 &&\n tags[providerTagIndex] === desiredTag &&\n LOCATION_ATTRIBUTE_KEYS.every((key) => {\n const want = desiredAttributes[key];\n const have = attributes[key];\n return want === undefined ? have === undefined : have === want;\n });\n if (alreadyCurrent) return { outcome: \"unchanged\" };\n\n if (providerTagIndex >= 0) tags[providerTagIndex] = desiredTag;\n else tags.push(desiredTag);\n for (const key of LOCATION_ATTRIBUTE_KEYS) delete attributes[key];\n Object.assign(attributes, desiredAttributes);\n const wasProviderOwned = isProviderOwned(frontmatter);\n return {\n patch: { tags, structuredAttributes: attributes },\n outcome: wasProviderOwned ? \"updated\" : \"tagged\",\n };\n}\n","/**\n * Location day-file + sync-state store (issue #2044).\n *\n * Day documents live at `<memoryDir>/locations/<YYYY-MM-DD>.md` — OUTSIDE the\n * memory scan roots (facts/, entities/, …) so raw location history never\n * surfaces as a memory in recall or governance passes, and INSIDE the QMD\n * collection root so the markdown stays full-text searchable once an index\n * update runs. Per-source sync state lives at\n * `<memoryDir>/state/locations/sync.json` and is written only after the day\n * document is durable (see pipeline.ts).\n *\n * Both writes are atomic (temp file + rename) and containment-checked: a\n * symlinked `locations/` root or day file is rejected even when it resolves\n * inside the memory dir (AGENTS.md pattern #3), and a path that escapes the\n * memory dir is refused outright.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { lstat, mkdir, readFile, readdir, realpath } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { writeFileAtomically } from \"../maintenance/atomic-file.js\";\nimport { pathIsInside } from \"../utils/path-containment.js\";\nimport { isValidLocationDate, placeDurations } from \"./intervals.js\";\nimport type { LocationSegment } from \"./types.js\";\n\nexport const LOCATIONS_DIR_NAME = \"locations\";\nexport const LOCATION_DAY_KIND = \"location-day\";\nexport const LOCATION_DAY_FORMAT_VERSION = 1;\n\n/** Cap on remembered day payloads per source (~3 months of days). */\nconst MAX_TRACKED_LOCATION_DAYS = 90;\n\nconst DAY_FILE_NAME_PATTERN = /^\\d{4}-\\d{2}-\\d{2}\\.md$/;\n\n// Serializes state load→mutate→save sections per state file so two sources\n// syncing concurrently cannot lose-update each other's entries.\nconst stateLocks = new Map<string, Promise<unknown>>();\n\nfunction withStateLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prior = stateLocks.get(key) ?? Promise.resolve();\n const next = prior.then(fn, fn);\n const tail = next.then(\n () => undefined,\n () => undefined,\n );\n stateLocks.set(key, tail);\n void tail.then(() => {\n if (stateLocks.get(key) === tail) stateLocks.delete(key);\n });\n return next;\n}\n\nexport function locationDayFilePath(memoryDir: string, date: string): string {\n if (!isValidLocationDate(date)) {\n // Never interpolate an unvalidated date into a filesystem path (a `../`\n // would escape <memoryDir>/locations/). Reject loudly.\n throw new RangeError(`Invalid location date \"${date}\"; expected a real YYYY-MM-DD day.`);\n }\n return path.join(memoryDir, LOCATIONS_DIR_NAME, `${date}.md`);\n}\n\nexport function locationSyncStateFilePath(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"locations\", \"sync.json\");\n}\n\n/** A source's derived day payload, kept in sync state for multi-source merges. */\nexport interface LocationSourceDayPayload {\n observationCount: number;\n segments: LocationSegment[];\n providerDisplayName?: string;\n}\n\nexport interface LocationSourceSyncState {\n lastSyncedAtUtc?: string;\n days?: Record<string, LocationSourceDayPayload>;\n}\n\nexport interface LocationSyncStateFile {\n version: 1;\n sources: Record<string, LocationSourceSyncState>;\n}\n\nexport function emptyLocationSyncState(): LocationSyncStateFile {\n return { version: 1, sources: {} };\n}\n\nexport async function loadLocationSyncState(memoryDir: string): Promise<LocationSyncStateFile> {\n let raw: string;\n try {\n raw = await readFile(locationSyncStateFilePath(memoryDir), \"utf-8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return emptyLocationSyncState();\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // A corrupt state file must not brick syncing forever; treat it as a cold\n // start. The worst case is re-syncing days already on disk, and the day\n // file's contentHash makes that rewrite idempotent.\n return emptyLocationSyncState();\n }\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n Array.isArray(parsed) ||\n typeof (parsed as LocationSyncStateFile).sources !== \"object\" ||\n (parsed as LocationSyncStateFile).sources === null\n ) {\n return emptyLocationSyncState();\n }\n return { version: 1, sources: (parsed as LocationSyncStateFile).sources };\n}\n\nexport async function saveLocationSyncState(\n memoryDir: string,\n state: LocationSyncStateFile,\n): Promise<void> {\n await mkdir(path.dirname(locationSyncStateFilePath(memoryDir)), { recursive: true, mode: 0o700 });\n await writeFileAtomically(\n locationSyncStateFilePath(memoryDir),\n `${JSON.stringify(state, null, 2)}\\n`,\n );\n}\n\nfunction pruneSourceDays(source: LocationSourceSyncState): void {\n const days = source.days;\n if (days === undefined) return;\n const keys = Object.keys(days).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n for (const key of keys.slice(0, Math.max(0, keys.length - MAX_TRACKED_LOCATION_DAYS))) {\n delete days[key];\n }\n}\n\n/**\n * Record one source's completed day sync. Runs the whole read-modify-write\n * under the per-directory state lock so concurrent sources cannot clobber\n * each other, and prunes day payloads beyond the retention cap.\n */\nexport async function updateLocationSourceDay(\n memoryDir: string,\n sourceId: string,\n date: string,\n payload: LocationSourceDayPayload,\n completedAtUtc: string,\n): Promise<LocationSyncStateFile> {\n if (!isValidLocationDate(date)) {\n throw new RangeError(`Invalid location date \"${date}\"; expected a real YYYY-MM-DD day.`);\n }\n return withStateLock(locationSyncStateFilePath(memoryDir), async () => {\n const state = await loadLocationSyncState(memoryDir);\n const source = state.sources[sourceId] ?? {};\n const days = source.days ?? {};\n days[date] = payload;\n source.days = days;\n source.lastSyncedAtUtc = completedAtUtc;\n state.sources[sourceId] = source;\n for (const candidate of Object.values(state.sources)) pruneSourceDays(candidate);\n await saveLocationSyncState(memoryDir, state);\n return state;\n });\n}\n/** Frontmatter persisted on a rendered day document. */\nexport interface LocationDayMeta {\n kind: typeof LOCATION_DAY_KIND;\n date: string;\n timezone: string;\n formatVersion: number;\n sources: string[];\n observationCount: number;\n /** SHA-256 of the rendered body (rebuild idempotency). */\n contentHash: string;\n}\n\n/** A parsed day document (frontmatter + rendered body). */\nexport interface LocationDayDocument {\n meta: LocationDayMeta;\n body: string;\n}\n\n/** The per-source view a day document is composed from. */\nexport interface LocationDaySourceEntry extends LocationSourceDayPayload {\n /** Provider display name for the timeline heading; falls back to the id. */\n providerDisplayName?: string;\n}\n\nexport function hashLocationBody(body: string): string {\n return createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\n}\n\nfunction clockHhMm(iso: string, timezone: string): string {\n return new Intl.DateTimeFormat(\"en-GB\", {\n timeZone: timezone,\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n }).format(new Date(iso));\n}\n\nfunction formatDuration(ms: number): string {\n const totalMinutes = Math.round(ms / 60_000);\n const hours = Math.floor(totalMinutes / 60);\n const minutes = totalMinutes % 60;\n if (hours <= 0) return `${minutes}m`;\n return `${hours}h ${String(minutes).padStart(2, \"0\")}m`;\n}\n\n/** Collapse whitespace and strip markdown emphasis/backticks from a label. */\nfunction safeLabel(label: string): string {\n return label.replace(/\\s+/g, \" \").replace(/[`*_]/g, \"\").trim();\n}\n\nfunction formatPlaceLabel(segment: LocationSegment): string {\n const label = safeLabel(segment.place.label);\n return segment.place.kind === undefined ? label : `${label} (${segment.place.kind})`;\n}\n\nfunction formatCoordinates(segment: LocationSegment): string {\n if (segment.place.latitude === undefined || segment.place.longitude === undefined) return \"\";\n return ` @ ${segment.place.latitude.toFixed(4)},${segment.place.longitude.toFixed(4)}`;\n}\n\nexport function composeLocationDayBody(\n date: string,\n timezone: string,\n sources: Record<string, LocationDaySourceEntry>,\n): string {\n const lines: string[] = [`# Location day — ${date} (${timezone})`, \"\"];\n const allSegments: LocationSegment[] = [];\n let observationCount = 0;\n for (const entry of Object.values(sources)) {\n allSegments.push(...entry.segments);\n observationCount += entry.observationCount;\n }\n\n lines.push(\"## Summary\", \"\");\n if (observationCount === 0) {\n lines.push(\"No location observations recorded.\", \"\");\n } else {\n const durations = placeDurations(allSegments).sort((a, b) => b.totalMs - a.totalMs);\n lines.push(\n `- Places visited: ${durations.length}`,\n ...durations.map(\n (duration) => `- ${safeLabel(duration.place.label)}: ${formatDuration(duration.totalMs)}`,\n ),\n \"\",\n );\n }\n\n const sourceIds = Object.keys(sources).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n for (const sourceId of sourceIds) {\n const entry = sources[sourceId]!;\n lines.push(`## Timeline — ${safeLabel(entry.providerDisplayName ?? sourceId)}`, \"\");\n if (entry.segments.length === 0) {\n lines.push(\"No observations.\", \"\");\n continue;\n }\n for (const segment of entry.segments) {\n lines.push(\n `- ${clockHhMm(segment.startUtc, timezone)}–${clockHhMm(segment.endUtc, timezone)} — ${formatPlaceLabel(segment)}${formatCoordinates(segment)}`,\n );\n }\n lines.push(\"\");\n }\n return `${lines.join(\"\\n\").trimEnd()}\\n`;\n}\n\nexport function composeLocationDayMeta(\n date: string,\n timezone: string,\n sources: Record<string, LocationDaySourceEntry>,\n body: string,\n): LocationDayMeta {\n let observationCount = 0;\n for (const entry of Object.values(sources)) observationCount += entry.observationCount;\n return {\n kind: LOCATION_DAY_KIND,\n date,\n timezone,\n formatVersion: LOCATION_DAY_FORMAT_VERSION,\n sources: Object.keys(sources).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),\n observationCount,\n contentHash: hashLocationBody(body),\n };\n}\n\nfunction frontmatterScalar(key: string, value: string | number): string {\n return `${key}: ${typeof value === \"number\" ? value : JSON.stringify(value)}`;\n}\n\nfunction frontmatterList(key: string, values: readonly string[]): string[] {\n if (values.length === 0) return [`${key}: []`];\n const lines = [`${key}:`];\n for (const value of values) lines.push(` - ${JSON.stringify(value)}`);\n return lines;\n}\n\nexport function serializeLocationDay(meta: LocationDayMeta, body: string): string {\n const lines: string[] = [\"---\"];\n lines.push(frontmatterScalar(\"kind\", meta.kind));\n lines.push(frontmatterScalar(\"date\", meta.date));\n lines.push(frontmatterScalar(\"timezone\", meta.timezone));\n lines.push(frontmatterScalar(\"formatVersion\", meta.formatVersion));\n lines.push(...frontmatterList(\"sources\", meta.sources));\n lines.push(frontmatterScalar(\"observationCount\", meta.observationCount));\n lines.push(frontmatterScalar(\"contentHash\", meta.contentHash));\n lines.push(\"---\", \"\", body);\n return lines.join(\"\\n\");\n}\n\nfunction parseScalar(raw: string): string {\n try {\n const parsed = JSON.parse(raw);\n return typeof parsed === \"string\" ? parsed : raw;\n } catch {\n return raw;\n }\n}\n\n/** A day document's frontmatter, parsed for idempotency checks and status. */\nexport interface LocationDaySummary {\n date: string;\n timezone: string;\n sources: string[];\n observationCount: number;\n contentHash: string;\n}\n\n/**\n * Parse a day document's frontmatter. Returns null when the content is not a\n * location day document (wrong kind, missing frontmatter) so callers can\n * distinguish a foreign file from a corrupt one.\n */\nexport function parseLocationDaySummary(raw: string): LocationDaySummary | null {\n if (!raw.startsWith(\"---\\n\")) return null;\n const closeIndex = raw.indexOf(\"\\n---\\n\", 4);\n if (closeIndex === -1) return null;\n const scalars: Record<string, string> = {};\n const lists: Record<string, string[]> = {};\n let currentList: string | null = null;\n for (const line of raw.slice(4, closeIndex).split(\"\\n\")) {\n const listItem = /^ {2}- (.*)$/.exec(line);\n if (listItem !== null && currentList !== null) {\n lists[currentList]!.push(parseScalar(listItem[1]!));\n continue;\n }\n currentList = null;\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator);\n const value = line.slice(separator + 1).trim();\n if (value === \"\" || value === \"[]\") {\n lists[key] = [];\n currentList = key;\n continue;\n }\n if (value.startsWith(\"[\")) {\n lists[key] = [parseScalar(value)];\n currentList = key;\n continue;\n }\n scalars[key] = value;\n }\n if (scalars.kind === undefined || parseScalar(scalars.kind) !== LOCATION_DAY_KIND) return null;\n if (scalars.date === undefined || scalars.contentHash === undefined) return null;\n return {\n date: parseScalar(scalars.date),\n timezone: scalars.timezone === undefined ? \"UTC\" : parseScalar(scalars.timezone),\n sources: lists.sources ?? [],\n observationCount: scalars.observationCount === undefined ? 0 : Number(scalars.observationCount) || 0,\n contentHash: parseScalar(scalars.contentHash),\n };\n}\n\n// ── Containment-checked day-file IO ─────────────────────────────────────────\n\nfunction isErrnoCode(err: unknown, code: string): boolean {\n return err instanceof Error && (err as NodeJS.ErrnoException).code === code;\n}\n\nasync function assertNotSymlink(target: string, kind: \"directory\" | \"day file\"): Promise<void> {\n let stat: { isSymbolicLink(): boolean };\n try {\n stat = await lstat(target);\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) return;\n throw err;\n }\n if (stat.isSymbolicLink()) {\n throw new Error(\n `locations ${kind} '${path.basename(target)}' is a symbolic link — refusing to follow it even when it resolves inside the memory dir (AGENTS.md pattern #3)`,\n );\n }\n}\n\nasync function assertNoEscape(rootReal: string, candidate: string): Promise<void> {\n let candidateReal: string;\n try {\n candidateReal = await realpath(candidate);\n } catch {\n return;\n }\n if (!pathIsInside(rootReal, candidateReal)) {\n throw new Error(\n \"location day path resolves outside the memory dir — refusing to follow a symlink/traversal (AGENTS.md pattern #3)\",\n );\n }\n}\n\nasync function assertDayPathContained(memoryDir: string, targetPath: string): Promise<void> {\n let rootReal: string;\n try {\n rootReal = await realpath(memoryDir);\n } catch {\n rootReal = path.resolve(memoryDir);\n }\n const locationsDir = path.join(memoryDir, LOCATIONS_DIR_NAME);\n await assertNoEscape(rootReal, locationsDir);\n await assertNoEscape(rootReal, targetPath);\n // Reject a symlinked locations root or day file outright — even when the\n // link resolves inside the memory dir (aliasing / tampering) — before IO.\n await assertNotSymlink(locationsDir, \"directory\");\n await assertNotSymlink(targetPath, \"day file\");\n}\n\n/**\n * Idempotently persist a day document: skip the write when the on-disk\n * contentHash already matches. The write is atomic and containment-checked;\n * the caller (pipeline) advances sync state only after this resolves.\n */\nexport async function writeLocationDay(\n memoryDir: string,\n date: string,\n serialized: string,\n): Promise<boolean> {\n const target = locationDayFilePath(memoryDir, date);\n await assertDayPathContained(memoryDir, target);\n try {\n if ((await readFile(target, \"utf-8\")) === serialized) return false;\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });\n await writeFileAtomically(target, serialized);\n return true;\n}\n\n/** Read a stored day document's raw markdown; null when absent. */\nexport async function readLocationDay(memoryDir: string, date: string): Promise<string | null> {\n const target = locationDayFilePath(memoryDir, date);\n await assertDayPathContained(memoryDir, target);\n try {\n return await readFile(target, \"utf-8\");\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) return null;\n throw err;\n }\n}\n\n/** List dates that have a stored day document, newest first. */\nexport async function listLocationDayDates(memoryDir: string): Promise<string[]> {\n const locationsDir = path.join(memoryDir, LOCATIONS_DIR_NAME);\n await assertDayPathContained(memoryDir, locationsDir);\n let entries: string[];\n try {\n entries = await readdir(locationsDir);\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) return [];\n throw err;\n }\n const dates = entries\n .filter((entry) => DAY_FILE_NAME_PATTERN.test(entry))\n .map((entry) => entry.slice(0, -3));\n dates.sort((a, b) => (a > b ? -1 : a < b ? 1 : 0));\n return dates;\n}\n","/**\n * Location tagging service (issue #2046) — the IO half around the pure\n * matcher in `matching.ts`. Three consumers share it so the policy can never\n * fork:\n *\n * 1. Write-time enrichment: after an extraction batch has cleared the\n * trust/importance/content-hash gates and persisted, the caller tags the\n * new memories (post-write, best-effort, never fails the extraction).\n * 2. Historical backfill (`location/backfill.ts`): the same plan/apply core\n * over a bounded date range, idempotent by construction.\n * 3. Wearable conversation fill: `WearableConversation.location` is filled\n * ONLY when the source did not provide one and the match passes policy.\n *\n * Segment data comes from the machine-global location sync state\n * (`state/locations/sync.json`, ≤ 90 tracked days — matching the bounded\n * backfill range). Reads are plain file loads; every memory mutation goes\n * through `StorageManager.writeMemoryFrontmatter`, the atomic frontmatter\n * chokepoint that preserves content (and therefore the content hash),\n * lifecycle, and versioning invariants.\n */\n\nimport type { StorageManager } from \"../index.js\";\nimport { log } from \"../logger.js\";\nimport type { MemoryFile } from \"../types.js\";\nimport type { WearableConversation } from \"../wearables/types.js\";\nimport { localDayKey, placeDurations } from \"./intervals.js\";\nimport {\n matchDominantPlace,\n memoryLocationWindow,\n planLocationUpdate,\n type LocationSourceSegments,\n type LocationTagPolicy,\n type LocationUpdatePlan,\n} from \"./matching.js\";\nimport { loadLocationSyncState } from \"./store.js\";\nimport type { LocationConfig } from \"./types.js\";\n\n/** Segments for one local day, per source id, from the sync state. */\nexport type DaySegmentIndex = Map<string, LocationSourceSegments[]>;\n\n/** Load every tracked day's per-source segments (one file read). */\nexport async function loadDaySegmentIndex(memoryDir: string): Promise<DaySegmentIndex> {\n const state = await loadLocationSyncState(memoryDir);\n const index: DaySegmentIndex = new Map();\n for (const [sourceId, source] of Object.entries(state.sources)) {\n for (const [date, payload] of Object.entries(source.days ?? {})) {\n const entry: LocationSourceSegments = { sourceId, segments: payload.segments ?? [] };\n const existing = index.get(date);\n if (existing === undefined) index.set(date, [entry]);\n else existing.push(entry);\n }\n }\n return index;\n}\n\nexport function locationTagPolicy(config: LocationConfig): LocationTagPolicy {\n return {\n minimumOverlapSeconds: config.minimumOverlapSeconds,\n minimumConfidence: config.minimumConfidence,\n retainCoordinates: config.retainCoordinates,\n };\n}\n\n/** Every tagging path is off unless BOTH gates are on. */\nexport function locationTaggingEnabled(config: LocationConfig): boolean {\n return config.enabled && config.tagging.enabled;\n}\n\n/**\n * Write-time post-persist hook (issue #2046): tag the memories an extraction\n * batch just made durable. Best-effort by contract — gated on both location\n * gates, and a location failure must never fail the extraction that already\n * persisted.\n */\nexport async function tagPersistedMemories(\n storage: StorageManager,\n memoryIds: string[],\n config: { memoryDir: string; location?: LocationConfig },\n): Promise<void> {\n if (memoryIds.length === 0 || !config.location || !locationTaggingEnabled(config.location)) return;\n try {\n await enrichMemoriesWithLocation({\n storage,\n memoryIds,\n memoryDir: config.memoryDir,\n config: config.location,\n });\n } catch (locationError) {\n log.warn(\"[location] post-write tagging failed (non-fatal)\", locationError);\n }\n}\n\nfunction segmentsForDays(index: DaySegmentIndex, days: readonly string[]): LocationSourceSegments[] {\n const merged = new Map<string, LocationSourceSegments>();\n for (const day of days) {\n for (const entry of index.get(day) ?? []) {\n const existing = merged.get(entry.sourceId);\n if (existing === undefined) {\n merged.set(entry.sourceId, { sourceId: entry.sourceId, segments: [...entry.segments] });\n continue;\n }\n existing.segments.push(...entry.segments);\n }\n }\n return [...merged.values()];\n}\n\n/** The full plan for one memory: window → segments → match → provider-owned diff. */\nfunction planForMemory(\n frontmatter: Pick<MemoryFile[\"frontmatter\"], \"valid_at\" | \"observedAt\" | \"invalid_at\" | \"tags\" | \"structuredAttributes\">,\n index: DaySegmentIndex,\n config: LocationConfig,\n): LocationUpdatePlan {\n const policy = locationTagPolicy(config);\n const result = memoryLocationWindow(frontmatter, (instant) => localDayKey(instant, config.timezone));\n if (result.rejected === \"span-too-long\") return { outcome: \"span-too-long\" };\n if (result.rejected === \"untimed\" || result.window === undefined || result.days === undefined) {\n return { outcome: \"untimed\" };\n }\n const sources = segmentsForDays(index, result.days);\n return planLocationUpdate(frontmatter, matchDominantPlace(result.window, sources, policy), policy);\n}\n\nexport interface LocationEnrichmentCounts {\n tagged: number;\n updated: number;\n removed: number;\n unchanged: number;\n unmatched: number;\n manual: number;\n untimed: number;\n spanTooLong: number;\n failed: number;\n}\n\nexport function emptyEnrichmentCounts(): LocationEnrichmentCounts {\n return {\n tagged: 0,\n updated: 0,\n removed: 0,\n unchanged: 0,\n unmatched: 0,\n manual: 0,\n untimed: 0,\n spanTooLong: 0,\n failed: 0,\n };\n}\n\nfunction countOutcome(counts: LocationEnrichmentCounts, outcome: LocationUpdatePlan[\"outcome\"]): void {\n if (outcome === \"tagged\") counts.tagged += 1;\n else if (outcome === \"updated\") counts.updated += 1;\n else if (outcome === \"removed\") counts.removed += 1;\n else if (outcome === \"unchanged\") counts.unchanged += 1;\n else if (outcome === \"manual-metadata\") counts.manual += 1;\n else if (outcome === \"unmatched\") counts.unmatched += 1;\n else if (outcome === \"untimed\") counts.untimed += 1;\n else if (outcome === \"span-too-long\") counts.spanTooLong += 1;\n}\n\nexport interface EnrichMemoriesOptions {\n storage: Pick<StorageManager, \"getMemoryById\" | \"writeMemoryFrontmatter\">;\n memoryDir: string;\n config: LocationConfig;\n /** Enrich exactly these memory ids (write-time path). */\n memoryIds?: string[];\n /** Pre-loaded memories (backfill path — one readAllMemories per run). */\n memories?: MemoryFile[];\n /** Reuse a caller-loaded segment index (backfill). */\n index?: DaySegmentIndex;\n /** Skip every mutation and only report (dry-run). */\n dryRun?: boolean;\n}\n\n/**\n * Apply the matcher to a set of memories and patch provider-owned location\n * metadata. A failure on ONE memory is counted and skipped — it never blocks\n * the others (failure isolation, issue #2046).\n */\nexport async function enrichMemoriesWithLocation(\n options: EnrichMemoriesOptions,\n): Promise<LocationEnrichmentCounts> {\n if (!locationTaggingEnabled(options.config)) return emptyEnrichmentCounts();\n const counts = emptyEnrichmentCounts();\n const index = options.index ?? (await loadDaySegmentIndex(options.memoryDir));\n\n let memories = options.memories;\n if (memories === undefined && options.memoryIds !== undefined) {\n memories = [];\n for (const id of options.memoryIds) {\n const memory = await options.storage.getMemoryById(id);\n if (memory !== null) memories.push(memory);\n }\n }\n if (memories === undefined) return counts;\n\n for (const memory of memories) {\n try {\n const plan = planForMemory(memory.frontmatter, index, options.config);\n // Count patch outcomes (tagged/updated/removed) only after the write\n // lands — a rejected write is `failed`, never also `tagged`.\n if (plan.patch === undefined || options.dryRun === true) {\n countOutcome(counts, plan.outcome);\n continue;\n }\n await options.storage.writeMemoryFrontmatter(memory, plan.patch, { actor: \"location-tagging\" });\n countOutcome(counts, plan.outcome);\n } catch {\n counts.failed += 1;\n }\n }\n return counts;\n}\n\n/**\n * Fill `WearableConversation.location` for conversations whose source did not\n * provide one. Missing-only and source-aware: a provider-supplied value is\n * never overwritten, and a failing conversation never blocks the others.\n */\nexport async function fillWearableConversationLocations(\n conversations: WearableConversation[],\n deps: { memoryDir: string; config: LocationConfig },\n): Promise<void> {\n if (!locationTaggingEnabled(deps.config) || conversations.length === 0) return;\n let index: DaySegmentIndex;\n try {\n index = await loadDaySegmentIndex(deps.memoryDir);\n } catch {\n return;\n }\n const policy = locationTagPolicy(deps.config);\n for (const conversation of conversations) {\n if (conversation.location !== undefined && conversation.location.length > 0) continue;\n try {\n const startMs = Date.parse(conversation.startIso);\n const endMs = conversation.endIso !== undefined ? Date.parse(conversation.endIso) : Number.NaN;\n const window =\n Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs\n ? { kind: \"interval\" as const, startUtc: conversation.startIso, endUtc: conversation.endIso as string }\n : { kind: \"instant\" as const, atUtc: conversation.startIso };\n const anchor = window.kind === \"interval\" ? new Date(Date.parse(window.endUtc) - 1).toISOString() : window.atUtc;\n const days = [...new Set([localDayKey(anchor, deps.config.timezone), localDayKey(conversation.startIso, deps.config.timezone)])];\n const outcome = matchDominantPlace(window, segmentsForDays(index, days), policy);\n if (outcome.status === \"matched\") {\n conversation.location = outcome.match.place.label;\n }\n } catch {\n // One bad conversation never blocks the rest of the day's fill.\n }\n }\n}\n\n/** Render an opt-in, labels-only location context section for a day summary. */\nexport async function renderDayLocationContext(\n memoryDir: string,\n date: string,\n config: LocationConfig,\n): Promise<string | null> {\n if (!locationTaggingEnabled(config)) return null;\n const state = await loadLocationSyncState(memoryDir);\n const segments = [];\n for (const source of Object.values(state.sources)) {\n for (const segment of source.days?.[date]?.segments ?? []) segments.push(segment);\n }\n if (segments.length === 0) return null;\n const durations = placeDurations(segments)\n .filter((duration) => [\"home\", \"work\", \"poi\"].includes(duration.place.kind ?? \"poi\"))\n .sort((a, b) => (a.totalMs !== b.totalMs ? b.totalMs - a.totalMs : a.place.id < b.place.id ? -1 : 1));\n if (durations.length === 0) return null;\n const lines = durations.map((duration) => {\n const minutes = Math.round(duration.totalMs / 60_000);\n const hours = Math.floor(minutes / 60);\n const rendered = hours <= 0 ? `${minutes}m` : `${hours}h ${String(minutes % 60).padStart(2, \"0\")}m`;\n return `- ${duration.place.label.replace(/\\s+/g, \" \").replace(/[`*_]/g, \"\").trim()}: ${rendered}`;\n });\n return `## Location context\\n\\n${lines.join(\"\\n\")}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYO,SAAS,oBAAoB,MAAuB;AACzD,SAAO,oBAAoB,IAAI;AACjC;AAGO,SAAS,kBAAkB,MAAc,UAAwD;AACtG,MAAI,CAAC,oBAAoB,IAAI,GAAG;AAC9B,UAAM,IAAI,WAAW,0BAA0B,IAAI,oCAAoC;AAAA,EACzF;AACA,SAAO,kBAAkB,MAAM,QAAQ;AACzC;AAEA,SAAS,oBAAoB,KAAa,MAAsB;AAC9D,QAAM,KAAK,KAAK,MAAM,GAAG;AACzB,MAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,SAAS,EAAE,GAAG;AACnD,UAAM,IAAI,WAAW,GAAG,IAAI,yCAAyC,OAAO,GAAG,CAAC,GAAG;AAAA,EACrF;AACA,SAAO;AACT;AAGO,SAAS,YAAY,YAAoB,UAA0B;AACxE,sBAAoB,YAAY,YAAY;AAC5C,SAAO,IAAI,KAAK,eAAe,SAAS;AAAA,IACtC,UAAU;AAAA,IACV,MAAM;AAAA,IACN,OAAO;AAAA,IACP,KAAK;AAAA,EACP,CAAC,EAAE,OAAO,IAAI,KAAK,UAAU,CAAC;AAChC;AAEA,SAAS,oBAAoB,GAAwB,GAAgC;AACnF,MAAI,EAAE,kBAAkB,EAAE,eAAe;AACvC,WAAO,EAAE,gBAAgB,EAAE,gBAAgB,KAAK;AAAA,EAClD;AAGA,MAAI,EAAE,MAAM,OAAO,EAAE,MAAM,IAAI;AAC7B,WAAO,EAAE,MAAM,KAAK,EAAE,MAAM,KAAK,KAAK;AAAA,EACxC;AACA,SAAO;AACT;AAGO,SAAS,wBACd,cACA,UACoC;AACpC,QAAM,UAAU,oBAAI,IAAmC;AACvD,aAAW,eAAe,cAAc;AACtC,wBAAoB,YAAY,eAAe,2BAA2B;AAC1E,UAAM,MAAM,YAAY,YA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","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/maintenance/rebuild-memory-lifecycle-ledger.ts"],"sourcesContent":["import path from \"node:path\";\nimport { stat } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport { assertInjectedStorageRooted } from \"./projection-support.js\";\nimport { log } from \"../logger.js\";\nimport { displayErrorDetail } from \"../runtime/better-sqlite.js\";\nimport type { MemoryLifecycleEvent } from \"../types.js\";\nimport { toBackupStamp } from \"./backup-stamp.js\";\nimport { copyExistingFileToBackup, writeFileAtomically } from \"./atomic-file.js\";\nimport {\n buildLifecycleEventsForMemory,\n compareMemoryLifecycleEvents,\n sortMemoryLifecycleEvents,\n isFrontmatterDerivedLifecycleEventType,\n memoryLifecycleEventProjectionIdentity,\n memoryLifecycleLedgerLockPath,\n MEMORY_LIFECYCLE_LEDGER_LOCK_STALE_MS,\n} from \"../memory-lifecycle-ledger-utils.js\";\nimport { withHeldFileLock, type HeldFileLockOptions, type HeldFileLockController } from \"../utils/serialize-mutations.js\";\nimport { probeEncryptedRegularFileHeader } from \"../secure-store/secure-fs.js\";\n\n\nexport interface RebuildMemoryLifecycleLedgerOptions {\n memoryDir: string;\n dryRun?: boolean;\n now?: Date;\n /**\n * Active storage context (issue #1910). When provided, memories are read\n * through it (so encrypted-at-rest memories in a secure-store deployment are\n * decrypted with the live key) and the rebuilt ledger is rewritten through\n * its secure writer (so it stays encrypted at rest). Its `dir` MUST equal\n * `memoryDir`. When omitted, a fresh plaintext `StorageManager` is used and\n * the ledger is written as plaintext — the CLI default.\n */\n storage?: StorageManager;\n /**\n * Preserve append-only lifecycle events that have no frontmatter equivalent\n * (issue #1910). `buildLifecycleEventsForMemory` only reconstructs\n * `created`/`updated`/`superseded`/`archived` from frontmatter, so a bare\n * rebuild silently drops history like `explicit_capture_accepted`,\n * `explicit_capture_queued`, `imported`, `promoted`, `merged`, `restored`,\n * and `rejected`. When true, the existing ledger's non-reconstructable rows\n * are read (via the same secure/permissive `readAllMemoryLifecycleEvents`\n * path), merged with the rebuilt rows, deduplicated by `eventId`, and sorted\n * canonically. Background auto-compaction sets this so it never loses events;\n * the manual/CLI repair rebuild leaves it off (reconstruct purely from\n * frontmatter).\n */\n preserveExistingEvents?: boolean;\n /**\n * Override the ledger-lock acquisition timing (issue #2033). Only\n * `maxWaitMs`/`pollMs` are honored; `staleMs` stays fixed at\n * `MEMORY_LIFECYCLE_LEDGER_LOCK_STALE_MS`. Used by tests to force the\n * lock-acquisition-failure branch (`acquired=false`) deterministically\n * without a multi-second wait.\n */\n lockOptions?: Pick<HeldFileLockOptions, \"maxWaitMs\" | \"pollMs\">;\n /**\n * Upper bound (bytes) on the rewritten ledger when preserving events (issue\n * #2033). A preserving compaction carries over ALL append-only history, which\n * — if the history alone is large — could leave the rewritten ledger over the\n * whole-file read/decrypt cap (STATE_FILE_MAX_DECRYPT_BYTES), the exact\n * unreadable-ledger failure compaction exists to prevent. When set and the\n * preserved payload would exceed it, the OLDEST rows are dropped from the\n * active ledger until it fits; because the full pre-compaction ledger is\n * copied verbatim to the timestamped backup first, those rows are archived,\n * not lost. Ignored when `preserveExistingEvents` is off (a frontmatter-only\n * rebuild is already bounded by the corpus). `0`/undefined disables bounding.\n */\n maxLedgerBytes?: number;\n}\n\nexport interface SkippedLifecycleBlankIdMemory {\n path: string;\n}\n\nexport interface SkippedDuplicateLifecycleEvent {\n eventId: string;\n keptPath: string;\n skippedPath: string;\n}\n\nexport interface RebuildMemoryLifecycleLedgerResult {\n dryRun: boolean;\n scannedMemories: number;\n rebuiltRows: number;\n outputPath: string;\n backupPath?: string;\n skippedBlankIdMemories: SkippedLifecycleBlankIdMemory[];\n skippedDuplicateEvents: SkippedDuplicateLifecycleEvent[];\n /**\n * Count of existing-ledger rows carried over beyond the frontmatter\n * reconstruction (only set when `preserveExistingEvents` is on; issue #1910):\n * append-only history with no frontmatter equivalent, plus any\n * frontmatter-derived row that raced in after the corpus scan and so was not\n * reproduced by the reconstruction (#2033).\n */\n preservedAppendOnlyRows?: number;\n /**\n * Count of oldest rows dropped from the ACTIVE ledger to keep it under\n * `maxLedgerBytes` (issue #2033). They remain in the verbatim timestamped\n * backup, so this is a bound-and-archive, not a loss. Set only when bounding\n * actually trimmed rows.\n */\n archivedOverflowRows?: number;\n /**\n * Whether the active ledger was actually backed up and rewritten (issue #2033\n * thread PRRT_kwDORJXyws6SExst). A preserving write-mode rebuild that would\n * reproduce the current ledger byte-for-byte (same decrypted content AND same\n * at-rest format) skips the backup+rewrite, so callers can distinguish a real\n * compaction from a no-op and avoid re-archiving an unchanged ledger every\n * interval. `true` for every dry run's non-write preview is never set — only\n * write-mode results carry it; defaults to `false` when no rewrite happened.\n */\n rewritten?: boolean;\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\n/** Serialized on-disk size (bytes, incl. trailing newline) of one ledger row. */\nfunction lifecycleRowBytes(event: MemoryLifecycleEvent): number {\n return Buffer.byteLength(`${JSON.stringify(event)}\\n`, \"utf8\");\n}\n\n/**\n * Keep the NEWEST canonically-ordered events whose serialized payload fits\n * strictly under `cap` bytes (issue #2033). Recency is by `timestamp` (newest\n * first), tie-broken by the canonical comparator, so a large append-only\n * history is trimmed to its most recent rows rather than to a single memoryId\n * group (the ledger's on-disk order is by memoryId then time).\n *\n * A row too large to fit the remaining budget is SKIPPED, and scanning\n * continues to older rows that still fit — one oversized (or future-dated,\n * hence recency-first) row cannot truncate the entire older history. The kept\n * subset is returned in the input's canonical order; the caller relies on the\n * verbatim backup to retain the dropped rows.\n */\nexport function boundLifecycleEventsToByteCap(\n events: MemoryLifecycleEvent[],\n cap: number,\n): { kept: MemoryLifecycleEvent[]; dropped: number } {\n if (!(cap > 0)) return { kept: events, dropped: 0 };\n const sizes = new Map<MemoryLifecycleEvent, number>();\n let total = 0;\n for (const event of events) {\n const bytes = lifecycleRowBytes(event);\n sizes.set(event, bytes);\n total += bytes;\n }\n if (total <= cap) return { kept: events, dropped: 0 };\n const byRecency = [...events].sort((a, b) => {\n if (a.timestamp !== b.timestamp) return b.timestamp.localeCompare(a.timestamp);\n return -compareMemoryLifecycleEvents(a, b);\n });\n const keep = new Set<MemoryLifecycleEvent>();\n let running = 0;\n for (const event of byRecency) {\n const bytes = sizes.get(event)!;\n if (running + bytes > cap) continue; // skip this row, keep scanning older rows that still fit\n running += bytes;\n keep.add(event);\n }\n const kept = events.filter((event) => keep.has(event));\n return { kept, dropped: events.length - kept.length };\n}\n\nexport async function backupExistingLedger(\n memoryDir: string,\n outputPath: string,\n now: Date,\n): Promise<string | undefined> {\n try {\n await stat(outputPath);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return undefined;\n }\n throw err;\n }\n\n const backupPath = path.join(\n memoryDir,\n \"archive\",\n \"memory-lifecycle-ledger\",\n toBackupStamp(now),\n \"state\",\n \"memory-lifecycle-ledger.jsonl\",\n );\n return backupPath;\n}\n\nexport async function rebuildMemoryLifecycleLedger(\n options: RebuildMemoryLifecycleLedgerOptions,\n): Promise<RebuildMemoryLifecycleLedgerResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const outputPath = path.join(options.memoryDir, \"state\", \"memory-lifecycle-ledger.jsonl\");\n const storage = assertInjectedStorageRooted(\"rebuildMemoryLifecycleLedger\", options.memoryDir, options.storage) ?? new StorageManager(options.memoryDir);\n const secureRewrite = options.storage !== undefined;\n const tiers = [\n await storage.readAllMemories(),\n await storage.readAllColdMemories(),\n await storage.readArchivedMemories(),\n ];\n const allMemories = tiers.flat();\n const skippedBlankIdMemories: SkippedLifecycleBlankIdMemory[] = [];\n const eventCandidates: Array<{ event: MemoryLifecycleEvent; path: string }> = [];\n for (const tier of tiers) {\n for (const memory of [...tier].sort((left, right) => left.path.localeCompare(right.path))) {\n if (!memory.frontmatter.id.trim()) {\n skippedBlankIdMemories.push({ path: memory.path });\n log.warn(`lifecycle ledger rebuild skipped blank memory id: path=${memory.path}`);\n continue;\n }\n for (const event of buildLifecycleEventsForMemory(memory)) {\n eventCandidates.push({ event, path: memory.path });\n }\n }\n }\n\n const orderedEvents = sortMemoryLifecycleEvents(eventCandidates.map((candidate) => candidate.event));\n const candidateByEvent = new Map(\n eventCandidates.map((candidate) => [candidate.event, candidate]),\n );\n const keptByEventId = new Map<string, { event: MemoryLifecycleEvent; path: string }>();\n const events: MemoryLifecycleEvent[] = [];\n const skippedDuplicateEvents: SkippedDuplicateLifecycleEvent[] = [];\n for (const event of orderedEvents) {\n const candidate = candidateByEvent.get(event)!;\n const kept = keptByEventId.get(event.eventId);\n if (kept) {\n skippedDuplicateEvents.push({\n eventId: event.eventId,\n keptPath: kept.path,\n skippedPath: candidate.path,\n });\n log.warn(\n `lifecycle ledger rebuild skipped duplicate event_id=${event.eventId}: `\n + `kept=${kept.path} skipped=${candidate.path}`,\n );\n continue;\n }\n keptByEventId.set(event.eventId, candidate);\n events.push(event);\n }\n\n let finalEvents = events;\n let preservedAppendOnlyRows: number | undefined;\n let archivedOverflowRows: number | undefined;\n let backupPath: string | undefined;\n let rewritten = false;\n // The preserve-read + whole-file rewrite are serialized against concurrent\n // lifecycle appends ONLY in write mode (issue #1910, codex):\n // appendMemoryLifecycleEvents holds this same cross-process lock, so an event\n // appended after the preserve-read but before the atomic rename waits and\n // lands on the compacted ledger instead of being clobbered by the rename. A\n // DRY RUN takes no lock — it reads the ledger read-only to compute the\n // preserve/merge/byte-cap PREVIEW and never rewrites, so it must not block\n // appends (#2033 Cursor). The corpus scan above stays outside the lock in\n // both modes — frontmatter-derived rows come from the memory files.\n const runLedgerCriticalSection = async (\n acquired: boolean,\n lock: HeldFileLockController | null,\n ): Promise<void> => {\n // A WRITE that read or rewrote the ledger without the lock could race a\n // concurrent append/rewrite and lose data, so REFUSE the unlocked fallback\n // withHeldFileLock takes on acquisition timeout (issue #2033 CodeRabbit\n // Critical / codex). A dry run passes lock=null and acquired=true: it never\n // reaches the rewrite, so the unlocked preview read is safe.\n if (!dryRun && !acquired) {\n throw new Error(\n \"lifecycle ledger rebuild aborted: could not acquire the ledger lock within the \"\n + \"acquisition budget; refusing to read or rewrite unlocked so a concurrent append \"\n + \"or compaction cannot be clobbered (issue #1910).\",\n );\n }\n if (options.preserveExistingEvents) {\n // Merge the frontmatter reconstruction (`events`) with the CURRENT ledger\n // so compaction never deletes a lifecycle row that raced the scan (issue\n // #1910, #2033). Read the existing ledger through the uncapped BUFFER\n // path — it decrypts with the live key when `storage` carries the secure\n // context and bypasses the whole-file string decrypt cap, so an oversize\n // encrypted ledger (the exact file compaction must shrink) is still\n // readable here rather than aborting (#2033 Cursor High).\n // preserveExistingEvents means \"never lose history\": if the current\n // ledger genuinely cannot be read (corruption, or a locked required\n // store), ABORT rather than rewrite from frontmatter only and silently\n // drop that history. An absent ledger reads as [] (ENOENT swallowed\n // downstream), so a throw here is always a real read failure.\n let existing: MemoryLifecycleEvent[];\n try {\n existing = await storage.readAllMemoryLifecycleEventsForCompaction();\n } catch (err) {\n throw new Error(\n `lifecycle ledger rebuild aborted: cannot read existing events to preserve `\n + `(${displayErrorDetail(err) || \"unknown error\"})`,\n );\n }\n // The corpus scan (`events`) runs OUTSIDE the lock and is therefore a\n // stale snapshot; `existing` is read here under the lock and is\n // authoritative for what the ledger holds at rewrite time. A\n // frontmatter-derived row (created/updated/superseded/archived) is safe to\n // collapse into the reconstruction ONLY when the scan actually reproduced\n // the same logical event — same (memoryId, eventType, timestamp), which is\n // exactly what the live append stamps (fm.created/updated/...) and what\n // makeRebuiltMemoryLifecycleEvent emits. A frontmatter-derived row whose\n // content key the reconstruction did NOT produce raced in after the scan\n // (a memory created/updated between the scan and this locked read); the\n // reconstruction has no equivalent, so dropping it by eventType alone\n // would delete it. Preserve it instead, deduped by content key so a\n // retried append of the same logical event still collapses to one. Rows\n // that are not frontmatter-derived are append-only history with no\n // reconstruction — always carried over, deduped by eventId in the merge.\n const reconstructedKeys = new Set(events.map(memoryLifecycleEventProjectionIdentity));\n const racedFrontmatterByKey = new Map<string, MemoryLifecycleEvent>();\n const appendOnly: MemoryLifecycleEvent[] = [];\n for (const event of existing) {\n if (!isFrontmatterDerivedLifecycleEventType(event.eventType)) {\n appendOnly.push(event);\n continue;\n }\n const key = memoryLifecycleEventProjectionIdentity(event);\n if (reconstructedKeys.has(key)) continue; // collapsed into reconstruction\n if (!racedFrontmatterByKey.has(key)) racedFrontmatterByKey.set(key, event);\n }\n const mergedById = new Map<string, MemoryLifecycleEvent>();\n for (const event of sortMemoryLifecycleEvents([\n ...events,\n ...racedFrontmatterByKey.values(),\n ...appendOnly,\n ])) {\n if (!mergedById.has(event.eventId)) mergedById.set(event.eventId, event);\n }\n finalEvents = [...mergedById.values()];\n preservedAppendOnlyRows = finalEvents.length - events.length;\n // Bound the rewritten ledger so a preserving compaction can never leave it\n // over the whole-file read/decrypt cap (#2033). This must run whenever a\n // cap is set — NOT only when `existing.length > 0`: an oversized on-disk\n // ledger whose every row fails validation reads as `existing === []`, yet\n // `finalEvents` (the frontmatter reconstruction) can itself exceed the cap.\n // Overflow (oldest) rows are dropped from the active ledger but survive\n // both in the timestamped backup (a verbatim copy when the ledger is\n // plaintext, re-encrypted under the backup path's own AAD when it is\n // encrypted so it still decrypts there, #2033) and, for frontmatter-derived\n // rows, in the memory files they were reconstructed from — so a later full\n // rebuild regenerates them.\n if (options.maxLedgerBytes && options.maxLedgerBytes > 0) {\n const bounded = boundLifecycleEventsToByteCap(finalEvents, options.maxLedgerBytes);\n if (bounded.dropped > 0) {\n finalEvents = bounded.kept;\n archivedOverflowRows = bounded.dropped;\n log.warn(\n `lifecycle ledger rebuild bounded to ${options.maxLedgerBytes} bytes: `\n + `dropped ${bounded.dropped} oldest row(s) from the active ledger `\n + `(preserved in the backup) to stay under the read/decrypt cap.`,\n );\n }\n }\n }\n\n // Re-assert the lock immediately before the destructive active-ledger\n // rewrite. Everything above (the preserve read, merge, sort, byte-cap\n // bound, and JSON serialize) is CPU-bound and blocks the event loop, so the\n // timer heartbeat inside withHeldFileLock cannot refresh the lock's mtime;\n // a peer that judged the lock stale within the 30s window could have broken\n // it and appended to the current ledger. `lock.refresh()` (a) reports the\n // lock LOST so we ABORT rather than rename our compacted file over that\n // peer's append, and (b) when still held, re-stamps the mtime so the bounded\n // write below cannot itself be judged stale mid-rename (issue #1910/#2033).\n const abortIfLockLost = async (): Promise<void> => {\n if (lock && await lock.refresh()) return;\n throw new Error(\n \"lifecycle ledger rebuild aborted: lost the ledger lock during the compaction \"\n + \"rewrite (a peer stale-broke it while the event loop was blocked by CPU-bound \"\n + \"merge/serialize); refusing to clobber a concurrent append (issue #1910/#2033).\",\n );\n };\n if (!dryRun) {\n const payload = finalEvents.map((event) => JSON.stringify(event)).join(\"\\n\");\n const content = payload.length > 0 ? `${payload}\\n` : \"\";\n // No-op skip (#2033 thread PRRT_kwDORJXyws6SExst): a preserving rebuild\n // bounds the ACTIVE ledger to the read/decrypt cap, so a VALID ledger that\n // sits above the configured compaction trigger but below the cap would\n // otherwise be rewritten to identical content and re-archived on every\n // maintenance interval — unbounded growth of archive/memory-lifecycle-ledger\n // plus pointless disk/CPU churn. Skip the backup+rewrite when it would\n // change neither the logical (decrypted) content NOR the at-rest format.\n // The raw read here doubles as the source for the encrypted verbatim backup\n // below, so the current ledger is read at most once. An absent ledger reads\n // as ENOENT (a create is always a real change) and any other read/probe\n // error propagates rather than masking a needed rewrite.\n let currentEncrypted = false;\n let priorRawBuffer: Buffer | null = null;\n try {\n currentEncrypted = await probeEncryptedRegularFileHeader(outputPath);\n priorRawBuffer = await storage.readMemoryLifecycleLedgerRawBufferForCompaction();\n } catch (err) {\n if (!isNodeError(err) || err.code !== \"ENOENT\") throw err;\n }\n // Preserve encryption at rest (#2033). An already-encrypted ledger (or its\n // encrypted backup) MUST be rewritten encrypted even when the\n // `secureStoreEncryptOnWrite` policy is paused — otherwise the compaction\n // silently DOWNGRADES encrypted state to plaintext. Force encryption\n // whenever the current ledger is encrypted and the store is unlocked (a\n // key is available); reaching this point with an encrypted ledger already\n // implies an unlocked store, since the raw read above decrypts and would\n // have thrown under a locked key. A plaintext ledger keeps the ordinary\n // policy (`willEncryptStateWrites`), so existing plaintext behavior holds.\n const forceEncrypt =\n secureRewrite && currentEncrypted && storage.isSecureStoreUnlocked();\n const replacementEncrypted =\n secureRewrite && (storage.willEncryptStateWrites() || forceEncrypt);\n // Compare as buffers, never decoding the raw ledger to one giant string:\n // a multi-hundred-MB decrypted ledger can exceed V8's max string length,\n // so `priorRawBuffer.equals(...)` (byte compare) must be used, NOT\n // `.toString()` (#2033 giant-string invariant). `content` is the freshly\n // serialized replacement, already a string; Buffer.from() reuses it.\n if (\n priorRawBuffer !== null &&\n currentEncrypted === replacementEncrypted &&\n priorRawBuffer.equals(Buffer.from(content, \"utf8\"))\n ) {\n // Nothing to change: leave the active ledger and archive untouched.\n rewritten = false;\n } else {\n const desiredBackup = await backupExistingLedger(options.memoryDir, outputPath, now);\n if (secureRewrite) {\n // Preserve encrypted-at-rest (issue #1910). The BACKUP needs care under\n // secure-store (#2033): when the existing ledger is encrypted, its bytes\n // are path-bound via AAD, so a byte-for-byte copy to the archive path\n // cannot be decrypted there — it would silently orphan the overflow rows\n // a bounded rewrite claims to preserve. Reuse the RAW decrypted ledger\n // content read above (no event parsing, so malformed/truncated/future\n // rows survive exactly as the plaintext verbatim copy keeps them) and\n // re-encrypt it under the backup path's own AAD, yielding a directly\n // decryptable backup that retains every original byte. A PLAINTEXT\n // existing ledger is already readable, so a verbatim copy is correct.\n // Then rewrite the active ledger through the secure writer.\n if (desiredBackup && currentEncrypted) {\n const rawForBackup =\n priorRawBuffer ?? (await storage.readMemoryLifecycleLedgerRawBufferForCompaction());\n await storage.writeMemoryLifecycleLedgerContent(rawForBackup, desiredBackup, forceEncrypt);\n backupPath = desiredBackup;\n } else {\n backupPath = desiredBackup\n ? await copyExistingFileToBackup(outputPath, desiredBackup)\n : undefined;\n }\n await abortIfLockLost();\n await storage.writeMemoryLifecycleLedgerContent(content, undefined, forceEncrypt);\n } else {\n await abortIfLockLost();\n backupPath = await writeFileAtomically(outputPath, content, desiredBackup);\n }\n rewritten = true;\n }\n }\n };\n // Write mode holds the ledger lock across the preserve-read and atomic\n // rewrite so a concurrent append lands on the compacted ledger instead of\n // being clobbered. A dry run computes the SAME preserve/merge/byte-cap\n // preview but WITHOUT the lock (read-only, no rewrite), so `rebuiltRows`,\n // `preservedAppendOnlyRows`, and `archivedOverflowRows` report what a --write\n // would apply while never blocking concurrent appends (#2033 Cursor). A dry\n // run with nothing to preserve touches nothing at all.\n if (!dryRun) {\n await withHeldFileLock(\n memoryLifecycleLedgerLockPath(outputPath),\n { staleMs: MEMORY_LIFECYCLE_LEDGER_LOCK_STALE_MS, ...options.lockOptions },\n runLedgerCriticalSection,\n );\n } else if (options.preserveExistingEvents) {\n await runLedgerCriticalSection(true, null);\n }\n\n return {\n dryRun,\n scannedMemories: allMemories.length,\n rebuiltRows: finalEvents.length,\n outputPath,\n backupPath,\n skippedBlankIdMemories,\n skippedDuplicateEvents,\n preservedAppendOnlyRows,\n archivedOverflowRows,\n rewritten,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,YAAY;AAoHrB,SAAS,YAAY,KAA4C;AAC/D,SAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU;AAC9D;AAGA,SAAS,kBAAkB,OAAqC;AAC9D,SAAO,OAAO,WAAW,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,GAAM,MAAM;AAC/D;AAeO,SAAS,8BACd,QACA,KACmD;AACnD,MAAI,EAAE,MAAM,GAAI,QAAO,EAAE,MAAM,QAAQ,SAAS,EAAE;AAClD,QAAM,QAAQ,oBAAI,IAAkC;AACpD,MAAI,QAAQ;AACZ,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAQ,kBAAkB,KAAK;AACrC,UAAM,IAAI,OAAO,KAAK;AACtB,aAAS;AAAA,EACX;AACA,MAAI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;AACtB,gBAAM,QAAQ,kCAAkC,SAAS,QAAW,YAAY;AAAA,QAClF,OAAO;AACL,gBAAM,gBAAgB;AACtB,uBAAa,MAAM,oBAAoB,YAAY,SAAS,aAAa;AAAA,QAC3E;AACA,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAQA,MAAI,CAAC,QAAQ;AACX,UAAM;AAAA,MACJ,8BAA8B,UAAU;AAAA,MACxC,EAAE,SAAS,uCAAuC,GAAG,QAAQ,YAAY;AAAA,MACzE;AAAA,IACF;AAAA,EACF,WAAW,QAAQ,wBAAwB;AACzC,UAAM,yBAAyB,MAAM,IAAI;AAAA,EAC3C;AAEA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,YAAY;AAAA,IAC7B,aAAa,YAAY;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/maintenance/purge.ts"],"sourcesContent":["/**\n * Operator-facing bulk hard-delete (issue #686 retention-completion).\n *\n * `purgeMemories(opts)` hard-deletes memories that are:\n * - older than `olderThanMs` (measured against `updated ?? created`), AND\n * - in the specified tier (`\"cold\"` or `\"all\"`), AND\n * - optionally in `status: \"forgotten\"` only (when `forgottenOnly` is true)\n *\n * Hard-delete means:\n * 1. Remove the file from disk.\n * 2. Trigger a QMD collection update so the index no longer contains it.\n * 3. Append a purge audit entry to the observation ledger.\n *\n * `dryRun: true` (the default) reports what *would* be deleted without\n * actually removing anything — callers must opt into mutations by\n * setting `dryRun: false`.\n *\n * The CLI surface enforces an explicit `--confirm yes` guard and\n * defaults to `--dry-run` to make accidental data loss impossible.\n */\n\nimport path from \"node:path\";\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { MemoryFile } from \"../types.js\";\nimport { markProjectedMemoryPathInvalid } from \"../memory-projection-store.js\";\nimport type { SearchBackend } from \"../search/port.js\";\n\nexport type PurgeTierFilter = \"cold\" | \"all\";\n\nexport interface PurgeMemoriesOptions {\n storage: StorageManager;\n /**\n * Only memories whose `updated ?? created` timestamp is older than this\n * value (in milliseconds, Unix epoch) will be candidates.\n */\n olderThanMs: number;\n /**\n * `\"cold\"` — only memories in the cold tier (files under `.../cold/`).\n * `\"all\"` — memories in any tier (hot, cold, or archived).\n * Default: `\"cold\"`.\n */\n tier?: PurgeTierFilter;\n /**\n * When `true`, only memories with `status === \"forgotten\"` are candidates.\n * Default: `false` (purge by age + tier regardless of status).\n */\n forgottenOnly?: boolean;\n /** When `true` (default), report candidates but do not delete. */\n dryRun?: boolean;\n /**\n * Optional QMD backend. When supplied and `dryRun === false`, a\n * `updateCollection` call is issued after each deletion so the index stays\n * consistent. Pass `undefined` or omit to skip index maintenance (e.g. in\n * tests that don't have a live QMD instance).\n */\n qmd?: SearchBackend;\n /** Hot-tier QMD collection name (default: `\"openclaw-engram\"`). */\n hotCollection?: string;\n /** Cold-tier QMD collection name (default: `\"openclaw-engram-cold\"`). */\n coldCollection?: string;\n /** Optional hook for long-lived hosts to clear their live dedupe mirror after purge hash cleanup. */\n afterFactHashRemoval?: () => void | Promise<void>;\n /** Optional shutdown signal forwarded to QMD collection refreshes. */\n signal?: AbortSignal;\n /** Override clock for tests. */\n now?: () => Date;\n}\n\nexport interface PurgeCandidate {\n id: string;\n path: string;\n tier: \"hot\" | \"cold\" | \"archive\";\n status: string;\n updatedOrCreated: string;\n ageMs: number;\n}\n\nexport interface PurgeMemoriesResult {\n dryRun: boolean;\n tier: PurgeTierFilter;\n olderThanMs: number;\n candidates: PurgeCandidate[];\n purgedCount: number;\n alreadyAbsentCount: number;\n errorCount: number;\n errors: Array<{ id: string; path: string; error: string }>;\n}\n\nfunction hasErrorCode(err: unknown, code: string): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && (err as { code?: unknown }).code === code;\n}\n\nfunction resolveTimestamp(memory: MemoryFile): string {\n const fm = memory.frontmatter as unknown as Record<string, unknown>;\n const updated = typeof fm.updated === \"string\" ? (fm.updated as string) : \"\";\n const created = typeof fm.created === \"string\" ? (fm.created as string) : \"\";\n return updated.length > 0 ? updated : created;\n}\n\nasync function logPurgeAudit(\n storage: StorageManager,\n candidates: PurgeCandidate[],\n now: Date,\n event: \"PURGE_DELETE_INTENT\" | \"PURGE_HARD_DELETE\" | \"PURGE_ALREADY_ABSENT\" = \"PURGE_HARD_DELETE\",\n): Promise<void> {\n if (candidates.length === 0) return;\n const ledgerDir = path.join(storage.dir, \"state\", \"observation-ledger\");\n await mkdir(ledgerDir, { recursive: true });\n const ledgerPath = path.join(ledgerDir, \"purge-audit.jsonl\");\n const entries = candidates.map((c) =>\n JSON.stringify({\n event,\n timestamp: now.toISOString(),\n memoryId: c.id,\n path: c.path,\n tier: c.tier,\n status: c.status,\n updatedOrCreated: c.updatedOrCreated,\n }),\n );\n if (entries.length > 0) {\n await appendFile(ledgerPath, `${entries.join(\"\\n\")}\\n`, \"utf-8\");\n }\n}\n\nexport async function purgeMemories(\n options: PurgeMemoriesOptions,\n): Promise<PurgeMemoriesResult> {\n const {\n storage,\n olderThanMs,\n tier = \"cold\",\n forgottenOnly = false,\n dryRun = true,\n qmd,\n hotCollection = \"openclaw-engram\",\n coldCollection = \"openclaw-engram-cold\",\n } = options;\n\n if (!Number.isFinite(olderThanMs) || olderThanMs <= 0) {\n throw new Error(\"olderThanMs must be a finite positive number\");\n }\n\n const now = (options.now ?? (() => new Date()))();\n const nowMs = now.getTime();\n\n // Collect all memories from applicable tiers\n const [hotMemories, coldMemories, archivedMemories] = await Promise.all([\n tier === \"all\" ? storage.readAllMemories() : Promise.resolve([]),\n storage.readAllColdMemories(),\n tier === \"all\" ? storage.readArchivedMemories() : Promise.resolve([]),\n ]);\n\n const poolEntries: Array<{ memory: MemoryFile; resolvedTier: \"hot\" | \"cold\" | \"archive\" }> = [];\n\n if (tier === \"all\") {\n for (const m of hotMemories) {\n poolEntries.push({ memory: m, resolvedTier: \"hot\" });\n }\n for (const m of archivedMemories) {\n poolEntries.push({ memory: m, resolvedTier: \"archive\" });\n }\n }\n for (const m of coldMemories) {\n poolEntries.push({ memory: m, resolvedTier: \"cold\" });\n }\n\n // Build candidate list\n const candidates: PurgeCandidate[] = [];\n const candidateMemoriesByPath = new Map<string, MemoryFile>();\n for (const { memory, resolvedTier } of poolEntries) {\n const ts = resolveTimestamp(memory);\n if (ts.length === 0) continue;\n\n const tsMs = Date.parse(ts);\n if (!Number.isFinite(tsMs)) continue;\n\n const ageMs = nowMs - tsMs;\n if (ageMs < olderThanMs) continue;\n\n const fm = memory.frontmatter as unknown as Record<string, unknown>;\n const status: string =\n typeof fm.status === \"string\" ? (fm.status as string) : \"active\";\n\n if (forgottenOnly && status !== \"forgotten\") continue;\n\n candidates.push({\n id: memory.frontmatter.id,\n path: memory.path,\n tier: resolvedTier,\n status,\n updatedOrCreated: ts,\n ageMs,\n });\n candidateMemoriesByPath.set(memory.path, memory);\n }\n\n if (dryRun) {\n return {\n dryRun: true,\n tier,\n olderThanMs,\n candidates,\n purgedCount: 0,\n alreadyAbsentCount: 0,\n errorCount: 0,\n errors: [],\n };\n }\n\n // Hard-delete phase\n const errors: Array<{ id: string; path: string; error: string }> = [];\n try {\n await logPurgeAudit(storage, candidates, now, \"PURGE_DELETE_INTENT\");\n } catch (auditErr) {\n errors.push({\n id: \"(purge-audit)\",\n path: path.join(storage.dir, \"state\", \"observation-ledger\", \"purge-audit.jsonl\"),\n error: auditErr instanceof Error ? auditErr.message : String(auditErr),\n });\n }\n\n const actuallyPurged: PurgeCandidate[] = [];\n const alreadyAbsent: PurgeCandidate[] = [];\n const collectionsToUpdate = new Set<string>();\n const addCollectionForCandidate = (candidate: PurgeCandidate) => {\n if (candidate.tier === \"cold\") {\n collectionsToUpdate.add(coldCollection);\n } else if (candidate.tier === \"hot\") {\n collectionsToUpdate.add(hotCollection);\n }\n };\n\n for (const candidate of candidates) {\n try {\n const memory = candidateMemoriesByPath.get(candidate.path);\n if (!memory) throw new Error(`purge candidate memory missing: ${candidate.id}`);\n const removed = await storage.deleteMemoryForMaintenance(memory);\n if (removed) {\n actuallyPurged.push(candidate);\n addCollectionForCandidate(candidate);\n } else {\n alreadyAbsent.push(candidate);\n addCollectionForCandidate(candidate);\n markProjectedMemoryPathInvalid(storage.dir, candidate.id);\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (hasErrorCode(err, \"ENOENT\")) {\n alreadyAbsent.push(candidate);\n addCollectionForCandidate(candidate);\n markProjectedMemoryPathInvalid(storage.dir, candidate.id);\n } else {\n errors.push({ id: candidate.id, path: candidate.path, error: message });\n }\n }\n }\n\n const recordPostDeleteAudit = async (\n purgedCandidates: PurgeCandidate[],\n event: \"PURGE_HARD_DELETE\" | \"PURGE_ALREADY_ABSENT\",\n ) => {\n try {\n await logPurgeAudit(storage, purgedCandidates, now, event);\n } catch (auditErr) {\n errors.push({\n id: \"(purge-audit)\",\n path: path.join(storage.dir, \"state\", \"observation-ledger\", \"purge-audit.jsonl\"),\n error: auditErr instanceof Error ? auditErr.message : String(auditErr),\n });\n }\n };\n await recordPostDeleteAudit(actuallyPurged, \"PURGE_HARD_DELETE\");\n await recordPostDeleteAudit(alreadyAbsent, \"PURGE_ALREADY_ABSENT\");\n\n const resolvedPurges = [...actuallyPurged, ...alreadyAbsent];\n\n const invalidateTierCaches = (\n storage as unknown as {\n invalidateMemoryCachesForTiers?: (tiers: Iterable<\"hot\" | \"cold\" | \"archive\">) => void;\n }\n ).invalidateMemoryCachesForTiers;\n if (typeof invalidateTierCaches === \"function\") {\n invalidateTierCaches.call(storage, new Set(resolvedPurges.map((candidate) => candidate.tier)));\n } else if (typeof (storage as unknown as { invalidateAllMemoriesCacheForDir?: () => void }).invalidateAllMemoriesCacheForDir === \"function\") {\n (storage as unknown as { invalidateAllMemoriesCacheForDir: () => void }).invalidateAllMemoriesCacheForDir();\n }\n\n // Update QMD index for affected collections\n if (qmd) {\n for (const collection of collectionsToUpdate) {\n try {\n if (typeof qmd.updateCollectionStrict === \"function\") {\n await qmd.updateCollectionStrict(collection, { signal: options.signal });\n } else {\n await qmd.updateCollection(collection, { signal: options.signal });\n }\n } catch (indexErr) {\n // Non-fatal — operator can re-index manually\n errors.push({\n id: \"(qmd-update)\",\n path: collection,\n error: indexErr instanceof Error ? indexErr.message : String(indexErr),\n });\n }\n }\n }\n\n const purgedFactMemories = resolvedPurges\n .map((candidate) => candidateMemoriesByPath.get(candidate.path))\n .filter((memory): memory is MemoryFile => memory?.frontmatter.category === \"fact\");\n if (purgedFactMemories.length > 0) {\n const removeFactHashes = (\n storage as unknown as {\n removeFactContentHashesForMemories?: (memories: MemoryFile[]) => Promise<void>;\n }\n ).removeFactContentHashesForMemories;\n if (typeof removeFactHashes === \"function\") {\n try {\n await removeFactHashes.call(storage, purgedFactMemories);\n await options.afterFactHashRemoval?.();\n } catch (hashErr) {\n errors.push({\n id: \"(fact-hash-index)\",\n path: path.join(storage.dir, \"state\", \"fact-hashes.txt\"),\n error: hashErr instanceof Error ? hashErr.message : String(hashErr),\n });\n }\n }\n }\n\n return {\n dryRun: false,\n tier,\n olderThanMs,\n candidates,\n purgedCount: actuallyPurged.length,\n alreadyAbsentCount: alreadyAbsent.length,\n errorCount: errors.length,\n errors,\n };\n}\n"],"mappings":";;;;;;;;AAqBA,OAAO,UAAU;AACjB,SAAS,YAAY,aAAa;AAmElC,SAAS,aAAa,KAAc,MAAuB;AACzD,SAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAQ,IAA2B,SAAS;AAC1G;AAEA,SAAS,iBAAiB,QAA4B;AACpD,QAAM,KAAK,OAAO;AAClB,QAAM,UAAU,OAAO,GAAG,YAAY,WAAY,GAAG,UAAqB;AAC1E,QAAM,UAAU,OAAO,GAAG,YAAY,WAAY,GAAG,UAAqB;AAC1E,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,eAAe,cACb,SACA,YACA,KACA,QAA8E,qB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O,qBAAqB,YAAY;AAC1C,UAAI;AACF,cAAM,iBAAiB,KAAK,SAAS,kBAAkB;AACvD,cAAM,QAAQ,uBAAuB;AAAA,MACvC,SAAS,SAAS;AAChB,eAAO,KAAK;AAAA,UACV,IAAI;AAAA,UACJ,MAAM,KAAK,KAAK,QAAQ,KAAK,SAAS,iBAAiB;AAAA,UACvD,OAAO,mBAAmB,QAAQ,QAAQ,UAAU,OAAO,OAAO;AAAA,QACpE,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA,aAAa,eAAe;AAAA,IAC5B,oBAAoB,cAAc;AAAA,IAClC,YAAY,OAAO;AAAA,IACnB;AAAA,EACF;AACF;","names":[]}
@@ -1098,34 +1098,34 @@ declare const SupportPassportDraftModelInputSchema: z.ZodEffects<z.ZodObject<{
1098
1098
  memoryId: z.ZodString;
1099
1099
  content: z.ZodString;
1100
1100
  }, "strict", z.ZodTypeAny, {
1101
- memoryId: string;
1102
1101
  content: string;
1103
- }, {
1104
1102
  memoryId: string;
1103
+ }, {
1105
1104
  content: string;
1105
+ memoryId: string;
1106
1106
  }>, "many">;
1107
1107
  }, "strict", z.ZodTypeAny, {
1108
1108
  memories: {
1109
- memoryId: string;
1110
1109
  content: string;
1110
+ memoryId: string;
1111
1111
  }[];
1112
1112
  consent: true;
1113
1113
  }, {
1114
1114
  memories: {
1115
- memoryId: string;
1116
1115
  content: string;
1116
+ memoryId: string;
1117
1117
  }[];
1118
1118
  consent: true;
1119
1119
  }>, {
1120
1120
  memories: {
1121
- memoryId: string;
1122
1121
  content: string;
1122
+ memoryId: string;
1123
1123
  }[];
1124
1124
  consent: true;
1125
1125
  }, {
1126
1126
  memories: {
1127
- memoryId: string;
1128
1127
  content: string;
1128
+ memoryId: string;
1129
1129
  }[];
1130
1130
  consent: true;
1131
1131
  }>;