@remnic/core 10.0.191 → 10.0.192

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 (272) hide show
  1. package/dist/abstraction-nodes.js +4 -4
  2. package/dist/access-admin-ops-surface.js +62 -62
  3. package/dist/access-cli.js +62 -62
  4. package/dist/access-extraction-force-flush-preempt.js +62 -62
  5. package/dist/access-extraction-force-flush.js +62 -62
  6. package/dist/access-http-briefing.js +62 -62
  7. package/dist/access-http-query.js +62 -62
  8. package/dist/access-http.js +62 -62
  9. package/dist/access-identity-continuity-surface.js +62 -62
  10. package/dist/access-lcm-surface.js +62 -62
  11. package/dist/access-mcp.js +62 -62
  12. package/dist/access-observe-write-surface.js +62 -62
  13. package/dist/access-operations-batch.js +62 -62
  14. package/dist/access-operations.js +62 -62
  15. package/dist/access-recall-concurrency.js +62 -62
  16. package/dist/access-recall-diagnostics.js +2 -2
  17. package/dist/access-recall-response.js +62 -62
  18. package/dist/access-recall-surface.js +62 -62
  19. package/dist/access-service.js +62 -62
  20. package/dist/active-recall.js +11 -11
  21. package/dist/briefing.js +11 -11
  22. package/dist/buffer-persistence.d.ts +7 -0
  23. package/dist/buffer-persistence.d.ts.map +1 -1
  24. package/dist/buffer-persistence.js +1 -1
  25. package/dist/buffer.d.ts +2 -0
  26. package/dist/buffer.d.ts.map +1 -1
  27. package/dist/buffer.js +6 -6
  28. package/dist/{capsule-merge-BADOICNP.js → capsule-merge-3FARYIHP.js} +5 -5
  29. package/dist/causal-consolidation.js +12 -12
  30. package/dist/{chunk-IMSLPQJB.js → chunk-2QW5HPKU.js} +2 -2
  31. package/dist/{chunk-KNYUEYB6.js → chunk-2YJ2ST23.js} +2 -2
  32. package/dist/{chunk-BZ5VO7KO.js → chunk-3BICT225.js} +2 -2
  33. package/dist/{chunk-UWKHLWUE.js → chunk-3RZ4GDOH.js} +2 -2
  34. package/dist/{chunk-ODIBCZLG.js → chunk-3YID7KZ6.js} +2 -2
  35. package/dist/{chunk-4SUNBSPD.js → chunk-4EAVEDLG.js} +9 -9
  36. package/dist/{chunk-TLRIRISJ.js → chunk-4LCA2GEX.js} +2 -2
  37. package/dist/{chunk-4N33L4HY.js → chunk-5GIYIYJI.js} +2 -2
  38. package/dist/{chunk-JQCEG54G.js → chunk-75K6DRPN.js} +12 -9
  39. package/dist/chunk-75K6DRPN.js.map +1 -0
  40. package/dist/{chunk-ZDLVHGIC.js → chunk-7EP4FURO.js} +2 -2
  41. package/dist/{chunk-CAUADFDM.js → chunk-7SOKOEAZ.js} +2 -2
  42. package/dist/{chunk-7Q74DD2W.js → chunk-7V6GNQC2.js} +2 -2
  43. package/dist/{chunk-C6YKKH73.js → chunk-AALJHIKH.js} +3 -3
  44. package/dist/{chunk-C2UN2CY7.js → chunk-AJ7JHHRY.js} +2 -2
  45. package/dist/{chunk-QSVWIKNY.js → chunk-BDFSVUUZ.js} +9 -7
  46. package/dist/chunk-BDFSVUUZ.js.map +1 -0
  47. package/dist/{chunk-3DADRUGW.js → chunk-BGA7S5EF.js} +3 -3
  48. package/dist/{chunk-7GMOB4FF.js → chunk-CJSTQNE5.js} +2 -2
  49. package/dist/{chunk-6YAQ3AJ5.js → chunk-DYUPSTCV.js} +3 -3
  50. package/dist/{chunk-E5QI6C6C.js → chunk-E3LGAZJC.js} +3 -3
  51. package/dist/{chunk-NL5KFA5N.js → chunk-EEA2RM4B.js} +2 -2
  52. package/dist/{chunk-BL7WULM5.js → chunk-FDO7ITP6.js} +2 -2
  53. package/dist/{chunk-7BIGO6ZL.js → chunk-FGFU6J26.js} +3 -3
  54. package/dist/{chunk-6TIQLG7I.js → chunk-FKHXXL42.js} +2 -2
  55. package/dist/{chunk-QPD7EYGI.js → chunk-G2MS56KM.js} +2 -2
  56. package/dist/{chunk-FFTGLWHI.js → chunk-GH7IKABD.js} +2 -2
  57. package/dist/{chunk-RC2TVYY2.js → chunk-GYCUX3N4.js} +2 -2
  58. package/dist/{chunk-CJYVVVOG.js → chunk-HEJFE3BC.js} +3 -3
  59. package/dist/{chunk-KM4QO4LN.js → chunk-HLQANATZ.js} +2 -2
  60. package/dist/{chunk-RQOUKIFS.js → chunk-J7RQ3RP7.js} +2 -2
  61. package/dist/{chunk-QTHFGP5F.js → chunk-JITK24KX.js} +7 -7
  62. package/dist/{chunk-EJYUAN5F.js → chunk-K6UXWVQ6.js} +2 -2
  63. package/dist/{chunk-3XJITLZQ.js → chunk-KJ65WZHB.js} +2 -2
  64. package/dist/{chunk-JOR4Y326.js → chunk-KOVQZJ27.js} +2 -2
  65. package/dist/{chunk-O6QSBI3U.js → chunk-KZ4BJRGQ.js} +2 -2
  66. package/dist/{chunk-FZPZML67.js → chunk-LR6LWX33.js} +4 -4
  67. package/dist/{chunk-NTS2RCQK.js → chunk-NAULI3EG.js} +2 -2
  68. package/dist/{chunk-V5W67PQV.js → chunk-NOKHMWMW.js} +4 -4
  69. package/dist/{chunk-JGVW6F3Q.js → chunk-ODI4K32P.js} +5 -5
  70. package/dist/{chunk-H7USCTPQ.js → chunk-OLD2GKQJ.js} +3 -3
  71. package/dist/{chunk-D7HOJFDS.js → chunk-ONSEODO2.js} +2 -2
  72. package/dist/{chunk-R3YMWUF3.js → chunk-P3IAZQPS.js} +2 -2
  73. package/dist/{chunk-LL6WEMTC.js → chunk-P3OONWJJ.js} +2 -2
  74. package/dist/chunk-P3OONWJJ.js.map +1 -0
  75. package/dist/{chunk-7KC6LT7U.js → chunk-PSQ347YP.js} +3 -3
  76. package/dist/{chunk-U6OQ7GWU.js → chunk-QFKNIKUF.js} +2 -2
  77. package/dist/{chunk-RFVX4WE7.js → chunk-QIPRDRGM.js} +1 -1
  78. package/dist/chunk-QIPRDRGM.js.map +1 -0
  79. package/dist/{chunk-2DFXIJPZ.js → chunk-QZMGZBTF.js} +2 -2
  80. package/dist/{chunk-NSFHMGOF.js → chunk-SKJM4PKE.js} +2 -2
  81. package/dist/{chunk-T7R42MWB.js → chunk-STSORBX5.js} +2 -2
  82. package/dist/{chunk-ICA5SCIT.js → chunk-T765HQ5U.js} +3 -3
  83. package/dist/{chunk-RFEQ7DQN.js → chunk-TDG5NZAZ.js} +2 -2
  84. package/dist/{chunk-2S6PPGIR.js → chunk-TWYYUMYO.js} +2 -2
  85. package/dist/{chunk-U6JZGQXC.js → chunk-TZ7ZA2LM.js} +2 -2
  86. package/dist/{chunk-AIS7RLTG.js → chunk-UAEJKURK.js} +58 -56
  87. package/dist/{chunk-AIS7RLTG.js.map → chunk-UAEJKURK.js.map} +1 -1
  88. package/dist/{chunk-JIB3UUYV.js → chunk-UH2VY2QQ.js} +3 -3
  89. package/dist/{chunk-X5XK6WWV.js → chunk-VHQNJW4Q.js} +2 -2
  90. package/dist/{chunk-CP6MUXNI.js → chunk-WEI6HEUX.js} +11 -6
  91. package/dist/chunk-WEI6HEUX.js.map +1 -0
  92. package/dist/{chunk-3IA2SUWM.js → chunk-WRVKI6ZO.js} +2 -2
  93. package/dist/{chunk-R5S57GRK.js → chunk-XSRZM6CQ.js} +38 -13
  94. package/dist/chunk-XSRZM6CQ.js.map +1 -0
  95. package/dist/{chunk-2CWCJYT3.js → chunk-XZLCAL5O.js} +2 -2
  96. package/dist/{chunk-7MAMRCZ7.js → chunk-XZMQLON4.js} +430 -292
  97. package/dist/chunk-XZMQLON4.js.map +1 -0
  98. package/dist/{chunk-HL53XYHC.js → chunk-YCJJODER.js} +5 -5
  99. package/dist/chunk-YCJJODER.js.map +1 -0
  100. package/dist/{chunk-W7FZ7ZZE.js → chunk-Z6EFSXU3.js} +2 -2
  101. package/dist/{chunk-GRX5BE73.js → chunk-ZNCCX7P6.js} +2 -2
  102. package/dist/cli.js +62 -62
  103. package/dist/coding/export-okf-codegraph.js +10 -10
  104. package/dist/compounding/engine.js +12 -12
  105. package/dist/config.d.ts.map +1 -1
  106. package/dist/config.js +11 -11
  107. package/dist/connectors/codex-materialize-runner.js +11 -11
  108. package/dist/connectors/index.js +11 -11
  109. package/dist/consolidation-provenance-check.js +5 -5
  110. package/dist/consolidation-undo.js +4 -4
  111. package/dist/contradiction/index.js +3 -3
  112. package/dist/convergence-refresh.js +13 -13
  113. package/dist/corpus-watermark.js +13 -13
  114. package/dist/cue-anchors.js +5 -5
  115. package/dist/{entity-canonical-id-migration-74IDJFPB.js → entity-canonical-id-migration-46EMEXTB.js} +4 -4
  116. package/dist/entity-retrieval.d.ts.map +1 -1
  117. package/dist/entity-retrieval.js +11 -11
  118. package/dist/explicit-capture.js +62 -62
  119. package/dist/extraction.js +15 -15
  120. package/dist/harmonic-construction.js +6 -6
  121. package/dist/harmonic-graph-version.js +3 -3
  122. package/dist/harmonic-retrieval.d.ts +15 -0
  123. package/dist/harmonic-retrieval.d.ts.map +1 -1
  124. package/dist/harmonic-retrieval.js +16 -14
  125. package/dist/index.js +62 -62
  126. package/dist/location/index.js +12 -12
  127. package/dist/maintenance/memory-governance.js +11 -11
  128. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +11 -11
  129. package/dist/maintenance/rebuild-memory-projection-runner.js +13 -13
  130. package/dist/maintenance/rebuild-memory-projection.js +12 -12
  131. package/dist/memory-browse.js +5 -5
  132. package/dist/memory-cache.d.ts +44 -3
  133. package/dist/memory-cache.d.ts.map +1 -1
  134. package/dist/memory-cache.js +9 -1
  135. package/dist/memory-corpus-version.js +2 -2
  136. package/dist/namespaces/migrate.js +12 -12
  137. package/dist/namespaces/search.js +4 -4
  138. package/dist/namespaces/storage.js +11 -11
  139. package/dist/operator-doctor-corpus.js +14 -14
  140. package/dist/operator-toolkit.js +19 -19
  141. package/dist/orchestration/backlog-scheduler.js +63 -63
  142. package/dist/orchestration/buffer-drain-runner.js +63 -63
  143. package/dist/orchestration/maintenance.js +19 -19
  144. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  145. package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
  146. package/dist/orchestrator.js +62 -62
  147. package/dist/page-versioning.js +4 -4
  148. package/dist/qmd.js +2 -2
  149. package/dist/recall-explain-renderer.js +3 -3
  150. package/dist/recall-navigate-access.js +2 -2
  151. package/dist/recall-navigate-disclosure.js +2 -2
  152. package/dist/recall-navigate.js +2 -2
  153. package/dist/recall-navigation.js +62 -62
  154. package/dist/recall-state-view-admission.js +5 -5
  155. package/dist/recall-why-service.js +5 -5
  156. package/dist/recall-xray-cli.js +4 -4
  157. package/dist/recall-xray-renderer.js +3 -3
  158. package/dist/recall-xray.js +2 -2
  159. package/dist/{resolution-RWIGFH2W.js → resolution-4QPPLDEN.js} +4 -4
  160. package/dist/resume-bundles.js +12 -12
  161. package/dist/search/factory.js +3 -3
  162. package/dist/search/index.js +3 -3
  163. package/dist/semantic-consolidation.js +12 -12
  164. package/dist/semantic-rule-promotion.js +11 -11
  165. package/dist/semantic-rule-verifier.js +11 -11
  166. package/dist/source-agent-qualifier.js +14 -14
  167. package/dist/standup/build.js +11 -11
  168. package/dist/storage/entity-listing.d.ts +20 -0
  169. package/dist/storage/entity-listing.d.ts.map +1 -0
  170. package/dist/storage/entity-store.d.ts +5 -0
  171. package/dist/storage/entity-store.d.ts.map +1 -1
  172. package/dist/storage/hot-cache-validation.d.ts +60 -0
  173. package/dist/storage/hot-cache-validation.d.ts.map +1 -0
  174. package/dist/storage.d.ts +2 -0
  175. package/dist/storage.d.ts.map +1 -1
  176. package/dist/storage.js +10 -10
  177. package/dist/transfer/capsule-import.js +5 -5
  178. package/dist/transfer/export-okf.js +11 -11
  179. package/dist/types.d.ts +2 -0
  180. package/dist/types.d.ts.map +1 -1
  181. package/dist/types.js +1 -1
  182. package/dist/verified-recall.js +11 -11
  183. package/dist/who-knows-cli.js +12 -12
  184. package/dist/who-knows.js +11 -11
  185. package/package.json +2 -2
  186. package/src/buffer-large-session-defer.test.ts +81 -0
  187. package/src/buffer-persistence.ts +8 -1
  188. package/src/buffer.ts +9 -4
  189. package/src/config.test.ts +9 -0
  190. package/src/config.ts +3 -6
  191. package/src/entity-recall-hot-cache.test.ts +116 -0
  192. package/src/entity-retrieval.ts +22 -4
  193. package/src/harmonic-graph-cache.test.ts +28 -9
  194. package/src/harmonic-retrieval.ts +20 -4
  195. package/src/memory-cache-hot.test.ts +47 -0
  196. package/src/memory-cache.ts +96 -17
  197. package/src/observe-flush-force-keys.test.ts +130 -0
  198. package/src/orchestration/recall-internal.ts +1 -0
  199. package/src/orchestration/turn-ingestion-buffered.test.ts +6 -2
  200. package/src/orchestration/turn-ingestion-buffered.ts +5 -1
  201. package/src/storage/entity-listing.ts +73 -0
  202. package/src/storage/entity-store.ts +25 -26
  203. package/src/storage/hot-cache-validation.ts +149 -0
  204. package/src/storage-contract/cache-coherence.test.ts +42 -5
  205. package/src/storage-hot-cache-stat-validate.test.ts +112 -0
  206. package/src/storage.ts +58 -44
  207. package/src/types.ts +2 -0
  208. package/dist/chunk-7MAMRCZ7.js.map +0 -1
  209. package/dist/chunk-CP6MUXNI.js.map +0 -1
  210. package/dist/chunk-HL53XYHC.js.map +0 -1
  211. package/dist/chunk-JQCEG54G.js.map +0 -1
  212. package/dist/chunk-LL6WEMTC.js.map +0 -1
  213. package/dist/chunk-QSVWIKNY.js.map +0 -1
  214. package/dist/chunk-R5S57GRK.js.map +0 -1
  215. package/dist/chunk-RFVX4WE7.js.map +0 -1
  216. /package/dist/{capsule-merge-BADOICNP.js.map → capsule-merge-3FARYIHP.js.map} +0 -0
  217. /package/dist/{chunk-IMSLPQJB.js.map → chunk-2QW5HPKU.js.map} +0 -0
  218. /package/dist/{chunk-KNYUEYB6.js.map → chunk-2YJ2ST23.js.map} +0 -0
  219. /package/dist/{chunk-BZ5VO7KO.js.map → chunk-3BICT225.js.map} +0 -0
  220. /package/dist/{chunk-UWKHLWUE.js.map → chunk-3RZ4GDOH.js.map} +0 -0
  221. /package/dist/{chunk-ODIBCZLG.js.map → chunk-3YID7KZ6.js.map} +0 -0
  222. /package/dist/{chunk-4SUNBSPD.js.map → chunk-4EAVEDLG.js.map} +0 -0
  223. /package/dist/{chunk-TLRIRISJ.js.map → chunk-4LCA2GEX.js.map} +0 -0
  224. /package/dist/{chunk-4N33L4HY.js.map → chunk-5GIYIYJI.js.map} +0 -0
  225. /package/dist/{chunk-ZDLVHGIC.js.map → chunk-7EP4FURO.js.map} +0 -0
  226. /package/dist/{chunk-CAUADFDM.js.map → chunk-7SOKOEAZ.js.map} +0 -0
  227. /package/dist/{chunk-7Q74DD2W.js.map → chunk-7V6GNQC2.js.map} +0 -0
  228. /package/dist/{chunk-C6YKKH73.js.map → chunk-AALJHIKH.js.map} +0 -0
  229. /package/dist/{chunk-C2UN2CY7.js.map → chunk-AJ7JHHRY.js.map} +0 -0
  230. /package/dist/{chunk-3DADRUGW.js.map → chunk-BGA7S5EF.js.map} +0 -0
  231. /package/dist/{chunk-7GMOB4FF.js.map → chunk-CJSTQNE5.js.map} +0 -0
  232. /package/dist/{chunk-6YAQ3AJ5.js.map → chunk-DYUPSTCV.js.map} +0 -0
  233. /package/dist/{chunk-E5QI6C6C.js.map → chunk-E3LGAZJC.js.map} +0 -0
  234. /package/dist/{chunk-NL5KFA5N.js.map → chunk-EEA2RM4B.js.map} +0 -0
  235. /package/dist/{chunk-BL7WULM5.js.map → chunk-FDO7ITP6.js.map} +0 -0
  236. /package/dist/{chunk-7BIGO6ZL.js.map → chunk-FGFU6J26.js.map} +0 -0
  237. /package/dist/{chunk-6TIQLG7I.js.map → chunk-FKHXXL42.js.map} +0 -0
  238. /package/dist/{chunk-QPD7EYGI.js.map → chunk-G2MS56KM.js.map} +0 -0
  239. /package/dist/{chunk-FFTGLWHI.js.map → chunk-GH7IKABD.js.map} +0 -0
  240. /package/dist/{chunk-RC2TVYY2.js.map → chunk-GYCUX3N4.js.map} +0 -0
  241. /package/dist/{chunk-CJYVVVOG.js.map → chunk-HEJFE3BC.js.map} +0 -0
  242. /package/dist/{chunk-KM4QO4LN.js.map → chunk-HLQANATZ.js.map} +0 -0
  243. /package/dist/{chunk-RQOUKIFS.js.map → chunk-J7RQ3RP7.js.map} +0 -0
  244. /package/dist/{chunk-QTHFGP5F.js.map → chunk-JITK24KX.js.map} +0 -0
  245. /package/dist/{chunk-EJYUAN5F.js.map → chunk-K6UXWVQ6.js.map} +0 -0
  246. /package/dist/{chunk-3XJITLZQ.js.map → chunk-KJ65WZHB.js.map} +0 -0
  247. /package/dist/{chunk-JOR4Y326.js.map → chunk-KOVQZJ27.js.map} +0 -0
  248. /package/dist/{chunk-O6QSBI3U.js.map → chunk-KZ4BJRGQ.js.map} +0 -0
  249. /package/dist/{chunk-FZPZML67.js.map → chunk-LR6LWX33.js.map} +0 -0
  250. /package/dist/{chunk-NTS2RCQK.js.map → chunk-NAULI3EG.js.map} +0 -0
  251. /package/dist/{chunk-V5W67PQV.js.map → chunk-NOKHMWMW.js.map} +0 -0
  252. /package/dist/{chunk-JGVW6F3Q.js.map → chunk-ODI4K32P.js.map} +0 -0
  253. /package/dist/{chunk-H7USCTPQ.js.map → chunk-OLD2GKQJ.js.map} +0 -0
  254. /package/dist/{chunk-D7HOJFDS.js.map → chunk-ONSEODO2.js.map} +0 -0
  255. /package/dist/{chunk-R3YMWUF3.js.map → chunk-P3IAZQPS.js.map} +0 -0
  256. /package/dist/{chunk-7KC6LT7U.js.map → chunk-PSQ347YP.js.map} +0 -0
  257. /package/dist/{chunk-U6OQ7GWU.js.map → chunk-QFKNIKUF.js.map} +0 -0
  258. /package/dist/{chunk-2DFXIJPZ.js.map → chunk-QZMGZBTF.js.map} +0 -0
  259. /package/dist/{chunk-NSFHMGOF.js.map → chunk-SKJM4PKE.js.map} +0 -0
  260. /package/dist/{chunk-T7R42MWB.js.map → chunk-STSORBX5.js.map} +0 -0
  261. /package/dist/{chunk-ICA5SCIT.js.map → chunk-T765HQ5U.js.map} +0 -0
  262. /package/dist/{chunk-RFEQ7DQN.js.map → chunk-TDG5NZAZ.js.map} +0 -0
  263. /package/dist/{chunk-2S6PPGIR.js.map → chunk-TWYYUMYO.js.map} +0 -0
  264. /package/dist/{chunk-U6JZGQXC.js.map → chunk-TZ7ZA2LM.js.map} +0 -0
  265. /package/dist/{chunk-JIB3UUYV.js.map → chunk-UH2VY2QQ.js.map} +0 -0
  266. /package/dist/{chunk-X5XK6WWV.js.map → chunk-VHQNJW4Q.js.map} +0 -0
  267. /package/dist/{chunk-3IA2SUWM.js.map → chunk-WRVKI6ZO.js.map} +0 -0
  268. /package/dist/{chunk-2CWCJYT3.js.map → chunk-XZLCAL5O.js.map} +0 -0
  269. /package/dist/{chunk-W7FZ7ZZE.js.map → chunk-Z6EFSXU3.js.map} +0 -0
  270. /package/dist/{chunk-GRX5BE73.js.map → chunk-ZNCCX7P6.js.map} +0 -0
  271. /package/dist/{entity-canonical-id-migration-74IDJFPB.js.map → entity-canonical-id-migration-46EMEXTB.js.map} +0 -0
  272. /package/dist/{resolution-RWIGFH2W.js.map → resolution-4QPPLDEN.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { readNativeChunks, readEntityIndexStateText } from \"./entity-recall-reads.js\";\nimport { renderAuthorityBoundContent } from \"./recall-context-composition.js\";\nimport { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\nimport { truncateGraphemeSafe } from \"./whitespace.js\";\nimport { prepareAliasQuery, scoreAliasMatch, tokenize } from \"./entity-alias-score.js\";\nimport {\n detectEntityQueryMode,\n isStructuralEntityFollowUpQuery,\n type EntityQueryMode,\n} from \"./entity-retrieval-i18n.js\";\nimport { buildOriginStructuredSections, sanitizeOriginatedFacts, type EntityOriginStructuredSection } from \"./entity-origin-fields.js\";\nimport {\n checkEntityRecallAbort,\n entityRecallSectionAbsent,\n yieldEntityRecallScan,\n yieldEntityRecallScanEvery,\n} from \"./entity-recall-cancellation.js\";\nimport { applyCarriedMemorySnippets } from \"./entity-mention-carry.js\";\nimport {\n entityMentionCacheGeneration,\n entityMentionIdentity,\n entityMentionPersistedIndexReadable,\n entityMentionScopeKey,\n resolveEntityMentionIndex,\n writePersistedEntityMentionIndex,\n} from \"./entity-mention-index-cache.js\";\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n summary?: string;\n aliases: string[];\n facts: string[];\n timelineFacts: string[];\n timelineFactOrigins?: Array<string | undefined>;\n structuredSections: EntityOriginStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n origin?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[]; memorySnippetOrigins?: Array<string | undefined>;\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entityStatusVersion?: number;\n entities: EntityMentionIndexEntry[];\n /** In-memory only. A new canonical id had no snippets to carry. */\n pendingSnippetReconcile?: boolean;\n};\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\"; origin?: string;\n};\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n originAuthorityEnabled?: boolean; untrustedOrigins?: readonly string[];\n /**\n * Cancels the build at its next checkpoint (issue #2291). Entity recall reads\n * every entity and memory file across the recalled namespaces, which is\n * minutes of work on a large or slow store; without this the scan kept running\n * after the recall that asked for it had been abandoned.\n */\n abortSignal?: AbortSignal;\n}\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${truncateGraphemeSafe(normalized, maxLength - 1).trimEnd()}…`;\n}\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n const existing = deduped.get(key);\n if (!existing) {\n deduped.set(key, snippet);\n continue;\n }\n if (existing.origin !== snippet.origin) {\n existing.origin = undefined;\n }\n }\n return [...deduped.values()];\n}\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\ntype RecalledEntityFact = { text: string; sourceIndex: number };\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): RecalledEntityFact[] {\n if (!isBeliefLedgerSection(section)) {\n return section.facts.map((text, sourceIndex) => ({ text, sourceIndex }));\n }\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): RecalledEntityFact[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: RecalledEntityFact[] }>();\n for (const [sourceIndex, fact] of facts.entries()) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [{ text: text.trim(), sourceIndex }] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push({ text: text.trim(), sourceIndex });\n }\n }\n return [...byClaim.values()].flatMap((current) => current.status === \"active\" ? current.texts : []);\n}\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !resolveNamespaceCapabilities(config).namespaces ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n return storages.length > 0 ? storages : [storage];\n}\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(\n storage: StorageManager,\n abortSignal?: AbortSignal,\n): Promise<EntityMentionIndex | null> {\n const raw = await readEntityIndexStateText(entityIndexStatePath(storage), abortSignal);\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\nasync function readCurrentPersistedEntityIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n abortSignal?: AbortSignal,\n): Promise<EntityMentionIndex | null> {\n if (\n resolveNamespaceCapabilities(config).namespaces &&\n namespaceStorage &&\n recallNamespaces &&\n recallNamespaces.length > 0\n ) {\n return null;\n }\n const index = await readEntityIndexState(storage, abortSignal);\n checkEntityRecallAbort(abortSignal);\n if (!entityMentionPersistedIndexReadable(storage.dir) || !index || index.entityStatusVersion !== storage.getMemoryStatusVersion()) {\n return null;\n }\n return index;\n}\ntype CarriedMemorySnippets = Map<string, { memorySnippets: string[]; memorySnippetOrigins?: (string | undefined)[] }>;\n\nfunction carriedMemorySnippets(index: EntityMentionIndex): CarriedMemorySnippets {\n return new Map(index.entities.map((entry) => [entry.canonicalId, {\n memorySnippets: entry.memorySnippets.slice(),\n memorySnippetOrigins: entry.memorySnippetOrigins?.slice(),\n }]));\n}\n\nfunction nativeEntityIndexRevision(chunks: NativeKnowledgeChunk[]): string {\n const projection = chunks.map((chunk) => [\n chunk.chunkId,\n chunk.sourcePath,\n chunk.title,\n chunk.sourceKind,\n uniqueStrings(chunk.aliases ?? []),\n compactLine(chunk.content, 180),\n chunk.derivedDate ?? null,\n ]);\n return createHash(\"sha256\").update(JSON.stringify(projection)).digest(\"hex\");\n}\n\nasync function writeEntityIndexState(\n storage: StorageManager,\n index: EntityMentionIndex,\n persistGeneration: number,\n): Promise<void> {\n await writePersistedEntityMentionIndex(storage.dir, persistGeneration, JSON.stringify(index, null, 2) + \"\\n\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nfunction hasFreshNativeExplicitMention(\n index: EntityMentionIndex,\n nativeChunks: NativeKnowledgeChunk[],\n query: string,\n): boolean {\n if (nativeChunks.length === 0) return false;\n const nativeCanonicalIds = new Set(nativeChunks.map(nativePseudoCanonicalId));\n const freshNativeIndex: EntityMentionIndex = {\n ...index,\n entities: [\n ...index.entities.filter((entry) => !nativeCanonicalIds.has(entry.canonicalId)),\n ...nativeChunks.map(createPseudoNativeEntry),\n ],\n };\n return resolveLanguageIndependentExplicitCandidates(freshNativeIndex, query).length > 0;\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n nativeChunksOverride?: NativeKnowledgeChunk[],\n resolvedStorages?: StorageManager[],\n abortSignal?: AbortSignal,\n carrySnippets?: CarriedMemorySnippets,\n): Promise<EntityMentionIndex> {\n checkEntityRecallAbort(abortSignal);\n const storages = resolvedStorages ?? await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const persistGeneration = entityMentionCacheGeneration(storage.dir);\n const entityStatusVersionBefore = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage, abortSignal) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles({ abortSignal }))),\n carrySnippets\n ? Promise.resolve([])\n : Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories({ abortSignal }))),\n nativeChunksOverride ? Promise.resolve(nativeChunksOverride) : readNativeChunks(config, recallNamespaces, abortSignal),\n ]);\n // The bulk reads now stop at their own scan boundaries (issue #2307); this\n // checkpoint still guards the (larger) indexing pass over their results.\n checkEntityRecallAbort(abortSignal);\n // Pair each entity with the storage that owns it (#1534): canonical ids must\n // reflect that store's aliases and historical migration mappings, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, storage: storages[index]! })),\n );\n const memories = memorySets.flat();\n\n // The two passes over the corpus below never await real I/O, so without an\n // explicit yield they hold the event loop and no recall section deadline can\n // fire during them (issue #2291).\n let scanned = 0;\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, storage: entityStorage } of entityRecords) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const canonicalId =\n typeof entityStorage.normalizeEntityName === \"function\"\n ? entityStorage.normalizeEntityName(entity.name, entity.type)\n : normalizeEntityName(entity.name, entity.type, entityStorage.entityAliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const { facts: timelineFacts, origins: timelineFactOrigins } = sanitizeOriginatedFacts(\n entity.timeline,\n sanitizeEntityFact,\n compactLine,\n true,\n );\n const structuredSections = buildOriginStructuredSections(\n rawStructuredSections,\n recallFactsForStructuredSection,\n sanitizeEntityFact,\n compactLine,\n );\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts,\n ...(timelineFactOrigins.some((origin) => origin !== undefined) ? { timelineFactOrigins } : {}),\n structuredSections,\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n scanned = 0;\n const pendingSnippetReconcile = carrySnippets\n ? applyCarriedMemorySnippets(entities.values(), carrySnippets)\n : false;\n if (!carrySnippets) {\n for (const memory of memories) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const entry = typeof memory.frontmatter.entityRef === \"string\" ? entities.get(memory.frontmatter.entityRef) : undefined;\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (entry.memorySnippets.includes(snippet)) continue;\n entry.memorySnippets.push(snippet);\n entry.memorySnippetOrigins = [...(entry.memorySnippetOrigins ?? []), memory.frontmatter.origin];\n }\n }\n // Each remaining phase is another synchronous pass over the whole index\n // (alias map, native-chunk merge, sort, two full serializations). Yield between\n // them so a section deadline can fire between passes instead of only after all\n // of them (issue #2291).\n await yieldEntityRecallScan(abortSignal);\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n await yieldEntityRecallScan(abortSignal);\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n await yieldEntityRecallScan(abortSignal);\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n await yieldEntityRecallScan(abortSignal);\n const nextEntities = JSON.stringify(sortedEntities);\n const entityStatusVersionAfter = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const canPersistIndex = shouldPersistIndex && entityStatusVersionBefore === entityStatusVersionAfter && persistGeneration === entityMentionCacheGeneration(storage.dir);\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entityStatusVersion: canPersistIndex ? entityStatusVersionAfter : undefined,\n entities: sortedEntities,\n };\n if (canPersistIndex) {\n checkEntityRecallAbort(abortSignal);\n await writeEntityIndexState(storage, index, persistGeneration);\n }\n if (pendingSnippetReconcile) index.pendingSnippetReconcile = true;\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n const aliasQuery = prepareAliasQuery(query);\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(aliasQuery, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nconst EXPLICIT_ENTITY_MENTION_SCORE = 9;\n\nconst IMPLICIT_ENTITY_STOP_WORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"by\",\n \"can\",\n \"do\",\n \"for\",\n \"from\",\n \"has\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"me\",\n \"my\",\n \"of\",\n \"on\",\n \"or\",\n \"the\",\n \"to\",\n \"was\",\n \"what\",\n \"when\",\n \"where\",\n \"who\",\n \"why\",\n \"with\",\n \"you\",\n \"your\",\n]);\n\nfunction isDistinctiveImplicitAlias(normalizedAlias: string): boolean {\n const tokens = normalizedAlias.split(/\\s+/).filter(Boolean);\n if (tokens.length > 1 && tokens.every((token) => IMPLICIT_ENTITY_STOP_WORDS.has(token))) return false;\n if (tokens.length !== 1) return true;\n const token = tokens[0]!;\n return Array.from(token).length > 1 && !IMPLICIT_ENTITY_STOP_WORDS.has(token);\n}\n\nfunction isShortLatinAlias(alias: string): boolean {\n return /^[A-Za-z]{2,3}$/.test(alias.trim());\n}\n\nfunction hasStrongShortLatinAliasMention(query: string, alias: string): boolean {\n const normalizedAlias = alias.trim();\n const titleCaseAlias = `${normalizedAlias[0]!.toUpperCase()}${normalizedAlias.slice(1).toLowerCase()}`;\n const forms = new Set([normalizedAlias, normalizedAlias.toUpperCase(), titleCaseAlias]);\n return [...forms].some((form) => {\n if (form === form.toLowerCase()) return false;\n const escaped = form.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?:^|[^A-Za-z0-9])${escaped}(?:$|[^A-Za-z0-9])`).test(query);\n });\n}\n\nfunction resolveLanguageIndependentExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const canonicalIdsByAlias = new Map<string, Set<string>>();\n for (const entry of index.entities) {\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) continue;\n const canonicalIds = canonicalIdsByAlias.get(normalizedAlias) ?? new Set<string>();\n canonicalIds.add(entry.canonicalId);\n canonicalIdsByAlias.set(normalizedAlias, canonicalIds);\n }\n }\n\n const candidates: EntityCandidate[] = [];\n const aliasQuery = prepareAliasQuery(query);\n for (const entry of index.entities) {\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n const score = scoreAliasMatch(aliasQuery, alias);\n if (\n !normalizedAlias ||\n !isDistinctiveImplicitAlias(normalizedAlias) ||\n (isShortLatinAlias(alias) && !hasStrongShortLatinAliasMention(query, alias)) ||\n canonicalIdsByAlias.get(normalizedAlias)?.size !== 1 ||\n score < EXPLICIT_ENTITY_MENTION_SCORE ||\n score <= bestScore\n ) {\n continue;\n }\n bestAlias = alias;\n bestScore = score;\n }\n if (bestAlias) {\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n }\n\n return candidates.sort(\n (left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name),\n );\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n const turnQuery = prepareAliasQuery(turn.content);\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turnQuery, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const [index, fact] of section.facts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 8 : 9,\n kind: \"section\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n } else {\n for (const [index, fact] of entry.timelineFacts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: entry.timelineFactOrigins?.[index],\n });\n }\n for (const section of entry.structuredSections) {\n for (const [index, fact] of section.facts.entries()) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const [index, memorySnippet] of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4)).entries()) {\n snippets.push({ text: memorySnippet, score: 5, kind: \"memory\", origin: entry.memorySnippetOrigins?.[index] });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing) {\n deduped.set(normalized, scored);\n } else if (existing.origin !== scored.origin) {\n deduped.set(normalized, { ...(scored.score > existing.score ? scored : existing), origin: undefined });\n } else if (scored.score > existing.score) {\n deduped.set(normalized, scored);\n }\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n originAuthorityEnabled: boolean, untrustedOrigins: readonly string[],\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n // #1955 review: non-native snippet kinds may embed extraction-written content\n // without per-field origin — fence as unknown (least privilege; plumbing #2397).\n const renderSnippet = (snippet: EntityHintSnippet): string => snippet.kind !== \"native\"\n ? renderAuthorityBoundContent(snippet.text, snippet.origin, { enabled: originAuthorityEnabled, untrustedOrigins }) : snippet.text;\n // (see comment above)\n // #1955 review: inline fields (names/types/aliases/targets) cannot carry the\n // multi-line block fence without collapsing the hint list structure —\n // per-field origin plumbing is tracked in #2397.\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => {\n const text = sanitizeEntityFact(entry.text);\n return text\n ? scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n origin: entry.origin,\n }, queryTokens)\n : null;\n })\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n lines.push(`- resolution: ${candidate.source === \"recent_turn\" ? \"carried forward from recent turns via alias\" : \"matched alias\"} \"${candidate.alias}\"${candidate.source === \"recent_turn\" ? \"\" : \" in the query\"}`);\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${truncateGraphemeSafe(result, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n // Checkpoints sit at the real I/O boundaries below (persisted-index read,\n // native-chunk read, storage resolution, index build). The per-candidate\n // formatting that follows never awaits real I/O, so a deadline that fires\n // during a scan is observed here (issue #2291).\n checkEntityRecallAbort(options.abortSignal);\n const prefixedMode = detectEntityQueryMode(options.query);\n // #2193: in zero-pronoun scripts a short question with no entity name\n // never trips a pronoun word list, so the structural signal routes it\n // into the same coreference path as an English \"what about him?\".\n // Latin-script queries stay on the cue tables / English rules so the\n // generic technical-question guard keeps working. Resolution gates.\n const structuralFollowUp = prefixedMode === null\n && isStructuralEntityFollowUpQuery(\n options.query,\n options.recentTurns > 0 && options.transcriptEntries.length > 0,\n );\n const earlyMode = prefixedMode ?? (structuralFollowUp ? \"follow_up\" : null);\n const persistedIndex = earlyMode\n ? null\n : await readCurrentPersistedEntityIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n options.abortSignal,\n );\n checkEntityRecallAbort(options.abortSignal);\n let nativeChunks: NativeKnowledgeChunk[] | undefined;\n if (\n !earlyMode &&\n persistedIndex &&\n resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0\n ) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces, options.abortSignal);\n if (!hasFreshNativeExplicitMention(persistedIndex, nativeChunks, options.query)) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n }\n const namespaceScoped =\n resolveNamespaceCapabilities(options.config).namespaces &&\n options.namespaceStorage !== undefined &&\n (options.recallNamespaces?.length ?? 0) > 0;\n if (namespaceScoped) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces, options.abortSignal);\n }\n const resolvedStorages = namespaceScoped\n ? await resolveEntityIndexStorages(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n )\n : undefined;\n if (!nativeChunks) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces, options.abortSignal);\n }\n const indexStorages = resolvedStorages ?? [options.storage];\n const index = await resolveEntityMentionIndex({\n scopeKey: entityMentionScopeKey(options.recallNamespaces, indexStorages, nativeEntityIndexRevision(nativeChunks)),\n currentIdentity: () => entityMentionIdentity(indexStorages),\n abortSignal: options.abortSignal,\n buildFull: (signal) => buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n nativeChunks,\n indexStorages,\n signal,\n ),\n rebuildEntities: (previous, signal) => buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n nativeChunks,\n indexStorages,\n signal,\n carriedMemorySnippets(previous),\n ),\n });\n // Candidate resolution is another synchronous pass over every entity and alias,\n // reached even on a cache hit that did no I/O at all — so yield here too, or a\n // cached corpus could still hold the loop past the section budget (issue #2291).\n await yieldEntityRecallScan(options.abortSignal);\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n await yieldEntityRecallScan(options.abortSignal);\n const queryCandidates = prefixedMode\n ? explicitCandidates\n : resolveLanguageIndependentExplicitCandidates(index, options.query);\n if (\n queryCandidates.length === 0\n && /^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/i.test(normalizeEntityText(options.query))\n ) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n\n // Explicit mentions keep #2161 behavior (direct mode) even when the\n // structural follow-up signal also fired; only name-less short questions\n // fall through to coreference.\n const mode = prefixedMode\n ?? (queryCandidates.length > 0\n ? \"direct\"\n : structuralFollowUp\n ? \"follow_up\"\n : null);\n if (!mode) return entityRecallSectionAbsent(options.abortSignal);\n\n const candidates = queryCandidates.length > 0\n ? queryCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return entityRecallSectionAbsent(options.abortSignal);\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = queryCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(\n enriched,\n queryTokens,\n mode,\n options.maxRelatedEntities,\n options.maxChars,\n options.originAuthorityEnabled === true,\n options.untrustedOrigins ?? [],\n );\n // `entityRecallSectionAbsent` so a cancelled build is not recorded as a\n // successful section that simply found no entities.\n if (!section) return entityRecallSectionAbsent(options.abortSignal);\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_INDEX_VERSION;\nexport const entityRecentTranscriptLookbackHours = RECENT_TRANSCRIPT_LOOKBACK_HOURS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,kBAAkB;AAG3B,OAAO,UAAU;AA4BjB,IAAM,uBAAuB;AAC7B,IAAM,mCAAmC;AACzC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;AAC5B,IAAM,4BAA4B;AAClC,IAAM,wBAAwB;AAwE9B,SAAS,cAAc,QAA4B;AACjD,SAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,CAAC,CAAC,CAAC;AAC7F;AACA,SAAS,YAAY,OAAe,YAAoB,KAAa;AACnE,QAAM,aAAa,MAAM,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACnD,MAAI,WAAW,UAAU,UAAW,QAAO;AAC3C,SAAO,GAAG,qBAAqB,YAAY,YAAY,CAAC,EAAE,QAAQ,CAAC;AACrE;AACA,SAAS,yBAAyB,UAAoD;AACpF,QAAM,UAAU,oBAAI,IAA+B;AACnD,aAAW,WAAW,UAAU;AAC9B,UAAM,MAAM,oBAAoB,QAAQ,IAAI;AAC5C,UAAM,WAAW,QAAQ,IAAI,GAAG;AACh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B,QAAQ,WAAW;AAEjF,QAAM,cAAc,SAAS,QAAQ,KAAK;AAC1C,QAAM,iBAAiB,gBAAgB,WAAW,KAAK,SAAS,cAC5D,IACA,QAAQ;AACZ,QAAM,mBAAmB,WAAW,MAAM,GAAG,cAAc;AAC3D,QAAM,WAAW,MAAM,QAAQ;AAAA,IAC7B,iBAAiB,IAAI,OAAO,cAAc;AACxC,YAAM,uBAAuB,IAAI;AAAA,QAC/B;AAAA,UACE,QAAQ;AAAA,UACR,UAAU,MAAM;AAAA,UAChB,UAAU,MAAM;AAAA,UAChB,QAAQ,OAAO;AAAA,QACjB;AAAA,MACF;AACA,YAAM,WAAW,MAAM;AAAA,QACrB,UAAU;AAAA,QACV;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,aAAa,qBAAqB,QAAQ;AAAA,MAC5C;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,UAAU;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ,2BAA2B;AAAA,IACnC,QAAQ,oBAAoB,CAAC;AAAA,EAC/B;AAGA,MAAI,CAAC,QAAS,QAAO,0BAA0B,QAAQ,WAAW;AAClE,SAAO;AACT;AAEA,eAAsB,kCACpB,0BACA,aAC4B;AAC5B,MAAI,eAAe,EAAG,QAAO,CAAC;AAC9B,QAAM,oBAAoB,MAAM,yBAAyB,MAAM,MAAM,CAAC,CAAC;AACvE,MAAI,kBAAkB,WAAW,EAAG,QAAO,CAAC;AAC5C,SAAO,kBAAkB,MAAM,CAAC,KAAK,IAAI,GAAG,cAAc,CAAC,CAAC;AAC9D;AAEO,IAAM,qBAAqB;AAC3B,IAAM,sCAAsC;","names":["index","token"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/buffer.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport { throwIfAborted } from \"./abort-error.js\";\nimport { scanSignals } from \"./signal.js\";\nimport { BufferSessionPersistence, type BufferStorage } from \"./buffer-persistence.js\";\nimport { selectEvictedBufferKeys } from \"./buffer-eviction.js\";\nimport type {\n BufferEntryState,\n BufferState,\n BufferSurpriseEvent,\n BufferTurn,\n PluginConfig,\n} from \"./types.js\";\nimport { resolvePresentationCapabilities, resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { resolvePrincipal } from \"./namespaces/principal.js\";\nimport { scopeProfilePlanIdentity, subtractBufferTurns } from \"./buffer-turn-helpers.js\";\nimport { ExtractionDeadlineError } from \"./orchestration/extraction-run.js\";\nimport type { ExtractionBufferSnapshot } from \"./extraction-liveness.js\";\nimport {\n bufferEntryCounts,\n bufferTurnArrayIsSuffixOfSnapshot,\n bufferTurnArraysEqual,\n bufferTurnsEqual,\n copyBufferTurn,\n describeError,\n EVICTION_HOOKS,\n entryHoldsAcceptedCapture,\n evaluateTriggerDecision,\n hasPinnedCaptureScope,\n liveTurnsFromExtractionSnapshot,\n matchingQueuedExtractionPrefixLength,\n matchingSessionBufferKeys,\n normalizeBufferState,\n probeWithTimeout,\n selectRetainedDeferredTurns,\n type BufferEntryCounts,\n} from \"./buffer-turn-helpers.js\";\nimport { BufferAdmissionRefusedError, BufferSessionTurnRefusedError, canAdmitNewEntryUnlocked } from \"./buffer-admission.js\";\nimport { BufferIngressCounters } from \"./buffer-ingress-counters.js\";\nimport { addTurnsBoundedWithAdmissionKey, type AddTurnsBoundedHost, type BoundedRefusalListener } from \"./buffer-add-turns-bounded.js\";\nimport { refuseOverCapSingle, resolveMaxTurnsPerSession, sessionTurnCapReached } from \"./buffer-session-cap.js\";\nexport { BufferAdmissionRefusedError, BufferSessionTurnRefusedError } from \"./buffer-admission.js\";\nimport type { AddTurnMutationResult, AddTurnOutcome, RetainedTurnCleanupOptions, TriggerDecision } from \"./buffer-types.js\";\n\nexport type { TriggerDecision, AddTurnOutcome, RetainedTurnCleanupOptions } from \"./buffer-types.js\";\n\nexport type { BufferSurpriseProbe } from \"./buffer-types.js\";\nimport type { BufferSurpriseProbe, SurpriseTelemetryQueueEntry } from \"./buffer-types.js\";\n\n// Raised from 200 in #3303: live captures were being dropped at busy hours\n// while the single extraction worker drained a backlog.\nconst FALLBACK_MAX_BUFFER_SESSIONS = 1000;\nexport { BUFFER_ADMISSION_IDEMPOTENCY_CAP } from \"./buffer-admission-idempotency.js\";\n\n/**\n * Upper bound on how long a debounced buffer save may be deferred under\n * sustained activity (issue #1909). Each new turn re-arms the trailing-edge\n * timer, so a steady stream of turns could otherwise push the save out\n * indefinitely and widen the crash-loss window without bound. Once a pending\n * save has been deferred this many debounce windows, the next scheduled save\n * forces an inline flush instead of re-arming.\n */\nconst BUFFER_SAVE_MAX_DEFER_MULTIPLIER = 5;\n\n/**\n * Node's maximum 32-bit `setTimeout` delay (2^31-1 ms, ~24.8 days). A larger\n * value is overflow-clamped by Node to 1ms with a TimeoutOverflowWarning, so we\n * clamp defensively at every timer arm (issue #1909 review round 5) even though\n * parseConfig already caps `bufferSaveDebounceMs` — a directly-constructed config\n * could still exceed it.\n */\nconst MAX_SET_TIMEOUT_MS = 2_147_483_647;\n\n/** Retry delay for a failed save when `bufferSaveDebounceMs` is 0: a transient\n * failure must still re-arm (PR 3481 review round 3); 1s bounds the dirty\n * window without a hot retry loop on a persistently failing backend. */\nconst BUFFER_SAVE_RETRY_DELAY_MS = 1_000;\n\nexport class SmartBuffer {\n private state: BufferState;\n private loaded = false;\n private loadPromise: Promise<void> | null = null;\n private readonly surpriseProbe: BufferSurpriseProbe | null;\n /** Process-local add-path counters (#3444); instance-owned, no module state. Read via `ingress.snapshot()`. */\n readonly ingress: BufferIngressCounters;\n private mutationChain: Promise<unknown> = Promise.resolve();\n /**\n * Serialized write chain for `BUFFER_SURPRISE` telemetry events.\n *\n * The telemetry path is fire-and-forget (`addTurn` does not await the\n * ledger append), but multiple concurrent appends would still settle\n * out of order under variable filesystem latency. The report path\n * assumes chronological ordering — it slices the tail of the ledger\n * and treats the most recent entry as the current threshold in force.\n * Chaining ensures each append only runs after the previous settles,\n * preserving wall-clock order.\n *\n * We include a `.catch` on every link so a rejected append does not\n * poison the chain (CLAUDE.md rule #40).\n */\n private surpriseTelemetryWriteChain: Promise<unknown> = Promise.resolve();\n\n /**\n * Debounced buffer-save state (issue #1909). Steady-state buffering used to\n * serialize + rewrite the whole multi-session buffer on EVERY turn. We now\n * coalesce those writes onto a trailing-edge timer; correctness boundaries\n * (extraction trigger, extraction clear, shutdown) still force an immediate\n * flush. `bufferSaveDebounceMs: 0` restores save-every-turn exactly.\n */\n private saveTimer: NodeJS.Timeout | null = null;\n private pendingSave = false;\n /** Wall-clock ms when the currently-pending save was first scheduled (issue\n * #1909). Null when nothing is pending. Used to bound deferral under sustained\n * activity (see BUFFER_SAVE_MAX_DEFER_MULTIPLIER). */\n private firstPendingAtMs: number | null = null;\n\n /** Which sessions' persisted files are stale (per-session incremental saves). */\n private readonly persistence: BufferSessionPersistence;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly storage: BufferStorage,\n surpriseProbe: BufferSurpriseProbe | null = null,\n /** #3444 test seam: `false` disables the ingress counters; `persistence` injects a test-clocked tracker (#3389). */\n options: { countIngress?: boolean; persistence?: BufferSessionPersistence } = {},\n ) {\n this.state = { turns: [], lastExtractionAt: null, extractionCount: 0 };\n this.surpriseProbe = surpriseProbe;\n this.persistence = options.persistence ?? new BufferSessionPersistence();\n this.ingress = new BufferIngressCounters(undefined, options.countIngress !== false);\n }\n\n /** Distinct sessions admitted before backpressure; configurable (#3303, raised from 200). */\n private get maxSessionEntries(): number {\n // parseConfig defaults, validates, and floors bufferMaxSessions at the I/O\n // boundary; FALLBACK_MAX_BUFFER_SESSIONS covers direct constructions with\n // configs from before the knob existed.\n return this.config.bufferMaxSessions ?? FALLBACK_MAX_BUFFER_SESSIONS;\n }\n\n private enqueueMutation<T>(op: () => Promise<T>): Promise<T> {\n const run = this.mutationChain.catch(() => {}).then(op);\n this.mutationChain = run.catch(() => {});\n return run;\n }\n\n private entryFor(key: string): BufferEntryState {\n if (!this.state.entries) {\n this.state.entries = Object.create(null) as NonNullable<BufferState[\"entries\"]>;\n }\n const entries = this.state.entries as NonNullable<BufferState[\"entries\"]>;\n if (Object.hasOwn(entries, key)) {\n const stored = entries[key];\n // Guard against corrupted state/buffer.json — if the stored entry\n // is not a valid object shape, discard it and recreate.\n if (stored && typeof stored === \"object\" && Array.isArray(stored.turns)) {\n return stored;\n }\n // Corrupted — fall through to recreate.\n }\n const created: BufferEntryState = {\n turns: [],\n lastExtractionAt: null,\n extractionCount: 0,\n };\n entries[key] = created;\n return created;\n }\n\n private peekEntry(key: string): BufferEntryState | null {\n const existing = this.state.entries?.[key];\n if (existing) return existing;\n if (key !== \"default\") return null;\n return {\n turns: Array.isArray(this.state.turns) ? this.state.turns : [],\n lastExtractionAt: this.state.lastExtractionAt ?? null,\n extractionCount:\n typeof this.state.extractionCount === \"number\" ? this.state.extractionCount : 0,\n };\n }\n\n /** Evict oldest entries past this.maxSessionEntries and queue their session files for deletion. */\n private pruneEntries(retainKeys: string[], maxCount = this.maxSessionEntries): void {\n const entries = this.state.entries;\n if (!entries) return;\n const evicted = selectEvictedBufferKeys(entries, retainKeys, maxCount, EVICTION_HOOKS);\n for (const key of evicted) delete entries[key];\n this.persistence.markEvicted(evicted);\n }\n\n private async loadUnlocked(): Promise<void> {\n if (this.loaded) return;\n if (!this.loadPromise) {\n this.loadPromise = this.storage.loadBuffer()\n .then((state) => {\n this.state = normalizeBufferState(state);\n this.loaded = true;\n })\n .finally(() => {\n this.loadPromise = null;\n });\n }\n await this.loadPromise;\n }\n\n async load(): Promise<void> {\n await this.enqueueMutation(async () => this.loadUnlocked());\n }\n\n /** Snapshot of buffered, not-yet-extracted work across sessions (#2151): session count,\n * pending-turn total, oldest buffered turn. Counts retained (#562) + active turns per entry. */\n async getBufferSnapshot(): Promise<ExtractionBufferSnapshot> {\n await this.load();\n let bufferedSessionCount = 0;\n let pendingTurnCount = 0;\n let oldestMs = Number.POSITIVE_INFINITY;\n let oldestTurnTimestamp: string | null = null;\n const consider = (turns: BufferTurn[] | undefined): void => {\n if (!Array.isArray(turns) || turns.length === 0) return;\n bufferedSessionCount += 1;\n pendingTurnCount += turns.length;\n const first = turns[0]?.timestamp;\n const parsed = typeof first === \"string\" ? Date.parse(first) : Number.NaN;\n if (Number.isFinite(parsed) && parsed < oldestMs) {\n oldestMs = parsed;\n oldestTurnTimestamp = first ?? null;\n }\n };\n const entries = this.state.entries;\n if (entries) {\n // Retained turns (deferred #562) are pending too - count with active (oldest-first), like getTurns().\n for (const entry of Object.values(entries)) consider([...(entry?.retainedTurns ?? []), ...(entry?.turns ?? [])]);\n } else {\n consider(this.state.turns);\n }\n return { bufferedSessionCount, pendingTurnCount, oldestTurnTimestamp };\n }\n\n /**\n * Reset the buffer to an empty, usable state.\n * Called when the persisted buffer file is corrupt and load() fails,\n * so the buffer can still accept new turns for the rest of the session.\n */\n resetToEmpty(): void {\n for (const key of Object.keys(this.state.entries ?? {})) {\n this.persistence.markDeleted(key);\n }\n this.state = { turns: [], lastExtractionAt: null, extractionCount: 0 };\n this.loaded = true;\n }\n\n private async saveUnlocked(\n reconcile?: { key: string; drained: import(\"./buffer-turn-helpers.js\").DrainedTurnSets },\n opts?: { allowDeferral?: boolean },\n ): Promise<import(\"./buffer-persistence.js\").BufferPersistOutcome> {\n const outcome = await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? undefined, reconcile, { allowDeferral: opts?.allowDeferral === true });\n const { handedOver, drainedTurns } = outcome;\n // A drain tombstone: the turns the drain extracted leave this copy too,\n // so a stale owner never extracts (or persists) them a second time.\n for (const [key, drained] of drainedTurns) {\n const entry = this.peekEntry(key);\n if (!entry) continue;\n entry.turns = subtractBufferTurns(entry.turns, drained.turns);\n if (entry.retainedTurns && entry.retainedTurns.length > 0) {\n entry.retainedTurns = subtractBufferTurns(entry.retainedTurns, drained.retainedTurns);\n if (entry.retainedTurns.length === 0) delete entry.retainedTurns;\n }\n if (key === \"default\") this.state.turns = entry.turns;\n }\n if (handedOver.length === 0) return outcome;\n // A drain claim now owns these sessions' turns (durable in the claim\n // file): drop the in-memory entries so this process cannot resurrect\n // them. A later observe for the same key starts a fresh entry whose\n // turns flow into the claim at the next handover.\n const entries = this.state.entries;\n if (!entries) return outcome;\n for (const key of handedOver) {\n delete entries[key];\n if (key === \"default\") {\n this.state.turns = [];\n }\n }\n return outcome;\n }\n\n /** Sync gate for the extraction queue: is this session claimed by a buffer drain? */\n isSessionClaimed(key: string): boolean {\n return this.storage.isBufferSessionClaimed?.(key) === true;\n }\n\n /** Per-key pending counts over the IN-MEMORY state (counts only — no turn\n * payloads), for the daemon backlog scheduler's bounded candidate scan. */\n entryCounts(): Map<string, BufferEntryCounts> {\n return bufferEntryCounts(this.state);\n }\n\n async save(reconcile?: { key: string; drained: import(\"./buffer-turn-helpers.js\").DrainedTurnSets }): Promise<void> {\n await this.enqueueMutation(async () => this.saveUnlocked(reconcile));\n }\n\n /**\n * Schedule a coalesced, TRUE trailing-edge buffer save (issue #1909). Only\n * used for the debounced (`bufferSaveDebounceMs > 0`) steady-state buffering\n * path; the debounce-off and correctness-boundary paths save inline within the\n * mutation (see `recordTurnUnlocked`). Each call re-arms the timer from now so\n * the write lands one full window after the LAST turn, not the first. To keep\n * sustained activity from deferring the save without bound (which would widen\n * the crash-loss window), once a pending save has been deferred\n * BUFFER_SAVE_MAX_DEFER_MULTIPLIER windows it is flushed inline instead of\n * re-armed. Runs inside the record mutation, so the inline save is awaited.\n */\n private async scheduleSave(): Promise<void> {\n const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);\n const now = Date.now();\n this.pendingSave = true;\n if (this.firstPendingAtMs === null) this.firstPendingAtMs = now;\n if (now - this.firstPendingAtMs >= ms * BUFFER_SAVE_MAX_DEFER_MULTIPLIER) {\n // Staleness cap hit: run the persist pass inline rather than re-arming\n // the debounce. Session-level deferral (#3389) may still rate-limit a\n // large rewrite; when it does, armDeferredRetry keeps the save pending\n // and retries at the session's eligibility time, so the pass's tail\n // cannot sit in memory waiting for a turn that may never come (3481\n // review). Drop the armed timer and only mark clean on success — a\n // failure keeps the save pending + re-arms so shutdown/the next timer\n // retries (issue #1909 review round 2), never diverging memory from disk.\n clearTimeout(this.saveTimer ?? undefined);\n this.saveTimer = null;\n try {\n const outcome = await this.saveUnlocked(undefined, { allowDeferral: true });\n if (outcome.deferredRetryDelayMs !== undefined) {\n this.armDeferredRetry(outcome.deferredRetryDelayMs);\n } else {\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n }\n } catch (err) {\n log.warn(`buffer.scheduleSave: staleness-cap save failed, keeping it pending: ${describeError(err)}`);\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave({ allowDeferral: true });\n }, ms);\n this.saveTimer.unref?.();\n }\n return;\n }\n // True trailing edge: drop any armed timer and re-arm from now.\n clearTimeout(this.saveTimer ?? undefined);\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave({ allowDeferral: true });\n }, ms);\n this.saveTimer.unref?.();\n }\n\n /**\n * A persist pass deferred one or more large sessions (#3389): keep the save\n * pending and arm a retry for when the earliest becomes rewrite-eligible.\n * Without this the tail of a burst sat in memory until the next turn or a\n * barrier — wider than the sanctioned crash-loss window (PR 3481 review).\n */\n private armDeferredRetry(delayMs: number): void {\n this.pendingSave = true;\n if (this.firstPendingAtMs === null) this.firstPendingAtMs = Date.now();\n clearTimeout(this.saveTimer ?? undefined);\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave({ allowDeferral: true });\n }, Math.min(Math.max(0, delayMs), MAX_SET_TIMEOUT_MS));\n this.saveTimer.unref?.();\n }\n\n /** Cancel any armed debounced save without persisting. */\n private cancelScheduledSave(): void {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n }\n\n /**\n * Persist the current in-memory buffer state inline, keeping the global\n * pending-save state armed until the write SUCCEEDS (issue #1909). On failure\n * the save stays pending and — when debounced — a background retry timer is\n * (re-)armed before the error propagates, so a graceful shutdown flush and the\n * next timer tick both retry. A failed post-mutation save therefore can never\n * silently drop buffered turns, including turns from OTHER sessions that were\n * only in the debounced pending state. The pending flag is cleared (and any\n * armed timer dropped) only after a durable write.\n */\n private async saveNowRetainingPendingOnFailure(context: string, opts?: { allowDeferral?: boolean }): Promise<void> {\n this.pendingSave = true;\n if (this.firstPendingAtMs === null) this.firstPendingAtMs = Date.now();\n try {\n const outcome = await this.saveUnlocked(undefined, opts);\n if (outcome.deferredRetryDelayMs !== undefined) {\n this.armDeferredRetry(outcome.deferredRetryDelayMs);\n } else {\n this.cancelScheduledSave();\n }\n } catch (err) {\n log.warn(\n `buffer.${context}: inline save failed, keeping it pending for retry: ${describeError(err)}`,\n );\n const ms = Math.min(\n this.config.bufferSaveDebounceMs || BUFFER_SAVE_RETRY_DELAY_MS,\n MAX_SET_TIMEOUT_MS,\n );\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave({ allowDeferral: opts?.allowDeferral === true });\n }, ms);\n this.saveTimer.unref?.();\n }\n throw err;\n }\n }\n\n /**\n * Force any pending debounced save to land now (issue #1909). Idempotent and\n * safe to call from outside a mutation (timer tick, shutdown/dispose, or the\n * surprise-promotion path in `addTurnWithOutcome`). Do NOT `await` this from\n * inside a mutation — it enqueues its own mutation and would deadlock the\n * serializer.\n *\n * `throwOnFailure` (review round 7 finding 5): when set, a failed write is\n * rethrown AFTER the keep-pending + re-arm bookkeeping, so the surprise\n * extraction boundary gets the same durability guarantee as the built-in\n * extract triggers (which propagate saveUnlocked failures) instead of\n * proceeding to extract_now on a non-durable triggering turn. Default false\n * keeps the fail-open behavior for the timer/shutdown callers.\n */\n async flushPendingSave(opts?: { throwOnFailure?: boolean; allowDeferral?: boolean }): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n // resetToEmpty-only deletions are pending work too, even with no\n // pending-save flag set.\n if (!this.pendingSave && !this.persistence.hasPending()) return;\n try {\n await this.enqueueMutation(async () => {\n // Re-check under the serializer: a concurrent flush may have already\n // persisted this pending save. Skip the redundant write (no phantom\n // writes). resetToEmpty-only deletions also land here without a\n // pending-save flag.\n if (!this.pendingSave && !this.persistence.hasPending()) return;\n const outcome = await this.saveUnlocked(undefined, { allowDeferral: opts?.allowDeferral === true });\n // Clear the pending flag INSIDE the same serialized mutation as the\n // write (issue #1909 review): an addTurn interleaving between the\n // write and the clear would lose its re-armed timer. Deferred\n // sessions keep the flag — still dirty — and armDeferredRetry\n // schedules their write at eligibility.\n if (outcome.deferredRetryDelayMs !== undefined) {\n this.armDeferredRetry(outcome.deferredRetryDelayMs);\n } else {\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n }\n });\n } catch (err) {\n // The write failed: memory and disk diverge (issue #1909 review round 2).\n // Keep the save PENDING (do NOT clear pendingSave/firstPendingAtMs) so a\n // graceful shutdown flush and the re-armed timer both retry it — clearing\n // the flag here would drop the buffered turns permanently. Re-arm a\n // background retry even when debounce is off (3481 review round 3).\n log.warn(`buffer.flushPendingSave: save failed, keeping it pending for retry: ${describeError(err)}`);\n const ms = Math.min(\n this.config.bufferSaveDebounceMs || BUFFER_SAVE_RETRY_DELAY_MS,\n MAX_SET_TIMEOUT_MS,\n );\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n // A steady-state retry must not escalate into a barrier write of a\n // rate-limited session (3481 review).\n void this.flushPendingSave({ allowDeferral: opts?.allowDeferral === true });\n }, ms);\n this.saveTimer.unref?.();\n }\n // Surprise-extraction boundary needs the durability guarantee — surface\n // the failure so the caller does not proceed with a non-durable flush.\n if (opts?.throwOnFailure) throw err;\n return; // fail-open for timer/shutdown callers\n }\n }\n\n async addTurn(bufferKey: string, turn: BufferTurn): Promise<TriggerDecision> {\n return (await this.addTurnWithOutcome(bufferKey, turn)).decision;\n }\n\n /** Admit atomically; refuse at capacity rather than evict accepted work. */\n async addTurnBounded(bufferKey: string, turn: BufferTurn): Promise<AddTurnOutcome | null> {\n const mutation = await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n if (refuseOverCapSingle(this.peekEntry(bufferKey), resolveMaxTurnsPerSession(this.config.bufferMaxTurnsPerSession), bufferKey)) return this.ingress.refuseOne(turn);\n if (this.peekEntry(bufferKey) === null) {\n this.makeRoomForEntryUnlocked();\n if (Object.keys(this.state.entries ?? {}).length >= this.maxSessionEntries) {\n log.warn(`buffer[${bufferKey}]: durable capture refused at the session-entry cap (${this.maxSessionEntries})`);\n return this.ingress.refuseOne(turn);\n }\n }\n return this.recordTurnUnlocked(bufferKey, turn);\n });\n if (mutation === null) return null;\n return this.completeAddTurnOutcome(bufferKey, turn, mutation);\n }\n /**\n * Admit a multi-session durable capture as one capacity transaction.\n * Preflight every new key under the mutation lock before persisting any\n * turn; refusal records nothing and drops nothing.\n */\n\n private addTurnsBoundedHost(): AddTurnsBoundedHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get maxSessionEntries() {\n return self.maxSessionEntries;\n },\n get state() {\n return self.state;\n },\n get persistence() {\n return self.persistence;\n },\n get ingress() {\n return self.ingress;\n },\n enqueueMutation: (work) => self.enqueueMutation(work),\n loadUnlocked: () => self.loadUnlocked(),\n peekEntry: (bufferKey) => self.peekEntry(bufferKey),\n recordTurnUnlocked: (bufferKey, turn) => self.recordTurnUnlocked(bufferKey, turn),\n completeAddTurnOutcome: (bufferKey, turn, mutation) =>\n self.completeAddTurnOutcome(bufferKey, turn, mutation),\n };\n }\n\n async addTurnsBounded(\n batches: readonly { bufferKey: string; turns: readonly BufferTurn[] }[], onRefused?: BoundedRefusalListener,\n ): Promise<Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }> | null> {\n const result = await addTurnsBoundedWithAdmissionKey(this.addTurnsBoundedHost(), batches, undefined, onRefused);\n return result === \"duplicate\" ? null : result;\n }\n\n /** #3368 durable observe replay only; duplicate means the scoped client key already landed. */\n async addTurnsBoundedForObserveReplay(\n batches: readonly { bufferKey: string; turns: readonly BufferTurn[] }[],\n admissionKey: string, onRefused?: BoundedRefusalListener,\n ): Promise<Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }> | null | \"duplicate\"> {\n return addTurnsBoundedWithAdmissionKey(this.addTurnsBoundedHost(), batches, admissionKey.trim(), onRefused);\n }\n\n /** Free one slot only when an empty entry can be reclaimed. */\n private makeRoomForEntryUnlocked(): void {\n const entries = this.state.entries ?? {};\n const target = Math.max(0, this.maxSessionEntries - 1);\n const pinned = Object.keys(entries).filter((k) => k === \"default\" || entryHoldsAcceptedCapture(entries[k]));\n if (pinned.length <= target) this.pruneEntries([], target);\n }\n\n async addTurnWithOutcome(\n bufferKey: string,\n turn: BufferTurn,\n ): Promise<AddTurnOutcome> {\n const mutation = await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n if (\n this.peekEntry(bufferKey) === null &&\n !canAdmitNewEntryUnlocked(this.state.entries ?? {}, bufferKey, this.maxSessionEntries, EVICTION_HOOKS)\n ) {\n throw this.ingress.refuseThrow(turn, new BufferAdmissionRefusedError(bufferKey, this.maxSessionEntries));\n }\n const maxTurns = resolveMaxTurnsPerSession(this.config.bufferMaxTurnsPerSession);\n if (sessionTurnCapReached(this.peekEntry(bufferKey), 1, maxTurns)) throw this.ingress.refuseThrow(turn, new BufferSessionTurnRefusedError(bufferKey, maxTurns));\n return this.recordTurnUnlocked(bufferKey, turn);\n });\n return this.completeAddTurnOutcome(bufferKey, turn, mutation);\n }\n\n /** Run probes outside the mutation lock to avoid reentrancy deadlocks. */\n private async completeAddTurnOutcome(\n bufferKey: string,\n turn: BufferTurn,\n mutation: AddTurnMutationResult,\n ): Promise<AddTurnOutcome> {\n let decision = mutation.decision;\n let extractionTurns: BufferTurn[] | undefined;\n\n // Surprise-gated flush (issue #563). Additive only: if the probe is\n // disabled, unavailable, or the score is below threshold, the decision\n // from the existing trigger logic stands. The probe only ever *promotes*\n // `keep_buffering` → `extract_now`; it never suppresses an existing\n // flush. This preserves the invariant that enabling surprise cannot\n // *reduce* extraction frequency.\n if (\n decision === \"keep_buffering\" &&\n resolvePresentationCapabilities(this.config).bufferSurpriseTrigger &&\n this.surpriseProbe !== null &&\n // Matching the existing \"smart\" branch: surprise is a lower-tier\n // novelty signal that should not second-guess a high-signal hit\n // (which already flushes) or fight `every_n` / `time_based` modes.\n this.config.triggerMode === \"smart\" &&\n mutation.signalLevel !== \"high\"\n ) {\n const surprise = await this.computeSurpriseSafe(bufferKey, turn, mutation.priorTurns);\n if (surprise !== null) {\n const shouldPromote = surprise > this.config.bufferSurpriseThreshold;\n let triggered = false;\n if (shouldPromote) {\n const currentTurns = await this.getExtractionTurnsIfBufferSnapshotStillCurrent(\n bufferKey,\n mutation.activeTurnsSnapshot,\n mutation.retainedTurnsSnapshot,\n );\n if (currentTurns) {\n log.debug(\n `buffer[${bufferKey}]: surprise=${surprise.toFixed(3)} > threshold=${this.config.bufferSurpriseThreshold} → extract_now`,\n );\n decision = \"extract_now\";\n triggered = true;\n extractionTurns = currentTurns;\n // Issue #1909 (review): the record mutation for a `keep_buffering`\n // turn only SCHEDULED a debounced save. Surprise now promotes it to\n // extract_now AFTER that mutation, so force the buffer durable before\n // the caller runs extraction — otherwise state/buffer.json lags the\n // extracted turns by up to the debounce window on a crash. Safe to\n // await here: we are outside the record mutation (deadlock-free).\n // throwOnFailure (round 7 finding 5): match the built-in extract\n // triggers — a failed durability write must NOT silently proceed to\n // extract_now on a non-durable turn.\n await this.flushPendingSave({ throwOnFailure: true });\n } else {\n log.debug(\n `buffer[${bufferKey}]: surprise=${surprise.toFixed(3)} ignored because buffer changed before probe resolved`,\n );\n }\n }\n // Emit telemetry on every scored turn — both triggering and\n // non-triggering — so operators can fit the threshold to real\n // traffic distributions. Fire-and-forget: `addTurn` does NOT\n // await the ledger append, so slow/contended filesystems cannot\n // add JSONL-append latency to every `processTurn`. But we DO\n // serialize writes through a promise chain so concurrent\n // appends settle in wall-clock order — the report path assumes\n // chronological tail rows and reads the most recent as the\n // \"current\" threshold.\n //\n // Project only the fields we need into the queue entry rather\n // than capturing the full `BufferTurn` — under slow filesystem\n // latency the chain can back up, and we must not retain the\n // (potentially large) `turn.content` string for every pending\n // append.\n this.queueSurpriseTelemetryWrite({\n bufferKey,\n turnRole: turn.role,\n sessionKey:\n typeof turn.sessionKey === \"string\" ? turn.sessionKey : null,\n surpriseScore: surprise,\n triggered,\n turnCountInWindow: mutation.turnCountInWindow,\n // Stamp at decision time so backpressure on the write chain\n // does not shift the event's apparent moment away from when\n // the turn was actually scored.\n timestamp: new Date().toISOString(),\n // Snapshot the threshold used to compute `triggered` so a\n // concurrent config mutation cannot retroactively change\n // what the ledger row claims the decision was against.\n threshold: this.config.bufferSurpriseThreshold,\n });\n }\n }\n\n log.debug(\n `buffer[${bufferKey}]: ${mutation.turnCountInWindow} turns, signal=${mutation.signalLevel}, decision=${decision}`,\n );\n if (decision !== \"keep_buffering\" && extractionTurns === undefined) {\n extractionTurns = [\n ...mutation.retainedTurnsSnapshot,\n ...mutation.activeTurnsSnapshot,\n ];\n }\n return extractionTurns ? { decision, extractionTurns } : { decision };\n }\n\n private async recordTurnUnlocked(bufferKey: string, turn: BufferTurn): Promise<AddTurnMutationResult> {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n const signal = scanSignals(turn.content, this.config.highSignalPatterns);\n // #3444: observe BEFORE the push so a lazily rebuilt digest memo cannot\n // see the current turn (it must only flag turns already in the entry).\n this.ingress.noteAppendedTurn(entry, turn);\n entry.turns.push(turn);\n const decision = evaluateTriggerDecision(this.config, entry, signal.level);\n // Snapshots serve only extraction decisions and surprise-eligible keep_buffering turns (probe, smart mode, sub-high signal); steady-state buffering copies nothing.\n const surpriseEligible = this.surpriseProbe !== null && this.config.triggerMode === \"smart\" && signal.level !== \"high\";\n const snapshotsNeeded = decision !== \"keep_buffering\" || surpriseEligible;\n const priorTurns = snapshotsNeeded ? entry.turns.slice(0, -1) : [];\n const activeTurnsSnapshot = snapshotsNeeded ? entry.turns.map(copyBufferTurn) : [];\n const retainedTurnsSnapshot = snapshotsNeeded ? (entry.retainedTurns ?? []).map(copyBufferTurn) : [];\n if (bufferKey === \"default\") this.state.turns = entry.turns;\n const turnCountInWindow = entry.turns.length;\n\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n if (decision === \"keep_buffering\" && this.config.bufferSaveDebounceMs > 0) {\n // Steady-state buffering: coalesce the whole-state serialize onto a\n // trailing-edge timer (issue #1909) instead of rewriting per turn.\n await this.scheduleSave();\n } else {\n // Persist immediately within this mutation (awaited) when either:\n // - the turn triggered extraction (the buffer must be durable), or\n // - debounce is disabled (bufferSaveDebounceMs <= 0), which reproduces\n // the legacy save-every-turn behavior byte-for-byte.\n // Round 8 thread 4: the write is attempted BEFORE the pending state is\n // cleared, and a failed write leaves it pending (+ a re-armed timer) for\n // shutdown/timer retry instead of dropping the in-memory turns.\n // #3389: a keep_buffering turn has no extraction barrier, so this pass\n // may defer rewriting a large session file that was just persisted —\n // the rewrite cadence for huge sessions collapses from per-turn to\n // once per BUFFER_SESSION_DEFER_INTERVAL_MS. A triggering turn is a\n // durability barrier and passes allowDeferral: false.\n await this.saveNowRetainingPendingOnFailure(\"recordTurn\", { allowDeferral: decision === \"keep_buffering\" });\n }\n return {\n decision,\n signalLevel: signal.level,\n priorTurns,\n activeTurnsSnapshot,\n retainedTurnsSnapshot,\n turnCountInWindow,\n };\n }\n\n private async getExtractionTurnsIfBufferSnapshotStillCurrent(\n bufferKey: string,\n activeTurnsSnapshot: readonly BufferTurn[],\n retainedTurnsSnapshot: readonly BufferTurn[],\n ): Promise<BufferTurn[] | null> {\n return this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.peekEntry(bufferKey);\n if (!entry) return null;\n const retained = entry.retainedTurns ?? [];\n const stillCurrent =\n bufferTurnArrayIsSuffixOfSnapshot(entry.turns, activeTurnsSnapshot) &&\n bufferTurnArraysEqual(retained, retainedTurnsSnapshot);\n if (!stillCurrent) return null;\n return [...retained, ...entry.turns];\n });\n }\n\n /**\n * Enqueue a telemetry append on the serialized write chain.\n *\n * The chain is a classic `writeChain = writeChain.then(fn).catch(...)`\n * — each link waits for the previous to settle before its append\n * starts, so out-of-order chronology cannot happen even under\n * variable filesystem latency. We always attach `.catch` so one\n * rejection does not poison the chain for the rest of the session\n * (CLAUDE.md rule #40). The error is logged through\n * `emitSurpriseEventSafe` itself, which swallows its own rejections.\n *\n * Public surface is deliberately narrow — only `addTurn` should call\n * this, so the surprise telemetry path stays centralized.\n */\n private queueSurpriseTelemetryWrite(params: SurpriseTelemetryQueueEntry): void {\n this.surpriseTelemetryWriteChain = this.surpriseTelemetryWriteChain\n .then(() => this.emitSurpriseEventSafe(params))\n .catch(() => {\n // `emitSurpriseEventSafe` already handles the logging. We\n // swallow here only so one failure does not break the chain\n // for future writes.\n });\n }\n\n /**\n * Append a single `BUFFER_SURPRISE` telemetry row (issue #563 PR 3).\n *\n * Deliberately swallows write errors: the buffer must never fail to\n * record a turn because the observation ledger is read-only, out of\n * disk, or otherwise unhappy. The log line at debug lets operators\n * confirm the path fired without polluting the error channel.\n */\n private async emitSurpriseEventSafe(\n params: SurpriseTelemetryQueueEntry,\n ): Promise<void> {\n const storage = this.storage;\n if (typeof storage.appendBufferSurpriseEvents !== \"function\") {\n // Older StorageManager / test double without the telemetry sink.\n // Silently skip — core path is still covered by the log line above.\n return;\n }\n const event: BufferSurpriseEvent = {\n event: \"BUFFER_SURPRISE\",\n // Use the decision-time stamp captured when the event was\n // queued, NOT `Date.now()` here — backpressure on the write\n // chain could otherwise shift timestamps into the future relative\n // to when the turn was scored.\n timestamp: params.timestamp,\n bufferKey: params.bufferKey,\n sessionKey: params.sessionKey,\n turnRole: params.turnRole,\n surpriseScore: params.surpriseScore,\n // Use the snapshotted threshold from the queue entry, not the\n // live config — see `SurpriseTelemetryQueueEntry.threshold`\n // doc for the rationale.\n threshold: params.threshold,\n triggeredFlush: params.triggered,\n turnCountInWindow: params.turnCountInWindow,\n };\n try {\n await storage.appendBufferSurpriseEvents([event]);\n } catch (err) {\n // Same guard as `computeSurpriseSafe`: non-Error rejections must\n // not crash the telemetry helper, which would defeat the whole\n // point of isolating the ledger write from the hot path.\n log.debug(\n `buffer[${params.bufferKey}]: surprise telemetry write failed, continuing: ${describeError(err)}`,\n );\n }\n }\n\n /**\n * Invoke the injected surprise probe defensively. Any error (probe throws,\n * embedder unavailable, timeout) is swallowed and logged at debug: the\n * surprise path must never crash the happy-path trigger evaluation. A\n * `null` return indicates \"no score available, fall through to existing\n * triggers\".\n */\n private async computeSurpriseSafe(\n bufferKey: string,\n turn: BufferTurn,\n priorTurns: readonly BufferTurn[],\n ): Promise<number | null> {\n if (!this.surpriseProbe) return null;\n try {\n // Hard timeout around the probe so a hung embedder cannot stall\n // `addTurn()` before `save()`. A slow probe would otherwise\n // prevent the just-appended turn from ever being persisted. The\n // timeout is a soft bound — we race it against the probe, take\n // whichever settles first, and treat the timeout as\n // \"probe unavailable, fall through\" rather than an error that\n // surfaces to the caller.\n const score = await probeWithTimeout(\n this.surpriseProbe.scoreTurn(bufferKey, turn, priorTurns),\n this.config.bufferSurpriseProbeTimeoutMs,\n );\n if (score === null) return null;\n if (typeof score !== \"number\" || !Number.isFinite(score)) {\n log.debug(\n `buffer[${bufferKey}]: surprise probe returned non-finite score (${String(score)}), ignoring`,\n );\n return null;\n }\n // Defensive clamp: formula lives in buffer-surprise.ts, but we never\n // want a misbehaving probe to inject an out-of-range value into the\n // threshold comparison.\n if (score < 0) return 0;\n if (score > 1) return 1;\n return score;\n } catch (err) {\n // `err` may be any thrown value — `throw null` and\n // `Promise.reject(\"x\")` are both legal. Accessing `.message` on a\n // non-Error would itself throw and defeat the failure-isolation\n // contract, so describe the value safely.\n log.debug(\n `buffer[${bufferKey}]: surprise probe failed, falling back to existing triggers: ${describeError(err)}`,\n );\n return null;\n }\n }\n\n getTurns(bufferKey = \"default\"): BufferTurn[] {\n const entry = this.peekEntry(bufferKey);\n if (!entry) return [];\n const retained = entry.retainedTurns ?? [];\n // Retained turns (from a previous defer verdict, issue #562 PR 2) are\n // prepended so the chronological order — oldest context first — is\n // preserved for the next extraction pass.\n return [...retained, ...entry.turns];\n }\n\n /**\n * Retain a subset of the current turns across `clearAfterExtraction` so a\n * future extraction pass sees the context behind a deferred candidate\n * (issue #562, PR 2). Callers pass the turns that were seen during the\n * current extraction; the buffer keeps the tail (latest `max` turns) as\n * the retention window. Passing an empty array or `max <= 0` clears the\n * retention slot instead.\n */\n async retainDeferredTurns(\n bufferKey: string,\n turns: BufferTurn[],\n max = 10,\n originalTurns?: readonly BufferTurn[],\n ): Promise<void> {\n await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n const retained = selectRetainedDeferredTurns(\n entry.retainedTurns ?? [], turns, max, originalTurns,\n );\n if (retained.length > 0) entry.retainedTurns = retained;\n else delete entry.retainedTurns;\n this.persistence.markDirty(bufferKey);\n await this.saveUnlocked();\n });\n }\n\n /**\n * Return the current retention window (issue #562, PR 2). Primarily for\n * tests and diagnostics.\n */\n getRetainedDeferredTurns(bufferKey = \"default\"): BufferTurn[] { const entry = this.peekEntry(bufferKey); return entry?.retainedTurns ? [...entry.retainedTurns] : []; }\n\n /**\n * Clear deferred retention copies for a force-flushed session. Normal\n * extraction preserves these copies so a deferred candidate can be retried;\n * an explicit force flush is the caller's request to drain that context.\n */\n async clearRetainedTurnsForSession(\n sessionKey: string,\n ownerPrincipal?: string,\n options: RetainedTurnCleanupOptions = {},\n ): Promise<void> {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return;\n const normalizedOwnerPrincipal =\n typeof ownerPrincipal === \"string\" && ownerPrincipal.trim().length > 0\n ? ownerPrincipal.trim()\n : undefined;\n const namespacesEnabled = resolveNamespaceCapabilities(this.config).namespaces === true;\n const normalizedCleanupNamespace =\n namespacesEnabled && options.writeNamespaceOverride !== undefined && options.writeNamespaceOverride.length > 0\n ? options.writeNamespaceOverride\n : undefined;\n const assertLifecycle = (): void => {\n throwIfAborted(options.abortSignal, \"extraction force-flush aborted\");\n if (typeof options.deadlineMs === \"number\" && Date.now() >= options.deadlineMs) {\n throw new ExtractionDeadlineError(\"retained_turn_cleanup\");\n }\n };\n assertLifecycle();\n await this.enqueueMutation(async () => {\n assertLifecycle();\n const hadPendingSave = this.pendingSave;\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.loadUnlocked();\n assertLifecycle();\n const bufferKeys = matchingSessionBufferKeys(\n this.state.entries ?? {},\n this.peekEntry(sessionKey),\n sessionKey,\n );\n if (bufferKeys.length === 0) {\n if (hadPendingSave) {\n assertLifecycle();\n await this.saveNowRetainingPendingOnFailure(\"clearRetainedTurnsForSession\");\n }\n return;\n }\n let changed = false;\n const matchesCleanupScope = (turn: BufferTurn): boolean => {\n // Legacy unpinned turns keep their existing cleanup semantics.\n if (\n turn.writeNamespaceOverride !== undefined &&\n normalizedCleanupNamespace !== undefined &&\n turn.writeNamespaceOverride !== normalizedCleanupNamespace\n ) {\n return false;\n }\n // Equal write namespaces can still belong to different project bindings.\n if (options.scopeProfileWritePlan && hasPinnedCaptureScope(turn)) {\n if (\n scopeProfilePlanIdentity(turn.scopeProfileWritePlan) !== scopeProfilePlanIdentity(options.scopeProfileWritePlan) &&\n !(turn.acceptedCapture === true && turn.scopeProfileWritePlan === undefined)\n ) {\n return false;\n }\n const ctx = options.codingContext;\n if (\n ctx && turn.codingContext &&\n (turn.codingContext.projectId !== ctx.projectId ||\n turn.codingContext.rootPath !== ctx.rootPath ||\n turn.codingContext.branch !== ctx.branch ||\n turn.codingContext.defaultBranch !== ctx.defaultBranch)\n ) {\n return false;\n }\n }\n return true;\n };\n const belongsToOwner = (turn: BufferTurn): boolean => {\n if (turn.sessionKey !== sessionKey) return false;\n if (!matchesCleanupScope(turn)) return false;\n if (normalizedOwnerPrincipal === undefined) return true;\n if (turn.sessionOwnerPrincipal === normalizedOwnerPrincipal) return true;\n return (\n turn.sessionOwnerPrincipal === undefined &&\n resolvePrincipal(turn.sessionKey, this.config) === normalizedOwnerPrincipal\n );\n };\n for (const bufferKey of bufferKeys) {\n const entry = this.entryFor(bufferKey);\n const retainedTurns = entry.retainedTurns ?? [];\n const remainingTurns = retainedTurns.filter((turn) => !belongsToOwner(turn));\n if (remainingTurns.length === retainedTurns.length) continue;\n changed = true;\n if (remainingTurns.length > 0) entry.retainedTurns = remainingTurns;\n else delete entry.retainedTurns;\n if (bufferKey === \"default\") this.state.turns = entry.turns;\n this.persistence.markDirty(bufferKey);\n }\n if (changed || hadPendingSave) {\n assertLifecycle();\n await this.saveNowRetainingPendingOnFailure(\"clearRetainedTurnsForSession\");\n }\n assertLifecycle();\n });\n }\n\n async findBufferKeyForSession(sessionKey: string): Promise<string | null> {\n const bufferKeys = await this.findBufferKeysForSession(sessionKey);\n return bufferKeys[0] ?? null;\n }\n\n async findBufferKeysForSession(sessionKey: string): Promise<string[]> {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return [];\n await this.mutationChain.catch(() => {});\n await this.load();\n return matchingSessionBufferKeys(\n this.state.entries ?? {},\n this.peekEntry(sessionKey),\n sessionKey,\n );\n }\n\n async clearAfterExtraction(\n bufferKey = \"default\",\n extractedTurns?: readonly BufferTurn[],\n options?: { allowNonPrefix?: boolean },\n ): Promise<void> {\n await this.enqueueMutation(async () => {\n // Drop any armed debounce TIMER so it cannot fire mid-mutation and race\n // our post-clear write, but KEEP the pending-save state (issue #1909\n // review round 13): the post-clear save below can fail, and clearing the\n // pending flag here would strand buffered turns — including turns from\n // OTHER sessions that only ever entered the debounced pending state — with\n // nothing left to retry them. saveNowRetainingPendingOnFailure clears the\n // pending state only after a durable write, or re-arms it on failure.\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n if (Array.isArray(extractedTurns)) {\n const liveExtractedTurns = liveTurnsFromExtractionSnapshot(\n entry,\n extractedTurns,\n );\n let clearedLiveTurns = false;\n if (liveExtractedTurns.length > 0) {\n if (options?.allowNonPrefix === true) {\n const remainingTurns = [...entry.turns];\n for (const extractedTurn of liveExtractedTurns) {\n const matchingIndex = remainingTurns.findIndex((liveTurn) =>\n bufferTurnsEqual(liveTurn, extractedTurn),\n );\n if (matchingIndex >= 0) {\n remainingTurns.splice(matchingIndex, 1);\n clearedLiveTurns = true;\n }\n }\n if (clearedLiveTurns) entry.turns = remainingTurns;\n } else {\n const matchedCount = matchingQueuedExtractionPrefixLength(\n entry.turns,\n liveExtractedTurns,\n );\n if (matchedCount > 0) {\n entry.turns = entry.turns.slice(matchedCount);\n clearedLiveTurns = true;\n }\n }\n if (!clearedLiveTurns) {\n log.debug(\n `buffer[${bufferKey}]: extraction clear skipped because live turns changed before clear`,\n );\n }\n }\n if (!clearedLiveTurns) {\n await this.saveNowRetainingPendingOnFailure(\"clearAfterExtraction\");\n return;\n }\n } else {\n entry.turns = [];\n }\n entry.lastExtractionAt = new Date().toISOString();\n entry.extractionCount += 1;\n if (bufferKey === \"default\") {\n this.state.turns = entry.turns;\n this.state.lastExtractionAt = entry.lastExtractionAt;\n this.state.extractionCount = entry.extractionCount;\n }\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n await this.saveNowRetainingPendingOnFailure(\"clearAfterExtraction\");\n });\n }\n\n /**\n * Remove an extraction-window chunk from the buffer WITHOUT recording an\n * extraction (trigger-drain drop path). Used when a chunk fails extraction\n * repeatedly and must be dropped so the session can drain; the caller is\n * responsible for the side-file copy and logging. Returns the number of\n * live turns dropped; 0 when the turns no longer match. `allowNonPrefix`\n * matches by identity, like `clearAfterExtraction`, for callers (native\n * groups) whose chunk can sit behind a pinned capture.\n */\n async dropExtractionChunk(\n bufferKey = \"default\",\n turns: readonly BufferTurn[],\n options?: { allowNonPrefix?: boolean },\n ): Promise<number> {\n return await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n // A window's head can be deferred-retained turns (retainDeferredTurns): take those out of the chunk first.\n const retained = [...(entry.retainedTurns ?? [])];\n const liveTurns: BufferTurn[] = [];\n for (const turn of turns) {\n const at = retained.findIndex((kept) => bufferTurnsEqual(kept, turn));\n if (at >= 0) retained.splice(at, 1);\n else liveTurns.push(turn);\n }\n const retainedDropped = (entry.retainedTurns?.length ?? 0) - retained.length;\n let remaining = entry.turns;\n if (options?.allowNonPrefix === true) {\n remaining = [...entry.turns];\n for (const turn of liveTurns) {\n const at = remaining.findIndex((live) => bufferTurnsEqual(live, turn));\n if (at >= 0) remaining.splice(at, 1);\n }\n } else {\n remaining = entry.turns.slice(matchingQueuedExtractionPrefixLength(entry.turns, liveTurns));\n }\n const matchedCount = entry.turns.length - remaining.length + retainedDropped;\n if (matchedCount === 0) return 0;\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n entry.turns = remaining;\n if (retainedDropped > 0) {\n if (retained.length > 0) entry.retainedTurns = retained;\n else delete entry.retainedTurns;\n }\n if (bufferKey === \"default\") {\n this.state.turns = entry.turns;\n }\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n await this.saveNowRetainingPendingOnFailure(\"dropExtractionChunk\");\n return matchedCount;\n });\n }\n\n getExtractionCount(bufferKey = \"default\"): number { return this.peekEntry(bufferKey)?.extractionCount ?? 0; }\n\n /**\n * Await any pending `BUFFER_SURPRISE` telemetry writes.\n *\n * The telemetry path is fire-and-forget from the hot path's point of\n * view, but tests and before-exit hooks sometimes need to make sure\n * the ledger has been flushed before they assert on its contents or\n * close the process. This method resolves once the current chain\n * head has settled; new writes scheduled after this call return a\n * separate, later settlement.\n *\n * Never throws — the chain already catches its own rejections.\n */\n async flushSurpriseTelemetry(): Promise<void>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;AAAA,MAC5F;AACA,YAAM,eAAe,MAAM,MAAM,SAAS,UAAU,SAAS;AAC7D,UAAI,iBAAiB,EAAG,QAAO;AAC/B,UAAI,KAAK,WAAW;AAClB,qBAAa,KAAK,SAAS;AAC3B,aAAK,YAAY;AAAA,MACnB;AACA,YAAM,QAAQ;AACd,UAAI,kBAAkB,GAAG;AACvB,YAAI,SAAS,SAAS,EAAG,OAAM,gBAAgB;AAAA,YAC1C,QAAO,MAAM;AAAA,MACpB;AACA,UAAI,cAAc,WAAW;AAC3B,aAAK,MAAM,QAAQ,MAAM;AAAA,MAC3B;AACA,WAAK,YAAY,UAAU,SAAS;AACpC,WAAK,aAAa,CAAC,SAAS,CAAC;AAC7B,YAAM,KAAK,iCAAiC,qBAAqB;AACjE,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAAA,EAEA,mBAAmB,YAAY,WAAmB;AAAE,WAAO,KAAK,UAAU,SAAS,GAAG,mBAAmB;AAAA,EAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc5G,MAAM,yBAAwC;AAC5C,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { realpath } from \"node:fs/promises\";\nimport { listJsonFilesStrict, readJsonFile } from \"./json-store.js\";\nimport { raceAbort, throwIfAborted } from \"./abort-error.js\";\nimport { log } from \"./logger.js\";\nimport { readHarmonicGraphStamp } from \"./harmonic-graph-version.js\";\nimport { inferMemoryStatus, toMemoryPathRel } from \"./memory-lifecycle-ledger-utils.js\";\n import {\n HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY,\n resolveAbstractionNodeStoreDir,\n validateAbstractionNode,\n type AbstractionNode,\n } from \"./abstraction-nodes.js\";\nimport { resolveCueAnchorStoreDir, validateCueAnchor, type CueAnchor, type CueAnchorType } from \"./cue-anchors.js\";\nimport { compareDeterministicStrings } from \"./deterministic-order.js\";\nimport { normalizeRecallTokenSet, normalizeRecallTokens } from \"./recall-tokenization.js\";\nimport { stripAttributesSuffix } from \"./structured-attributes.js\";\nimport { isValidityExpiredNow } from \"./temporal-validity.js\";\nimport { assertSafePathSegment, isRecord } from \"./store-contract.js\";\nimport { isSupportPassportPrivateMemory } from \"./support-passport/card-projection.js\";\nimport type { MemoryFile } from \"./types.js\";\nimport { readProjectedMemoryStates } from \"./memory-projection-batch.js\";\nimport { SecureStoreLockedError } from \"./secure-store/secure-fs.js\";\nimport { StorageManager } from \"./storage.js\";\nimport { RECALL_FALLBACK_DIRS } from \"./utils/category-dir.js\";\nimport { readHarmonicSourceMemory, readUnresolvedHarmonicSources } from \"./harmonic-source-lookup.js\";\nimport { mapInBatches } from \"./map-in-batches.js\";\n\n\ntype SourceMemoryMap = Map<string, MemoryFile>;\n\n\n// An index older than this is treated as unusable: the date window needed to\n// cover \"created since the last rebuild\" would stop being cheap.\nconst INDEX_MAX_AGE_MS = 7 * 86_400_000;\nconst DAY_MS = 86_400_000;\n\nfunction utcDaysSince(rebuiltMs: number, nowMs: number): string[] {\n const days: string[] = [];\n for (let day = Math.floor((rebuiltMs - DAY_MS) / DAY_MS) * DAY_MS; day <= nowMs; day += DAY_MS) {\n days.push(new Date(day).toISOString().slice(0, 10));\n }\n return days;\n}\n\n\n// Memories the projection has no row for were written after its last rebuild, so\n// their dated directory is normally one of `days`. Hot and cold tiers are probed\n// by exact path. Only recall-corpus categories are probed: `questions/` is a queue\n// and `artifacts/` is outside the recall surface, so neither can be a source.\nfunction unprojectedCandidatePaths(memoryDir: string, id: string, days: string[]): string[] {\n const paths: string[] = [];\n for (const root of [memoryDir, path.join(memoryDir, \"cold\")]) {\n for (const dir of RECALL_FALLBACK_DIRS) {\n paths.push(path.join(root, dir, `${id}.md`));\n for (const day of days) paths.push(path.join(root, dir, day, `${id}.md`));\n }\n }\n return paths;\n}\n\n/** Resolve indexed sources first, then use the durable unresolved-id path cache. */\nasync function readIndexedSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs: number;\n}): Promise<SourceMemoryMap | null> {\n // The ids go to SQL as bound parameters, so any id the projection holds is safe to look up.\n const batch = readProjectedMemoryStates(options.memoryDir, options.sourceMemoryIds);\n const rebuiltMs = Date.parse(batch?.rebuiltAt ?? \"\");\n if (!batch?.complete || !batch.rebuiltAt || !Number.isFinite(rebuiltMs) || options.nowMs - rebuiltMs > INDEX_MAX_AGE_MS) return null;\n const rootReal = await realpath(options.memoryDir).catch(() => null);\n if (rootReal === null) return null;\n\n const storage = new StorageManager(options.memoryDir);\n const days = utcDaysSince(rebuiltMs, options.nowMs);\n const sourceMemories: SourceMemoryMap = new Map();\n const pending: string[] = [];\n const resolved = await mapInBatches(options.sourceMemoryIds, async (id) => {\n const state = batch.states.get(id);\n // An id is only ever joined into a path when it is a single safe segment.\n let safeId = true;\n try {\n assertSafePathSegment(id, \"sourceMemoryId\");\n } catch {\n safeId = false;\n }\n // state.path was containment-checked by the projection reader.\n const candidates = state\n ? [state.path, path.join(options.memoryDir, \"cold\", state.pathRel)]\n : safeId ? unprojectedCandidatePaths(options.memoryDir, id, days) : [];\n for (const candidate of candidates) {\n const memory = await readHarmonicSourceMemory(storage, rootReal, candidate, options.abortSignal);\n if (memory?.frontmatter.id !== id) continue;\n return { id, memory };\n }\n return { id, memory: undefined };\n });\n for (const { id, memory } of resolved) {\n if (memory) sourceMemories.set(id, memory);\n else pending.push(id);\n }\n if (pending.length === 0) return sourceMemories;\n\n const unresolved = await readUnresolvedHarmonicSources({\n storage, rootReal, rebuiltAt: batch.rebuiltAt, sourceMemoryIds: pending,\n nowMs: options.nowMs, abortSignal: options.abortSignal,\n });\n for (const [id, memory] of unresolved) sourceMemories.set(id, memory);\n return sourceMemories;\n}\n\nasync function readCorpusSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n}): Promise<SourceMemoryMap> {\n const sourceMemories: SourceMemoryMap = new Map();\n try {\n const storage = new StorageManager(options.memoryDir);\n const [hotMemories, coldMemories] = await Promise.all([\n storage.readAllMemories({ abortSignal: options.abortSignal }),\n storage.readAllColdMemories({ abortSignal: options.abortSignal }),\n ]);\n for (const memory of [...hotMemories, ...coldMemories]) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n sourceMemories.set(memory.frontmatter.id, memory);\n }\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n // Source validation fails closed when the authorized memory directory is\n // unreadable. Source-less nodes remain eligible for retrieval.\n sourceMemories.clear();\n }\n return sourceMemories;\n}\n\nasync function readSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs?: number;\n}): Promise<SourceMemoryMap> {\n try {\n const indexed = await readIndexedSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds: options.sourceMemoryIds,\n nowMs: options.nowMs ?? Date.now(),\n });\n if (indexed) return indexed;\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n }\n return readCorpusSourceMemories(options);\n}\n\nfunction parseSourceMemoryInsertedAt(node: AbstractionNode): Map<string, string> {\n const insertedAtById = new Map<string, string>();\n const insertedAtRaw = node.metadata?.[HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY];\n if (!insertedAtRaw) return insertedAtById;\n try {\n const parsed = JSON.parse(insertedAtRaw) as unknown;\n if (!isRecord(parsed)) return insertedAtById;\n for (const [memoryId, value] of Object.entries(parsed)) {\n if (typeof value === \"string\") insertedAtById.set(memoryId, value);\n }\n } catch {\n // Malformed insertion metadata leaves ordering on the recordedAt fallback.\n }\n return insertedAtById;\n}\n\n/**\n * Whether a source memory can back a projected node at all. Shared with `earliestInvalidAtMs`, so the cache\n * deadline only follows a source that the projection would use.\n * #2332: a private support-passport record leaves the eligible set the same way a rejected one does — a node\n * title or anchor attribution rebuilt from it would leak governed metadata into the deep-recall frontier (and\n * every other graph reader) before any content check runs.\n */\nfunction isEligibleSourceMemory(memory: MemoryFile, memoryDir: string): boolean {\n return (\n !isSupportPassportPrivateMemory(memory) &&\n inferMemoryStatus(memory.frontmatter, toMemoryPathRel(memoryDir, memory.path)) === \"active\"\n );\n}\n\nfunction projectSourceBackedNode(\n node: AbstractionNode,\n sourceMemories: SourceMemoryMap,\n memoryDir: string,\n temporalExpiredInInjection: boolean,\n nowMs: number\n): AbstractionNode | null {\n const sourceMemoryIds = node.sourceMemoryIds ?? [];\n if (sourceMemoryIds.length === 0) return node;\n\n const activeSourceMemoryIds = sourceMemoryIds.filter((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return (\n memory !== undefined &&\n isEligibleSourceMemory(memory, memoryDir) &&\n (temporalExpiredInInjection || !isValidityExpiredNow(memory.frontmatter, nowMs))\n );\n });\n if (activeSourceMemoryIds.length === 0) return null;\n\n // Newest-first source order keeps the projected title and summary on the most\n // recently inserted facts. Equal or missing timestamps fall back to ascending\n // id order, which matches the stored sourceMemoryIds order.\n const insertedAtById = parseSourceMemoryInsertedAt(node);\n const insertedAtMs = (memoryId: string): number => {\n const parsedMs = Date.parse(insertedAtById.get(memoryId) ?? \"\");\n return Number.isFinite(parsedMs) ? parsedMs : Date.parse(node.recordedAt);\n };\n activeSourceMemoryIds.sort(\n (left, right) =>\n insertedAtMs(right) - insertedAtMs(left) || compareDeterministicStrings(left, right)\n );\n\n const activeMemories = activeSourceMemoryIds.flatMap((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return memory ? [memory] : [];\n });\n const activeContents = activeMemories.map((memory) =>\n memory.frontmatter.structuredAttributes ? stripAttributesSuffix(memory.content) : memory.content\n );\n let metadata: Record<string, string> | undefined;\n const activeInsertedAt = activeSourceMemoryIds.flatMap((memoryId) => {\n const value = insertedAtById.get(memoryId);\n return typeof value === \"string\" ? [[memoryId, value] as const] : [];\n });\n if (activeInsertedAt.length > 0) {\n metadata = {\n [HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY]: JSON.stringify(Object.fromEntries(activeInsertedAt)),\n };\n }\n\n return {\n ...node,\n sourceMemoryIds: activeSourceMemoryIds,\n title: activeContents[0]?.slice(0, 80) ?? node.title,\n summary: activeContents.slice(0, 3).join(\"; \").slice(0, 400),\n tags: [...new Set(activeMemories.flatMap((memory) => memory.frontmatter.tags))].sort(compareDeterministicStrings),\n entityRefs: [\n ...new Set(\n activeMemories.flatMap((memory) =>\n typeof memory.frontmatter.entityRef === \"string\" ? [memory.frontmatter.entityRef] : []\n )\n ),\n ].sort(compareDeterministicStrings),\n metadata,\n };\n}\n\nfunction anchorMatchesProjectedNode(\n anchor: CueAnchor,\n nodeRef: string,\n node: AbstractionNode,\n allowLegacyAttribution: boolean\n): boolean {\n const activeSourceMemoryIds = node.sourceMemoryIds ?? [];\n if (activeSourceMemoryIds.length === 0) return true;\n if (!anchor.sourceMemoryIdsByNodeRef) return allowLegacyAttribution;\n const anchorSourceMemoryIds = anchor.sourceMemoryIdsByNodeRef[nodeRef] ?? [];\n return anchorSourceMemoryIds.some((sourceMemoryId) => activeSourceMemoryIds.includes(sourceMemoryId));\n}\n\nexport interface HarmonicMatchedAnchor {\n anchorId: string;\n anchorType: CueAnchorType;\n anchorValue: string;\n}\n\nexport interface HarmonicRetrievalResult {\n node: AbstractionNode;\n score: number;\n nodeScore: number;\n anchorScore: number;\n matchedFields: string[];\n matchedAnchors: HarmonicMatchedAnchor[];\n}\n\ninterface HarmonicCandidate {\n node: AbstractionNode;\n nodeScore: number;\n anchorScore: number;\n matchedFields: Set<string>;\n matchedAnchors: Map<string, HarmonicMatchedAnchor>;\n}\n\nfunction tokenOverlap(queryTokens: Set<string>, fieldTokens: ReadonlySet<string>): number {\n let matches = 0;\n for (const token of queryTokens) {\n if (fieldTokens.has(token)) matches += 1;\n }\n return matches;\n}\n\ninterface HarmonicNodeTokens {\n title: ReadonlySet<string>;\n summary: ReadonlySet<string>;\n tags: ReadonlySet<string>;\n entities: ReadonlySet<string>;\n kind: ReadonlySet<string>;\n}\n\ninterface HarmonicAnchorTokens {\n value: ReadonlySet<string>;\n normalized: ReadonlySet<string>;\n type: ReadonlySet<string>;\n eligibleTags: ReadonlySet<string>;\n}\n\ninterface HarmonicSearchIndex {\n nodesById: Map<string, AbstractionNode>;\n nodeTokens: HarmonicNodeTokens[];\n anchorTokens: HarmonicAnchorTokens[];\n}\n\nexport const harmonicSearchIndexStats = { builds: 0 };\n\n/**\n * Per-graph scoring index, keyed on the frozen graph object itself. Scoring a\n * recall tokenizes every node's title/summary/tags/entities/kind and every\n * anchor's value/cue/type/eligible tags; on a cache hit that repeated the\n * whole normalization for each recall (~0.75 s on a ~2.5k node, ~10k anchor\n * corpus, issue #3450). The sets are identical to what `countRecallTokenOverlap`\n * computed from the raw fields, so scores and matchedFields are unchanged.\n * For an uncached graph the index is built per call — the same work the old\n * code did inline.\n */\nconst harmonicSearchIndexes = new WeakMap<ProjectedHarmonicGraph, HarmonicSearchIndex>();\n\nfunction getHarmonicSearchIndex(graph: ProjectedHarmonicGraph): HarmonicSearchIndex {\n const cached = harmonicSearchIndexes.get(graph);\n if (cached) return cached;\n harmonicSearchIndexStats.builds += 1;\n const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));\n // Node ids are only unique per record day (nodes/<day>/<nodeId>.json), so\n // tokens are indexed by position in graph.nodes.\n const nodeTokens = graph.nodes.map((node) => ({\n title: normalizeRecallTokenSet(node.title ?? \"\"),\n summary: normalizeRecallTokenSet(node.summary ?? \"\"),\n tags: normalizeRecallTokenSet(node.tags?.join(\" \") ?? \"\"),\n entities: normalizeRecallTokenSet(node.entityRefs?.join(\" \") ?? \"\"),\n kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`),\n }));\n // Anchor ids are only unique per anchorType (cue-anchors dedups by\n // type+id), so tokens are indexed by position in graph.anchors.\n const anchorTokens = graph.anchors.map((anchor) => {\n const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));\n const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];\n return {\n value: normalizeRecallTokenSet(anchor.anchorValue ?? \"\"),\n normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? \"\"),\n type: normalizeRecallTokenSet(anchor.anchorType),\n eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(\" \")),\n };\n });\n const index: HarmonicSearchIndex = { nodesById, nodeTokens, anchorTokens };\n harmonicSearchIndexes.set(graph, index);\n return index;\n}\n\nfunction scoreNode(tokens: HarmonicNodeTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = tokenOverlap(queryTokens, tokens.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = tokenOverlap(queryTokens, tokens.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.tags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = tokenOverlap(queryTokens, tokens.entities);\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = tokenOverlap(queryTokens, tokens.kind);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(tokens: HarmonicAnchorTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = tokenOverlap(queryTokens, tokens.value);\n const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);\n const cueMatches = Math.max(valueMatches, normalizedMatches);\n if (cueMatches > 0) {\n score += cueMatches * 4;\n if (valueMatches > 0) matchedFields.push(\"anchorValue\");\n if (normalizedMatches > 0) matchedFields.push(\"anchor\");\n }\n\n const typeMatches = tokenOverlap(queryTokens, tokens.type);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"anchorTags\");\n }\n\n return { score, matchedFields };\n}\n\nexport async function readAbstractionNodes(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<AbstractionNode[]> {\n const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const files = await listJsonFilesStrict(path.join(rootDir, \"nodes\"), { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateAbstractionNode(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((node): node is AbstractionNode => node !== null);\n}\n\nexport async function readCueAnchors(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<CueAnchor[]> {\n const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const rootDir = resolveCueAnchorStoreDir(abstractionRoot);\n const files = await listJsonFilesStrict(rootDir, { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateCueAnchor(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((anchor): anchor is CueAnchor => anchor !== null);\n}\n\nexport interface ProjectedHarmonicGraph {\n nodes: AbstractionNode[];\n anchors: CueAnchor[];\n}\n\n/**\n * Read nodes + anchors and project BOTH against the namespace's current active\n * memories. This is the single projection every graph reader shares: a raw\n * `readAbstractionNodes` / `readCueAnchors` pair still carries the stored title,\n * summary, tags, and anchor attribution of a memory that was later rejected,\n * quarantined, or otherwise moved out of the active set, so a second reader\n * that skipped the projection could leak governed metadata even when the\n * memory itself is excluded from the final results.\n *\n * - A node whose every source memory left the active set is dropped.\n * - A surviving node's title/summary/tags/entityRefs are rebuilt from its\n * active sources only.\n * - An anchor keeps a node reference only while its attribution runs through\n * one of that node's surviving active sources, and is dropped once no\n * reference survives.\n */\ninterface ExpiringHarmonicGraph extends ProjectedHarmonicGraph {\n /** First instant a source memory's `invalid_at` passes: from then on the graph is wrong without any write. */\n validUntilMs: number;\n}\n\nfunction earliestInvalidAtMs(sourceMemories: SourceMemoryMap, memoryDir: string, nowMs: number): number {\n let earliest = Number.POSITIVE_INFINITY;\n for (const memory of sourceMemories.values()) {\n // An ineligible source drops out of the projection whatever its `invalid_at`, so its deadline changes nothing.\n if (!isEligibleSourceMemory(memory, memoryDir)) continue;\n const invalidAtMs = Date.parse(memory.frontmatter.invalid_at?.trim() ?? \"\");\n if (Number.isFinite(invalidAtMs) && invalidAtMs > nowMs && invalidAtMs < earliest) earliest = invalidAtMs;\n }\n return earliest;\n}\n\nasync function buildProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n const { nodes, anchors } = await buildExpiringHarmonicGraph(options);\n return { nodes, anchors };\n}\n\nasync function buildExpiringHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ExpiringHarmonicGraph> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const buildDelayMs = harmonicGraphBuildTestHooks?.buildDelayMs;\n if (buildDelayMs !== undefined && buildDelayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, buildDelayMs));\n }\n const nodes = await readAbstractionNodes(options);\n const sourceMemoryIds = [...new Set(nodes.flatMap((node) => node.sourceMemoryIds ?? []))];\n const sourceMemories: SourceMemoryMap = sourceMemoryIds.length > 0\n ? await readSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds,\n nowMs: options.nowMs,\n })\n : new Map();\n const nowMs = options.nowMs ?? Date.now();\n // With temporalExpiredInInjection the validity filter is off, so no `invalid_at` can age the graph.\n const validUntilMs = options.temporalExpiredInInjection === true\n ? Number.POSITIVE_INFINITY\n : earliestInvalidAtMs(sourceMemories, options.memoryDir, nowMs);\n // A node whose full stored source set survived projection keeps legacy\n // anchor attribution (an anchor written before per-node source ids existed).\n const legacyCompatibleNodeRefs = new Set<string>();\n const projectedNodes = nodes.flatMap((node) => {\n const projected = projectSourceBackedNode(\n node,\n sourceMemories,\n options.memoryDir,\n options.temporalExpiredInInjection === true,\n nowMs\n );\n if (\n projected &&\n (node.sourceMemoryIds?.length ?? 0) > 0 &&\n projected.sourceMemoryIds?.length === node.sourceMemoryIds?.length\n ) {\n legacyCompatibleNodeRefs.add(node.nodeId);\n }\n return projected ? [projected] : [];\n });\n if (!options.anchorsEnabled) return { nodes: projectedNodes, anchors: [], validUntilMs };\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeIndex = new Map(projectedNodes.map((node) => [node.nodeId, node]));\n const anchors = (await readCueAnchors(options)).flatMap((anchor) => {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeRefs = anchor.nodeRefs.filter((nodeRef) => {\n const node = nodeIndex.get(nodeRef);\n return (\n node !== undefined &&\n anchorMatchesProjectedNode(anchor, nodeRef, node, legacyCompatibleNodeRefs.has(nodeRef))\n );\n });\n return nodeRefs.length > 0 ? [{ ...anchor, nodeRefs }] : [];\n });\n return { nodes: projectedNodes, anchors, validUntilMs };\n}\n\nconst GRAPH_CACHE_TTL_MS = 30_000;\n/**\n * Past the TTL a graph whose stamp is unchanged is still served while a refresh runs behind it, so no\n * recall waits for a rebuild just because the TTL lapsed. This is how long past the TTL; after it the graph is rebuilt first.\n */\nconst GRAPH_CACHE_MAX_STALE_MS = 300_000;\nconst GRAPH_CACHE_MAX_ENTRIES = 8;\n\ninterface GraphCacheEntry {\n stamp: string;\n /** When the build finished, so the TTL measures how long the graph has been available. */\n builtAtMs: number;\n validUntilMs: number;\n graph: ProjectedHarmonicGraph;\n}\n\ninterface GraphBuild {\n stamp: string;\n promise: Promise<ProjectedHarmonicGraph>;\n /** Cancels the build's source scan; fired when no caller is waiting for it. */\n controller: AbortController;\n /** Callers currently waiting for this build. */\n waiting: number;\n}\n\nconst graphCache = new Map<string, GraphCacheEntry>();\n/** One build per cache key at a time: every recall that lands on a miss waits for the same build. */\nconst graphBuilds = new Map<string, GraphBuild>();\n/** When a background refresh last failed, per key: stale reads retry at most once per TTL. Capped like the cache. */\nconst refreshFailedAtMs = new Map<string, number>();\n\nfunction rememberRefreshFailure(key: string): void {\n refreshFailedAtMs.delete(key);\n refreshFailedAtMs.set(key, Date.now());\n while (refreshFailedAtMs.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = refreshFailedAtMs.keys().next().value;\n if (oldest === undefined) break;\n refreshFailedAtMs.delete(oldest);\n }\n}\n\n/**\n * A source's `invalid_at` can pass while the build is still reading anchors, which would hand every caller\n * that joined this build a graph that is already expired. Rebuild until the graph is unexpired at completion.\n * Each round drops the sources that expired, so the set of future deadlines shrinks and the loop ends.\n */\nasync function buildUnexpiredHarmonicGraph(options: GraphReadOptions, abortSignal: AbortSignal): Promise<ExpiringHarmonicGraph> {\n for (;;) {\n const built = await buildExpiringHarmonicGraph({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n anchorsEnabled: options.anchorsEnabled,\n temporalExpiredInInjection: options.temporalExpiredInInjection,\n abortSignal,\n });\n if (Date.now() < built.validUntilMs) return built;\n }\n}\n/** Counters for tests and diagnostics. `stale` hits also count as `hits`. */\nexport const harmonicGraphCacheStats = { hits: 0, misses: 0, stale: 0, shared: 0, deadlineExits: 0 };\n\n/** Default per-caller bound on waiting for a shared graph build (see `waitBudgetMs`). */\nexport const HARMONIC_GRAPH_WAIT_BUDGET_MS = 5_000;\n\nconst HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE = \"harmonic graph wait deadline exceeded\";\n\nexport class HarmonicGraphWaitDeadlineError extends Error {\n constructor() {\n super(HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE);\n this.name = \"HarmonicGraphWaitDeadlineError\";\n }\n}\n\ninterface HarmonicGraphBuildTestHooks {\n /** Extra delay inside every build, for wait-budget tests. */\n buildDelayMs?: number;\n}\nlet harmonicGraphBuildTestHooks: HarmonicGraphBuildTestHooks | null = null;\nexport function setHarmonicGraphBuildTestHooks(hooks: HarmonicGraphBuildTestHooks | null): void {\n harmonicGraphBuildTestHooks = hooks;\n}\n\n/** Freeze records and their nested arrays/objects so a caller cannot corrupt the shared cache. */\nfunction deepFreeze<T extends object>(value: T): T {\n // isFrozen is true for primitives and null, and a frozen value is not revisited, so this ends on cycles too.\n if (Object.isFrozen(value)) return value;\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n return value;\n}\n\nexport function clearHarmonicGraphCache(): void {\n graphCache.clear();\n graphBuilds.clear();\n refreshFailedAtMs.clear();\n}\n\n/**\n * Resolves once every build running now has settled, and after the failure bookkeeping of a background\n * refresh (that handler was attached when the refresh started, so it runs first). For tests: a time-based\n * wait races a slow build.\n */\nexport async function settleHarmonicGraphBuilds(): Promise<void> {\n await Promise.allSettled([...graphBuilds.values()].map((build) => build.promise));\n}\n\ntype GraphReadOptions = Parameters<typeof buildProjectedHarmonicGraph>[0];\n\n/**\n * Start the one build for `key`. The build owns an abort controller instead of using one caller's signal,\n * so a caller that leaves does not cancel it for the others; `joinGraphBuild` cancels it when the last caller leaves.\n */\nfunction startGraphBuild(key: string, stamp: string, options: GraphReadOptions): GraphBuild {\n harmonicGraphCacheStats.misses++;\n const controller = new AbortController();\n const promise: Promise<ProjectedHarmonicGraph> = buildUnexpiredHarmonicGraph(options, controller.signal)\n .then((built) => {\n const graph = { nodes: deepFreeze(built.nodes), anchors: deepFreeze(built.anchors) };\n // A cleared cache or a newer build for this key has replaced this one: do not store a stale graph.\n if (graphBuilds.get(key)?.promise !== promise) return graph;\n refreshFailedAtMs.delete(key);\n graphCache.delete(key);\n graphCache.set(key, { stamp, builtAtMs: Date.now(), validUntilMs: built.validUntilMs, graph });\n while (graphCache.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = graphCache.keys().next().value;\n if (oldest === undefined) break;\n graphCache.delete(oldest);\n }\n return graph;\n })\n .finally(() => {\n if (graphBuilds.get(key)?.promise === promise) graphBuilds.delete(key);\n });\n const build: GraphBuild = { stamp, promise, controller, waiting: 0 };\n graphBuilds.set(key, build);\n return build;\n}\n\n/**\n * Wait for `build` on behalf of one caller. The caller's own signal ends only its own wait. When the last\n * waiting caller has left, the build is cancelled and dropped, so abandoned recalls do not leave full scans running\n * (cancelling a build that already finished does nothing). A caller that leaves on `waitBudgetMs` is the exception:\n * the build keeps running so its completed graph warms the cache for the next caller.\n */\nfunction joinGraphBuild(\n key: string,\n build: GraphBuild,\n signal: AbortSignal | undefined,\n waitBudgetMs?: number,\n): Promise<ProjectedHarmonicGraph> {\n build.waiting++;\n let timedOut = false;\n let timer: NodeJS.Timeout | undefined;\n const waited =\n waitBudgetMs === undefined || waitBudgetMs <= 0\n ? raceAbort(build.promise, signal, \"harmonic retrieval aborted\")\n : Promise.race([\n raceAbort(build.promise, signal, \"harmonic retrieval aborted\"),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new HarmonicGraphWaitDeadlineError());\n }, waitBudgetMs);\n }),\n ]);\n return waited.finally(() => {\n if (timer) clearTimeout(timer);\n build.waiting--;\n // A caller that left on the wait budget does not cancel the build: it keeps\n // running and stores the fresh graph, so the next caller gets a cache hit\n // instead of restarting the scan a write storm keeps invalidating.\n if (timedOut) harmonicGraphCacheStats.deadlineExits++;\n if (build.waiting > 0 || timedOut) return;\n if (graphBuilds.get(key) === build) graphBuilds.delete(key);\n build.controller.abort();\n });\n}\n\n/**\n * `readProjectedHarmonicGraph` with an opt-in in-memory cache. Every recall used\n * to re-read all nodes, anchors and source memories from disk (about 4.7 s on a\n * 2107 node, 9199 anchor, 4105 source graph). With `useCache` a completed graph is\n * reused while the stamp below is unchanged: the memory corpus, memory status and\n * cold-write version sentinels (bumped by every memory write, in any process) and\n * the graph version sentinel (bumped by node and anchor writes). A stamp read is\n * four stats, not a scan of the memories. The TTL bounds the one input a sentinel\n * cannot see, which is wall-clock validity expiry; past it the stale graph is served\n * while one refresh runs (up to GRAPH_CACHE_MAX_STALE_MS). A changed stamp always\n * waits for a fresh build, because a stale graph could carry governed metadata of a\n * memory that left the active set. Concurrent misses share one build. An explicit\n * `nowMs` bypasses the cache so tests stay deterministic. The cached arrays are\n * frozen: callers must not mutate them.\n */\nexport async function readProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n useCache?: boolean;\n /** Per-caller bound on joining a shared build, in ms. On expiry the caller\n * leaves with a HarmonicGraphWaitDeadlineError while the build keeps running.\n * `0` or unset waits without a bound. Applies only on the cached path. */\n waitBudgetMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n if (options.useCache !== true || options.nowMs !== undefined) return buildProjectedHarmonicGraph(options);\n // Same cancellation contract as the builder: a cache hit must not mask an aborted signal.\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeStoreDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const key = JSON.stringify([\n options.memoryDir,\n nodeStoreDir,\n options.anchorsEnabled === true,\n options.temporalExpiredInInjection === true,\n ]);\n // The stamp is read BEFORE the build, so a write that lands mid-build leaves the\n // entry stale and the next call rebuilds.\n const stamp = readHarmonicGraphStamp(options.memoryDir, nodeStoreDir);\n const nowMs = Date.now();\n const hit = graphCache.get(key);\n // A source's `invalid_at` passing changes the projection without bumping the stamp, so it ends the entry\n // at the exact instant, however fresh the entry is.\n if (hit && hit.stamp === stamp && nowMs < hit.validUntilMs && nowMs - hit.builtAtMs < GRAPH_CACHE_TTL_MS + GRAPH_CACHE_MAX_STALE_MS) {\n harmonicGraphCacheStats.hits++;\n graphCache.delete(key);\n graphCache.set(key, hit);\n if (nowMs - hit.builtAtMs >= GRAPH_CACHE_TTL_MS) {\n harmonicGraphCacheStats.stale++;\n const failedAtMs = refreshFailedAtMs.get(key);\n const backingOff = failedAtMs !== undefined && nowMs - failedAtMs < GRAPH_CACHE_TTL_MS;\n if (graphBuilds.get(key)?.stamp !== stamp && !backingOff) {\n startGraphBuild(key, stamp, options).promise.catch((err) => {\n rememberRefreshFailure(key);\n log.debug(`harmonic graph refresh failed: ${err}`);\n });\n }\n }\n return hit.graph;\n }\n const running = graphBuilds.get(key);\n if (running?.stamp === stamp) {\n harmonicGraphCacheStats.shared++;\n return joinGraphBuild(key, running, options.abortSignal, options.waitBudgetMs);\n }\n return joinGraphBuild(key, startGraphBuild(key, stamp, options), options.abortSignal, options.waitBudgetMs);\n}\n\nexport async function searchHarmonicRetrieval(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n query: string;\n maxResults: number;\n sessionKey?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n /** Share one projected graph between recalls until a write bumps a version sentinel (see readProjectedHarmonicGraph). */\n useGraphCache?: boolean;\n /** Bound on waiting for a shared graph build, in ms. Past it the search\n * rejects with a HarmonicGraphWaitDeadlineError so a recall fails open\n * instead of blocking on a rebuild a write storm keeps invalidating.\n * `0` waits without a bound. Defaults to HARMONIC_GRAPH_WAIT_BUDGET_MS. */\n waitBudgetMs?: number;\n}): Promise<HarmonicRetrievalResult[]> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const queryTokens = new Set(normalizeRecallTokens(options.query, [\"what\", \"which\"]));\n if (queryTokens.size === 0 || options.maxResults <= 0) return [];\n\n // One projection for every graph reader: nodes and anchors both arrive\n // already narrowed to the namespace's current active memories.\n const graph = await readProjectedHarmonicGraph({\n ...options,\n useCache: options.useGraphCache === true,\n waitBudgetMs:\n options.waitBudgetMs === undefined ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs,\n });\n const { nodes: eligibleNodes, anchors } = graph;\n const searchIndex = getHarmonicSearchIndex(graph);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const [nodeIndexPos, node] of eligibleNodes.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const tokens = searchIndex.nodeTokens[nodeIndexPos];\n const { score, matchedFields } = scoreNode(tokens, queryTokens);\n if (score <= 0) continue;\n candidates.set(node.nodeId, {\n node,\n nodeScore: score,\n anchorScore: 0,\n matchedFields: new Set(matchedFields),\n matchedAnchors: new Map(),\n });\n }\n\n if (options.anchorsEnabled) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n for (const [anchorIndex, anchor] of anchors.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n // `nodeRefs` are the projection's surviving references already.\n const eligibleNodeRefs = anchor.nodeRefs;\n const anchorTokens = searchIndex.anchorTokens[anchorIndex];\n const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);\n if (score <= 0) continue;\n for (const nodeRef of eligibleNodeRefs) {\n const node = searchIndex.nodesById.get(nodeRef);\n if (!node) continue;\n const existing = candidates.get(nodeRef) ?? {\n node,\n nodeScore: 0,\n anchorScore: 0,\n matchedFields: new Set<string>(),\n matchedAnchors: new Map<string, HarmonicMatchedAnchor>(),\n };\n existing.anchorScore += score;\n existing.matchedFields.add(\"anchor\");\n for (const field of matchedFields) existing.matchedFields.add(field);\n existing.matchedAnchors.set(anchor.anchorId, {\n anchorId: anchor.anchorId,\n anchorType: anchor.anchorType,\n anchorValue: anchor.anchorValue,\n });\n candidates.set(nodeRef, existing);\n }\n }\n }\n\n return [...candidates.values()]\n .map((candidate) => {\n let score = candidate.nodeScore + candidate.anchorScore;\n if (options.sessionKey && candidate.node.sessionKey === options.sessionKey) score += 0.5;\n return {\n node: candidate.node,\n score,\n nodeScore: candidate.nodeScore,\n anchorScore: candidate.anchorScore,\n matchedFields: [...candidate.matchedFields].sort(),\n matchedAnchors: [...candidate.matchedAnchors.values()].sort(\n (left, right) =>\n left.anchorType.localeCompare(right.anchorType) || left.anchorValue.localeCompare(right.anchorValue)\n ),\n };\n })\n .filter((result) => result.nodeScore > 0 || result.anchorScore > 0)\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.anchorScore - left.anchorScore ||\n right.node.recordedAt.localeCompare(left.node.recordedAt)\n )\n .slice(0, options.maxResults);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,gBAAgB;AAiCzB,IAAM,mBAAmB,IAAI;AAC7B,IAAM,SAAS;AAEf,SAAS,aAAa,WAAmB,OAAyB;AAChE,QAAM,OAAiB,CAAC;AACxB,WAAS,MAAM,KAAK,OAAO,YAAY,UAAU,MAAM,IAAI,QAAQ,OAAO,OAAO,OAAO,QAAQ;AAC9F,SAAK,KAAK,IAAI,KAAK,GAAG,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,EACpD;AACA,SAAO;AACT;AAOA,SAAS,0BAA0B,WAAmB,IAAY,MAA0B;AAC1F,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,CAAC,WAAW,KAAK,KAAK,WAAW,MAAM,CAAC,GAAG;AAC5D,eAAW,OAAO,sBAAsB;AACtC,YAAM,KAAK,KAAK,KAAK,MAAM,KAAK,GAAG,EAAE,KAAK,CAAC;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E;AAAA,IACC,CAAC,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,MAAM,cAAc,KAAK,eACzB,MAAM,KAAK,WAAW,cAAc,KAAK,KAAK,UAAU;AAAA,EAC5D,EACC,MAAM,GAAG,QAAQ,UAAU;AAChC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/buffer-persistence.ts"],"sourcesContent":["import type { DrainedTurnSets } from \"./buffer-turn-helpers.js\";\nimport type { BufferEntryState, BufferState, BufferSurpriseEvent } from \"./types.js\";\nimport type { BufferSessionSaveOutcome } from \"./storage/buffer-drain-claims.js\";\n\n/**\n * The buffer persistence surface SmartBuffer depends on.\n *\n * `saveBufferSession` / `deleteBufferSession` are the per-session incremental\n * writes (one file per session); when a storage backend does not provide\n * them, the buffer falls back to the whole-state `saveBuffer`. Both are\n * optional in the type so a storage double only has to implement what it\n * actually supports.\n */\nexport interface BufferStorage {\n loadBuffer(): Promise<BufferState>;\n saveBuffer(state: BufferState): Promise<void>;\n /** Reports \"handed_over\" when the session is claimed by `remnic buffer drain` and the entry moved into the claim instead of a session file. Legacy doubles may return void (treated as \"saved\"). */\n saveBufferSession?(key: string, entry: BufferEntryState): Promise<BufferSessionSaveOutcome | void>;\n deleteBufferSession?(key: string): Promise<void>;\n /** Sync claim check for the extraction gate; omitted when the backend has no drain-claim store. */\n isBufferSessionClaimed?(key: string): boolean;\n /** Optional surprise-telemetry sink; older storage and test doubles omit it. */\n appendBufferSurpriseEvents?(events: BufferSurpriseEvent[]): Promise<number>;\n /** Persist observe-buffer idempotency metadata (#3368 production path). */\n saveBufferAdmissionIdempotency?(state: BufferState): Promise<void>;\n}\n\n/** What one persist pass changed beyond plain writes. */\nexport interface BufferPersistOutcome {\n /** Sessions whose in-memory entry moved into a drain claim: the caller must evict them (a claimed session no longer lives in this process). */\n handedOver: string[];\n /** Per session, the turns a drain extracted, kept in their original lists. */\n drainedTurns: Map<string, DrainedTurnSets>;\n /** Sessions whose rewrite this pass deferred (#3389); they stay dirty. */\n deferred: string[];\n /**\n * Milliseconds until the earliest deferred session becomes rewrite-eligible\n * (set only when `deferred` is non-empty). The caller arms a retry for this\n * delay so a deferred tail of a burst lands without needing another turn.\n */\n deferredRetryDelayMs?: number;\n}\n\n/**\n * Session files at or above this estimated serialized size get rate-limited\n * rewrites on steady-state passes (issue #3389). A single hot session grew to\n * ~44 MB and its whole-file rewrite dominated `durable-bufferMs` (~99% of\n * observe latency, worst ~10 min) while real disk utilization sat at ~2%.\n */\nexport const BUFFER_SESSION_DEFER_MIN_BYTES = 8 * 1024 * 1024;\n\n/** A session past the size floor is rewritten at most once per this interval. */\nexport const BUFFER_SESSION_DEFER_INTERVAL_MS = 60_000;\n\n/**\n * The admission-idempotency metadata file is rewritten at most once per this\n * interval on steady-state passes (COS-825: it is ~1.16 MB and every observe\n * marks it dirty, so under fleet load it was re-serialized ~4x/s). The keys\n * stay in memory until the coalesced write lands; the pass arms\n * deferredRetryDelayMs so the tail write happens even if observes stop, and\n * durability barriers (allowDeferral omitted/false) always write immediately.\n */\nexport const ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS = 1_000;\n\nexport interface BufferPersistOptions {\n /** Injectable clock (monotonic ms) for tests. */\n now?: () => number;\n /**\n * Steady-state passes may defer rewriting a dirty session whose estimated\n * size is at or above BUFFER_SESSION_DEFER_MIN_BYTES and whose last persist\n * was within BUFFER_SESSION_DEFER_INTERVAL_MS. Durability barriers\n * (extraction-trigger saves, explicit buffer.save / flushPendingSave,\n * shutdown flushes) omit this: they always write. Deferral never applies to\n * a session's first persist or to a drain-claimed session. Bounds match the\n * sanctioned bufferSaveDebounceMs crash-loss window: deferred turns stay in\n * memory until the next pass or a forced flush.\n */\n allowDeferral?: boolean;\n}\n\n/** Approximate serialized size of one session file without stringifying it. */\nfunction estimateEntryBytes(entry: BufferEntryState): number {\n // ~15% over content for JSON structure + string escaping (quotes, braces,\n // key names, escape growth); the fixed per-turn overhead covers field names\n // and metadata. Under-counting here biases against deferral — the exact\n // case the floor exists for — so the estimate errs high.\n let bytes = 256;\n for (const turn of entry.turns) bytes += Math.ceil(turn.content.length * 1.15) + 128;\n for (const turn of entry.retainedTurns ?? [])\n bytes += Math.ceil(turn.content.length * 1.15) + 128;\n return bytes;\n}\n\n/**\n * Tracks which sessions' persisted files are stale and writes only those.\n *\n * Marks are cleared only after a durable write of that session. All calls\n * happen under SmartBuffer's serialized mutation chain: one writer.\n */\nexport interface BufferSessionPersistenceOptions {\n /** Injectable clock (monotonic ms) for tests; defaults to performance.now(). */\n now?: () => number;\n /** Test seam: override BUFFER_SESSION_DEFER_INTERVAL_MS. */\n deferIntervalMs?: number;\n /** Test seam: override ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS. */\n admissionPersistIntervalMs?: number;\n}\n\nexport class BufferSessionPersistence {\n private readonly dirty = new Set<string>();\n private readonly deleted = new Set<string>();\n private admissionIdempotencyDirty = false;\n /** Last successful admission-idempotency write (rate-limit bookkeeping, COS-825). */\n private lastAdmissionPersistAt?: number;\n /** Last successful session-file write per key (deferral bookkeeping, #3389). */\n private readonly lastPersistedAt = new Map<string, number>();\n private readonly clock: () => number;\n private readonly deferIntervalMs: number;\n private readonly admissionPersistIntervalMs: number;\n\n constructor(options: BufferSessionPersistenceOptions = {}) {\n this.clock = options.now ?? (() => performance.now());\n this.deferIntervalMs = options.deferIntervalMs ?? BUFFER_SESSION_DEFER_INTERVAL_MS;\n this.admissionPersistIntervalMs = options.admissionPersistIntervalMs ?? ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS;\n }\n\n markDirty(key: string): void {\n this.dirty.add(key);\n this.deleted.delete(key);\n }\n\n markDeleted(key: string): void {\n this.deleted.add(key);\n this.dirty.delete(key);\n this.lastPersistedAt.delete(key);\n }\n\n /** Eviction removed `key` from memory: its session file must go, any pending write is moot. */\n markEvicted(keys: readonly string[]): void {\n for (const key of keys) this.markDeleted(key);\n }\n\n markAdmissionIdempotencyDirty(): void {\n this.admissionIdempotencyDirty = true;\n }\n\n hasPending(): boolean {\n return this.dirty.size > 0 || this.deleted.size > 0 || this.admissionIdempotencyDirty;\n }\n\n /**\n * Persist buffer state. On session-capable storage this writes ONLY the\n * sessions whose state changed since the last successful persist and\n * deletes files for evicted/reset sessions, so the observe path never\n * re-serializes other sessions' turns. On legacy storage it falls back to\n * the whole-state saveBuffer. Files are deleted before dirty writes: a\n * crash mid-persist can then only resurrect already-evicted data (the same\n * exposure as a whole-file rewrite), never drop sessions the state says\n * exist.\n */\n async persist(\n storage: BufferStorage,\n state: BufferState,\n peekEntry: (key: string) => BufferEntryState | undefined,\n reconcile?: { key: string; drained: DrainedTurnSets },\n opts?: BufferPersistOptions,\n ): Promise<BufferPersistOutcome> {\n const drainedTurns = new Map<string, DrainedTurnSets>(\n reconcile ? [[reconcile.key, reconcile.drained]] : [],\n );\n const saveSession = storage.saveBufferSession?.bind(storage);\n const deleteSession = storage.deleteBufferSession?.bind(storage);\n if (!saveSession || !deleteSession) {\n await storage.saveBuffer(state);\n let admissionDeferredMs: number | undefined;\n if (this.admissionIdempotencyDirty && storage.saveBufferAdmissionIdempotency) {\n const nowMs = (opts?.now ?? this.clock)();\n const since = this.lastAdmissionPersistAt === undefined ? Infinity : nowMs - this.lastAdmissionPersistAt;\n if (opts?.allowDeferral === true && since < this.admissionPersistIntervalMs) {\n admissionDeferredMs = this.admissionPersistIntervalMs - since;\n } else {\n await storage.saveBufferAdmissionIdempotency(state);\n this.admissionIdempotencyDirty = false;\n this.lastAdmissionPersistAt = nowMs;\n }\n }\n this.dirty.clear();\n this.deleted.clear();\n if (admissionDeferredMs === undefined) this.admissionIdempotencyDirty = false;\n return { handedOver: [], drainedTurns, deferred: [], deferredRetryDelayMs: admissionDeferredMs };\n }\n const now = opts?.now ?? this.clock;\n const handedOver: string[] = [];\n const deferred: string[] = [];\n let nextEligibleAt: number | undefined;\n for (const key of [...this.deleted]) {\n await deleteSession(key);\n this.deleted.delete(key);\n }\n for (const key of [...this.dirty]) {\n const entry = peekEntry(key);\n if (!entry) {\n // A dirty key without state must not be written from a fabricated\n // empty entry: treat it as a deletion instead.\n this.markDeleted(key);\n continue;\n }\n if (opts?.allowDeferral === true && key !== reconcile?.key) {\n const last = this.lastPersistedAt.get(key);\n if (\n last !== undefined &&\n now() - last < this.deferIntervalMs &&\n estimateEntryBytes(entry) >= BUFFER_SESSION_DEFER_MIN_BYTES &&\n // Fail closed: a backend that omits isBufferSessionClaimed cannot\n // prove the session is unclaimed, so it never defers (PR 3481 review).\n storage.isBufferSessionClaimed?.(key) === false\n ) {\n deferred.push(key);\n const eligibleAt = last + this.deferIntervalMs;\n if (nextEligibleAt === undefined || eligibleAt < nextEligibleAt) {\n nextEligibleAt = eligibleAt;\n }\n continue;\n }\n }\n const saveOutcome = await saveSession(key, entry);\n this.dirty.delete(key);\n this.lastPersistedAt.set(key, now());\n // \"handed_over\": the entry moved into a drain claim. Content is durable\n // in the claim, so this key's pending state is settled — the caller\n // evicts the in-memory entry on its side.\n if (saveOutcome?.status === \"handed_over\") handedOver.push(key);\n // A drain tombstone: the turns it extracted must leave this process's\n // copy too, or the owner would extract them a second time.\n if (\n saveOutcome?.drainedTurns &&\n (saveOutcome.drainedTurns.turns.length > 0 || saveOutcome.drainedTurns.retainedTurns.length > 0)\n ) {\n drainedTurns.set(key, saveOutcome.drainedTurns);\n }\n if (saveOutcome?.status === \"handed_over\") this.lastPersistedAt.delete(key);\n }\n // #3368: never persist admission keys while session bodies are still deferred —\n // a crash after the key lands but before the deferred rewrite would make a\n // same-key retry swallow the unwritten turns.\n let admissionDeferredMs: number | undefined;\n if (this.admissionIdempotencyDirty && deferred.length === 0 && storage.saveBufferAdmissionIdempotency) {\n // COS-825: steady-state passes coalesce this ~1.16 MB rewrite to at most\n // one per interval; the tail write arms deferredRetryDelayMs so it lands\n // even if observes stop. Barriers (allowDeferral omitted) always write.\n const since = this.lastAdmissionPersistAt === undefined ? Infinity : now() - this.lastAdmissionPersistAt;\n if (opts?.allowDeferral === true && since < this.admissionPersistIntervalMs) {\n admissionDeferredMs = this.admissionPersistIntervalMs - since;\n } else {\n await storage.saveBufferAdmissionIdempotency(state);\n this.admissionIdempotencyDirty = false;\n this.lastAdmissionPersistAt = now();\n }\n }\n const outcome: BufferPersistOutcome = { handedOver, drainedTurns, deferred };\n if (deferred.length > 0 && nextEligibleAt !== undefined) {\n outcome.deferredRetryDelayMs = Math.max(0, nextEligibleAt - now());\n }\n if (admissionDeferredMs !== undefined) {\n const retry = Math.max(0, admissionDeferredMs);\n if (outcome.deferredRetryDelayMs === undefined || retry < outcome.deferredRetryDelayMs) {\n outcome.deferredRetryDelayMs = retry;\n }\n }\n return outcome;\n }\n}\n"],"mappings":";AAiDO,IAAM,iCAAiC,IAAI,OAAO;AAGlD,IAAM,mCAAmC;AAUzC,IAAM,4CAA4C;AAmBzD,SAAS,mBAAmB,OAAiC;AAK3D,MAAI,QAAQ;AACZ,aAAW,QAAQ,MAAM,MAAO,UAAS,KAAK,KAAK,KAAK,QAAQ,SAAS,IAAI,IAAI;AACjF,aAAW,QAAQ,MAAM,iBAAiB,CAAC;AACzC,aAAS,KAAK,KAAK,KAAK,QAAQ,SAAS,IAAI,IAAI;AACnD,SAAO;AACT;AAiBO,IAAM,2BAAN,MAA+B;AAAA,EACnB,QAAQ,oBAAI,IAAY;AAAA,EACxB,UAAU,oBAAI,IAAY;AAAA,EACnC,4BAA4B;AAAA;AAAA,EAE5B;AAAA;AAAA,EAES,kBAAkB,oBAAI,IAAoB;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,UAA2C,CAAC,GAAG;AACzD,SAAK,QAAQ,QAAQ,QAAQ,MAAM,YAAY,IAAI;AACnD,SAAK,kBAAkB,QAAQ,mBAAmB;AAClD,SAAK,6BAA6B,QAAQ,8BAA8B;AAAA,EAC1E;AAAA,EAEA,UAAU,KAAmB;AAC3B,SAAK,MAAM,IAAI,GAAG;AAClB,SAAK,QAAQ,OAAO,GAAG;AAAA,EACzB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