@remnic/core 10.0.92 → 10.0.93

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 (486) hide show
  1. package/dist/access-admin-ops-surface.js +331 -58
  2. package/dist/access-authorization-probe.js +2 -283
  3. package/dist/access-boundary.d.ts +1 -1
  4. package/dist/access-boundary.d.ts.map +1 -1
  5. package/dist/access-boundary.js +1 -282
  6. package/dist/access-cli.js +286 -302
  7. package/dist/access-cli.js.map +1 -1
  8. package/dist/access-coding-context-resolution.js +3 -3
  9. package/dist/access-extraction-force-flush.js +331 -58
  10. package/dist/access-http-briefing.js +331 -59
  11. package/dist/access-http-query.js +331 -60
  12. package/dist/access-http.js +329 -111
  13. package/dist/access-identity-continuity-surface.js +331 -58
  14. package/dist/access-lcm-surface.js +331 -58
  15. package/dist/access-mcp-frames.d.ts +20 -6
  16. package/dist/access-mcp-frames.d.ts.map +1 -1
  17. package/dist/access-mcp-frames.js +1 -1
  18. package/dist/access-mcp.d.ts +5 -0
  19. package/dist/access-mcp.d.ts.map +1 -1
  20. package/dist/access-mcp.js +329 -86
  21. package/dist/access-namespace-preflight.js +2 -282
  22. package/dist/access-observe-transcript.js +3 -3
  23. package/dist/access-observe-write-category.js +6 -6
  24. package/dist/access-observe-write-surface.js +331 -58
  25. package/dist/access-offline-manifest.js +12 -11
  26. package/dist/access-operations-batch.js +329 -63
  27. package/dist/access-operations.js +329 -72
  28. package/dist/access-recall-concurrency.js +331 -58
  29. package/dist/access-recall-diagnostics.js +5 -4
  30. package/dist/access-recall-response.js +331 -58
  31. package/dist/access-recall-surface.js +331 -58
  32. package/dist/access-schema.js +2 -2
  33. package/dist/access-service.js +334 -61
  34. package/dist/access-surface-catalog.js +6 -283
  35. package/dist/access-surface-catalog.js.map +1 -1
  36. package/dist/active-context-transform.js +1 -1
  37. package/dist/active-memory-bridge.js +3 -2
  38. package/dist/active-recall.js +35 -36
  39. package/dist/active-recall.js.map +1 -1
  40. package/dist/activity/journal-extract.d.ts +13 -1
  41. package/dist/activity/journal-extract.d.ts.map +1 -1
  42. package/dist/{auto-sync-3AZW7MXI.js → auto-sync-BO5YZKM6.js} +13 -15
  43. package/dist/{auto-sync-3AZW7MXI.js.map → auto-sync-BO5YZKM6.js.map} +1 -1
  44. package/dist/briefing.js +19 -19
  45. package/dist/buffer.js +16 -16
  46. package/dist/calibration.js +10 -10
  47. package/dist/{capsule-merge-2IIXFXN5.js → capsule-merge-6IDAYTKG.js} +6 -6
  48. package/dist/causal-consolidation.js +22 -22
  49. package/dist/{chunk-ATPWZ4F7.js → chunk-2LMA22UU.js} +5 -5
  50. package/dist/{chunk-RGUUBAT5.js → chunk-2WCLTWV2.js} +3 -3
  51. package/dist/{chunk-BQZEGOZ4.js → chunk-2YODOG2O.js} +2 -2
  52. package/dist/{chunk-WYG5UNDY.js → chunk-3AUDELZL.js} +2 -2
  53. package/dist/{chunk-N4KAE2NB.js → chunk-3CYOCE6U.js} +3 -3
  54. package/dist/{chunk-MB6ZJDN6.js → chunk-3FBAEPCU.js} +2 -2
  55. package/dist/{chunk-PIITB2YZ.js → chunk-3ZS3NUEI.js} +4 -4
  56. package/dist/{chunk-ANZZLRUX.js → chunk-4IVRQMZW.js} +2 -2
  57. package/dist/{chunk-63E37JCN.js → chunk-4RAJT5L2.js} +4 -4
  58. package/dist/{chunk-45VUHDV2.js → chunk-5CO5G4MN.js} +2 -2
  59. package/dist/{chunk-BRLXOZLM.js → chunk-5YT2IIFX.js} +729 -17
  60. package/dist/chunk-5YT2IIFX.js.map +1 -0
  61. package/dist/{chunk-E4IRW2FG.js → chunk-622V2AZA.js} +233 -40
  62. package/dist/chunk-622V2AZA.js.map +1 -0
  63. package/dist/{chunk-LUJCQQ3L.js → chunk-65HWAQ4F.js} +2 -2
  64. package/dist/{chunk-T67LUYCR.js → chunk-77NTFICT.js} +5 -5
  65. package/dist/chunk-A2WFUMUN.js +86 -0
  66. package/dist/chunk-A2WFUMUN.js.map +1 -0
  67. package/dist/{chunk-UE6RRXMF.js → chunk-A4F7OIC5.js} +2 -2
  68. package/dist/chunk-AHA5VQGP.js +117 -0
  69. package/dist/chunk-AHA5VQGP.js.map +1 -0
  70. package/dist/{chunk-SUSW74WU.js → chunk-ATG2PQ4V.js} +56 -5
  71. package/dist/chunk-ATG2PQ4V.js.map +1 -0
  72. package/dist/{chunk-U6UNF5ZS.js → chunk-B33YWUJV.js} +3 -3
  73. package/dist/{chunk-RRJBDXAQ.js → chunk-B377OKUP.js} +2 -2
  74. package/dist/{chunk-IUKYFTGW.js → chunk-B3DR2JBZ.js} +140 -125
  75. package/dist/chunk-B3DR2JBZ.js.map +1 -0
  76. package/dist/{chunk-ETZLQOUR.js → chunk-BGHCSLE5.js} +2 -2
  77. package/dist/{chunk-YYOMGOHB.js → chunk-BOK6BN5M.js} +2 -2
  78. package/dist/{chunk-OH7QLI6W.js → chunk-BPPUH5JM.js} +5 -5
  79. package/dist/{chunk-4J363OAA.js → chunk-BTI4C4MA.js} +2 -2
  80. package/dist/{chunk-O6ZSWHVR.js → chunk-C2KE5DMD.js} +4 -4
  81. package/dist/{chunk-47F6WWLQ.js → chunk-C73N66PR.js} +2 -2
  82. package/dist/{chunk-E3A7ELSG.js → chunk-CGJYL633.js} +2 -2
  83. package/dist/{chunk-WRT7GJ2D.js → chunk-CIWMTNHW.js} +4 -4
  84. package/dist/{chunk-O55EKIEC.js → chunk-D3ZKHLN2.js} +2 -2
  85. package/dist/{chunk-CD4BCCNP.js → chunk-DJ7WVEWX.js} +2 -2
  86. package/dist/{chunk-PWXPRVLK.js → chunk-EFL24KOI.js} +2 -2
  87. package/dist/{chunk-4CJTQHEG.js → chunk-ESLOLCD4.js} +3 -3
  88. package/dist/{chunk-6F42QONS.js → chunk-ETBVCRVL.js} +4 -4
  89. package/dist/{chunk-VILPVT4S.js → chunk-EZ47HOJ6.js} +4 -4
  90. package/dist/{chunk-EFYN5I7Z.js → chunk-F4QFU5IZ.js} +2 -2
  91. package/dist/{chunk-T6OZW2WR.js → chunk-FA7SLQ5X.js} +7 -1
  92. package/dist/chunk-FA7SLQ5X.js.map +1 -0
  93. package/dist/{chunk-7W3RXOIG.js → chunk-FMKILENU.js} +14 -14
  94. package/dist/{chunk-YLXETSAH.js → chunk-GCZJ7XRI.js} +2 -2
  95. package/dist/{chunk-5HFXGXE5.js → chunk-GQXOBKPL.js} +7 -9
  96. package/dist/{chunk-5HFXGXE5.js.map → chunk-GQXOBKPL.js.map} +1 -1
  97. package/dist/{chunk-UDKWFDV2.js → chunk-HLUHEMN4.js} +27 -3
  98. package/dist/chunk-HLUHEMN4.js.map +1 -0
  99. package/dist/{chunk-QFEDITXM.js → chunk-JNDMIAJ4.js} +2 -2
  100. package/dist/chunk-JTSSSR4L.js +359 -0
  101. package/dist/chunk-JTSSSR4L.js.map +1 -0
  102. package/dist/{chunk-5KBIOI4G.js → chunk-JVBAPAWZ.js} +217 -13
  103. package/dist/chunk-JVBAPAWZ.js.map +1 -0
  104. package/dist/{chunk-E5PPE4VA.js → chunk-K2VRKCPA.js} +2 -2
  105. package/dist/{chunk-MKRYQROF.js → chunk-LGEHAQHK.js} +4 -4
  106. package/dist/{chunk-7HTUYFR3.js → chunk-LLPMMMWG.js} +27 -10
  107. package/dist/chunk-LLPMMMWG.js.map +1 -0
  108. package/dist/{chunk-XYTQJD7F.js → chunk-LMJVP5CM.js} +2 -2
  109. package/dist/{chunk-FQKBJJYB.js → chunk-LPV72KRQ.js} +2 -2
  110. package/dist/{chunk-2LCRG2YV.js → chunk-M2XR6B6V.js} +2 -2
  111. package/dist/{chunk-P4WNBSTW.js → chunk-MH632KPO.js} +2 -2
  112. package/dist/{chunk-EQ4U73UH.js → chunk-MLAMXQAW.js} +14 -2
  113. package/dist/chunk-MLAMXQAW.js.map +1 -0
  114. package/dist/{chunk-ZU5JDLOH.js → chunk-MMRTPH3J.js} +2 -2
  115. package/dist/{chunk-PMJFRDJI.js → chunk-MUX7IL77.js} +2 -2
  116. package/dist/{chunk-HF3BKUVV.js → chunk-NAQ4A5IX.js} +7 -7
  117. package/dist/{chunk-TVIVY7KU.js → chunk-NED7IR7B.js} +4 -4
  118. package/dist/{chunk-6F5MJFXY.js → chunk-NHVAX7MH.js} +2 -2
  119. package/dist/{chunk-TG3R2SID.js → chunk-NMGHGTVR.js} +5 -5
  120. package/dist/{chunk-YCNIGRRF.js → chunk-NS7U4ZYU.js} +13 -117
  121. package/dist/chunk-NS7U4ZYU.js.map +1 -0
  122. package/dist/{chunk-NGHDW6UU.js → chunk-NUQEREIP.js} +2 -2
  123. package/dist/{chunk-5IIQU4JZ.js → chunk-OB72KNMF.js} +4 -4
  124. package/dist/{chunk-JV4S6VDH.js → chunk-OJXJWNFY.js} +2 -2
  125. package/dist/{chunk-QJPJXCS4.js → chunk-P3WRNWWM.js} +157 -4
  126. package/dist/chunk-P3WRNWWM.js.map +1 -0
  127. package/dist/{chunk-E6M225BJ.js → chunk-PC5DRBGD.js} +18 -8
  128. package/dist/chunk-PC5DRBGD.js.map +1 -0
  129. package/dist/{chunk-Z7JIZ42P.js → chunk-PRAUN6PN.js} +3 -3
  130. package/dist/{chunk-RWGRSKN5.js → chunk-PT4DZDJA.js} +2 -2
  131. package/dist/{chunk-7EPY3IQL.js → chunk-PZJQ46DH.js} +2 -2
  132. package/dist/{chunk-MXHMNKWG.js → chunk-QDESY76F.js} +3 -3
  133. package/dist/{chunk-I6QGI65T.js → chunk-QRMG4HK4.js} +3 -3
  134. package/dist/{chunk-ZU3NJNO7.js → chunk-QSF5SJAM.js} +4 -4
  135. package/dist/{chunk-5IYOKDM4.js → chunk-R23JWJD3.js} +5 -5
  136. package/dist/{chunk-RHQLIHMB.js → chunk-R4BBGPI2.js} +218 -218
  137. package/dist/chunk-R4BBGPI2.js.map +1 -0
  138. package/dist/{chunk-7GLJMDEQ.js → chunk-RM2YUFH6.js} +6 -6
  139. package/dist/{chunk-IPT2OY4B.js → chunk-RQFXZYTF.js} +35 -33
  140. package/dist/chunk-RQFXZYTF.js.map +1 -0
  141. package/dist/{chunk-AP6NCP3V.js → chunk-S3S72HRM.js} +8 -6
  142. package/dist/chunk-S3S72HRM.js.map +1 -0
  143. package/dist/{chunk-RIMK327Y.js → chunk-SGQPR5SX.js} +7 -7
  144. package/dist/{chunk-ZGFLIK5H.js → chunk-SPAKBUJY.js} +2 -2
  145. package/dist/{chunk-ER7XANP3.js → chunk-SQ3GEIEL.js} +4 -4
  146. package/dist/{chunk-BLJT6JP2.js → chunk-SVT5IA2H.js} +2 -2
  147. package/dist/{chunk-HVX4LPNY.js → chunk-T4KY6UYF.js} +5 -3
  148. package/dist/{chunk-HVX4LPNY.js.map → chunk-T4KY6UYF.js.map} +1 -1
  149. package/dist/{chunk-GVGAO3WV.js → chunk-TJ4F6H4H.js} +3 -3
  150. package/dist/{chunk-R6HMAIKM.js → chunk-TOSPNM4T.js} +2 -2
  151. package/dist/{chunk-HH5LY6RR.js → chunk-TRQE3RYR.js} +5 -5
  152. package/dist/{chunk-RMXS4I66.js → chunk-TVDJEUV5.js} +2 -2
  153. package/dist/{chunk-PLCYKAWH.js → chunk-TYRWSE4B.js} +2 -2
  154. package/dist/{chunk-B4QYQFGY.js → chunk-UBEKET2V.js} +383 -36
  155. package/dist/chunk-UBEKET2V.js.map +1 -0
  156. package/dist/{chunk-IQWUACVG.js → chunk-UHMHJX5G.js} +3 -3
  157. package/dist/{chunk-YODUDA6R.js → chunk-UN4RVUG2.js} +22 -22
  158. package/dist/{chunk-E6Z4FBX6.js → chunk-V2QSNFCT.js} +2 -2
  159. package/dist/{chunk-NBH6K6G5.js → chunk-V65H7MI6.js} +345 -16
  160. package/dist/chunk-V65H7MI6.js.map +1 -0
  161. package/dist/chunk-W54Z2MOP.js +4500 -0
  162. package/dist/chunk-W54Z2MOP.js.map +1 -0
  163. package/dist/{chunk-E7YZXWIS.js → chunk-WKSQTMU7.js} +2 -2
  164. package/dist/{chunk-RIZ5NUNN.js → chunk-WQ4XKIOX.js} +4 -4
  165. package/dist/{chunk-FSO3G4JJ.js → chunk-WQURALGV.js} +4995 -2747
  166. package/dist/chunk-WQURALGV.js.map +1 -0
  167. package/dist/{chunk-QEYTRFR3.js → chunk-X26YOFGS.js} +2 -2
  168. package/dist/{chunk-ITHZFHST.js → chunk-X2BVB74H.js} +2 -2
  169. package/dist/{chunk-XYKBWTWI.js → chunk-XIYLWEXC.js} +2 -2
  170. package/dist/{chunk-IBJ6U753.js → chunk-XKZBZOKV.js} +4 -4
  171. package/dist/{chunk-65AUYLU3.js → chunk-XPXHQI6N.js} +2 -2
  172. package/dist/{chunk-EXHXJETE.js → chunk-XRDYRWZI.js} +2 -2
  173. package/dist/chunk-XRWWCW4H.js +102 -0
  174. package/dist/chunk-XRWWCW4H.js.map +1 -0
  175. package/dist/chunk-YKJBSMMP.js +67137 -0
  176. package/dist/chunk-YKJBSMMP.js.map +1 -0
  177. package/dist/{chunk-2JSDPUKD.js → chunk-YMFPFXEX.js} +2 -2
  178. package/dist/{chunk-645WOU5I.js → chunk-ZDZJNXL6.js} +4 -4
  179. package/dist/{chunk-6TCXIRP5.js → chunk-ZKE4CO6B.js} +4 -4
  180. package/dist/{chunk-FNXQZGUS.js → chunk-ZSE774RV.js} +2 -2
  181. package/dist/cli.js +302 -184
  182. package/dist/coding/export-okf-codegraph.js +28 -28
  183. package/dist/compounding/engine.js +22 -23
  184. package/dist/config.js +35 -36
  185. package/dist/connectors/codex-materialize-runner.js +19 -19
  186. package/dist/connectors/index.js +20 -20
  187. package/dist/connectors/live/google-drive.d.ts +2 -0
  188. package/dist/connectors/live/google-drive.d.ts.map +1 -1
  189. package/dist/consolidation-provenance-check.js +4 -4
  190. package/dist/consolidation-undo.js +5 -5
  191. package/dist/contradiction/index.js +7 -6
  192. package/dist/{contradiction-scan-P2MHYFVG.js → contradiction-scan-IBPYGQZF.js} +4 -3
  193. package/dist/convergence-refresh.js +21 -21
  194. package/dist/corpus-watermark.js +22 -22
  195. package/dist/deep-recall-http-glue.js +2 -2
  196. package/dist/deep-recall-policy-llm.js +4 -4
  197. package/dist/direct-answer-wiring.js +2 -2
  198. package/dist/embedding-fallback.js +1 -1
  199. package/dist/entity-retrieval.js +20 -20
  200. package/dist/eval-trajectory-store.js +2 -2
  201. package/dist/eval-trajectory.js +2 -2
  202. package/dist/event-order-recall.js +2 -2
  203. package/dist/explicit-capture.d.ts +3 -2
  204. package/dist/explicit-capture.d.ts.map +1 -1
  205. package/dist/explicit-capture.js +530 -6
  206. package/dist/explicit-cue-recall.js +2 -2
  207. package/dist/external-wiki-access.js +2 -283
  208. package/dist/extraction-faithfulness.js +4 -4
  209. package/dist/extraction-judge.js +5 -5
  210. package/dist/extraction-normalization.js +1 -1
  211. package/dist/extraction-quote-grounding.d.ts.map +1 -1
  212. package/dist/extraction-quote-grounding.js +1 -1
  213. package/dist/extraction-source-grounding-rules.js +2 -2
  214. package/dist/extraction-source-grounding.js +3 -3
  215. package/dist/extraction.js +42 -43
  216. package/dist/fallback-llm-codex-subscription.js +2 -2
  217. package/dist/fallback-llm.js +3 -3
  218. package/dist/{first-start-migration-QFI7B5SH.js → first-start-migration-FILJH3RO.js} +6 -5
  219. package/dist/{first-start-migration-QFI7B5SH.js.map → first-start-migration-FILJH3RO.js.map} +1 -1
  220. package/dist/focused-list-recall.js +2 -2
  221. package/dist/harmonic-retrieval.js +19 -19
  222. package/dist/index.js +772 -793
  223. package/dist/lcm/index.js +2 -2
  224. package/dist/live-connectors-runner.js +2 -3
  225. package/dist/local-llm-config.js +2 -2
  226. package/dist/local-llm-helpers.d.ts +4 -0
  227. package/dist/local-llm-helpers.d.ts.map +1 -1
  228. package/dist/local-llm-helpers.js +3 -1
  229. package/dist/local-llm.d.ts +4 -1
  230. package/dist/local-llm.d.ts.map +1 -1
  231. package/dist/local-llm.js +4 -4
  232. package/dist/location/index.js +26 -28
  233. package/dist/maintenance/memory-governance.js +19 -19
  234. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +19 -19
  235. package/dist/maintenance/rebuild-memory-projection-runner.js +21 -21
  236. package/dist/maintenance/rebuild-memory-projection.js +20 -20
  237. package/dist/memory-browse-operations.js +2 -283
  238. package/dist/memory-browse.js +8 -7
  239. package/dist/memory-controller.js +2 -2
  240. package/dist/memory-subject.js +2 -2
  241. package/dist/namespaces/migrate.js +20 -20
  242. package/dist/namespaces/search.js +5 -5
  243. package/dist/namespaces/storage.js +19 -19
  244. package/dist/offline-sync-changeset-generations.js +1 -1
  245. package/dist/offline-sync-embedding-generation.js +1 -1
  246. package/dist/offline-sync-impression-drain.js +6 -6
  247. package/dist/offline-sync-snapshot-stream.js +1 -1
  248. package/dist/offline-sync.js +1 -1
  249. package/dist/operator-doctor-corpus.js +23 -23
  250. package/dist/operator-toolkit.js +57 -60
  251. package/dist/orchestration/backlog-scheduler.js +277 -293
  252. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  253. package/dist/orchestration/buffer-drain-runner.js +277 -293
  254. package/dist/orchestration/extraction-run.d.ts +4 -0
  255. package/dist/orchestration/extraction-run.d.ts.map +1 -1
  256. package/dist/orchestration/fact-dedup-window.d.ts +1 -1
  257. package/dist/orchestration/fact-dedup-window.d.ts.map +1 -1
  258. package/dist/orchestration/maintenance.js +38 -41
  259. package/dist/orchestrator.d.ts +9 -11
  260. package/dist/orchestrator.d.ts.map +1 -1
  261. package/dist/orchestrator.js +289 -306
  262. package/dist/page-versioning.js +3 -3
  263. package/dist/qmd-daemon-session.js +2 -2
  264. package/dist/qmd.js +3 -3
  265. package/dist/recall-explain-renderer.js +1 -1
  266. package/dist/recall-navigation-operations.js +2 -283
  267. package/dist/recall-navigation.js +331 -58
  268. package/dist/recall-planner-llm.js +3 -3
  269. package/dist/recall-state-view-admission.js +6 -6
  270. package/dist/recall-why-service.js +10 -9
  271. package/dist/recall-why.js +4 -3
  272. package/dist/recall-xray-cli.js +2 -2
  273. package/dist/recall-xray-renderer.js +1 -1
  274. package/dist/reconcile/manifest.js +3 -3
  275. package/dist/{resolution-N7H3F2E4.js → resolution-OVVIF7ZY.js} +8 -7
  276. package/dist/response-guidance-recall.js +2 -2
  277. package/dist/resume-bundles.js +39 -40
  278. package/dist/salvage-envelope.js +4 -4
  279. package/dist/search/factory.js +4 -4
  280. package/dist/search/index.js +4 -4
  281. package/dist/semantic-consolidation.js +22 -22
  282. package/dist/semantic-rule-promotion.js +19 -19
  283. package/dist/semantic-rule-verifier.js +19 -19
  284. package/dist/shared-context/manager.js +2 -3
  285. package/dist/source-agent-qualifier.js +31 -32
  286. package/dist/standup/build.js +19 -19
  287. package/dist/storage/content-hash-index.d.ts +10 -0
  288. package/dist/storage/content-hash-index.d.ts.map +1 -1
  289. package/dist/storage.js +18 -18
  290. package/dist/subject-config.js +3 -3
  291. package/dist/summarizer.d.ts +4 -1
  292. package/dist/summarizer.d.ts.map +1 -1
  293. package/dist/summarizer.js +6 -6
  294. package/dist/support-passport/index.js +53 -297
  295. package/dist/targeted-fact-recall.js +2 -2
  296. package/dist/tier-routing.js +3 -2
  297. package/dist/{tier-stats-FQGQSFET.js → tier-stats-FXEUJN73.js} +6 -5
  298. package/dist/{tier-stats-FQGQSFET.js.map → tier-stats-FXEUJN73.js.map} +1 -1
  299. package/dist/transcript.js +2 -2
  300. package/dist/transfer/capsule-import.js +4 -4
  301. package/dist/transfer/export-okf.js +19 -19
  302. package/dist/verified-recall.js +19 -19
  303. package/dist/wearables/memory-gen.d.ts +5 -1
  304. package/dist/wearables/memory-gen.d.ts.map +1 -1
  305. package/dist/wearables/service.d.ts.map +1 -1
  306. package/dist/who-knows-cli.js +20 -20
  307. package/dist/who-knows.js +19 -19
  308. package/dist/write-envelope.js +3 -3
  309. package/package.json +2 -2
  310. package/src/access-boundary.ts +5 -1
  311. package/src/access-category-alias.test.ts +5 -0
  312. package/src/access-mcp-frames.test.ts +60 -5
  313. package/src/access-mcp-frames.ts +72 -18
  314. package/src/access-mcp.test.ts +66 -2
  315. package/src/access-mcp.ts +19 -13
  316. package/src/access-service-coding-write.test.ts +7 -0
  317. package/src/activity/journal-extract-storage.test.ts +31 -0
  318. package/src/activity/journal-extract.test.ts +1 -0
  319. package/src/activity/journal-extract.ts +24 -3
  320. package/src/connectors/live/google-drive.test.ts +39 -0
  321. package/src/connectors/live/google-drive.ts +41 -12
  322. package/src/explicit-capture.test.ts +109 -17
  323. package/src/explicit-capture.ts +90 -37
  324. package/src/extraction-quote-grounding.test.ts +20 -0
  325. package/src/extraction-quote-grounding.ts +21 -11
  326. package/src/fact-dedup-window.test.ts +37 -0
  327. package/src/local-llm-helpers.ts +12 -0
  328. package/src/local-llm-shutdown.test.ts +194 -0
  329. package/src/local-llm.ts +32 -30
  330. package/src/orchestration/extraction-run.ts +12 -3
  331. package/src/orchestration/fact-dedup-window.ts +5 -1
  332. package/src/orchestrator-connector-dedup.test.ts +9 -5
  333. package/src/orchestrator.ts +47 -50
  334. package/src/storage/content-hash-index.ts +27 -2
  335. package/src/storage-fact-hash-publish-failure.test.ts +87 -0
  336. package/src/summarizer-shutdown.test.ts +195 -0
  337. package/src/summarizer.ts +15 -2
  338. package/src/wearables/memory-gen.test.ts +20 -0
  339. package/src/wearables/memory-gen.ts +14 -7
  340. package/src/wearables/service.ts +14 -1
  341. package/src/wearables/storage-io.test.ts +25 -0
  342. package/dist/chunk-2FGLEF7C.js +0 -61
  343. package/dist/chunk-2FGLEF7C.js.map +0 -1
  344. package/dist/chunk-3RLK65ZK.js +0 -203
  345. package/dist/chunk-3RLK65ZK.js.map +0 -1
  346. package/dist/chunk-4WR2OD7K.js +0 -43
  347. package/dist/chunk-4WR2OD7K.js.map +0 -1
  348. package/dist/chunk-5KBIOI4G.js.map +0 -1
  349. package/dist/chunk-5M5M22GW.js +0 -346
  350. package/dist/chunk-5M5M22GW.js.map +0 -1
  351. package/dist/chunk-7HTUYFR3.js.map +0 -1
  352. package/dist/chunk-AP6NCP3V.js.map +0 -1
  353. package/dist/chunk-B4QYQFGY.js.map +0 -1
  354. package/dist/chunk-BJRTMNCB.js +0 -1919
  355. package/dist/chunk-BJRTMNCB.js.map +0 -1
  356. package/dist/chunk-BRLXOZLM.js.map +0 -1
  357. package/dist/chunk-BSACVS6R.js +0 -621
  358. package/dist/chunk-BSACVS6R.js.map +0 -1
  359. package/dist/chunk-DKAA2IHQ.js +0 -3644
  360. package/dist/chunk-DKAA2IHQ.js.map +0 -1
  361. package/dist/chunk-E4IRW2FG.js.map +0 -1
  362. package/dist/chunk-E6M225BJ.js.map +0 -1
  363. package/dist/chunk-EQ4U73UH.js.map +0 -1
  364. package/dist/chunk-ETSJD5IV.js +0 -361
  365. package/dist/chunk-ETSJD5IV.js.map +0 -1
  366. package/dist/chunk-F55YQP7N.js +0 -336
  367. package/dist/chunk-F55YQP7N.js.map +0 -1
  368. package/dist/chunk-FHGWKODN.js +0 -2300
  369. package/dist/chunk-FHGWKODN.js.map +0 -1
  370. package/dist/chunk-FLRP63GU.js +0 -32219
  371. package/dist/chunk-FLRP63GU.js.map +0 -1
  372. package/dist/chunk-FSO3G4JJ.js.map +0 -1
  373. package/dist/chunk-ID6JGIMD.js +0 -25
  374. package/dist/chunk-ID6JGIMD.js.map +0 -1
  375. package/dist/chunk-IGLJNHOX.js +0 -62
  376. package/dist/chunk-IGLJNHOX.js.map +0 -1
  377. package/dist/chunk-IPT2OY4B.js.map +0 -1
  378. package/dist/chunk-IUKYFTGW.js.map +0 -1
  379. package/dist/chunk-NBH6K6G5.js.map +0 -1
  380. package/dist/chunk-NTRUKAAE.js +0 -223
  381. package/dist/chunk-NTRUKAAE.js.map +0 -1
  382. package/dist/chunk-OGXXGHW6.js +0 -223
  383. package/dist/chunk-OGXXGHW6.js.map +0 -1
  384. package/dist/chunk-PPCLZ4JU.js +0 -28
  385. package/dist/chunk-PPCLZ4JU.js.map +0 -1
  386. package/dist/chunk-QJPJXCS4.js.map +0 -1
  387. package/dist/chunk-R2LBF4HH.js +0 -729
  388. package/dist/chunk-R2LBF4HH.js.map +0 -1
  389. package/dist/chunk-RHQLIHMB.js.map +0 -1
  390. package/dist/chunk-RRTVGD3J.js +0 -792
  391. package/dist/chunk-RRTVGD3J.js.map +0 -1
  392. package/dist/chunk-SUSW74WU.js.map +0 -1
  393. package/dist/chunk-T6OZW2WR.js.map +0 -1
  394. package/dist/chunk-UDKWFDV2.js.map +0 -1
  395. package/dist/chunk-V7IZKJI3.js +0 -22
  396. package/dist/chunk-V7IZKJI3.js.map +0 -1
  397. package/dist/chunk-X562NQFA.js +0 -10144
  398. package/dist/chunk-X562NQFA.js.map +0 -1
  399. package/dist/chunk-XDSCJOH7.js +0 -3991
  400. package/dist/chunk-XDSCJOH7.js.map +0 -1
  401. package/dist/chunk-YCNIGRRF.js.map +0 -1
  402. package/dist/chunk-ZTTCDQ4I.js +0 -18796
  403. package/dist/chunk-ZTTCDQ4I.js.map +0 -1
  404. /package/dist/{capsule-merge-2IIXFXN5.js.map → capsule-merge-6IDAYTKG.js.map} +0 -0
  405. /package/dist/{chunk-ATPWZ4F7.js.map → chunk-2LMA22UU.js.map} +0 -0
  406. /package/dist/{chunk-RGUUBAT5.js.map → chunk-2WCLTWV2.js.map} +0 -0
  407. /package/dist/{chunk-BQZEGOZ4.js.map → chunk-2YODOG2O.js.map} +0 -0
  408. /package/dist/{chunk-WYG5UNDY.js.map → chunk-3AUDELZL.js.map} +0 -0
  409. /package/dist/{chunk-N4KAE2NB.js.map → chunk-3CYOCE6U.js.map} +0 -0
  410. /package/dist/{chunk-MB6ZJDN6.js.map → chunk-3FBAEPCU.js.map} +0 -0
  411. /package/dist/{chunk-PIITB2YZ.js.map → chunk-3ZS3NUEI.js.map} +0 -0
  412. /package/dist/{chunk-ANZZLRUX.js.map → chunk-4IVRQMZW.js.map} +0 -0
  413. /package/dist/{chunk-63E37JCN.js.map → chunk-4RAJT5L2.js.map} +0 -0
  414. /package/dist/{chunk-45VUHDV2.js.map → chunk-5CO5G4MN.js.map} +0 -0
  415. /package/dist/{chunk-LUJCQQ3L.js.map → chunk-65HWAQ4F.js.map} +0 -0
  416. /package/dist/{chunk-T67LUYCR.js.map → chunk-77NTFICT.js.map} +0 -0
  417. /package/dist/{chunk-UE6RRXMF.js.map → chunk-A4F7OIC5.js.map} +0 -0
  418. /package/dist/{chunk-U6UNF5ZS.js.map → chunk-B33YWUJV.js.map} +0 -0
  419. /package/dist/{chunk-RRJBDXAQ.js.map → chunk-B377OKUP.js.map} +0 -0
  420. /package/dist/{chunk-ETZLQOUR.js.map → chunk-BGHCSLE5.js.map} +0 -0
  421. /package/dist/{chunk-YYOMGOHB.js.map → chunk-BOK6BN5M.js.map} +0 -0
  422. /package/dist/{chunk-OH7QLI6W.js.map → chunk-BPPUH5JM.js.map} +0 -0
  423. /package/dist/{chunk-4J363OAA.js.map → chunk-BTI4C4MA.js.map} +0 -0
  424. /package/dist/{chunk-O6ZSWHVR.js.map → chunk-C2KE5DMD.js.map} +0 -0
  425. /package/dist/{chunk-47F6WWLQ.js.map → chunk-C73N66PR.js.map} +0 -0
  426. /package/dist/{chunk-E3A7ELSG.js.map → chunk-CGJYL633.js.map} +0 -0
  427. /package/dist/{chunk-WRT7GJ2D.js.map → chunk-CIWMTNHW.js.map} +0 -0
  428. /package/dist/{chunk-O55EKIEC.js.map → chunk-D3ZKHLN2.js.map} +0 -0
  429. /package/dist/{chunk-CD4BCCNP.js.map → chunk-DJ7WVEWX.js.map} +0 -0
  430. /package/dist/{chunk-PWXPRVLK.js.map → chunk-EFL24KOI.js.map} +0 -0
  431. /package/dist/{chunk-4CJTQHEG.js.map → chunk-ESLOLCD4.js.map} +0 -0
  432. /package/dist/{chunk-6F42QONS.js.map → chunk-ETBVCRVL.js.map} +0 -0
  433. /package/dist/{chunk-VILPVT4S.js.map → chunk-EZ47HOJ6.js.map} +0 -0
  434. /package/dist/{chunk-EFYN5I7Z.js.map → chunk-F4QFU5IZ.js.map} +0 -0
  435. /package/dist/{chunk-7W3RXOIG.js.map → chunk-FMKILENU.js.map} +0 -0
  436. /package/dist/{chunk-YLXETSAH.js.map → chunk-GCZJ7XRI.js.map} +0 -0
  437. /package/dist/{chunk-QFEDITXM.js.map → chunk-JNDMIAJ4.js.map} +0 -0
  438. /package/dist/{chunk-E5PPE4VA.js.map → chunk-K2VRKCPA.js.map} +0 -0
  439. /package/dist/{chunk-MKRYQROF.js.map → chunk-LGEHAQHK.js.map} +0 -0
  440. /package/dist/{chunk-XYTQJD7F.js.map → chunk-LMJVP5CM.js.map} +0 -0
  441. /package/dist/{chunk-FQKBJJYB.js.map → chunk-LPV72KRQ.js.map} +0 -0
  442. /package/dist/{chunk-2LCRG2YV.js.map → chunk-M2XR6B6V.js.map} +0 -0
  443. /package/dist/{chunk-P4WNBSTW.js.map → chunk-MH632KPO.js.map} +0 -0
  444. /package/dist/{chunk-ZU5JDLOH.js.map → chunk-MMRTPH3J.js.map} +0 -0
  445. /package/dist/{chunk-PMJFRDJI.js.map → chunk-MUX7IL77.js.map} +0 -0
  446. /package/dist/{chunk-HF3BKUVV.js.map → chunk-NAQ4A5IX.js.map} +0 -0
  447. /package/dist/{chunk-TVIVY7KU.js.map → chunk-NED7IR7B.js.map} +0 -0
  448. /package/dist/{chunk-6F5MJFXY.js.map → chunk-NHVAX7MH.js.map} +0 -0
  449. /package/dist/{chunk-TG3R2SID.js.map → chunk-NMGHGTVR.js.map} +0 -0
  450. /package/dist/{chunk-NGHDW6UU.js.map → chunk-NUQEREIP.js.map} +0 -0
  451. /package/dist/{chunk-5IIQU4JZ.js.map → chunk-OB72KNMF.js.map} +0 -0
  452. /package/dist/{chunk-JV4S6VDH.js.map → chunk-OJXJWNFY.js.map} +0 -0
  453. /package/dist/{chunk-Z7JIZ42P.js.map → chunk-PRAUN6PN.js.map} +0 -0
  454. /package/dist/{chunk-RWGRSKN5.js.map → chunk-PT4DZDJA.js.map} +0 -0
  455. /package/dist/{chunk-7EPY3IQL.js.map → chunk-PZJQ46DH.js.map} +0 -0
  456. /package/dist/{chunk-MXHMNKWG.js.map → chunk-QDESY76F.js.map} +0 -0
  457. /package/dist/{chunk-I6QGI65T.js.map → chunk-QRMG4HK4.js.map} +0 -0
  458. /package/dist/{chunk-ZU3NJNO7.js.map → chunk-QSF5SJAM.js.map} +0 -0
  459. /package/dist/{chunk-5IYOKDM4.js.map → chunk-R23JWJD3.js.map} +0 -0
  460. /package/dist/{chunk-7GLJMDEQ.js.map → chunk-RM2YUFH6.js.map} +0 -0
  461. /package/dist/{chunk-RIMK327Y.js.map → chunk-SGQPR5SX.js.map} +0 -0
  462. /package/dist/{chunk-ZGFLIK5H.js.map → chunk-SPAKBUJY.js.map} +0 -0
  463. /package/dist/{chunk-ER7XANP3.js.map → chunk-SQ3GEIEL.js.map} +0 -0
  464. /package/dist/{chunk-BLJT6JP2.js.map → chunk-SVT5IA2H.js.map} +0 -0
  465. /package/dist/{chunk-GVGAO3WV.js.map → chunk-TJ4F6H4H.js.map} +0 -0
  466. /package/dist/{chunk-R6HMAIKM.js.map → chunk-TOSPNM4T.js.map} +0 -0
  467. /package/dist/{chunk-HH5LY6RR.js.map → chunk-TRQE3RYR.js.map} +0 -0
  468. /package/dist/{chunk-RMXS4I66.js.map → chunk-TVDJEUV5.js.map} +0 -0
  469. /package/dist/{chunk-PLCYKAWH.js.map → chunk-TYRWSE4B.js.map} +0 -0
  470. /package/dist/{chunk-IQWUACVG.js.map → chunk-UHMHJX5G.js.map} +0 -0
  471. /package/dist/{chunk-YODUDA6R.js.map → chunk-UN4RVUG2.js.map} +0 -0
  472. /package/dist/{chunk-E6Z4FBX6.js.map → chunk-V2QSNFCT.js.map} +0 -0
  473. /package/dist/{chunk-E7YZXWIS.js.map → chunk-WKSQTMU7.js.map} +0 -0
  474. /package/dist/{chunk-RIZ5NUNN.js.map → chunk-WQ4XKIOX.js.map} +0 -0
  475. /package/dist/{chunk-QEYTRFR3.js.map → chunk-X26YOFGS.js.map} +0 -0
  476. /package/dist/{chunk-ITHZFHST.js.map → chunk-X2BVB74H.js.map} +0 -0
  477. /package/dist/{chunk-XYKBWTWI.js.map → chunk-XIYLWEXC.js.map} +0 -0
  478. /package/dist/{chunk-IBJ6U753.js.map → chunk-XKZBZOKV.js.map} +0 -0
  479. /package/dist/{chunk-65AUYLU3.js.map → chunk-XPXHQI6N.js.map} +0 -0
  480. /package/dist/{chunk-EXHXJETE.js.map → chunk-XRDYRWZI.js.map} +0 -0
  481. /package/dist/{chunk-2JSDPUKD.js.map → chunk-YMFPFXEX.js.map} +0 -0
  482. /package/dist/{chunk-645WOU5I.js.map → chunk-ZDZJNXL6.js.map} +0 -0
  483. /package/dist/{chunk-6TCXIRP5.js.map → chunk-ZKE4CO6B.js.map} +0 -0
  484. /package/dist/{chunk-FNXQZGUS.js.map → chunk-ZSE774RV.js.map} +0 -0
  485. /package/dist/{contradiction-scan-P2MHYFVG.js.map → contradiction-scan-IBPYGQZF.js.map} +0 -0
  486. /package/dist/{resolution-N7H3F2E4.js.map → resolution-OVVIF7ZY.js.map} +0 -0
@@ -18,7 +18,7 @@ import {
18
18
  } from "./chunk-3WCASNQZ.js";
19
19
 
20
20
  // src/storage/content-hash-index.ts
21
- import { mkdir, stat } from "fs/promises";
21
+ import { mkdir, stat, utimes } from "fs/promises";
22
22
  import path from "path";
23
23
  var CONTENT_HASH_INDEX_LOCK_STALE_MS = 3e4;
24
24
  var CONTENT_HASH_INDEX_FORMAT_HEADER = "# remnic-content-hash-index:v2";
@@ -185,6 +185,24 @@ var ContentHashIndex = class _ContentHashIndex {
185
185
  }
186
186
  return current.mtimeMs === last.mtimeMs && current.size === last.size && current.dev === last.dev && current.ino === last.ino && current.ctimeMs === last.ctimeMs && current.birthtimeMs === last.birthtimeMs;
187
187
  }
188
+ /**
189
+ * Change the durable file's mtime without touching its content. A publish
190
+ * that throws or stays deferred leaves the file as it was, so a peer that
191
+ * already synced it keeps answering authoritative MISSes for deltas this
192
+ * instance holds only in memory (#3355). A new stamp makes every holder of the
193
+ * old fingerprint, this instance included, fail the freshness check and
194
+ * confirm against the corpus. Best effort: a file that cannot be stamped
195
+ * leaves the callers' existing retry and rebuild paths as the only repair.
196
+ */
197
+ async invalidatePeerFreshness() {
198
+ try {
199
+ const { mtimeMs } = await stat(this.filePath);
200
+ const bumped = new Date(Math.max(Date.now(), mtimeMs + 1));
201
+ await utimes(this.filePath, bumped, bumped);
202
+ } catch (err) {
203
+ log.debug(`content-hash index: could not invalidate peer freshness of ${this.filePath}: ${err}`);
204
+ }
205
+ }
188
206
  /** Check if content already exists in the index. */
189
207
  has(content) {
190
208
  return this.hashes.has(_ContentHashIndex.computeHash(content));
@@ -305,9 +323,15 @@ var ContentHashIndex = class _ContentHashIndex {
305
323
  `content-hash index: lock not acquired for ${this.filePath}; deferring reconcile save (dirty retained, scheduling durable retry)`
306
324
  );
307
325
  this.scheduleReconcileRetry();
326
+ await this.invalidatePeerFreshness();
308
327
  return;
309
328
  }
310
- await publish();
329
+ try {
330
+ await publish();
331
+ } catch (err) {
332
+ await this.invalidatePeerFreshness();
333
+ throw err;
334
+ }
311
335
  if (this.dirty) {
312
336
  this.scheduleReconcileRetry();
313
337
  } else {
@@ -577,4 +601,4 @@ export {
577
601
  FactHashIndexNotAuthoritativeError,
578
602
  ContentHashIndex
579
603
  };
580
- //# sourceMappingURL=chunk-UDKWFDV2.js.map
604
+ //# sourceMappingURL=chunk-HLUHEMN4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/content-hash-index.ts"],"sourcesContent":["// Content-hash dedup index for facts, extracted from storage.ts (issue #1909 /\n// PR #2016 write-hot-paths). Self-contained: cross-process locked reconcile /\n// rebuild saves plus the deferred durable-retry machinery. storage.ts imports\n// these back and re-exports the class + companion types that were previously\n// part of its public API.\nimport { mkdir, stat, utimes } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { computeContentHash, normalizeContent } from \"../content-hash.js\";\nimport { log } from \"../logger.js\";\nimport { SecureStoreLockedError, readMaybeEncryptedFile, writeMaybeEncryptedFile } from \"../secure-store/secure-fs.js\";\nimport { isErrnoCode } from \"../utils/errno.js\";\nimport { withHeldFileLock } from \"../utils/serialize-mutations.js\";\n\n/**\n * Stale threshold (ms) for the per-file advisory lock guarding a fact-hash\n * index merge-save (issue #1909 review round 7). The critical section is a\n * single read+atomic-rewrite of one index file (≤ a few MB), so a holder older\n * than this is treated as crashed. Generous to tolerate slow/encrypted disks\n * without breaking a legitimately in-progress publish.\n */\nconst CONTENT_HASH_INDEX_LOCK_STALE_MS = 30_000;\n/** Version marker for the normalized Unicode hash index format. */\nconst CONTENT_HASH_INDEX_FORMAT_HEADER = \"# remnic-content-hash-index:v2\";\n\nfunction parseHashIndex(raw: string): { versioned: boolean; hashes: Set<string> } {\n const lines = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n if (lines[0] !== CONTENT_HASH_INDEX_FORMAT_HEADER) {\n return { versioned: false, hashes: new Set() };\n }\n return { versioned: true, hashes: new Set(lines.slice(1)) };\n}\n\nfunction serializeHashIndex(hashes: Set<string>): string {\n return `${CONTENT_HASH_INDEX_FORMAT_HEADER}\\n${[...hashes].join(\"\\n\")}\\n`;\n}\n\n/**\n * Durable-retry policy for a deferred content-hash reconcile save whose\n * cross-process lock acquire timed out (issue #1909 / PR #2016). When the lock\n * is contended past `withHeldFileLock`'s bounded wait, the added hashes are held\n * only in this process's memory; relying on \"some later batch save\" is not\n * durable (the run may be the last before idle/shutdown), and a long-lived peer\n * that already built its authoritative in-memory index will not see the write.\n * So we schedule a bounded, exponentially-backed-off background retry that keeps\n * re-attempting the locked publish until it lands. Bounded because the durable\n * fact `.md` is already on disk and a process restart rebuilds the index from\n * the corpus regardless — exhausting retries degrades to that rebuild safety\n * net, never to data loss or a fatal append failure.\n */\nconst CONTENT_HASH_INDEX_RETRY_MAX_ATTEMPTS = 5;\n/** Base backoff (ms) before the first deferred reconcile-save retry; doubles each attempt. */\nconst CONTENT_HASH_INDEX_RETRY_BASE_MS = 500;\n/** Ceiling (ms) for the exponential reconcile-save retry backoff. */\nexport const CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS = 5_000;\n\n/**\n * Tuning for {@link ContentHashIndex} cross-process lock waits and the\n * deferred reconcile-save durable retry (issue #1909 / PR #2016). All optional;\n * production uses the module defaults. Tests inject small values so the\n * lock-timeout + retry path is exercised deterministically without real\n * multi-second waits.\n */\nexport interface ContentHashIndexLockOptions {\n /** Bounded wait to acquire the per-file advisory lock; passed to `withHeldFileLock` (default 5000ms). */\n readonly maxWaitMs?: number;\n /** Poll interval while waiting for a busy lock (default 50ms). */\n readonly pollMs?: number;\n /** Base backoff before the first deferred-save retry (default 500ms). */\n readonly retryBaseMs?: number;\n /** Max deferred-save retries before falling back to the corpus-rebuild safety net (default 5). */\n readonly retryMaxAttempts?: number;\n /**\n * Tombstone-blocked capture write-lock backoff (COS-392). These do not\n * change the fact-hash index lock. Omitted fields use the 50ms / 2s / 60s\n * defaults. Converge copies its config here before replicating a file.\n */\n readonly captureWriteLockInitialDelayMs?: number;\n readonly captureWriteLockMaxDelayMs?: number;\n readonly captureWriteLockDeadlineMs?: number;\n /** Apply abort signal. Checked before each probe, during backoff, and before the write. */\n readonly captureWriteLockSignal?: AbortSignal;\n}\n\n/**\n * Thrown when the fact-hash index cannot be made authoritative — the\n * cross-process rebuild lock could not be acquired within the bounded retry\n * budget (PR #2016). Callers that require an authoritative dedup answer surface\n * this instead of silently trusting a stale loaded snapshot.\n */\nexport class FactHashIndexNotAuthoritativeError extends Error {\n constructor(stateDir: string) {\n super(\n `fact-hash index is not authoritative: the cross-process rebuild lock for ${stateDir} could not be acquired within the bounded retry budget`\n );\n this.name = \"FactHashIndexNotAuthoritativeError\";\n }\n}\n\n/**\n * One dedup lookup: whether the shared index holds the hash, and whether that\n * answer can be trusted as a clean MISS. Both fields describe the same instant.\n */\nexport interface ContentHashLookup {\n readonly present: boolean;\n readonly authoritative: boolean;\n}\n\ntype DiskFingerprint = {\n mtimeMs: number;\n size: number;\n dev: number;\n ino: number;\n ctimeMs: number;\n birthtimeMs: number;\n};\nexport interface ContentHashPathEntry {\n readonly path: string;\n readonly contentHash: string;\n}\n\n/**\n * Content-hash dedup index for facts.\n * Normalizes content (lowercase, strip punctuation, collapse whitespace),\n * computes SHA-256, and stores hashes in a line-delimited file.\n * Prevents writing semantically identical facts.\n */\nexport class ContentHashIndex {\n private hashes: Set<string> = new Set();\n /**\n * Fact-ONLY hash partition (issue #2474). `hashes` above is category-blind\n * (every write category registers there); this subset carries only\n * `category === \"fact\"` hashes so fact-only membership checks\n * (`hasFact*`) can never be satisfied by an unrelated decision/preference\n * sharing the same normalized body. In-memory only — never serialized to\n * fact-hashes.txt; `clear()` drops it and every authoritative rebuild\n * repopulates it via `addFactByHash`. Subset invariant: `factHashes ⊆\n * hashes` — `addFact*` registers in both, and the removal sites that drop\n * a shared hash also drop the partition entry (removal stays caller-paired\n * because shared-index removal is category-blind: archiving a non-fact\n * must not evict an active fact's fact-only membership).\n */\n private factHashes: Set<string> = new Set();\n private dirty = false;\n /** True when load() found the pre-Unicode, markerless on-disk format. */\n private formatMigrationRequired = false;\n /**\n * Hashes explicitly removed since the last successful save (issue #1909 review\n * round 8 thread 3). Tracked separately so `saveMergingWithDisk` can be\n * removal-AWARE: under the file lock it reads the latest on-disk set, DROPS\n * these, then unions our additions — so a removal batch cannot resurrect a\n * hash (union alone would) and cannot clobber a concurrent extraction's\n * appended hash (blind overwrite would). Consumed + cleared by every save.\n */\n private removed: Set<string> = new Set();\n /**\n * Hashes added by THIS instance since the last successful save (issue #1909\n * review round 9 finding 3). Tracked separately from the loaded snapshot so a\n * reconciling save publishes `(on-disk \\ removed) ∪ added` — it re-applies only\n * OUR additions, never the stale loaded entries. Without this, seeding the\n * merge from `this.hashes` (loaded ∪ added) would resurrect a hash a peer\n * removed on disk while this instance held a stale snapshot.\n */\n private added: Set<string> = new Set();\n private readonly filePath: string;\n private readonly secureStoreKeyProvider: () => Buffer | null;\n private readonly secureStoreWriteKeyProvider: () => Buffer | null;\n private readonly memoryDir: string;\n private readonly lockOptions: ContentHashIndexLockOptions;\n /**\n * Deferred reconcile-save durable-retry state (issue #1909 / PR #2016). At\n * most ONE retry is ever armed (`reconcileRetryTimer` is the reentrancy guard)\n * so successive timed-out saves cannot stack duplicate/parallel retries.\n * `reconcileRetryBarrier` resolves when the chain settles (published or gave\n * up) — awaited by tests and any caller wanting the eventual result.\n */\n private reconcileRetryTimer: NodeJS.Timeout | null = null;\n private reconcileRetryAttempts = 0;\n private reconcileRetryBarrier: Promise<void> | null = null;\n private reconcileRetryResolve: (() => void) | null = null;\n /**\n * On-disk fingerprint captured at the last point THIS instance's in-memory\n * set matched disk — after `load()`, `save()`, or a reconcile publish. A peer\n * process that advances the durable index changes its file generation even\n * when byte size and mtime collide, so the freshness check remains safe\n * without an O(file-size) read on the hot path.\n */\n private lastSyncedFingerprint: DiskFingerprint | null = null;\n constructor(\n stateDir: string,\n secureStoreKeyProvider: () => Buffer | null = () => null,\n secureStoreWriteKeyProvider: () => Buffer | null = secureStoreKeyProvider,\n memoryDir: string = path.dirname(stateDir),\n lockOptions: ContentHashIndexLockOptions = {}\n ) {\n this.filePath = path.join(stateDir, \"fact-hashes.txt\");\n this.secureStoreKeyProvider = secureStoreKeyProvider;\n this.secureStoreWriteKeyProvider = secureStoreWriteKeyProvider;\n this.memoryDir = memoryDir;\n this.lockOptions = lockOptions;\n }\n /** Whether a caller with an authoritative corpus must rebuild this legacy index. */\n get requiresFormatMigration(): boolean {\n return this.formatMigrationRequired;\n }\n\n /** Load existing hashes from disk. Safe to call multiple times. */\n async load(): Promise<void> {\n try {\n const raw = await readMaybeEncryptedFile(this.filePath, this.secureStoreKeyProvider(), this.memoryDir);\n const parsed = parseHashIndex(raw);\n this.formatMigrationRequired = !parsed.versioned;\n if (!parsed.versioned) {\n // Hashes from the pre-NFC format are unsafe after normalization changes.\n // Ignore them until an authoritative corpus rebuild publishes v2.\n this.hashes.clear();\n log.warn(`content-hash index: ignored legacy unversioned index at ${this.filePath}`);\n } else {\n for (const hash of parsed.hashes) this.hashes.add(hash);\n }\n log.debug(`content-hash index: loaded ${this.hashes.size} hashes`);\n } catch (err) {\n if (err instanceof SecureStoreLockedError) throw err;\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n log.debug(\"content-hash index: no existing index — starting fresh\");\n }\n // The loaded set now reflects the on-disk file — baseline the fingerprint so\n // a later peer write is detectable (PR #2016 review).\n await this.captureSyncedFingerprint();\n }\n\n /** Cheap `stat` of the durable index file; null when it does not exist yet. */\n private async statIndexFile(): Promise<DiskFingerprint | null> {\n try {\n const s = await stat(this.filePath);\n return {\n mtimeMs: s.mtimeMs,\n size: s.size,\n dev: s.dev,\n ino: s.ino,\n ctimeMs: s.ctimeMs,\n birthtimeMs: s.birthtimeMs,\n };\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) return null;\n throw err;\n }\n }\n\n /** Record the current on-disk fingerprint as this instance's synced baseline. */\n private async captureSyncedFingerprint(): Promise<void> {\n try {\n this.lastSyncedFingerprint = await this.statIndexFile();\n } catch (err) {\n // A stat failure other than ENOENT leaves no baseline; the next freshness\n // check reports non-current and the caller confirms against the corpus.\n this.lastSyncedFingerprint = null;\n log.debug(`content-hash index: could not fingerprint ${this.filePath}: ${err}`);\n }\n }\n\n /**\n * True when the durable index file is unchanged since this instance last\n * synced it (load / save / reconcile). False when a peer advanced it, when\n * the file appeared or vanished, or when freshness cannot be established\n * (stat error) — the caller then treats the in-memory snapshot as\n * non-authoritative and confirms a dedup miss against the durable corpus.\n * The stat includes file identity and generation metadata so same-size,\n * same-mtime atomic replacements are detected without reading the file body.\n */\n async isDiskFingerprintCurrent(): Promise<boolean> {\n let current: DiskFingerprint | null;\n try {\n current = await this.statIndexFile();\n } catch {\n return false;\n }\n const last = this.lastSyncedFingerprint;\n if (last === null || current === null) {\n return last === null && current === null;\n }\n return (\n current.mtimeMs === last.mtimeMs &&\n current.size === last.size &&\n current.dev === last.dev &&\n current.ino === last.ino &&\n current.ctimeMs === last.ctimeMs &&\n current.birthtimeMs === last.birthtimeMs\n );\n }\n\n /**\n * Change the durable file's mtime without touching its content. A publish\n * that throws or stays deferred leaves the file as it was, so a peer that\n * already synced it keeps answering authoritative MISSes for deltas this\n * instance holds only in memory (#3355). A new stamp makes every holder of the\n * old fingerprint, this instance included, fail the freshness check and\n * confirm against the corpus. Best effort: a file that cannot be stamped\n * leaves the callers' existing retry and rebuild paths as the only repair.\n */\n private async invalidatePeerFreshness(): Promise<void> {\n try {\n const { mtimeMs } = await stat(this.filePath);\n const bumped = new Date(Math.max(Date.now(), mtimeMs + 1));\n await utimes(this.filePath, bumped, bumped);\n } catch (err) {\n log.debug(`content-hash index: could not invalidate peer freshness of ${this.filePath}: ${err}`);\n }\n }\n\n /** Check if content already exists in the index. */\n has(content: string): boolean {\n return this.hashes.has(ContentHashIndex.computeHash(content));\n }\n\n /** Add content hash to the index. */\n add(content: string): void {\n const hash = ContentHashIndex.computeHash(content);\n // A re-add supersedes a pending removal of the same hash (round 8 thread 3).\n this.removed.delete(hash);\n // Record OUR durable delta even when the local snapshot already holds the\n // hash (PR #2016 thread SD-nG): local membership can be STALE — a peer\n // removed this hash on disk while this instance kept it in memory. Skipping\n // `added`/`dirty` on that path let the reconciling save compute\n // (on-disk \\ removed) ∪ added and silently drop the reintroduced hash, so\n // the peer never saw it again. Set semantics keep this idempotent (no\n // duplicate entries) and the `removed.delete` above preserves remove/add\n // ordering.\n this.hashes.add(hash);\n this.added.add(hash);\n this.dirty = true;\n }\n\n get size(): number {\n return this.hashes.size;\n }\n\n /** Clear all loaded hashes so the next save rewrites the index from scratch. */\n clear(): void {\n if (this.hashes.size > 0) {\n this.hashes.clear();\n }\n // The fact-only partition is rebuilt with the shared set on every\n // authoritative corpus rebuild, so it clears here too (issue #2474).\n this.factHashes.clear();\n // A full clear is always paired with a plain overwrite save() (rebuild);\n // pending per-hash add/remove deltas are subsumed by writing the rebuilt set.\n // Cancel any armed deferred-reconcile retry (PR #2016) so it cannot fire in\n // the clear→rebuild→save window and union the pre-clear on-disk rows back.\n this.added.clear();\n this.removed.clear();\n this.cancelReconcileRetry();\n this.dirty = true;\n }\n\n /** Persist index to disk if changed (plain whole-file overwrite). */\n async save(): Promise<void> {\n if (!this.dirty) return;\n await mkdir(path.dirname(this.filePath), { recursive: true });\n // Snapshot the deltas + overwrite body THIS save publishes BEFORE the write\n // yields the event loop. `writeMaybeEncryptedFile` materializes `serialized`\n // eagerly, then the disk await lets a concurrent same-process add()/remove()\n // land a late delta (PR #2016 thread PRRT_kwDORJXyws6SEBri). Clearing the\n // LIVE added/removed sets afterward — as the previous unconditional\n // clear()+`dirty = false` did — would drop that late hash from the index AND\n // leave no retry, so peers never see it until a corpus rebuild. Consume only\n // what we published; late deltas stay pending. Mirrors saveMergingWithDisk.\n const publishedAdded = new Set<string>(this.added);\n const publishedRemoved = new Set<string>(this.removed);\n const serialized = serializeHashIndex(this.hashes);\n await writeMaybeEncryptedFile(this.filePath, serialized, this.secureStoreWriteKeyProvider(), {}, this.memoryDir);\n this.formatMigrationRequired = false;\n // Consume ONLY the deltas this overwrite published; anything that arrived\n // during the awaits above remains pending for the next save.\n for (const h of publishedAdded) this.added.delete(h);\n for (const h of publishedRemoved) this.removed.delete(h);\n // Honest dirty state: true iff late deltas remain unpersisted.\n this.dirty = this.added.size > 0 || this.removed.size > 0;\n // This overwrite is now the on-disk state — re-baseline the freshness\n // fingerprint so our own write is not later mistaken for a peer's (PR #2016).\n await this.captureSyncedFingerprint();\n if (this.dirty) {\n // Late deltas landed mid-save: arm a bounded durable retry so they reach\n // disk even without a further batch save — never a silent in-memory-only\n // hash. The locked reconcile republishes only OUR delta onto the overwrite.\n this.scheduleReconcileRetry();\n } else {\n // Clean overwrite supersedes any pending deferred reconcile work.\n this.cancelReconcileRetry();\n }\n log.debug(`content-hash index: saved ${this.hashes.size} hashes`);\n }\n\n /**\n * Persist the index by RECONCILING with the latest on-disk state under a\n * cross-process lock (issue #1909). Used by the extraction-persist batch save\n * for BOTH append and removal batches, so appends and removals to the same\n * index serialize against each other:\n * final = (on-disk \\ this.removed) ∪ this.added\n * Note it re-applies only OUR local additions (`added`), NOT the loaded\n * snapshot (review round 9 finding 3): seeding from `this.hashes` would\n * resurrect a hash a peer removed on disk while we held a stale snapshot. This\n * preserves a concurrent writer's appended hashes (a blind overwrite would\n * drop them), never resurrects a removed hash, and never loses our additions.\n *\n * Hardening:\n * - Dirty short-circuit (round 7 finding 3): when this instance neither added\n * nor removed anything this run, skip the O(file) read+rewrite entirely.\n * - Cross-process lock (round 7 finding 2): serialize the read→reconcile→write\n * window on a per-file advisory lock. If the lock is NOT acquired (timeout),\n * do NOT publish (round 9 finding 2): keep `dirty` set AND schedule a bounded\n * durable background retry (PR #2016) that keeps re-attempting the locked\n * publish until the deferred additions land — never an unlocked write that\n * could clobber a peer, and never a silent \"batch save complete\" that leaves\n * the addition in this process's memory only.\n */\n async saveMergingWithDisk(): Promise<void> {\n if (!this.dirty) return;\n // The advisory lock file lives beside the index — ensure the dir exists\n // before acquiring it (the index dir may not exist on a first write).\n await mkdir(path.dirname(this.filePath), { recursive: true });\n const publish = async (): Promise<void> => {\n // Snapshot the deltas this publish is responsible for. The read+rewrite\n // below yields the event loop, so a concurrent add()/remove() can land\n // new deltas while we await disk (PR #2016 thread SD7Tj). Consuming the\n // LIVE sets afterward would drop those late deltas AND clear `dirty`,\n // stranding them in no save at all. We consume only what we published;\n // anything that arrived meanwhile stays pending for the next save.\n const publishedAdded = new Set<string>(this.added);\n const publishedRemoved = new Set<string>(this.removed);\n const merged = new Set<string>(publishedAdded);\n try {\n const raw = await readMaybeEncryptedFile(this.filePath, this.secureStoreKeyProvider(), this.memoryDir);\n const parsed = parseHashIndex(raw);\n if (parsed.versioned) {\n for (const hash of parsed.hashes) {\n // Keep prior/concurrent on-disk hashes EXCEPT the ones we removed.\n if (!publishedRemoved.has(hash)) merged.add(hash);\n }\n } else {\n // Do not carry hashes from the pre-NFC format into a v2 write.\n log.warn(`content-hash index: discarded legacy unversioned entries from ${this.filePath}`);\n }\n } catch (err) {\n if (err instanceof SecureStoreLockedError) throw err;\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n // ENOENT → no on-disk index yet; write our additions as-is.\n }\n await mkdir(path.dirname(this.filePath), { recursive: true });\n await writeMaybeEncryptedFile(\n this.filePath,\n serializeHashIndex(merged),\n this.secureStoreWriteKeyProvider(),\n {},\n this.memoryDir\n );\n this.formatMigrationRequired = false;\n // Consume ONLY the deltas we just published; deltas that arrived during\n // the awaits above remain pending.\n for (const h of publishedAdded) this.added.delete(h);\n for (const h of publishedRemoved) this.removed.delete(h);\n // Fold any still-pending deltas onto the reconciled set so the in-memory\n // view stays consistent with what the next save will publish.\n for (const h of this.added) merged.add(h);\n for (const h of this.removed) merged.delete(h);\n this.hashes = merged;\n // Honest dirty state: true iff late deltas remain to be persisted. A\n // subsequent batch save or the shutdown flush drains them.\n this.dirty = this.added.size > 0 || this.removed.size > 0;\n // The reconciled set is now the on-disk state — re-baseline the freshness\n // fingerprint (captured under the held lock) so our own publish is not\n // later mistaken for a peer's advance (PR #2016 review).\n await this.captureSyncedFingerprint();\n };\n await withHeldFileLock(\n `${this.filePath}.lock`,\n {\n staleMs: CONTENT_HASH_INDEX_LOCK_STALE_MS,\n ...(this.lockOptions.maxWaitMs !== undefined ? { maxWaitMs: this.lockOptions.maxWaitMs } : {}),\n ...(this.lockOptions.pollMs !== undefined ? { pollMs: this.lockOptions.pollMs } : {}),\n },\n async (acquired) => {\n if (!acquired) {\n // Never publish unlocked (round 9 finding 2): keep dirty AND schedule a\n // durable background retry (PR #2016). Relying on an unguaranteed later\n // batch save silently left the addition in this process's memory only;\n // the retry keeps re-attempting the locked publish until the addition\n // lands on disk.\n log.warn(\n `content-hash index: lock not acquired for ${this.filePath}; deferring reconcile save (dirty retained, scheduling durable retry)`\n );\n this.scheduleReconcileRetry();\n await this.invalidatePeerFreshness();\n return;\n }\n try {\n await publish();\n } catch (err) {\n await this.invalidatePeerFreshness();\n throw err;\n }\n if (this.dirty) {\n // A concurrent add()/remove() landed during publish's disk awaits, so\n // deltas remain unpersisted (PR #2016 thread SD7Tj). Arm a bounded\n // durable retry so they reach disk even if no further batch save comes\n // — never leave a settled barrier over pending work.\n this.scheduleReconcileRetry();\n } else {\n // Published cleanly: any pending deferred retry is now satisfied.\n this.cancelReconcileRetry();\n }\n }\n );\n log.debug(`content-hash index: reconcile-saved ${this.hashes.size} hashes`);\n }\n\n /**\n * Rebuild-and-publish the index from an authoritative source (the durable\n * corpus) under the SAME per-file cross-process lock the reconciling\n * append/removal saves (`saveMergingWithDisk`) use (issue #1909 / PR #2016).\n * The `populate` callback runs WHILE the lock is held and MUST repopulate this\n * index from the corpus (`clear()` then `addByHash(...)` for every corpus\n * hash); the rebuilt set is then published with a plain overwrite that is now\n * serialized against every locked writer.\n *\n * This closes the finding where the previous unlocked clear→scan→save() could\n * overwrite a peer's newer lock-merged or deferred additions: a locked writer\n * that committed BEFORE the rebuild acquired the lock has its memory `.md` on\n * disk and is re-scanned; one that commits AFTER the rebuild releases\n * reconciles its additions on top of the freshly-published set. No union with\n * the raw on-disk file is performed, so the rebuild keeps its\n * garbage-collection property (orphaned hashes for deleted memories drop).\n *\n * Lock-acquisition failure is explicit and non-destructive: `populate` is NOT\n * run and nothing is written (never an unlocked overwrite). Returns true when\n * the rebuild was published under the lock, false when the lock timed out —\n * the caller keeps the index non-authoritative and retries on next use. Uses\n * the same non-reentrant file lock as the reconcile path, so it can never\n * deadlock with the deferred reconcile-retry: a concurrent locked writer (or a\n * fired retry) simply yields `acquired=false` after the bounded wait.\n */\n async rebuildUnderLock(populate: () => Promise<void>): Promise<boolean> {\n // The advisory lock file lives beside the index — ensure the dir exists\n // before acquiring it (the index dir may not exist on a first rebuild).\n await mkdir(path.dirname(this.filePath), { recursive: true });\n let published = false;\n await withHeldFileLock(\n `${this.filePath}.lock`,\n {\n staleMs: CONTENT_HASH_INDEX_LOCK_STALE_MS,\n ...(this.lockOptions.maxWaitMs !== undefined ? { maxWaitMs: this.lockOptions.maxWaitMs } : {}),\n ...(this.lockOptions.pollMs !== undefined ? { pollMs: this.lockOptions.pollMs } : {}),\n },\n async (acquired) => {\n if (!acquired) {\n // Never publish unlocked: a concurrent locked writer holds the lock,\n // so overwriting now could clobber its addition. Leave the index as-is\n // and let the caller retry the authoritative rebuild on next use.\n log.warn(\n `content-hash index: lock not acquired for ${this.filePath}; deferring authoritative rebuild (index left non-authoritative, retried on next use)`\n );\n return;\n }\n await populate();\n // Publish under the held lock. save() takes no lock (no re-entrancy) and\n // is a full overwrite that supersedes any pending add/remove deltas.\n await this.save();\n published = true;\n }\n );\n return published;\n }\n\n /**\n * True while a background durable reconcile-save retry is armed (PR #2016).\n * Test/introspection hook.\n */\n get hasPendingReconcileRetry(): boolean {\n return this.reconcileRetryTimer !== null;\n }\n\n /** True while this index has in-memory changes not yet published to disk. */\n get hasPendingChanges(): boolean {\n return this.dirty;\n }\n\n /**\n * Resolve once any armed background reconcile-save retry chain has settled —\n * either it published the deferred additions, or it exhausted its bounded\n * attempts and fell back to the corpus-rebuild safety net. Resolves\n * immediately when nothing is armed. Lets a caller (or a test) await the\n * eventual durability outcome of a lock-timed-out save.\n */\n async whenReconcileRetrySettled(): Promise<void> {\n await (this.reconcileRetryBarrier ?? Promise.resolve());\n }\n\n /**\n * Drive any deferred lock-timeout reconcile save to completion INLINE at a\n * lifecycle boundary (PR #2016 finding 3). The background retry timer is\n * `unref`'d so it never keeps a long-lived daemon alive — but a short-lived\n * writer (a one-shot CLI) can exit before it fires, leaving a durable fact\n * `.md` whose hash never reached `fact-hashes.txt` for peers that already\n * built their in-memory index. `orchestrator.destroy()` calls this so the\n * addition publishes before the process exits; long-lived hosts only reach it\n * at their own shutdown, so their in-flight retries keep running in the\n * background until then. Bounded by the same attempt ceiling as the background\n * retry; a permanently contended lock falls back to the corpus-rebuild-on-\n * restart safety net (the fact `.md` is already durable). No deadlock: each\n * attempt is the same non-reentrant, bounded-wait file lock.\n */\n async flushReconcileRetry(): Promise<void> {\n if (!this.dirty) return;\n const maxAttempts = this.lockOptions.retryMaxAttempts ?? CONTENT_HASH_INDEX_RETRY_MAX_ATTEMPTS;\n const baseMs = this.lockOptions.retryBaseMs ?? CONTENT_HASH_INDEX_RETRY_BASE_MS;\n for (let attempt = 0; this.dirty && attempt < maxAttempts; attempt += 1) {\n // Cancel the unref'd background timer — we drive the locked publish inline.\n if (this.reconcileRetryTimer) {\n clearTimeout(this.reconcileRetryTimer);\n this.reconcileRetryTimer = null;\n }\n await this.saveMergingWithDisk();\n if (!this.dirty) break;\n if (attempt < maxAttempts - 1) {\n const wait = Math.min(baseMs * 2 ** attempt, CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS);\n await new Promise<void>((resolve) => setTimeout(resolve, wait));\n }\n }\n // Clear any timer the final saveMergingWithDisk armed and settle the barrier\n // so awaiters unblock — the bounded inline drain has done its best.\n if (this.reconcileRetryTimer) {\n clearTimeout(this.reconcileRetryTimer);\n this.reconcileRetryTimer = null;\n }\n this.reconcileRetryAttempts = 0;\n this.settleReconcileRetry();\n }\n\n /**\n * Schedule ONE bounded, exponentially-backed-off background retry of the\n * deferred reconcile save (PR #2016). Reentrant-safe: an already-armed timer\n * short-circuits, so successive timed-out saves never stack duplicate retries.\n * When attempts are exhausted the chain settles without publishing — the\n * durable fact `.md` is on disk and a process restart rebuilds the index from\n * the corpus, so this degrades to that safety net, never a fatal failure.\n */\n private scheduleReconcileRetry(): void {\n if (this.reconcileRetryTimer) return; // one retry in flight — no duplicate/reentrant retries\n const maxAttempts = this.lockOptions.retryMaxAttempts ?? CONTENT_HASH_INDEX_RETRY_MAX_ATTEMPTS;\n if (this.reconcileRetryAttempts >= maxAttempts) {\n log.warn(\n `content-hash index: exhausted ${maxAttempts} deferred reconcile-save retries for ${this.filePath}; ` +\n `${this.added.size} addition(s) remain dirty in-memory (a process restart rebuilds the index from the durable corpus)`\n );\n this.reconcileRetryAttempts = 0;\n this.settleReconcileRetry();\n return;\n }\n if (!this.reconcileRetryBarrier) {\n this.reconcileRetryBarrier = new Promise<void>((resolve) => {\n this.reconcileRetryResolve = resolve;\n });\n }\n const attempt = this.reconcileRetryAttempts + 1;\n const baseMs = this.lockOptions.retryBaseMs ?? CONTENT_HASH_INDEX_RETRY_BASE_MS;\n const delay = Math.min(baseMs * 2 ** (attempt - 1), CONTENT_HASH_INDEX_RETRY_MAX_DELAY_MS);\n this.reconcileRetryTimer = setTimeout(() => {\n this.reconcileRetryTimer = null;\n this.reconcileRetryAttempts = attempt;\n void this.saveMergingWithDisk()\n .catch((err) => {\n // A publish-time I/O/encryption error (not a lock timeout) is best-effort:\n // log and let the corpus-rebuild safety net cover it rather than loop.\n log.warn(`content-hash index: deferred reconcile-save retry failed for ${this.filePath}: ${err}`);\n })\n .finally(() => {\n // If the attempt neither published (dirty cleared → cancelReconcileRetry)\n // nor re-armed a further retry, the chain has ended — settle the barrier.\n if (this.dirty && !this.reconcileRetryTimer) this.settleReconcileRetry();\n });\n }, delay);\n this.reconcileRetryTimer.unref?.();\n }\n\n /** Cancel any armed reconcile-save retry and settle the barrier (a publish landed). */\n private cancelReconcileRetry(): void {\n if (this.reconcileRetryTimer) {\n clearTimeout(this.reconcileRetryTimer);\n this.reconcileRetryTimer = null;\n }\n this.reconcileRetryAttempts = 0;\n this.settleReconcileRetry();\n }\n\n /** Resolve and clear the retry barrier if one is outstanding. */\n private settleReconcileRetry(): void {\n const resolve = this.reconcileRetryResolve;\n this.reconcileRetryBarrier = null;\n this.reconcileRetryResolve = null;\n resolve?.();\n }\n\n /** Remove a hash from the index (used when archiving/deleting). */\n remove(content: string): void {\n const hash = ContentHashIndex.computeHash(content);\n // Record the removal (round 8 thread 3) even when the hash is not in our\n // in-memory set — a reconciling save must still drop it from the latest\n // on-disk state. A removal supersedes a pending add. Always mark dirty.\n this.added.delete(hash);\n this.removed.add(hash);\n this.hashes.delete(hash);\n this.dirty = true;\n }\n\n /**\n * Remove a pre-computed SHA-256 hash directly from the index without\n * re-hashing. Use this when the caller already holds the stored hash\n * (e.g. `memory.frontmatter.contentHash`) to avoid the double-hash bug\n * where `remove(hash)` would compute `hash(hash)` and never match the\n * entry.\n */\n removeByHash(hash: string): void {\n this.added.delete(hash);\n this.removed.add(hash);\n this.hashes.delete(hash);\n this.dirty = true;\n }\n\n /**\n * Add a pre-computed SHA-256 hash directly to the index without re-hashing.\n * Use this when the caller already holds the stored hash\n * (e.g. `memory.frontmatter.contentHash`) so that the index records the raw\n * content hash rather than re-hashing the citation-annotated body.\n *\n * @internal Only called from `StorageManager.ensureFactHashIndexAuthoritative`.\n * Not part of the public API — prefer `add(content)` for external callers.\n */\n addByHash(hash: string): void {\n // A re-add supersedes a pending removal of the same hash.\n this.removed.delete(hash);\n // Record OUR durable delta even when the local snapshot already holds the\n // hash (PR #2016 thread PRRT_kwDORJXyws6SEHve). Outside a rebuild\n // (StorageManager.addActiveFactContentHash on reactivation) local\n // membership can be STALE: a peer removed this hash on disk while this\n // instance kept it in memory. Skipping added/dirty on that path let the\n // reconciling save compute (on-disk \\ removed) ∪ added and silently drop\n // the reintroduced hash, so the peer never saw it again. Set semantics keep\n // this idempotent (no duplicate entries) and the removed.delete above\n // preserves remove/add ordering. Mirrors add().\n this.hashes.add(hash);\n this.added.add(hash);\n this.dirty = true;\n }\n\n // ── Fact-only partition (issue #2474) ─────────────────────────────────\n // Folded here from StorageManager's parallel `factOnlyHashes` set, which had\n // to be kept in lockstep by hand on every add/remove/rebuild site. The\n // partition lives on the index instance, so every path that mutates the\n // shared set and needs fact-only truth mutates it in the same breath.\n\n /** Register fact content in BOTH the shared index and the fact-only partition. */\n addFact(content: string): void {\n this.addFactByHash(ContentHashIndex.computeHash(content));\n }\n\n /** Register a pre-computed fact hash in both the shared index and the fact-only partition. */\n addFactByHash(hash: string): void {\n this.addByHash(hash);\n this.factHashes.add(hash);\n }\n\n /** Fact-ONLY membership: has this content been registered as a fact? */\n hasFact(content: string): boolean {\n return this.factHashes.has(ContentHashIndex.computeHash(content));\n }\n\n /** Fact-ONLY membership for a pre-computed SHA-256 hash. */\n hasFactByHash(hash: string): boolean {\n return this.factHashes.has(hash);\n }\n\n /**\n * Drop fact-only partition membership WITHOUT touching the shared index.\n * The shared removal stays caller-owned: a shared hash is dropped only when\n * no other active memory holds it, while fact-only membership follows the\n * fact's own lifecycle (supersede/archive/promotion).\n */\n removeFactByHash(hash: string): void {\n this.factHashes.delete(hash);\n }\n\n /**\n * Resolve a pre-computed semantic hash to one deterministic corpus path.\n *\n * This lookup is separate from durable hash membership: `this.hashes` stays\n * one hash per line and `has(content)` keeps its existing raw-content contract.\n * Reconciliation supplies short-lived manifest rows where hash and path coexist.\n */\n static resolvePathByHash(hash: string, entries: Iterable<ContentHashPathEntry>): string | undefined {\n const canonicalHash = hash.toLowerCase();\n if (!/^[a-f0-9]{64}$/.test(canonicalHash)) return undefined;\n let canonicalPath: string | undefined;\n for (const entry of entries) {\n if (entry.contentHash.toLowerCase() !== canonicalHash || entry.path.length === 0) continue;\n if (canonicalPath === undefined || entry.path < canonicalPath) canonicalPath = entry.path;\n }\n return canonicalPath;\n }\n\n /** Normalize content (delegates to content-hash.ts for a single source of truth). */\n static normalizeContent(content: string): string {\n return normalizeContent(content);\n }\n\n /** Compute SHA-256 hash (delegates to content-hash.ts for a single source of truth). */\n static computeHash(content: string): string {\n return computeContentHash(content);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAKA,SAAS,OAAO,MAAM,cAAc;AACpC,OAAO,UAAU;AAcjB,IAAM,mCAAmC;AAEzC,IAAM,mCAAmC;AAEzC,SAAS,eAAe,KAA0D;AAChF,QAAM,QAAQ,IACX,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC;AACnC,MAAI,MAAM,CAAC,MAAM,kCAAkC;AACjD,WAAO,EAAE,WAAW,OAAO,QAAQ,oBAAI,IAAI,EAAE;AAAA,EAC/C;AACA,SAAO,EAAE,WAAW,MAAM,QAAQ,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC,EAAE;AA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,cAAe,iBAAgB,MAAM;AAAA,IACvF;AACA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,iBAAiB,SAAyB;AAC/C,WAAO,iBAAiB,OAAO;AAAA,EACjC;AAAA;AAAA,EAGA,OAAO,YAAY,SAAyB;AAC1C,WAAO,mBAAmB,OAAO;AAAA,EACnC;AACF;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-AAD2ZS6P.js";
5
5
  import {
6
6
  gatewayTaskChainOptions
7
- } from "./chunk-ZU5JDLOH.js";
7
+ } from "./chunk-MMRTPH3J.js";
8
8
  import {
9
9
  extractJsonCandidates
10
10
  } from "./chunk-YBA52OKG.js";
@@ -685,4 +685,4 @@ export {
685
685
  serializeFaithfulnessFields,
686
686
  parseFaithfulnessField
687
687
  };
688
- //# sourceMappingURL=chunk-QFEDITXM.js.map
688
+ //# sourceMappingURL=chunk-JNDMIAJ4.js.map
@@ -0,0 +1,359 @@
1
+ import {
2
+ assertNamespaceAllowed,
3
+ assertOperationAuthorizationAllowed,
4
+ tokenCapabilityStore
5
+ } from "./chunk-OGBQMY46.js";
6
+ import {
7
+ expandTildePath
8
+ } from "./chunk-6KH5NLQS.js";
9
+ import {
10
+ EngramAccessInputError
11
+ } from "./chunk-CJCTKL6Y.js";
12
+
13
+ // src/access-boundary.ts
14
+ import { z } from "zod";
15
+ var OPERATION_NAMES = [
16
+ "memory_get",
17
+ "memory_search",
18
+ "external_wiki_search",
19
+ "memory_store",
20
+ "coding_decision",
21
+ "coding_architecture",
22
+ // codegraph parity tools (issue #1554) -- each maps to one codegraph_*
23
+ // boundary operation that delegates to the surface handler in
24
+ // coding/codegraph-surfaces.ts. Names match the external tool suffixes.
25
+ "codegraph_index",
26
+ "codegraph_list_projects",
27
+ "codegraph_delete_project",
28
+ "codegraph_index_status",
29
+ "codegraph_search_graph",
30
+ "codegraph_trace_path",
31
+ "codegraph_detect_changes",
32
+ "codegraph_query_graph",
33
+ "codegraph_get_schema",
34
+ "codegraph_get_snippet",
35
+ "codegraph_get_architecture",
36
+ "codegraph_search_code",
37
+ "codegraph_manage_adr",
38
+ "codegraph_ingest_traces",
39
+ "memory_correct_plan",
40
+ "memory_correct_apply",
41
+ "coding_delta",
42
+ // Remaining MCP/HTTP handlers migrated through the boundary (issue #1525).
43
+ "recall",
44
+ "recall_explain",
45
+ "set_coding_context",
46
+ "recall_tier_explain",
47
+ "recall_xray",
48
+ "recall_why",
49
+ "who_knows",
50
+ "promotion_candidates",
51
+ "namespace_writable",
52
+ "wearables_status",
53
+ "wearables_sync",
54
+ "transcript_day",
55
+ "transcript_search",
56
+ "transcript_memories",
57
+ "location_status",
58
+ "location_check",
59
+ "location_sync",
60
+ "location_backfill",
61
+ "location_day",
62
+ "meetings_list",
63
+ "meetings_get",
64
+ "meetings_build",
65
+ "deep_recall",
66
+ "memory_expand",
67
+ "memory_traverse",
68
+ "memory_ls",
69
+ "memory_tree",
70
+ "memory_find",
71
+ "standup",
72
+ "action_confidence",
73
+ "chatgpt_memory_inspector",
74
+ "day_summary",
75
+ "capsule_export",
76
+ "capsule_import",
77
+ "capsule_list",
78
+ "memory_governance_run",
79
+ "entity_synthesis_run",
80
+ "procedure_mining_run",
81
+ "pattern_reinforcement_run",
82
+ "procedural_stats",
83
+ "procedure_library_maintenance",
84
+ "memory_timeline",
85
+ "suggestion_submit",
86
+ "entity_get",
87
+ "review_queue_list",
88
+ "correction_pending",
89
+ "observe",
90
+ "lcm_search",
91
+ "lcm_compaction_flush",
92
+ "extraction_force_flush",
93
+ "lcm_compaction_record",
94
+ "continuity_audit_generate",
95
+ "continuity_incident_open",
96
+ "continuity_incident_close",
97
+ "continuity_incident_list",
98
+ "continuity_loop_add_or_update",
99
+ "continuity_loop_review",
100
+ "identity_anchor_get",
101
+ "identity_anchor_update",
102
+ "memory_identity",
103
+ "work_task",
104
+ "work_project",
105
+ "work_board",
106
+ "shared_context_write_output",
107
+ "shared_feedback_record",
108
+ "shared_priorities_append",
109
+ "relay_mission_append",
110
+ "relay_mission_read",
111
+ "shared_context_cross_signals_run",
112
+ "shared_context_curate_daily",
113
+ "compounding_weekly_synthesize",
114
+ "compounding_promote_candidate",
115
+ "compression_guidelines_optimize",
116
+ "compression_guidelines_activate",
117
+ "memory_profile",
118
+ "memory_entities_list",
119
+ "memory_questions",
120
+ "memory_last_recall",
121
+ "memory_intent_debug",
122
+ "memory_qmd_debug",
123
+ "memory_graph_explain",
124
+ "graph_snapshot",
125
+ "memory_feedback",
126
+ "memory_promote",
127
+ "memory_outcome",
128
+ "memory_action_apply",
129
+ "context_checkpoint",
130
+ "briefing",
131
+ "review_list",
132
+ "review_resolve",
133
+ "contradiction_scan_run",
134
+ "preference_drift_scan",
135
+ "memory_summarize_hourly",
136
+ "conversation_index_update",
137
+ "profiling_report",
138
+ "graph_edge_decay_run",
139
+ "live_connectors_run",
140
+ "peer_list",
141
+ "peer_get",
142
+ "peer_set",
143
+ "peer_delete",
144
+ "peer_profile_get",
145
+ "peer_forget",
146
+ "console_state",
147
+ "dreams_status",
148
+ "dreams_run",
149
+ "support_passport_memory_preview",
150
+ "support_passport_cards_list",
151
+ "support_passport_draft_create",
152
+ "support_passport_drafts_generate",
153
+ "support_passport_card_replace",
154
+ "support_passport_card_approve",
155
+ "support_passport_card_reject",
156
+ "support_passport_card_withdraw",
157
+ "support_passport_grant_create",
158
+ "support_passport_grants_list",
159
+ "support_passport_grant_revoke",
160
+ "support_passport_grant_read",
161
+ "support_passport_grant_ask",
162
+ // HTTP-only routes (no direct MCP tool equivalent).
163
+ "adapters_status",
164
+ "offline_sync_snapshot",
165
+ "offline_sync_snapshot_stream",
166
+ "offline_sync_files",
167
+ "offline_sync_file_content",
168
+ "offline_sync_apply_file_content",
169
+ "offline_sync_apply",
170
+ "lcm_status",
171
+ "memory_list",
172
+ "recall_timings",
173
+ "entity_list",
174
+ "maintenance_status",
175
+ "quality_status",
176
+ "trust_zones_status",
177
+ "trust_zones_records",
178
+ "review_disposition",
179
+ "review_deck_list",
180
+ "review_deck_action",
181
+ "review_deck_undo",
182
+ "trust_zones_promote",
183
+ "trust_zones_demo_seed",
184
+ "citations_observed",
185
+ "contradiction_detail",
186
+ "graph_events",
187
+ // Chat surface — conversational memory inspection/correction (issue #1583).
188
+ "chat_message",
189
+ "chat_events"
190
+ ];
191
+ var IMPLICIT_HTTP_NAMESPACE_OPERATIONS = /* @__PURE__ */ new Set([
192
+ "offline_sync_snapshot",
193
+ "offline_sync_snapshot_stream",
194
+ "memory_list",
195
+ "entity_list",
196
+ "maintenance_status",
197
+ "quality_status",
198
+ "trust_zones_status",
199
+ "graph_events",
200
+ "citations_observed"
201
+ ]);
202
+ var PRINCIPAL_NAMESPACE_OPERATIONS = /* @__PURE__ */ new Set([
203
+ "support_passport_memory_preview",
204
+ "support_passport_cards_list",
205
+ "support_passport_draft_create",
206
+ "support_passport_drafts_generate",
207
+ "support_passport_card_replace",
208
+ "support_passport_card_approve",
209
+ "support_passport_card_reject",
210
+ "support_passport_card_withdraw",
211
+ "support_passport_grant_create",
212
+ "support_passport_grants_list",
213
+ "support_passport_grant_revoke"
214
+ ]);
215
+ function coerceBooleanLike(value) {
216
+ if (value === void 0 || value === null || value === "") return void 0;
217
+ if (typeof value === "boolean") return value;
218
+ if (typeof value === "string") {
219
+ const lower = value.trim().toLowerCase();
220
+ if (lower === "true" || lower === "1" || lower === "yes" || lower === "on") return true;
221
+ if (lower === "false" || lower === "0" || lower === "no" || lower === "off") return false;
222
+ }
223
+ throw new EngramAccessInputError(
224
+ `expected a boolean-like value (true|false|1|0|yes|no|on|off); got ${JSON.stringify(value)}`
225
+ );
226
+ }
227
+ function coercePositiveInteger(value, label) {
228
+ if (value === void 0 || value === null || value === "") return void 0;
229
+ if (typeof value === "number") {
230
+ if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
231
+ throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);
232
+ }
233
+ return value;
234
+ }
235
+ if (typeof value === "string") {
236
+ const trimmed = value.trim();
237
+ if (!/^[+-]?\d+$/.test(trimmed)) {
238
+ throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);
239
+ }
240
+ const parsed = Number(trimmed);
241
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
242
+ throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);
243
+ }
244
+ return parsed;
245
+ }
246
+ throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);
247
+ }
248
+ function normalizeOptionalPath(value) {
249
+ if (value === void 0 || value === null || value === "") return void 0;
250
+ if (typeof value !== "string") {
251
+ throw new EngramAccessInputError(`expected a path string; got ${JSON.stringify(value)}`);
252
+ }
253
+ return expandTildePath(value);
254
+ }
255
+ function formatZodIssues(error) {
256
+ const parts = [];
257
+ for (const issue of error.issues) {
258
+ const hasNumeric = issue.path.some((p) => typeof p === "number");
259
+ const path = hasNumeric ? issue.path.filter((p) => typeof p === "string").join(".") || "(root)" : issue.path.length > 0 ? issue.path.join(".") : "(root)";
260
+ const options = enumOptionsFromIssue(issue);
261
+ const suffix = options ? `. Valid: ${options.join(", ")}` : "";
262
+ parts.push(`${path}: ${humanReadableIssueMessage(issue, path, hasNumeric)}${suffix}`);
263
+ }
264
+ return parts.length > 0 ? `request validation failed: ${parts.join("; ")}` : "request validation failed";
265
+ }
266
+ function enumOptionsFromIssue(issue) {
267
+ if (issue.code !== "invalid_value") return void 0;
268
+ const rawValues = "values" in issue ? issue.values : void 0;
269
+ return Array.isArray(rawValues) ? rawValues.map((opt) => String(opt)) : void 0;
270
+ }
271
+ function humanReadableIssueMessage(issue, pathLabel, hasNumericPath) {
272
+ if (issue.code !== "invalid_type") return issue.message;
273
+ const expected = issue.expected;
274
+ if (issue.message.endsWith("received undefined")) return issue.message;
275
+ if (hasNumericPath && expected) {
276
+ return `${pathLabel} must be an array of ${expected}s`;
277
+ }
278
+ const fieldName = issue.path.length > 0 ? String(issue.path[issue.path.length - 1]) : "value";
279
+ switch (expected) {
280
+ case "string":
281
+ return `${fieldName} must be a string`;
282
+ case "boolean":
283
+ return `${fieldName} must be a boolean`;
284
+ case "number":
285
+ return `${fieldName} must be a number`;
286
+ case "array":
287
+ return `${fieldName} must be an array`;
288
+ case "object":
289
+ return `${fieldName} must be an object`;
290
+ default:
291
+ return issue.message;
292
+ }
293
+ }
294
+ var registry = /* @__PURE__ */ new Map();
295
+ function defineOperation(spec) {
296
+ if (registry.has(spec.name)) {
297
+ throw new Error(`access-boundary: operation already registered: ${spec.name}`);
298
+ }
299
+ const bound = {
300
+ spec,
301
+ run: async (rawInput, ctx) => {
302
+ const parseResult = spec.schema.safeParse(rawInput);
303
+ if (!parseResult.success) {
304
+ throw new EngramAccessInputError(formatZodIssues(parseResult.error));
305
+ }
306
+ assertOperationAuthorizationAllowed(tokenCapabilityStore.getStore(), spec);
307
+ if (operationRequiresAuthorizedNamespace(spec.name)) {
308
+ const parsedNamespace = parseResult.data.namespace;
309
+ if (parsedNamespace) {
310
+ assertNamespaceAllowed(tokenCapabilityStore.getStore(), parsedNamespace);
311
+ }
312
+ }
313
+ return spec.handler(parseResult.data, { ...ctx, rawInput });
314
+ }
315
+ };
316
+ registry.set(spec.name, bound);
317
+ return bound;
318
+ }
319
+ function getOperation(name) {
320
+ return registry.get(name);
321
+ }
322
+ function operationRequiresAuthorizedNamespace(name) {
323
+ if (name === "namespace_writable") return false;
324
+ if (IMPLICIT_HTTP_NAMESPACE_OPERATIONS.has(name)) return true;
325
+ let schema = registry.get(name)?.spec.schema;
326
+ while (schema instanceof z.ZodType && !(schema instanceof z.ZodObject)) {
327
+ const wrapper = schema;
328
+ const sides = [wrapper.in, wrapper.out].filter(
329
+ (side) => side instanceof z.ZodType && !(side instanceof z.ZodTransform)
330
+ );
331
+ if (sides.length !== 1) break;
332
+ schema = sides[0];
333
+ }
334
+ return schema instanceof z.ZodObject && Object.hasOwn(schema.shape, "namespace");
335
+ }
336
+ function operationUsesPrincipalNamespace(name) {
337
+ return PRINCIPAL_NAMESPACE_OPERATIONS.has(name);
338
+ }
339
+ function listRegisteredOperations() {
340
+ return [...registry.keys()];
341
+ }
342
+ function __resetRegistryForTest() {
343
+ registry.clear();
344
+ }
345
+
346
+ export {
347
+ OPERATION_NAMES,
348
+ coerceBooleanLike,
349
+ coercePositiveInteger,
350
+ normalizeOptionalPath,
351
+ formatZodIssues,
352
+ defineOperation,
353
+ getOperation,
354
+ operationRequiresAuthorizedNamespace,
355
+ operationUsesPrincipalNamespace,
356
+ listRegisteredOperations,
357
+ __resetRegistryForTest
358
+ };
359
+ //# sourceMappingURL=chunk-JTSSSR4L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-boundary.ts"],"sourcesContent":["/**\n * Single input-validation and error boundary for the CLI/MCP/HTTP access\n * surfaces (issue #1525, epic #1520 Phase 1).\n *\n * Every operation that crosses the access-service facade passes through ONE\n * registry entry: a zod-validated request envelope, a shared error mapper,\n * and the \"reject invalid input and list valid options\" behavior that\n * CLAUDE.md rules 14/17/24/28/36/48/51 previously had to be re-implemented\n * per handler. The three surfaces become thin adapters — one operation\n * definition, three transports — so a validation fix lands everywhere at\n * once.\n *\n * Host-agnostic (rule 31): operation names carry no `openclaw-*`/`engram-*`\n * prefix. Session/namespace tenancy stays in the handler layer (resolved via\n * ScopePlan #1521); the boundary validates SHAPE, not tenancy.\n */\n\nimport { z } from \"zod\";\n// The input error lives in the leaf module; importing it from access-service\n// here (a re-export) drags the whole service hub into this module's init and\n// leaves `registry` TDZ-uninitialized when the cycle re-enters (#3354).\nimport { EngramAccessInputError } from \"./access-errors.js\";\nimport type { EngramAccessService } from \"./access-service.js\";\nimport {\n assertNamespaceAllowed,\n assertOperationAuthorizationAllowed,\n tokenCapabilityStore,\n} from \"./access-token-capabilities.js\";\nimport { expandTildePath } from \"./utils/path.js\";\n\n// ---------------------------------------------------------------------------\n// Canonical operation names — host-agnostic (rule 31)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical operation ids. One id is shared by the MCP tool, the HTTP route,\n * and the CLI command that expose the same operation. Add to this union as\n * each domain-group migration PR (memory ops → connectors → namespaces …)\n * lands; the fitness test in `access-surface-catalog.test.ts` treats the\n * registered set as the migration state.\n */\nexport const OPERATION_NAMES = [\n \"memory_get\",\n \"memory_search\",\n \"external_wiki_search\",\n \"memory_store\",\n \"coding_decision\",\n \"coding_architecture\",\n // codegraph parity tools (issue #1554) -- each maps to one codegraph_*\n // boundary operation that delegates to the surface handler in\n // coding/codegraph-surfaces.ts. Names match the external tool suffixes.\n \"codegraph_index\",\n \"codegraph_list_projects\",\n \"codegraph_delete_project\",\n \"codegraph_index_status\",\n \"codegraph_search_graph\",\n \"codegraph_trace_path\",\n \"codegraph_detect_changes\",\n \"codegraph_query_graph\",\n \"codegraph_get_schema\",\n \"codegraph_get_snippet\",\n \"codegraph_get_architecture\",\n \"codegraph_search_code\",\n \"codegraph_manage_adr\",\n \"codegraph_ingest_traces\",\n \"memory_correct_plan\",\n \"memory_correct_apply\",\n \"coding_delta\",\n // Remaining MCP/HTTP handlers migrated through the boundary (issue #1525).\n \"recall\",\n \"recall_explain\",\n \"set_coding_context\",\n \"recall_tier_explain\",\n \"recall_xray\",\n \"recall_why\",\n \"who_knows\",\n \"promotion_candidates\",\n \"namespace_writable\",\n \"wearables_status\",\n \"wearables_sync\",\n \"transcript_day\",\n \"transcript_search\",\n \"transcript_memories\",\n \"location_status\",\n \"location_check\",\n \"location_sync\",\n \"location_backfill\",\n \"location_day\",\n \"meetings_list\",\n \"meetings_get\",\n \"meetings_build\",\n \"deep_recall\",\n \"memory_expand\",\n \"memory_traverse\",\n \"memory_ls\",\n \"memory_tree\",\n \"memory_find\",\n \"standup\",\n \"action_confidence\",\n \"chatgpt_memory_inspector\",\n \"day_summary\",\n \"capsule_export\",\n \"capsule_import\",\n \"capsule_list\",\n \"memory_governance_run\",\n \"entity_synthesis_run\",\n \"procedure_mining_run\",\n \"pattern_reinforcement_run\",\n \"procedural_stats\",\n \"procedure_library_maintenance\",\n \"memory_timeline\",\n \"suggestion_submit\",\n \"entity_get\",\n \"review_queue_list\",\n \"correction_pending\",\n \"observe\",\n \"lcm_search\",\n \"lcm_compaction_flush\",\n \"extraction_force_flush\",\n \"lcm_compaction_record\",\n \"continuity_audit_generate\",\n \"continuity_incident_open\",\n \"continuity_incident_close\",\n \"continuity_incident_list\",\n \"continuity_loop_add_or_update\",\n \"continuity_loop_review\",\n \"identity_anchor_get\",\n \"identity_anchor_update\",\n \"memory_identity\",\n \"work_task\",\n \"work_project\",\n \"work_board\",\n \"shared_context_write_output\",\n \"shared_feedback_record\",\n \"shared_priorities_append\",\n \"relay_mission_append\",\n \"relay_mission_read\",\n \"shared_context_cross_signals_run\",\n \"shared_context_curate_daily\",\n \"compounding_weekly_synthesize\",\n \"compounding_promote_candidate\",\n \"compression_guidelines_optimize\",\n \"compression_guidelines_activate\",\n \"memory_profile\",\n \"memory_entities_list\",\n \"memory_questions\",\n \"memory_last_recall\",\n \"memory_intent_debug\",\n \"memory_qmd_debug\",\n \"memory_graph_explain\",\n \"graph_snapshot\",\n \"memory_feedback\",\n \"memory_promote\",\n \"memory_outcome\",\n \"memory_action_apply\",\n \"context_checkpoint\",\n \"briefing\",\n \"review_list\",\n \"review_resolve\",\n \"contradiction_scan_run\",\n \"preference_drift_scan\",\n \"memory_summarize_hourly\",\n \"conversation_index_update\",\n \"profiling_report\",\n \"graph_edge_decay_run\",\n \"live_connectors_run\",\n \"peer_list\",\n \"peer_get\",\n \"peer_set\",\n \"peer_delete\",\n \"peer_profile_get\",\n \"peer_forget\",\n \"console_state\",\n \"dreams_status\",\n \"dreams_run\",\n \"support_passport_memory_preview\",\n \"support_passport_cards_list\",\n \"support_passport_draft_create\",\n \"support_passport_drafts_generate\",\n \"support_passport_card_replace\",\n \"support_passport_card_approve\",\n \"support_passport_card_reject\",\n \"support_passport_card_withdraw\",\n \"support_passport_grant_create\",\n \"support_passport_grants_list\",\n \"support_passport_grant_revoke\",\n \"support_passport_grant_read\",\n \"support_passport_grant_ask\",\n // HTTP-only routes (no direct MCP tool equivalent).\n \"adapters_status\",\n \"offline_sync_snapshot\",\n \"offline_sync_snapshot_stream\",\n \"offline_sync_files\",\n \"offline_sync_file_content\",\n \"offline_sync_apply_file_content\",\n \"offline_sync_apply\",\n \"lcm_status\",\n \"memory_list\",\n \"recall_timings\",\n \"entity_list\",\n \"maintenance_status\",\n \"quality_status\",\n \"trust_zones_status\",\n \"trust_zones_records\",\n \"review_disposition\",\n \"review_deck_list\",\n \"review_deck_action\",\n \"review_deck_undo\",\n \"trust_zones_promote\",\n \"trust_zones_demo_seed\",\n \"citations_observed\",\n \"contradiction_detail\",\n \"graph_events\",\n // Chat surface — conversational memory inspection/correction (issue #1583).\n \"chat_message\",\n \"chat_events\",\n] as const;\n\n/**\n * Canonical operation ids. One id is shared by the MCP tool, the HTTP route,\n * and the CLI command that expose the same operation. Derived from\n * {@link OPERATION_NAMES} (single source of truth) so the runtime catalog\n * used for token-capability validation cannot drift from the type. The\n * fitness test in `access-surface-catalog.test.ts` treats the registered set\n * as the migration state.\n */\nexport type OperationName = (typeof OPERATION_NAMES)[number];\n\nconst IMPLICIT_HTTP_NAMESPACE_OPERATIONS = new Set<OperationName>([\n \"offline_sync_snapshot\",\n \"offline_sync_snapshot_stream\",\n \"memory_list\",\n \"entity_list\",\n \"maintenance_status\",\n \"quality_status\",\n \"trust_zones_status\",\n \"graph_events\",\n \"citations_observed\",\n]);\n\nconst PRINCIPAL_NAMESPACE_OPERATIONS = new Set<OperationName>([\n \"support_passport_memory_preview\",\n \"support_passport_cards_list\",\n \"support_passport_draft_create\",\n \"support_passport_drafts_generate\",\n \"support_passport_card_replace\",\n \"support_passport_card_approve\",\n \"support_passport_card_reject\",\n \"support_passport_card_withdraw\",\n \"support_passport_grant_create\",\n \"support_passport_grants_list\",\n \"support_passport_grant_revoke\",\n]);\n\n// ---------------------------------------------------------------------------\n// Operation context — what every handler receives\n// ---------------------------------------------------------------------------\n\n/**\n * Per-call context. `service` is the facade the handler delegates to; the\n * boundary never reaches past it. `authenticatedPrincipal` is resolved by\n * the SURFACE (MCP header / HTTP identity / CLI flag) before the boundary\n * runs, so handlers stay principal-source-agnostic. `hooks` carries\n * transport-level callbacks (e.g. HTTP write-quota enforcement) that must\n * fire atomically inside the service call; surfaces that have no such hook\n * leave it undefined.\n */\nexport interface OperationContext {\n readonly service: EngramAccessService;\n readonly authenticatedPrincipal?: string;\n readonly operatorPrincipal?: string;\n /** Per-request cancellation supplied by transports that own a request lifecycle. */\n readonly abortSignal?: AbortSignal;\n /** Server-resolved connector identity (Phase 1 provenance). Set by the HTTP auth boundary from the matched token's connector; flows to write handlers so frontmatter records which connector submitted the memory. Client-supplied values are always overridden. */\n readonly sourceConnector?: string;\n /**\n * The PRE-validation raw envelope exactly as the transport supplied it\n * (issue #2829). Handlers use it to retain input spellings the schema's\n * transforms canonicalize — e.g. the memory-store category aliases — so\n * diagnostics can name what the caller actually sent. Never trust it for\n * behavior; only the parsed `input` is validated.\n */\n readonly rawInput?: unknown;\n readonly hooks?: OperationHooks;\n}\n\n/**\n * Transport-level callbacks a handler forwards into the service call. Kept\n * narrow on purpose: the boundary owns validation + dispatch shape, not\n * transport policy. Add fields here only when a surface genuinely needs a\n * callback the service itself consumes.\n */\nexport interface OperationHooks {\n /** HTTP write-quota gate; throws to reject the write when exhausted. */\n readonly enforceWriteQuota?: () => void | Promise<void>;\n /** Commit-boundary accounting for writes that can fail after durability. */\n readonly recordWriteCommit?: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Operation spec + bound operation\n// ---------------------------------------------------------------------------\n\nexport interface OperationSpec<In, Out> {\n /** Canonical operation id; matches an {@link OperationName}. */\n readonly name: OperationName;\n readonly description: string;\n /**\n * Zod schema validating the raw request envelope. Input type may differ\n * from the output `In` — schemas that canonicalize during parsing (issue\n * #2829 category aliases) are first-class, declared truthfully instead of\n * cast into an input-equals-output shape.\n */\n readonly schema: z.ZodType<In, unknown>;\n /** Handler invoked with the parsed input; throws EngramAccessInputError for domain faults. */\n readonly handler: (input: In, ctx: OperationContext) => Promise<Out>;\n /**\n * Marks an operation as inherently FLEET-WIDE / global — it runs across ALL\n * namespaces (or against a single non-namespaced global layer) and carries no\n * `namespace` argument, so the MCP `tools/call` effective-namespace chokepoint\n * never applies. When set, {@link defineOperation}'s run wrapper rejects any\n * namespace-SCOPED token (fail closed) via assertFleetWideOperationAllowed\n * BEFORE the handler — no side effect on denial. Unrestricted/legacy tokens\n * (cron, internal callers, no capability record) are unaffected (issue #1850).\n */\n readonly fleetWide?: boolean;\n /**\n * Alternate op allow-list: when set, the token may invoke this operation if\n * its ops allow-list permits ANY of these ops (instead of the default rule\n * that requires the op's own {@link name}). Lets a read-only diagnostic be\n * granted by the write ops it diagnoses — e.g. `namespace_writable` is\n * runnable by any token permitted to `observe`/`memory_store`, so a token\n * minted before the diagnostic op existed can still call it. Unrestricted /\n * legacy tokens (no ops axis) are unaffected. Keeps the boundary and any HTTP\n * transport for the same op enforcing ONE policy.\n */\n readonly allowedByOps?: readonly OperationName[];\n}\n\nexport interface BoundOperation<In = unknown, Out = unknown> {\n readonly spec: OperationSpec<In, Out>;\n /** Validate the raw envelope, then invoke the handler. Throws EngramAccessInputError on any validation failure. */\n readonly run: (rawInput: unknown, ctx: OperationContext) => Promise<Out>;\n}\n\n// ---------------------------------------------------------------------------\n// Shared normalizers the boundary owns (rules 17, 28, 36, 48, 51)\n// ---------------------------------------------------------------------------\n\n/**\n * Coerce boolean-like strings at the edge (rule 36). Accepts actual booleans\n * and the string spellings clients send (\"true\"/\"false\"/\"1\"/\"0\"/\"yes\"/\"no\"/\n * \"on\"/\"off\", case-insensitive). Rejects anything else loudly — `Boolean(\"false\")`\n * would silently be `true`, which is the bug rule 36 exists to prevent.\n *\n * `undefined`/`null`/`\"\"` → `undefined`, so callers can keep treating an\n * absent flag as \"use the default\" without a separate presence check.\n */\nexport function coerceBooleanLike(value: unknown): boolean | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const lower = value.trim().toLowerCase();\n if (lower === \"true\" || lower === \"1\" || lower === \"yes\" || lower === \"on\") return true;\n if (lower === \"false\" || lower === \"0\" || lower === \"no\" || lower === \"off\") return false;\n }\n throw new EngramAccessInputError(\n `expected a boolean-like value (true|false|1|0|yes|no|on|off); got ${JSON.stringify(value)}`,\n );\n}\n\n/**\n * Coerce + validate a positive integer from a numeric string or number\n * (rule 28). Loosely-typed MCP/CLI clients send `\"5\"`; `typeof saved === \"number\"`\n * on read-back would reject it later, so we coerce at the edge and reject\n * booleans/objects loudly (`Number(true) === 1` would silently pass otherwise).\n *\n * `undefined`/`null`/`\"\"` → `undefined`.\n */\nexport function coercePositiveInteger(value: unknown, label: string): number | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n return value;\n }\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!/^[+-]?\\d+$/.test(trimmed)) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n const parsed = Number(trimmed);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n }\n return parsed;\n }\n throw new EngramAccessInputError(`${label} expects a positive integer; got ${JSON.stringify(value)}`);\n}\n\n/**\n * Expand `~` in a path-shaped input (rule 17). Node `fs` does NOT expand `~`;\n * ad-hoc regex drifts. `undefined`/`null`/`\"\"` → `undefined`.\n */\nexport function normalizeOptionalPath(value: unknown): string | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") {\n throw new EngramAccessInputError(`expected a path string; got ${JSON.stringify(value)}`);\n }\n return expandTildePath(value);\n}\n\n// ---------------------------------------------------------------------------\n// Error formatting — rule 51: list valid options, never silently default\n// ---------------------------------------------------------------------------\n\n/**\n * Turn a zod failure into an {@link EngramAccessInputError} whose message\n * names the offending field and — for enum/union issues — lists the valid\n * options, so the caller can correct rather than guess (rule 51).\n */\nexport function formatZodIssues(error: z.ZodError): string {\n const parts: string[] = [];\n for (const issue of error.issues) {\n // Collapse array-index paths (e.g. [\"currentContextScopes\", 1]) to\n // the field name so the message reads \"field: must be ...\" not\n // \"field.1: must be ...\".\n const hasNumeric = issue.path.some((p) => typeof p === \"number\");\n const path = hasNumeric\n ? issue.path.filter((p) => typeof p === \"string\").join(\".\") || \"(root)\"\n : issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n const options = enumOptionsFromIssue(issue);\n const suffix = options ? `. Valid: ${options.join(\", \")}` : \"\";\n parts.push(`${path}: ${humanReadableIssueMessage(issue, path, hasNumeric)}${suffix}`);\n }\n return parts.length > 0\n ? `request validation failed: ${parts.join(\"; \")}`\n : \"request validation failed\";\n}\n\nfunction enumOptionsFromIssue(issue: z.core.$ZodIssue): readonly string[] | undefined {\n // zod 4 exposes accepted enum values on invalid_value issues as `values`\n // (the v3 `options` spelling is kept as a fallback). Reading them here\n // keeps \"list valid options\" in ONE place rather than per handler.\n if (issue.code !== \"invalid_value\") return undefined;\n const rawValues = \"values\" in issue ? issue.values : undefined;\n return Array.isArray(rawValues) ? rawValues.map((opt) => String(opt)) : undefined;\n}\n\n/**\n * Human-readable \"must be a <type>\" message for generic type mismatches\n * (rule 51). zod 4 removed parse-time error maps, so the boundary applies\n * this post-parse in formatZodIssues instead — same messages, one place.\n * The caller supplies the collapsed path label and its numeric-segment\n * verdict so this helper runs no representation checks of its own.\n */\nfunction humanReadableIssueMessage(issue: z.core.$ZodIssue, pathLabel: string, hasNumericPath: boolean): string {\n if (issue.code !== \"invalid_type\") return issue.message;\n const expected = issue.expected;\n // zod 4 issues carry no `received` field; its message ends \"received undefined\"\n // for an absent value, which is a missing field, not a type mismatch.\n if (issue.message.endsWith(\"received undefined\")) return issue.message;\n if (hasNumericPath && expected) {\n return `${pathLabel} must be an array of ${expected}s`;\n }\n const fieldName = issue.path.length > 0 ? String(issue.path[issue.path.length - 1]) : \"value\";\n switch (expected) {\n case \"string\": return `${fieldName} must be a string`;\n case \"boolean\": return `${fieldName} must be a boolean`;\n case \"number\": return `${fieldName} must be a number`;\n case \"array\": return `${fieldName} must be an array`;\n case \"object\": return `${fieldName} must be an object`;\n default: return issue.message;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\nconst registry = new Map<OperationName, BoundOperation>();\n\n/**\n * Register an operation. Throws if the name is already registered — duplicate\n * registration is a programming error, not a runtime input fault, so it throws\n * a plain Error (not the input-error class surfaces translate for clients).\n */\nexport function defineOperation<In, Out>(spec: OperationSpec<In, Out>): BoundOperation<In, Out> {\n if (registry.has(spec.name)) {\n throw new Error(`access-boundary: operation already registered: ${spec.name}`);\n }\n const bound: BoundOperation<In, Out> = {\n spec,\n run: async (rawInput, ctx) => {\n const parseResult = spec.schema.safeParse(rawInput);\n if (!parseResult.success) {\n throw new EngramAccessInputError(formatZodIssues(parseResult.error));\n }\n assertOperationAuthorizationAllowed(tokenCapabilityStore.getStore(), spec);\n // Post-parse namespace re-check (issue #3225 B1): the transports authorize\n // the RAW namespace before preprocessing. Re-check the PARSED value so a\n // namespace that only appears after validation cannot bypass the token\n // allow-list. Absent namespaces keep the transport check; no default is\n // invented here.\n if (operationRequiresAuthorizedNamespace(spec.name)) {\n // SAFETY: namespace-bearing schemas parse `namespace` as a non-empty\n // string, an explicit null (transport null-for-absent idiom), or\n // undefined; falsy spellings mean absent and keep the transport check.\n const parsedNamespace = (parseResult.data as { namespace?: string | null }).namespace;\n if (parsedNamespace) {\n assertNamespaceAllowed(tokenCapabilityStore.getStore(), parsedNamespace);\n }\n }\n return spec.handler(parseResult.data, { ...ctx, rawInput });\n },\n };\n // Store under the canonical name; the cast is safe because In/Out are\n // erased at the registry boundary and recovered by callers via getOperation.\n registry.set(spec.name, bound as unknown as BoundOperation);\n return bound;\n}\n\n/** Look up a registered operation by canonical name. */\nexport function getOperation(name: OperationName): BoundOperation | undefined {\n return registry.get(name);\n}\n\n/** Whether a probe must authorize an operation's effective namespace. */\nexport function operationRequiresAuthorizedNamespace(name: OperationName): boolean {\n if (name === \"namespace_writable\") return false;\n if (IMPLICIT_HTTP_NAMESPACE_OPERATIONS.has(name)) return true;\n let schema: unknown = registry.get(name)?.spec.schema;\n // zod 4 has no ZodEffects. Transforms and preprocessors wrap as pipes with\n // the base schema on the side opposite the ZodTransform. Unwrap until the\n // base object appears — one unwrap left suggestion_submit looking\n // namespace-free after the category transform, so the loop stays.\n while (schema instanceof z.ZodType && !(schema instanceof z.ZodObject)) {\n // SAFETY: pipe wrappers expose their two sides as `in` / `out`.\n const wrapper = schema as { in?: unknown; out?: unknown };\n const sides = [wrapper.in, wrapper.out].filter(\n (side) => side instanceof z.ZodType && !(side instanceof z.ZodTransform),\n );\n if (sides.length !== 1) break;\n schema = sides[0];\n }\n return schema instanceof z.ZodObject && Object.hasOwn(schema.shape, \"namespace\");\n}\n\n/** Whether an operation resolves its namespace from the authenticated principal. */\nexport function operationUsesPrincipalNamespace(name: OperationName): boolean {\n return PRINCIPAL_NAMESPACE_OPERATIONS.has(name);\n}\n\n/** All registered operation names. */\nexport function listRegisteredOperations(): readonly OperationName[] {\n return [...registry.keys()];\n}\n\n/** Test-only: clear the registry so pilot definitions can be re-registered. */\nexport function __resetRegistryForTest(): void {\n registry.clear();\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAS,SAAS;AAwBX,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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