@remnic/core 10.0.1 → 10.0.3

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 (261) hide show
  1. package/dist/access-admin-ops-surface.js +40 -39
  2. package/dist/access-authorization-probe.js +41 -40
  3. package/dist/access-boundary.js +40 -39
  4. package/dist/access-citation-namespace.js +2 -2
  5. package/dist/access-cli.js +89 -88
  6. package/dist/access-cli.js.map +1 -1
  7. package/dist/access-extraction-force-flush.js +40 -39
  8. package/dist/access-http-briefing.js +41 -40
  9. package/dist/access-http-query.js +42 -41
  10. package/dist/access-http.js +58 -57
  11. package/dist/access-identity-continuity-surface.js +40 -39
  12. package/dist/access-lcm-surface.js +40 -39
  13. package/dist/access-mcp.js +49 -48
  14. package/dist/access-namespace-preflight.js +40 -39
  15. package/dist/access-observe-write-category.js +9 -9
  16. package/dist/access-observe-write-surface.js +40 -39
  17. package/dist/access-offline-manifest.js +6 -6
  18. package/dist/access-operations-batch.js +41 -40
  19. package/dist/access-operations.js +48 -47
  20. package/dist/access-recall-concurrency.js +40 -39
  21. package/dist/access-recall-response.js +40 -39
  22. package/dist/access-recall-surface.js +40 -39
  23. package/dist/access-schema.js +8 -8
  24. package/dist/access-service.js +40 -39
  25. package/dist/access-surface-catalog.js +42 -41
  26. package/dist/access-surface-catalog.js.map +1 -1
  27. package/dist/active-recall.js +12 -12
  28. package/dist/briefing.js +8 -8
  29. package/dist/causal-consolidation.js +9 -9
  30. package/dist/{chunk-A7V7GZ7F.js → chunk-2DHJTJIY.js} +2 -2
  31. package/dist/{chunk-MJ737UIA.js → chunk-2NV7MMMM.js} +2 -2
  32. package/dist/{chunk-34TSXVQS.js → chunk-2QZFZNXO.js} +2 -2
  33. package/dist/{chunk-TVPDF6CZ.js → chunk-44PBRUXB.js} +2 -2
  34. package/dist/{chunk-YX5F4V7H.js → chunk-4DDIWRT7.js} +2 -2
  35. package/dist/{chunk-EPFNPPWH.js → chunk-4NRZ7BRS.js} +2 -2
  36. package/dist/{chunk-VSPBXHGR.js → chunk-5QXMESS7.js} +2 -2
  37. package/dist/{chunk-S4DDLTPX.js → chunk-5Y43VGYB.js} +2 -2
  38. package/dist/{chunk-VXCTQ3B3.js → chunk-6AA7XFMO.js} +2 -2
  39. package/dist/{chunk-LI3OM3NP.js → chunk-6GU3TNJJ.js} +5 -5
  40. package/dist/{chunk-HPEONBM3.js → chunk-6JIHC5AS.js} +4 -4
  41. package/dist/chunk-6JIHC5AS.js.map +1 -0
  42. package/dist/{chunk-B2UCJX76.js → chunk-7KICGR5W.js} +2 -2
  43. package/dist/chunk-7PZHH4KC.js +63 -0
  44. package/dist/chunk-7PZHH4KC.js.map +1 -0
  45. package/dist/{chunk-UT7WE7RM.js → chunk-AUWMKDKL.js} +2 -2
  46. package/dist/{chunk-U6VC6RP3.js → chunk-AWLQNLTM.js} +2 -2
  47. package/dist/{chunk-PJSK6OJM.js → chunk-BANSBRNX.js} +2 -2
  48. package/dist/{chunk-2TCNEJ36.js → chunk-BNMI3JBV.js} +3 -3
  49. package/dist/{chunk-LTDWZ2HC.js → chunk-CFCEJNOE.js} +2 -2
  50. package/dist/{chunk-R6NHHKXE.js → chunk-CGOKNQDK.js} +2 -2
  51. package/dist/{chunk-HNU5CZ7E.js → chunk-CHI37EHP.js} +6 -6
  52. package/dist/{chunk-SFDKLEIY.js → chunk-CSLK7BN6.js} +2 -2
  53. package/dist/{chunk-6O2VUWV6.js → chunk-EIFYYHAF.js} +2 -2
  54. package/dist/{chunk-7AUC2YSU.js → chunk-GBA4N2SG.js} +16 -16
  55. package/dist/{chunk-V3NKVYUD.js → chunk-GUD6FYQG.js} +2 -2
  56. package/dist/{chunk-YY5FM5M7.js → chunk-HO7IQP7G.js} +3 -3
  57. package/dist/{chunk-EUYNHJTK.js → chunk-HP4CU2ZA.js} +2 -2
  58. package/dist/{chunk-GS6LTJFW.js → chunk-HRZZJ4XB.js} +2 -2
  59. package/dist/{chunk-KM2HQZR3.js → chunk-I2KEH2LS.js} +2 -2
  60. package/dist/{chunk-GYLDYYRA.js → chunk-I6WFBNA4.js} +4 -4
  61. package/dist/{chunk-S3BB34NI.js → chunk-IHCYCE6D.js} +3 -3
  62. package/dist/{chunk-PXDEIJL5.js → chunk-IXYIW3MZ.js} +2 -2
  63. package/dist/{chunk-BOT276JC.js → chunk-JSUA4YFE.js} +2 -2
  64. package/dist/{chunk-7LCGFUMB.js → chunk-KQAFEZQX.js} +4 -4
  65. package/dist/{chunk-WWUFQ3AG.js → chunk-KRTIHXWC.js} +2 -2
  66. package/dist/{chunk-VH76UQK3.js → chunk-KW77LGDX.js} +2 -2
  67. package/dist/{chunk-DX3ZODO3.js → chunk-L6DJJEFW.js} +2 -2
  68. package/dist/{chunk-FF4KLI5W.js → chunk-LDPPTPO5.js} +8 -1
  69. package/dist/chunk-LDPPTPO5.js.map +1 -0
  70. package/dist/{chunk-CRZ7BU6R.js → chunk-LMMC55WM.js} +2 -2
  71. package/dist/{chunk-3I375S4J.js → chunk-ME2LMFHF.js} +42 -42
  72. package/dist/{chunk-DHQUQ34W.js → chunk-MYYHACOW.js} +2 -2
  73. package/dist/{chunk-BKPV47BK.js → chunk-NGOZH7R5.js} +27 -27
  74. package/dist/{chunk-DPX3J2N4.js → chunk-NLDMTXWV.js} +2 -2
  75. package/dist/{chunk-U46P4UAR.js → chunk-NQHSXHJP.js} +4 -4
  76. package/dist/{chunk-FB6FQT4P.js → chunk-NXVD46HT.js} +2 -2
  77. package/dist/{chunk-QPG72IPU.js → chunk-O24EWFPQ.js} +3 -3
  78. package/dist/{chunk-DDPPV3KA.js → chunk-O6AYMAPJ.js} +2 -2
  79. package/dist/{chunk-JLUS56YZ.js → chunk-OV7EYM6M.js} +2 -2
  80. package/dist/{chunk-WIVBNNA3.js → chunk-OWHPA4JS.js} +2 -2
  81. package/dist/{chunk-3UP6NP4C.js → chunk-OZVHLBH6.js} +2 -2
  82. package/dist/{chunk-QHHWJVVW.js → chunk-PNFWIB4X.js} +2 -2
  83. package/dist/{chunk-AM4T6CHX.js → chunk-Q4E24IRR.js} +9 -8
  84. package/dist/chunk-Q4E24IRR.js.map +1 -0
  85. package/dist/{chunk-SBBZXDVJ.js → chunk-Q6GI7HEC.js} +2 -2
  86. package/dist/{chunk-TFA6HPOA.js → chunk-QCP75JGO.js} +5 -5
  87. package/dist/{chunk-OJP3N7UK.js → chunk-R7WYAXPO.js} +2 -2
  88. package/dist/{chunk-6DNMUYEE.js → chunk-RIEGCK2W.js} +2 -2
  89. package/dist/{chunk-BCTDTVSR.js → chunk-RKSGUMVL.js} +2 -2
  90. package/dist/{chunk-GZRTH3WZ.js → chunk-RXT6UB25.js} +127 -6
  91. package/dist/chunk-RXT6UB25.js.map +1 -0
  92. package/dist/{chunk-47I2EK6G.js → chunk-SIYZDT2V.js} +3 -3
  93. package/dist/{chunk-5R4YPRAR.js → chunk-TGF43K66.js} +18 -18
  94. package/dist/{chunk-UP3XXGEN.js → chunk-TNVZCLJU.js} +2 -2
  95. package/dist/{chunk-RGGXSN5A.js → chunk-U6HWKOGD.js} +2 -2
  96. package/dist/{chunk-RWZXVCGX.js → chunk-UK5EH7AI.js} +4 -4
  97. package/dist/{chunk-DYZHVVJM.js → chunk-UVVSOSHL.js} +36 -36
  98. package/dist/{chunk-NUSQ3YEL.js → chunk-UXIZ5XN5.js} +2 -2
  99. package/dist/{chunk-DB6XFMOF.js → chunk-VC4J4UTI.js} +5 -5
  100. package/dist/{chunk-FYX2LXIX.js → chunk-WI37MWRZ.js} +2 -2
  101. package/dist/{chunk-P5FPO2BR.js → chunk-WWDO7ZWM.js} +3 -3
  102. package/dist/{chunk-GZ2KV2RO.js → chunk-WWLAKRMX.js} +4 -4
  103. package/dist/{chunk-QJWZJ7HL.js → chunk-X6X4UASX.js} +7 -5
  104. package/dist/chunk-X6X4UASX.js.map +1 -0
  105. package/dist/{chunk-NVZRIHW5.js → chunk-Y2ADLCB3.js} +7 -7
  106. package/dist/{chunk-VKQI47DJ.js → chunk-Y7427SL7.js} +4 -4
  107. package/dist/{chunk-LQGX5TCI.js → chunk-YQSWNFZE.js} +2 -2
  108. package/dist/{chunk-7DB7KYSR.js → chunk-ZS7RK6H6.js} +4 -4
  109. package/dist/cli.js +75 -74
  110. package/dist/coding/export-okf-codegraph.js +7 -7
  111. package/dist/compounding/engine.js +8 -8
  112. package/dist/config.js +12 -12
  113. package/dist/connectors/codex-materialize-runner.js +8 -8
  114. package/dist/connectors/index.js +8 -8
  115. package/dist/convergence-refresh.js +10 -10
  116. package/dist/conversation-index/backend.js +2 -2
  117. package/dist/corpus-watermark.js +10 -10
  118. package/dist/deep-recall-http-glue.js +9 -9
  119. package/dist/entity-retrieval.js +8 -8
  120. package/dist/explicit-capture.js +3 -3
  121. package/dist/external-wiki-access.js +41 -40
  122. package/dist/extraction.js +8 -8
  123. package/dist/harmonic-retrieval.d.ts.map +1 -1
  124. package/dist/harmonic-retrieval.js +91 -1
  125. package/dist/index.js +94 -93
  126. package/dist/lcm/engine.js +2 -2
  127. package/dist/lcm/index.js +2 -2
  128. package/dist/location/index.js +10 -10
  129. package/dist/maintenance/memory-governance.js +8 -8
  130. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +8 -8
  131. package/dist/maintenance/rebuild-memory-projection.d.ts.map +1 -1
  132. package/dist/maintenance/rebuild-memory-projection.js +9 -9
  133. package/dist/memory-browse-operations.js +41 -40
  134. package/dist/memory-projection-batch.d.ts +20 -0
  135. package/dist/memory-projection-batch.d.ts.map +1 -0
  136. package/dist/memory-projection-batch.js +11 -0
  137. package/dist/memory-projection-batch.js.map +1 -0
  138. package/dist/namespaces/migrate.js +9 -9
  139. package/dist/namespaces/search.js +4 -4
  140. package/dist/namespaces/storage.js +8 -8
  141. package/dist/offline-sync-changeset-generations.js +3 -3
  142. package/dist/offline-sync-embedding-generation.js +2 -2
  143. package/dist/offline-sync-snapshot-stream.js +6 -6
  144. package/dist/offline-sync.js +5 -5
  145. package/dist/operator-doctor-corpus.js +11 -11
  146. package/dist/operator-toolkit.js +21 -21
  147. package/dist/orchestration/maintenance.js +16 -16
  148. package/dist/orchestrator.js +91 -90
  149. package/dist/recall-navigation-operations.js +41 -40
  150. package/dist/recall-navigation.js +40 -39
  151. package/dist/resume-bundles.js +15 -15
  152. package/dist/search/factory.js +3 -3
  153. package/dist/search/index.js +3 -3
  154. package/dist/semantic-consolidation.js +9 -9
  155. package/dist/semantic-rule-promotion.js +8 -8
  156. package/dist/semantic-rule-verifier.js +8 -8
  157. package/dist/session-identity.js +2 -2
  158. package/dist/session-transcript-migration.js +3 -3
  159. package/dist/source-agent-qualifier.js +8 -8
  160. package/dist/standup/build.js +8 -8
  161. package/dist/storage-paths.d.ts +11 -0
  162. package/dist/storage-paths.d.ts.map +1 -1
  163. package/dist/storage-paths.js +3 -1
  164. package/dist/storage.d.ts +1 -1
  165. package/dist/storage.d.ts.map +1 -1
  166. package/dist/storage.js +7 -7
  167. package/dist/summarizer.js +4 -4
  168. package/dist/summary-snapshot.js +2 -2
  169. package/dist/support-passport/index.js +43 -42
  170. package/dist/threading.js +2 -2
  171. package/dist/transcript.d.ts +3 -3
  172. package/dist/transcript.d.ts.map +1 -1
  173. package/dist/transcript.js +3 -3
  174. package/dist/transfer/capsule-export.js +2 -2
  175. package/dist/transfer/capsule-import.js +2 -2
  176. package/dist/transfer/export-okf.js +8 -8
  177. package/dist/verified-recall.js +8 -8
  178. package/dist/who-knows-cli.js +9 -9
  179. package/dist/who-knows.js +8 -8
  180. package/dist/write-quarantine.js +2 -2
  181. package/package.json +2 -2
  182. package/src/harmonic-retrieval-index.test.ts +387 -0
  183. package/src/harmonic-retrieval.ts +181 -15
  184. package/src/maintenance/rebuild-memory-projection.ts +3 -0
  185. package/src/memory-projection-batch.ts +82 -0
  186. package/src/storage-paths.ts +18 -0
  187. package/src/storage.ts +1 -1
  188. package/src/transcript-recent-unscoped.test.ts +139 -0
  189. package/src/transcript.ts +6 -6
  190. package/dist/chunk-AM4T6CHX.js.map +0 -1
  191. package/dist/chunk-FF4KLI5W.js.map +0 -1
  192. package/dist/chunk-GZRTH3WZ.js.map +0 -1
  193. package/dist/chunk-HPEONBM3.js.map +0 -1
  194. package/dist/chunk-QJWZJ7HL.js.map +0 -1
  195. /package/dist/{chunk-A7V7GZ7F.js.map → chunk-2DHJTJIY.js.map} +0 -0
  196. /package/dist/{chunk-MJ737UIA.js.map → chunk-2NV7MMMM.js.map} +0 -0
  197. /package/dist/{chunk-34TSXVQS.js.map → chunk-2QZFZNXO.js.map} +0 -0
  198. /package/dist/{chunk-TVPDF6CZ.js.map → chunk-44PBRUXB.js.map} +0 -0
  199. /package/dist/{chunk-YX5F4V7H.js.map → chunk-4DDIWRT7.js.map} +0 -0
  200. /package/dist/{chunk-EPFNPPWH.js.map → chunk-4NRZ7BRS.js.map} +0 -0
  201. /package/dist/{chunk-VSPBXHGR.js.map → chunk-5QXMESS7.js.map} +0 -0
  202. /package/dist/{chunk-S4DDLTPX.js.map → chunk-5Y43VGYB.js.map} +0 -0
  203. /package/dist/{chunk-VXCTQ3B3.js.map → chunk-6AA7XFMO.js.map} +0 -0
  204. /package/dist/{chunk-LI3OM3NP.js.map → chunk-6GU3TNJJ.js.map} +0 -0
  205. /package/dist/{chunk-B2UCJX76.js.map → chunk-7KICGR5W.js.map} +0 -0
  206. /package/dist/{chunk-UT7WE7RM.js.map → chunk-AUWMKDKL.js.map} +0 -0
  207. /package/dist/{chunk-U6VC6RP3.js.map → chunk-AWLQNLTM.js.map} +0 -0
  208. /package/dist/{chunk-PJSK6OJM.js.map → chunk-BANSBRNX.js.map} +0 -0
  209. /package/dist/{chunk-2TCNEJ36.js.map → chunk-BNMI3JBV.js.map} +0 -0
  210. /package/dist/{chunk-LTDWZ2HC.js.map → chunk-CFCEJNOE.js.map} +0 -0
  211. /package/dist/{chunk-R6NHHKXE.js.map → chunk-CGOKNQDK.js.map} +0 -0
  212. /package/dist/{chunk-HNU5CZ7E.js.map → chunk-CHI37EHP.js.map} +0 -0
  213. /package/dist/{chunk-SFDKLEIY.js.map → chunk-CSLK7BN6.js.map} +0 -0
  214. /package/dist/{chunk-6O2VUWV6.js.map → chunk-EIFYYHAF.js.map} +0 -0
  215. /package/dist/{chunk-7AUC2YSU.js.map → chunk-GBA4N2SG.js.map} +0 -0
  216. /package/dist/{chunk-V3NKVYUD.js.map → chunk-GUD6FYQG.js.map} +0 -0
  217. /package/dist/{chunk-YY5FM5M7.js.map → chunk-HO7IQP7G.js.map} +0 -0
  218. /package/dist/{chunk-EUYNHJTK.js.map → chunk-HP4CU2ZA.js.map} +0 -0
  219. /package/dist/{chunk-GS6LTJFW.js.map → chunk-HRZZJ4XB.js.map} +0 -0
  220. /package/dist/{chunk-KM2HQZR3.js.map → chunk-I2KEH2LS.js.map} +0 -0
  221. /package/dist/{chunk-GYLDYYRA.js.map → chunk-I6WFBNA4.js.map} +0 -0
  222. /package/dist/{chunk-S3BB34NI.js.map → chunk-IHCYCE6D.js.map} +0 -0
  223. /package/dist/{chunk-PXDEIJL5.js.map → chunk-IXYIW3MZ.js.map} +0 -0
  224. /package/dist/{chunk-BOT276JC.js.map → chunk-JSUA4YFE.js.map} +0 -0
  225. /package/dist/{chunk-7LCGFUMB.js.map → chunk-KQAFEZQX.js.map} +0 -0
  226. /package/dist/{chunk-WWUFQ3AG.js.map → chunk-KRTIHXWC.js.map} +0 -0
  227. /package/dist/{chunk-VH76UQK3.js.map → chunk-KW77LGDX.js.map} +0 -0
  228. /package/dist/{chunk-DX3ZODO3.js.map → chunk-L6DJJEFW.js.map} +0 -0
  229. /package/dist/{chunk-CRZ7BU6R.js.map → chunk-LMMC55WM.js.map} +0 -0
  230. /package/dist/{chunk-3I375S4J.js.map → chunk-ME2LMFHF.js.map} +0 -0
  231. /package/dist/{chunk-DHQUQ34W.js.map → chunk-MYYHACOW.js.map} +0 -0
  232. /package/dist/{chunk-BKPV47BK.js.map → chunk-NGOZH7R5.js.map} +0 -0
  233. /package/dist/{chunk-DPX3J2N4.js.map → chunk-NLDMTXWV.js.map} +0 -0
  234. /package/dist/{chunk-U46P4UAR.js.map → chunk-NQHSXHJP.js.map} +0 -0
  235. /package/dist/{chunk-FB6FQT4P.js.map → chunk-NXVD46HT.js.map} +0 -0
  236. /package/dist/{chunk-QPG72IPU.js.map → chunk-O24EWFPQ.js.map} +0 -0
  237. /package/dist/{chunk-DDPPV3KA.js.map → chunk-O6AYMAPJ.js.map} +0 -0
  238. /package/dist/{chunk-JLUS56YZ.js.map → chunk-OV7EYM6M.js.map} +0 -0
  239. /package/dist/{chunk-WIVBNNA3.js.map → chunk-OWHPA4JS.js.map} +0 -0
  240. /package/dist/{chunk-3UP6NP4C.js.map → chunk-OZVHLBH6.js.map} +0 -0
  241. /package/dist/{chunk-QHHWJVVW.js.map → chunk-PNFWIB4X.js.map} +0 -0
  242. /package/dist/{chunk-SBBZXDVJ.js.map → chunk-Q6GI7HEC.js.map} +0 -0
  243. /package/dist/{chunk-TFA6HPOA.js.map → chunk-QCP75JGO.js.map} +0 -0
  244. /package/dist/{chunk-OJP3N7UK.js.map → chunk-R7WYAXPO.js.map} +0 -0
  245. /package/dist/{chunk-6DNMUYEE.js.map → chunk-RIEGCK2W.js.map} +0 -0
  246. /package/dist/{chunk-BCTDTVSR.js.map → chunk-RKSGUMVL.js.map} +0 -0
  247. /package/dist/{chunk-47I2EK6G.js.map → chunk-SIYZDT2V.js.map} +0 -0
  248. /package/dist/{chunk-5R4YPRAR.js.map → chunk-TGF43K66.js.map} +0 -0
  249. /package/dist/{chunk-UP3XXGEN.js.map → chunk-TNVZCLJU.js.map} +0 -0
  250. /package/dist/{chunk-RGGXSN5A.js.map → chunk-U6HWKOGD.js.map} +0 -0
  251. /package/dist/{chunk-RWZXVCGX.js.map → chunk-UK5EH7AI.js.map} +0 -0
  252. /package/dist/{chunk-DYZHVVJM.js.map → chunk-UVVSOSHL.js.map} +0 -0
  253. /package/dist/{chunk-NUSQ3YEL.js.map → chunk-UXIZ5XN5.js.map} +0 -0
  254. /package/dist/{chunk-DB6XFMOF.js.map → chunk-VC4J4UTI.js.map} +0 -0
  255. /package/dist/{chunk-FYX2LXIX.js.map → chunk-WI37MWRZ.js.map} +0 -0
  256. /package/dist/{chunk-P5FPO2BR.js.map → chunk-WWDO7ZWM.js.map} +0 -0
  257. /package/dist/{chunk-GZ2KV2RO.js.map → chunk-WWLAKRMX.js.map} +0 -0
  258. /package/dist/{chunk-NVZRIHW5.js.map → chunk-Y2ADLCB3.js.map} +0 -0
  259. /package/dist/{chunk-VKQI47DJ.js.map → chunk-Y7427SL7.js.map} +0 -0
  260. /package/dist/{chunk-LQGX5TCI.js.map → chunk-YQSWNFZE.js.map} +0 -0
  261. /package/dist/{chunk-7DB7KYSR.js.map → chunk-ZS7RK6H6.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transcript.ts"],"sourcesContent":["import { appendFile, mkdir, readdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport type { TranscriptEntry, Checkpoint, PluginConfig } from \"./types.js\";\nimport { analyzeSessionIntegrity, type SessionIntegrityReport } from \"./session-integrity.js\";\nimport { isDailyFileDatedBefore, resolveSafeStoragePath } from \"./storage-paths.js\";\nimport { sessionStoragePaths } from \"./session-identity.js\";\nimport { estimateTokenCount } from \"./token-estimate.js\";\n\ntype DirectorySessionStatus = \"missing\" | \"empty\" | \"matches\" | \"occupied\";\ntype DirectoryOwnershipCacheEntry = {\n status: \"empty\" | \"matches\";\n fileSizes: Map<string, number>;\n};\n\n/**\n * De-duplicate JSONL lines collected across multiple read-back candidate\n * directories. A partially-applied migration (issue #1496) can leave the SAME\n * raw row in both the primary `session/<hash>` tree and a legacy read-back dir\n * (`other/default` or an old `parts.length >= 3` directory) when the source was\n * copied but not yet trimmed. Without this guard, `readRecent`, `readToolUse`,\n * footprint estimation, and the summarizer fetch would return that row twice\n * (cursor review on PR #1504). The exact raw JSONL line is the stable identity:\n * the migration preserves byte content per session, so a copied-but-not-trimmed\n * row is byte-identical in both locations. Returns `true` the first time a line\n * is seen, `false` for every subsequent duplicate.\n */\nfunction makeRawLineDeduper(): (rawLine: string) => boolean {\n const seen = new Set<string>();\n return (rawLine: string): boolean => {\n if (seen.has(rawLine)) return false;\n seen.add(rawLine);\n return true;\n };\n}\n\n/**\n * Compute the half-open UTC instant range `[start, end)` that covers an entire\n * calendar day, suitable for {@link TranscriptManager.readRange}.\n *\n * `readRange` filters with an EXCLUSIVE upper bound (`entryTime < end`, CLAUDE.md\n * rule #35 / AGENTS.md rule 23). The end is therefore the NEXT day's\n * `00:00:00Z`, not `${date}T23:59:59Z`: a literal `23:59:59Z` end (== `.000Z`)\n * would drop any entry stamped in the final second of the day\n * (`23:59:59.000Z`–`23:59:59.999Z`). Using the next day's midnight keeps the\n * `[start, end)` semantics intact while including the whole day.\n *\n * @param date - A `YYYY-MM-DD` calendar day (UTC).\n */\nexport function utcDayRange(date: string): { start: string; end: string } {\n const start = `${date}T00:00:00Z`;\n const startMs = Date.parse(start);\n if (Number.isNaN(startMs)) {\n // Malformed date: preserve the pre-existing \"empty range\" behavior (an\n // unparseable bound makes `readRange` match nothing) rather than throwing.\n return { start, end: start };\n }\n const next = new Date(startMs);\n next.setUTCDate(next.getUTCDate() + 1);\n return { start, end: `${next.toISOString().slice(0, 10)}T00:00:00Z` };\n}\n\n/**\n * Manages conversation transcript storage, checkpointing, and recall formatting.\n *\n * Transcripts are stored as JSONL files in a hierarchical structure:\n * transcripts/{channelType}/{channelId}.jsonl\n *\n * Channel types are extracted from sessionKey (discord, slack, cron, main, etc.)\n * Checkpoints are used to preserve conversation context across compaction events.\n */\nexport class TranscriptManager {\n private transcriptsDir: string;\n private checkpointPath: string;\n private stateDir: string;\n private toolUsageDir: string;\n private config: PluginConfig;\n private sessionFootprintCache = new Map<\n string,\n {\n totalBytes: number;\n totalTokens: number;\n fileBytes: Map<string, number>;\n fileSizes: Map<string, number>;\n fileTokens: Map<string, number>;\n }\n >();\n private directoryOwnershipCache = new Map<string, DirectoryOwnershipCacheEntry>();\n\n /** Default checkpoint TTL in hours */\n private static readonly DEFAULT_CHECKPOINT_TTL_HOURS = 24;\n\n constructor(config: PluginConfig) {\n this.config = config;\n this.transcriptsDir = path.join(config.memoryDir, \"transcripts\");\n this.stateDir = path.join(config.memoryDir, \"state\");\n this.checkpointPath = path.join(this.stateDir, \"checkpoint.json\");\n this.toolUsageDir = path.join(this.stateDir, \"tool-usage\");\n }\n\n /**\n * Resolve the storage path pieces for a sessionKey via the shared\n * {@link sessionStoragePaths} helper (issue #1496, rule #22).\n *\n * Legacy `agent:<id>:...` shapes keep their existing readable channel paths.\n * Arbitrary / non-legacy keys (e.g. `pi-geek:abc123`) route to\n * `transcripts/session/<hash>/YYYY-MM-DD.jsonl` from the FIRST write — they\n * never start life in `other/default`. For those keys a list of\n * read-back-only `readbackDirs` is returned so data written by older builds\n * (under `other/default`, or under an old `parts.length >= 3` directory such\n * as `baz/default`) stays discoverable until migrated. New writes never\n * target read-back dirs. See `session-identity.ts`.\n *\n * @returns Object with raw channel identifiers and encoded storage path pieces.\n */\n getTranscriptPath(sessionKey: string): {\n dir: string;\n file: string;\n channelType: string;\n channelId: string;\n alternateDir: string;\n legacyDir?: string;\n readbackDirs: string[];\n } {\n const paths = sessionStoragePaths(sessionKey);\n\n // Daily rotation: transcripts/{channelType}/{channelId}/YYYY-MM-DD.jsonl\n const today = new Date().toISOString().slice(0, 10);\n\n return {\n dir: paths.dir,\n file: `${today}.jsonl`,\n channelType: paths.channelType,\n channelId: paths.channelId,\n alternateDir: paths.alternateDir,\n legacyDir: paths.legacyDir,\n readbackDirs: paths.readbackDirs,\n };\n }\n\n /**\n * Initialize the transcript manager by ensuring directories exist.\n */\n async initialize(): Promise<void> {\n await mkdir(this.transcriptsDir, { recursive: true });\n await mkdir(this.stateDir, { recursive: true });\n await mkdir(this.toolUsageDir, { recursive: true });\n log.info(\"transcript manager initialized\");\n }\n\n /**\n * Best-effort list of sessionKeys that have transcript files on disk.\n * This is used by cron-style tooling (hourly summaries, conversation indexing)\n * to iterate across \"active\" sessions.\n */\n async listSessionKeys(): Promise<string[]> {\n const transcriptDir = this.transcriptsDir;\n const sessionKeys = new Set<string>();\n\n try {\n const typeEntries = await readdir(transcriptDir, { withFileTypes: true });\n for (const typeEnt of typeEntries) {\n if (!typeEnt.isDirectory()) continue;\n const typeDir = path.join(transcriptDir, typeEnt.name);\n const idEntries = await readdir(typeDir, { withFileTypes: true });\n for (const idEnt of idEntries) {\n if (!idEnt.isDirectory()) continue;\n const chanDir = path.join(typeDir, idEnt.name);\n const files = (await readdir(chanDir)).filter((f) => f.endsWith(\".jsonl\")).sort();\n const last = files[files.length - 1];\n if (!last) continue;\n try {\n const raw = await readFile(path.join(chanDir, last), \"utf-8\");\n const firstLine = raw.split(\"\\n\").find((l) => l.trim().length > 0);\n if (!firstLine) continue;\n const entry = JSON.parse(firstLine) as TranscriptEntry;\n if (typeof entry.sessionKey === \"string\" && entry.sessionKey.length > 0) {\n sessionKeys.add(entry.sessionKey);\n }\n } catch {\n // ignore\n }\n }\n }\n } catch {\n return [];\n }\n\n return Array.from(sessionKeys);\n }\n\n getToolUsagePath(sessionKey: string): {\n dir: string;\n file: string;\n alternateDir: string;\n legacyDir?: string;\n readbackDirs: string[];\n } {\n const p = this.getTranscriptPath(sessionKey);\n return {\n dir: p.dir,\n file: p.file,\n alternateDir: p.alternateDir,\n legacyDir: p.legacyDir,\n readbackDirs: p.readbackDirs,\n };\n }\n\n private async selectStorageDirForWrite(\n root: string,\n dir: string,\n legacyDir?: string,\n sessionKey?: string,\n alternateDir?: string,\n ): Promise<{ dir: string; channelDir: string }> {\n const channelDir = await resolveSafeStoragePath(root, dir);\n const encodedStatus = await this.directorySessionStatus(root, dir, sessionKey);\n if (encodedStatus === \"matches\" || encodedStatus === \"empty\") return { dir, channelDir };\n\n if (legacyDir) {\n const legacyChannelDir = await resolveSafeStoragePath(root, legacyDir);\n if ((await this.directorySessionStatus(root, legacyDir, sessionKey)) === \"matches\") {\n return { dir: legacyDir, channelDir: legacyChannelDir };\n }\n }\n\n if (encodedStatus === \"missing\") return { dir, channelDir };\n\n if (alternateDir) {\n const alternateChannelDir = await resolveSafeStoragePath(root, alternateDir);\n const alternateStatus = await this.directorySessionStatus(root, alternateDir, sessionKey);\n if (\n alternateStatus === \"missing\" ||\n alternateStatus === \"empty\" ||\n alternateStatus === \"matches\"\n ) {\n return { dir: alternateDir, channelDir: alternateChannelDir };\n }\n }\n\n throw new Error(`transcript storage path collision for session: ${sessionKey ?? \"(unknown)\"}`);\n }\n\n private async directorySessionStatus(\n root: string,\n dir: string,\n sessionKey?: string,\n ): Promise<DirectorySessionStatus> {\n let channelDir: string;\n try {\n channelDir = await resolveSafeStoragePath(root, dir);\n if (!(await stat(channelDir)).isDirectory()) return \"occupied\";\n } catch (err) {\n const code =\n err && typeof err === \"object\" && \"code\" in err\n ? (err as { code?: string }).code\n : undefined;\n if (code === \"ENOENT\") return \"missing\";\n throw err;\n }\n\n let names: string[];\n try {\n names = (await readdir(channelDir)).filter((file) => file.endsWith(\".jsonl\"));\n } catch {\n return \"occupied\";\n }\n\n const fileSizes = await this.directoryJsonlFileSizes(root, dir, names);\n if (!fileSizes) return \"occupied\";\n\n if (!sessionKey) return \"matches\";\n const cacheKey = this.directoryOwnershipCacheKey(root, dir, sessionKey);\n const cached = this.directoryOwnershipCache.get(cacheKey);\n if (cached && this.sameFileSizes(cached.fileSizes, fileSizes)) {\n return cached.status;\n }\n\n let hasEntries = false;\n let hasMatchingEntry = false;\n\n for (const name of names) {\n const filePath = await resolveSafeStoragePath(root, dir, name).catch(() => null);\n if (filePath === null) return \"occupied\";\n try {\n const raw = await readFile(filePath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n hasEntries = true;\n try {\n const obj = JSON.parse(line) as { sessionKey?: string };\n if (obj.sessionKey === sessionKey) {\n hasMatchingEntry = true;\n } else {\n return \"occupied\";\n }\n } catch {\n return \"occupied\";\n }\n }\n } catch {\n return \"occupied\";\n }\n }\n\n const status = hasMatchingEntry ? \"matches\" : hasEntries ? \"occupied\" : \"empty\";\n if (status === \"matches\" || status === \"empty\") {\n this.directoryOwnershipCache.set(cacheKey, { status, fileSizes });\n }\n return status;\n }\n\n private directoryOwnershipCacheKey(root: string, dir: string, sessionKey: string): string {\n return `${path.resolve(root)}\\0${dir}\\0${sessionKey}`;\n }\n\n private sameFileSizes(left: Map<string, number>, right: Map<string, number>): boolean {\n if (left.size !== right.size) return false;\n for (const [name, size] of left) {\n if (right.get(name) !== size) return false;\n }\n return true;\n }\n\n private async directoryJsonlFileSizes(\n root: string,\n dir: string,\n names: string[],\n ): Promise<Map<string, number> | null> {\n const fileSizes = new Map<string, number>();\n for (const name of names) {\n const filePath = await resolveSafeStoragePath(root, dir, name).catch(() => null);\n if (filePath === null) return null;\n const fileInfo = await stat(filePath).catch(() => null);\n if (!fileInfo?.isFile()) return null;\n fileSizes.set(name, Math.max(0, fileInfo.size));\n }\n return fileSizes;\n }\n\n private async rememberDirectoryOwnership(\n root: string,\n dir: string,\n sessionKey: string,\n ): Promise<void> {\n try {\n const channelDir = await resolveSafeStoragePath(root, dir);\n const names = (await readdir(channelDir)).filter((file) => file.endsWith(\".jsonl\"));\n const fileSizes = await this.directoryJsonlFileSizes(root, dir, names);\n if (!fileSizes) return;\n this.directoryOwnershipCache.set(\n this.directoryOwnershipCacheKey(root, dir, sessionKey),\n { status: \"matches\", fileSizes },\n );\n } catch {\n // Cache refresh is best-effort; write path correctness does not depend on it.\n }\n }\n\n private async getSessionStorageFiles(\n root: string,\n dir: string,\n legacyDir?: string,\n alternateDir?: string,\n readbackDirs: string[] = [],\n ): Promise<Array<{ cacheKey: string; name: string; path: string }>> {\n const files: Array<{ cacheKey: string; name: string; path: string }> = [];\n const seenDirs = new Set<string>();\n\n for (const candidateDir of [dir, alternateDir, legacyDir, ...readbackDirs]) {\n if (!candidateDir || seenDirs.has(candidateDir)) continue;\n seenDirs.add(candidateDir);\n\n let channelDir: string;\n try {\n channelDir = await resolveSafeStoragePath(root, candidateDir);\n } catch {\n continue;\n }\n\n let names: string[];\n try {\n names = (await readdir(channelDir)).filter((file) => file.endsWith(\".jsonl\")).sort();\n } catch {\n continue;\n }\n\n for (const name of names) {\n const filePath = await resolveSafeStoragePath(root, candidateDir, name).catch(() => null);\n if (filePath === null) continue;\n files.push({\n cacheKey: path.join(candidateDir, name),\n name,\n path: filePath,\n });\n }\n }\n\n return files.sort((a, b) => a.cacheKey.localeCompare(b.cacheKey));\n }\n\n async appendToolUse(entry: { timestamp: string; sessionKey: string; tool: string }): Promise<void> {\n const { dir, file, alternateDir, legacyDir } = this.getToolUsagePath(entry.sessionKey);\n const { dir: writeDir, channelDir } = await this.selectStorageDirForWrite(\n this.toolUsageDir,\n dir,\n legacyDir,\n entry.sessionKey,\n alternateDir,\n );\n await mkdir(channelDir, { recursive: true });\n const filePath = await resolveSafeStoragePath(this.toolUsageDir, writeDir, file);\n await appendFile(filePath, JSON.stringify(entry) + \"\\n\", \"utf-8\");\n await this.rememberDirectoryOwnership(this.toolUsageDir, writeDir, entry.sessionKey);\n }\n\n async readToolUse(\n sessionKey: string,\n startTime: Date,\n endTime: Date,\n ): Promise<Array<{ timestamp: string; sessionKey: string; tool: string }>> {\n const { dir, alternateDir, legacyDir, readbackDirs } = this.getToolUsagePath(sessionKey);\n try {\n const files = await this.getSessionStorageFiles(\n this.toolUsageDir,\n dir,\n legacyDir,\n alternateDir,\n readbackDirs,\n );\n const out: Array<{ timestamp: string; sessionKey: string; tool: string }> = [];\n // Dedup identical raw rows that a partially-applied migration may have left\n // in both the primary dir and a read-back dir (issue #1496, cursor review).\n const keepRawLine = makeRawLineDeduper();\n for (const file of files) {\n const raw = await readFile(file.path, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line) as any;\n const ts = new Date(String(obj.timestamp ?? \"\")).getTime();\n if (!Number.isFinite(ts)) continue;\n if (ts >= startTime.getTime() && ts < endTime.getTime()) {\n if (typeof obj.tool === \"string\" && typeof obj.sessionKey === \"string\") {\n if (obj.sessionKey === sessionKey && keepRawLine(line)) {\n out.push({ timestamp: obj.timestamp, sessionKey: obj.sessionKey, tool: obj.tool });\n }\n }\n }\n } catch {\n // ignore\n }\n }\n }\n return out;\n } catch {\n return [];\n }\n }\n\n async estimateSessionFootprint(sessionKey: string): Promise<{ bytes: number; tokens: number }> {\n const { dir, alternateDir, legacyDir, readbackDirs } = this.getTranscriptPath(sessionKey);\n let bytes = 0;\n let tokens = 0;\n try {\n const files = await this.getSessionStorageFiles(\n this.transcriptsDir,\n dir,\n legacyDir,\n alternateDir,\n readbackDirs,\n );\n const cached = this.sessionFootprintCache.get(sessionKey);\n if (!cached) {\n const fileBytes = new Map<string, number>();\n const fileSizes = new Map<string, number>();\n const fileTokens = new Map<string, number>();\n for (const file of files) {\n try {\n const fileInfo = await stat(file.path);\n const estimate = await this.estimateSessionBytesInFile(file.path, sessionKey);\n fileBytes.set(file.cacheKey, estimate.bytes);\n fileTokens.set(file.cacheKey, estimate.tokens);\n fileSizes.set(file.cacheKey, Math.max(0, fileInfo.size));\n bytes += estimate.bytes;\n tokens += estimate.tokens;\n } catch {\n }\n }\n this.sessionFootprintCache.set(sessionKey, { totalBytes: bytes, totalTokens: tokens, fileBytes, fileSizes, fileTokens });\n } else {\n bytes = cached.totalBytes;\n tokens = cached.totalTokens;\n const seen = new Set(files.map((file) => file.cacheKey));\n\n for (const [cachedFile, cachedSessionBytes] of cached.fileBytes.entries()) {\n if (!seen.has(cachedFile)) {\n bytes -= cachedSessionBytes;\n tokens -= cached.fileTokens.get(cachedFile) ?? 0;\n cached.fileBytes.delete(cachedFile);\n cached.fileTokens.delete(cachedFile);\n cached.fileSizes.delete(cachedFile);\n }\n }\n\n for (const file of files) {\n if (cached.fileBytes.has(file.cacheKey)) continue;\n try {\n const fileInfo = await stat(file.path);\n const estimate = await this.estimateSessionBytesInFile(file.path, sessionKey);\n cached.fileBytes.set(file.cacheKey, estimate.bytes);\n cached.fileTokens.set(file.cacheKey, estimate.tokens);\n cached.fileSizes.set(file.cacheKey, Math.max(0, fileInfo.size));\n bytes += estimate.bytes;\n tokens += estimate.tokens;\n } catch {\n }\n }\n\n for (const file of files) {\n try {\n const fileInfo = await stat(file.path);\n const size = Math.max(0, fileInfo.size);\n const previousEstimate = {\n bytes: cached.fileBytes.get(file.cacheKey) ?? 0,\n tokens: cached.fileTokens.get(file.cacheKey) ?? 0,\n };\n const previousSize = cached.fileSizes.get(file.cacheKey) ?? -1;\n if (size !== previousSize) {\n const estimate = await this.estimateSessionBytesInFile(file.path, sessionKey);\n cached.fileBytes.set(file.cacheKey, estimate.bytes);\n cached.fileTokens.set(file.cacheKey, estimate.tokens);\n cached.fileSizes.set(file.cacheKey, size);\n bytes += estimate.bytes - previousEstimate.bytes;\n tokens += estimate.tokens - previousEstimate.tokens;\n }\n } catch {\n }\n }\n\n bytes = Math.max(0, bytes);\n tokens = Math.max(0, tokens);\n cached.totalBytes = bytes;\n cached.totalTokens = tokens;\n }\n } catch {\n this.sessionFootprintCache.delete(sessionKey);\n }\n\n return { bytes, tokens };\n }\n\n private async estimateSessionBytesInFile(\n filePath: string,\n sessionKey: string,\n ): Promise<{ bytes: number; tokens: number }> {\n try {\n const raw = await readFile(filePath, \"utf-8\");\n let bytes = 0;\n let tokens = 0;\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line) as { sessionKey?: string; content?: unknown };\n if (parsed.sessionKey === sessionKey) {\n bytes += Buffer.byteLength(`${line}\\n`, \"utf-8\");\n if (typeof parsed.content === \"string\") tokens += estimateTokenCount(parsed.content);\n }\n } catch {\n // fail-open for malformed lines\n }\n }\n return { bytes, tokens };\n } catch {\n return { bytes: 0, tokens: 0 };\n }\n }\n\n private isLegacyTranscriptFile(filename: string): boolean {\n return /^\\d{4}-\\d{2}-\\d{2}\\.jsonl$/.test(filename);\n }\n\n /**\n * Append a turn to the appropriate transcript file.\n * Files are stored hierarchically: transcripts/{channelType}/{channelId}.jsonl\n *\n * Skips channel types in config.transcriptSkipChannelTypes (e.g., \"cron\").\n */\n async append(entry: TranscriptEntry): Promise<void> {\n try {\n const { dir, file, channelType, alternateDir, legacyDir } = this.getTranscriptPath(entry.sessionKey);\n\n // Skip if this channel type is in the skip list\n if (this.config.transcriptSkipChannelTypes.includes(channelType)) {\n return;\n }\n\n const { dir: writeDir, channelDir } = await this.selectStorageDirForWrite(\n this.transcriptsDir,\n dir,\n legacyDir,\n entry.sessionKey,\n alternateDir,\n );\n const filePath = await resolveSafeStoragePath(this.transcriptsDir, writeDir, file);\n\n // Ensure channel directory exists\n await mkdir(channelDir, { recursive: true });\n\n const line = JSON.stringify(entry) + \"\\n\";\n await appendFile(filePath, line, \"utf-8\");\n await this.rememberDirectoryOwnership(this.transcriptsDir, writeDir, entry.sessionKey);\n log.debug(`appended transcript entry for ${entry.sessionKey}: ${entry.turnId}`);\n } catch (err) {\n log.error(\"failed to append transcript entry:\", err);\n throw err;\n }\n }\n\n /**\n * Get all transcript files from the hierarchical directory structure.\n * Recursively finds all .jsonl files in transcripts/{channelType}/{channelId}/ subdirectories.\n */\n private async getAllTranscriptFiles(): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const entries = await readdir(this.transcriptsDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n // This is a channel type directory (discord, slack, cron, main, etc.)\n const channelTypeDir = path.join(this.transcriptsDir, entry.name);\n try {\n const channelTypeEntries = await readdir(channelTypeDir, { withFileTypes: true });\n\n for (const channelTypeEntry of channelTypeEntries) {\n if (channelTypeEntry.isDirectory()) {\n // This is a channel ID directory - contains daily transcript files\n const channelDir = path.join(channelTypeDir, channelTypeEntry.name);\n try {\n const channelFiles = await readdir(channelDir);\n for (const file of channelFiles) {\n if (file.endsWith(\".jsonl\")) {\n files.push(path.join(entry.name, channelTypeEntry.name, file));\n }\n }\n } catch {\n // Skip unreadable directories\n }\n } else if (channelTypeEntry.isFile() && channelTypeEntry.name.endsWith(\".jsonl\")) {\n // Legacy: channel type dir contains .jsonl files directly\n files.push(path.join(entry.name, channelTypeEntry.name));\n }\n }\n } catch {\n // Skip unreadable directories\n }\n } else if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n // Legacy flat file - still include for backward compatibility\n files.push(entry.name);\n }\n }\n } catch {\n // Directory doesn't exist or is unreadable\n }\n\n return files;\n }\n\n /**\n * Read transcript entries for a date range.\n * Returns entries within the time range, optionally filtered by sessionKey.\n * Reads from all channel subdirectories in the hierarchical structure.\n *\n * The window is half-open `[start, end)`: the upper bound is exclusive so\n * caller-specified ranges (explicit dates, analytics buckets) don't\n * double-count at shared boundaries (CLAUDE.md rule #35 / AGENTS.md rule 23).\n * readRecent's inclusive-of-now behavior is handled by readRecent itself\n * extending its end, not by relaxing this bound.\n */\n async readRange(startTime: string, endTime: string, sessionKey?: string, skipFilesDatedBefore?: string): Promise<TranscriptEntry[]> {\n const start = new Date(startTime);\n const end = new Date(endTime);\n const entries: TranscriptEntry[] = [];\n\n // When a sessionKey is given, a partially-applied #1496 migration can leave\n // the SAME raw row in both the primary `session/<hash>` dir and a read-back\n // dir (`other/default` or an old `parts.length >= 3` dir). `readRange` scans\n // EVERY transcript file, so it would append that row once per directory.\n // Dedup by exact raw line to give the same exact-once guarantee `readRecent`\n // / `readToolUse` / the summarizer fetch already provide (cursor review on\n // PR #1504). Only applied for the session-scoped path so unfiltered range\n // scans (each file already enumerated once) keep their existing behavior.\n const keepRawLine = sessionKey ? makeRawLineDeduper() : undefined;\n\n try {\n // Get all transcript files from the hierarchical structure\n const transcriptFiles = (await this.getAllTranscriptFiles()).filter((f) => !isDailyFileDatedBefore(f, skipFilesDatedBefore));\n\n // Read each relevant file\n for (const relativePath of transcriptFiles) {\n const filePath = path.join(this.transcriptsDir, relativePath);\n try {\n const content = await readFile(filePath, \"utf-8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const entryTime = new Date(entry.timestamp);\n\n // Check if entry is within time range (half-open: exclusive end)\n if (entryTime >= start && entryTime < end) {\n // Filter by sessionKey if provided\n if (!sessionKey || entry.sessionKey === sessionKey) {\n if (keepRawLine && !keepRawLine(line)) continue;\n entries.push(entry);\n }\n }\n } catch {\n // Skip malformed lines\n log.debug(`skipped malformed transcript line in ${relativePath}`);\n }\n }\n } catch {\n // File doesn't exist or is unreadable - skip\n }\n }\n\n // Sort by timestamp\n entries.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());\n\n log.debug(`read ${entries.length} transcript entries from ${transcriptFiles.length} file(s)`);\n return entries;\n } catch (err) {\n log.error(\"failed to read transcript range:\", err);\n return [];\n }\n }\n\n /**\n * Read the last N hours of transcript.\n *\n * Fast path: when sessionKey is given, reads only the 1-2 daily files for that channel. Without one,\n * every channel is scanned but daily files older than the window (less a day of clock skew) are skipped.\n */\n async readRecent(hours: number, sessionKey?: string): Promise<TranscriptEntry[]> {\n const now = new Date();\n // The recent-read window is inclusive of \"now\": a turn that is buffered and\n // then immediately read back can carry the same millisecond timestamp as\n // this read, so a half-open [start, now) filter would drop it. Extend the\n // upper bound by 1ms so the exclusive [start, end) filters in\n // readRecentForSession / readRange (which stay half-open for\n // caller-specified ranges, CLAUDE.md rule #35) still capture an entry\n // stamped at exactly \"now\". This is the only place the \"up to now\" boundary\n // is widened; explicit ranges are unaffected.\n const end = new Date(now.getTime() + 1);\n const start = new Date(now.getTime() - hours * 60 * 60 * 1000);\n\n if (sessionKey) {\n return this.readRecentForSession(start, end, sessionKey);\n }\n return this.readRange(start.toISOString(), end.toISOString(), undefined, new Date(start.getTime() - 86_400_000).toISOString().slice(0, 10));\n }\n\n /**\n * Optimized read for a specific session: only looks in that session's channel\n * directory and only reads files whose date falls within the lookback window.\n */\n private async readRecentForSession(\n start: Date,\n end: Date,\n sessionKey: string,\n ): Promise<TranscriptEntry[]> {\n const { dir, alternateDir, legacyDir, readbackDirs } = this.getTranscriptPath(sessionKey);\n\n // Build set of date strings that overlap with [start, end].\n // Always include end's date to handle midnight-crossing lookbacks\n // (e.g. start=23:30 yesterday, end=00:30 today).\n const dateStrings = new Set<string>();\n const cursor = new Date(start);\n while (cursor <= end) {\n dateStrings.add(cursor.toISOString().slice(0, 10));\n cursor.setDate(cursor.getDate() + 1);\n }\n dateStrings.add(end.toISOString().slice(0, 10));\n\n const entries: TranscriptEntry[] = [];\n const files = await this.getSessionStorageFiles(\n this.transcriptsDir,\n dir,\n legacyDir,\n alternateDir,\n readbackDirs,\n );\n\n // Dedup identical raw rows that a partially-applied migration may have left\n // in both the primary dir and a read-back dir (issue #1496, cursor review).\n const keepRawLine = makeRawLineDeduper();\n for (const file of files) {\n // Only read files whose date is within the window\n const dateStr = file.name.slice(0, 10);\n if (!dateStrings.has(dateStr)) continue;\n\n try {\n const content = await readFile(file.path, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const ts = new Date(entry.timestamp);\n // Half-open window: exclusive end. readRecent widens its own end by\n // 1ms so a just-written \"now\" entry is still captured here without\n // relaxing this bound for direct callers (tests/transcript-boundary).\n if (ts >= start && ts < end && entry.sessionKey === sessionKey && keepRawLine(line)) {\n entries.push(entry);\n }\n } catch {\n // skip malformed line\n }\n }\n } catch {\n // skip unreadable file\n }\n }\n\n entries.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());\n log.debug(`readRecentForSession: ${entries.length} entries from ${files.length} file(s) in ${dir}`);\n return entries;\n }\n\n /**\n * Cleanup old transcript entries that are older than retentionDays.\n * For hierarchical structure, reads each file and rewrites without old entries.\n * Legacy flat files are deleted if their date is older than retentionDays.\n * Returns the number of files processed (cleaned or deleted).\n */\n async cleanup(retentionDays: number): Promise<number> {\n if (retentionDays <= 0) {\n log.warn(\"cleanup called with invalid retentionDays:\", retentionDays);\n return 0;\n }\n\n const cutoff = new Date();\n cutoff.setDate(cutoff.getDate() - retentionDays);\n cutoff.setHours(0, 0, 0, 0);\n\n let processed = 0;\n\n try {\n const entries = await readdir(this.transcriptsDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n // This is a channel type directory (discord, slack, cron, main, etc.)\n const channelTypeDir = path.join(this.transcriptsDir, entry.name);\n try {\n const channelTypeEntries = await readdir(channelTypeDir, { withFileTypes: true });\n\n for (const channelTypeEntry of channelTypeEntries) {\n if (channelTypeEntry.isDirectory()) {\n // This is a channel ID directory - contains daily transcript files\n const channelDir = path.join(channelTypeDir, channelTypeEntry.name);\n try {\n const channelFiles = await readdir(channelDir);\n for (const file of channelFiles) {\n if (!file.endsWith(\".jsonl\")) continue;\n\n const filePath = path.join(channelDir, file);\n\n // Check if file is a daily transcript file (YYYY-MM-DD.jsonl)\n if (this.isLegacyTranscriptFile(file)) {\n const dateStr = file.slice(0, 10);\n const fileDate = new Date(dateStr);\n\n if (!isNaN(fileDate.getTime()) && fileDate < cutoff) {\n try {\n await unlink(filePath);\n processed++;\n log.debug(`deleted old daily transcript file: ${entry.name}/${channelTypeEntry.name}/${file}`);\n } catch (err) {\n log.error(`failed to delete transcript file ${filePath}:`, err);\n }\n }\n } else {\n // Legacy file in new structure - clean up old entries\n const cleaned = await this.cleanupTranscriptFile(filePath, cutoff);\n if (cleaned) {\n processed++;\n }\n }\n }\n } catch (err) {\n log.debug(`failed to process channel directory ${entry.name}/${channelTypeEntry.name}:`, err);\n }\n } else if (channelTypeEntry.isFile() && channelTypeEntry.name.endsWith(\".jsonl\")) {\n // Legacy: channel type dir contains .jsonl files directly\n const filePath = path.join(channelTypeDir, channelTypeEntry.name);\n const cleaned = await this.cleanupTranscriptFile(filePath, cutoff);\n if (cleaned) {\n processed++;\n }\n }\n }\n } catch (err) {\n log.debug(`failed to process channel type directory ${entry.name}:`, err);\n }\n } else if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n // Handle legacy flat files - delete if older than retentionDays\n if (this.isLegacyTranscriptFile(entry.name)) {\n const dateStr = entry.name.slice(0, 10);\n const fileDate = new Date(dateStr);\n\n if (!isNaN(fileDate.getTime()) && fileDate < cutoff) {\n const filePath = path.join(this.transcriptsDir, entry.name);\n try {\n await unlink(filePath);\n processed++;\n log.debug(`deleted old legacy transcript file: ${entry.name}`);\n } catch (err) {\n log.error(`failed to delete legacy transcript file ${entry.name}:`, err);\n }\n }\n }\n }\n }\n\n if (processed > 0) {\n log.info(`cleaned up ${processed} transcript file(s) older than ${retentionDays} days`);\n }\n\n return processed;\n } catch (err) {\n log.error(\"failed to cleanup old transcripts:\", err);\n return 0;\n }\n }\n\n /**\n * Clean up old entries from a single transcript file.\n * Reads the file, filters out entries older than cutoff, and rewrites if needed.\n * Returns true if the file was processed (cleaned or deleted).\n */\n private async cleanupTranscriptFile(filePath: string, cutoff: Date): Promise<boolean> {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n\n const validLines: string[] = [];\n let hasOldEntries = false;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const entryTime = new Date(entry.timestamp);\n\n if (entryTime >= cutoff) {\n validLines.push(line);\n } else {\n hasOldEntries = true;\n }\n } catch {\n // Keep malformed lines to avoid data loss\n validLines.push(line);\n }\n }\n\n if (validLines.length === 0) {\n // No valid entries left, delete the file\n try {\n await unlink(filePath);\n log.debug(`deleted empty transcript file: ${filePath}`);\n return true;\n } catch (err) {\n log.error(`failed to delete empty transcript file ${filePath}:`, err);\n return false;\n }\n }\n\n if (hasOldEntries) {\n // Rewrite file without old entries\n await writeFile(filePath, validLines.join(\"\\n\") + \"\\n\", \"utf-8\");\n log.debug(`cleaned old entries from transcript file: ${filePath}`);\n return true;\n }\n\n // No old entries found, no action needed\n return false;\n } catch (err) {\n // File doesn't exist or is unreadable\n return false;\n }\n }\n\n /**\n * Save a checkpoint to preserve conversation context.\n * Called when compaction is detected.\n */\n async saveCheckpoint(checkpoint: Checkpoint): Promise<void> {\n try {\n await writeFile(this.checkpointPath, JSON.stringify(checkpoint, null, 2), \"utf-8\");\n log.info(`saved checkpoint for session ${checkpoint.sessionKey} with ${checkpoint.turns.length} turn(s)`);\n } catch (err) {\n log.error(\"failed to save checkpoint:\", err);\n throw err;\n }\n }\n\n /**\n * Load a checkpoint if one exists and is not expired.\n * Returns null if no checkpoint exists or if it has expired.\n */\n async loadCheckpoint(sessionKey?: string): Promise<Checkpoint | null> {\n try {\n const raw = await readFile(this.checkpointPath, \"utf-8\");\n const checkpoint = JSON.parse(raw) as Checkpoint;\n\n // Validate checkpoint structure\n if (!checkpoint.sessionKey || !checkpoint.capturedAt || !checkpoint.ttl || !Array.isArray(checkpoint.turns)) {\n log.warn(\"checkpoint file has invalid structure\");\n return null;\n }\n\n // Check if checkpoint is for the requested session (if specified)\n if (sessionKey && checkpoint.sessionKey !== sessionKey) {\n log.debug(`checkpoint session mismatch: ${checkpoint.sessionKey} vs ${sessionKey}`);\n return null;\n }\n\n // Check if checkpoint has expired\n const ttl = new Date(checkpoint.ttl);\n if (isNaN(ttl.getTime())) {\n log.warn(\"checkpoint has invalid TTL format\");\n return null;\n }\n\n if (ttl < new Date()) {\n log.info(`checkpoint expired at ${checkpoint.ttl}`);\n return null;\n }\n\n log.info(`loaded checkpoint with ${checkpoint.turns.length} turn(s), expires at ${checkpoint.ttl}`);\n return checkpoint;\n } catch (err) {\n // File doesn't exist or is unreadable - that's fine\n log.debug(\"no valid checkpoint found\");\n return null;\n }\n }\n\n /**\n * Clear (delete) the checkpoint file.\n * Called after successful injection of checkpoint context.\n */\n async clearCheckpoint(): Promise<void> {\n try {\n await unlink(this.checkpointPath);\n log.info(\"cleared checkpoint\");\n } catch (err) {\n // File doesn't exist - that's fine\n log.debug(\"no checkpoint to clear\");\n }\n }\n\n /**\n * Format entries for recall injection.\n * Returns a formatted string suitable for injecting into agent context.\n *\n * Format:\n * ## Recent Conversation (last X hours)\n * [10:32] User: message content\n * [10:33] Assistant: response content\n *\n * Content is trimmed to approximately maxTokens.\n */\n formatForRecall(entries: TranscriptEntry[], maxTokens: number): string {\n if (entries.length === 0) {\n return \"\";\n }\n\n const maxTokenBudget = Math.max(0, Math.floor(maxTokens));\n if (maxTokenBudget === 0) return \"\";\n const lines: string[] = [];\n // Calculate time range for header\n const firstEntry = new Date(entries[0].timestamp);\n const lastEntry = new Date(entries[entries.length - 1].timestamp);\n const hoursDiff = Math.round((lastEntry.getTime() - firstEntry.getTime()) / (60 * 60 * 1000));\n\n // Add header\n if (hoursDiff < 1) {\n lines.push(\"## Recent Conversation (last few minutes)\");\n } else {\n lines.push(`## Recent Conversation (last ${hoursDiff} hour${hoursDiff === 1 ? \"\" : \"s\"})`);\n }\n lines.push(\"\");\n if (estimateTokenCount(lines.join(\"\\n\")) > maxTokenBudget) {\n return \"\";\n }\n\n // Format each entry\n const formattedEntries: string[] = [];\n for (const entry of entries) {\n const time = new Date(entry.timestamp);\n const timeStr = time.toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n });\n const roleLabel = entry.role === \"user\" ? \"User\" : \"Assistant\";\n formattedEntries.push(`[${timeStr}] ${roleLabel}: ${entry.content}`);\n }\n\n const selectedEntries: string[] = [];\n\n for (let i = formattedEntries.length - 1; i >= 0; i--) {\n const entry = formattedEntries[i];\n const candidate = [...lines, entry, ...selectedEntries, \"\"].join(\"\\n\");\n if (estimateTokenCount(candidate) > maxTokenBudget) {\n if (selectedEntries.length > 0) break;\n return \"\";\n }\n\n selectedEntries.unshift(entry);\n }\n if (selectedEntries.length === 0) return \"\";\n\n lines.push(...selectedEntries);\n lines.push(\"\"); // Trailing newline\n\n const result = lines.join(\"\\n\");\n log.debug(`formatted ${selectedEntries.length}/${entries.length} transcript entries for recall (~${result.length} chars)`);\n\n return result;\n }\n\n /**\n * Create a checkpoint from the current buffer state.\n * Helper method for creating checkpoints before compaction.\n */\n createCheckpoint(sessionKey: string, turns: TranscriptEntry[], ttlHours?: number): Checkpoint {\n const ttl = ttlHours ?? TranscriptManager.DEFAULT_CHECKPOINT_TTL_HOURS;\n const expiresAt = new Date();\n expiresAt.setHours(expiresAt.getHours() + ttl);\n\n return {\n sessionKey,\n capturedAt: new Date().toISOString(),\n turns: [...turns], // Copy turns to avoid mutation\n ttl: expiresAt.toISOString(),\n };\n }\n\n /**\n * Get statistics about stored transcripts.\n * Returns counts from the hierarchical directory structure.\n */\n async getStats(): Promise<{\n totalFiles: number;\n totalEntries: number;\n oldestFile: string | null;\n newestFile: string | null;\n channelTypes: Record<string, number>;\n }> {\n try {\n const allFiles = await this.getAllTranscriptFiles();\n\n if (allFiles.length === 0) {\n return {\n totalFiles: 0,\n totalEntries: 0,\n oldestFile: null,\n newestFile: null,\n channelTypes: {},\n };\n }\n\n // Sort files by path\n const sortedFiles = allFiles.sort();\n\n let totalEntries = 0;\n const channelTypes: Record<string, number> = {};\n\n for (const relativePath of allFiles) {\n const filePath = path.join(this.transcriptsDir, relativePath);\n try {\n const content = await readFile(filePath, \"utf-8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n totalEntries += lines.length;\n\n // Count by channel type (first directory in path)\n const channelType = relativePath.includes(path.sep)\n ? relativePath.split(path.sep)[0]\n : \"legacy\";\n channelTypes[channelType] = (channelTypes[channelType] || 0) + 1;\n } catch {\n // Skip unreadable files\n }\n }\n\n return {\n totalFiles: allFiles.length,\n totalEntries,\n oldestFile: sortedFiles[0],\n newestFile: sortedFiles[sortedFiles.length - 1],\n channelTypes,\n };\n } catch (err) {\n log.error(\"failed to get transcript stats:\", err);\n return {\n totalFiles: 0,\n totalEntries: 0,\n oldestFile: null,\n newestFile: null,\n channelTypes: {},\n };\n }\n }\n\n async analyzeIntegrity(): Promise<SessionIntegrityReport> {\n return analyzeSessionIntegrity({ memoryDir: this.config.memoryDir });\n }\n\n async getRecoverySummary(sessionKey?: string): Promise<{\n generatedAt: string;\n sessionKey?: string;\n healthy: boolean;\n issueCount: number;\n incompleteTurns: number;\n brokenChains: number;\n checkpointHealthy: boolean;\n }> {\n const report = await this.analyzeIntegrity();\n const selectedSessions = sessionKey\n ? report.sessions.filter((session) => session.sessionKey === sessionKey)\n : report.sessions;\n const incompleteTurns = selectedSessions.reduce((sum, session) => sum + session.incompleteTurns, 0);\n const brokenChains = selectedSessions.reduce((sum, session) => sum + session.brokenChains, 0);\n const filteredIssues = report.issues.filter((issue) => !sessionKey || issue.sessionKey === sessionKey);\n const issueCount = filteredIssues.length;\n const severeIssueCount = filteredIssues.filter((issue) => issue.severity !== \"info\").length;\n return {\n generatedAt: report.generatedAt,\n sessionKey,\n healthy: sessionKey ? severeIssueCount === 0 && report.checkpoint.healthy : report.healthy,\n issueCount,\n incompleteTurns,\n brokenChains,\n checkpointHealthy: report.checkpoint.healthy,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,OAAO,SAAS,UAAU,MAAM,QAAQ,iBAAiB;AAC9E,OAAO,UAAU;AA0BjB,SAAS,qBAAmD;AAC1D,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,CAAC,YAA6B;AACnC,QAAI,KAAK,IAAI,OAAO,EAAG,QAAO;AAC9B,SAAK,IAAI,OAAO;AAChB,WAAO;AAAA,EACT;AACF;AAeO,SAAS,YAAY,MAA8C;AACxE,QAAM,QAAQ,GAAG,IAAI;AACrB,QAAM,UAAU,KAAK,MAAM,KAAK;AAChC,MAAI,OAAO,MAAM,OAAO,GAAG;AAGzB,WAAO,EAAE,OAAO,KAAK,MAAM;AAAA,EAC7B;AACA,QAAM,OAAO,IAAI,KAAK,OAAO;AAC7B,OAAK,WAAW,KAAK,WAAW,IAAI,CAAC;AACrC,SAAO,EAAE,OAAO,KAAK,GAAG,KAAK,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC,aAAa;AACtE;AAWO,IAAM,oBAAN,M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Y,MAAM,QAAQ,iBAAiB,CAAC;AAClG,UAAM,eAAe,iBAAiB,OAAO,CAAC,KAAK,YAAY,MAAM,QAAQ,cAAc,CAAC;AAC5F,UAAM,iBAAiB,OAAO,OAAO,OAAO,CAAC,UAAU,CAAC,cAAc,MAAM,eAAe,UAAU;AACrG,UAAM,aAAa,eAAe;AAClC,UAAM,mBAAmB,eAAe,OAAO,CAAC,UAAU,MAAM,aAAa,MAAM,EAAE;AACrF,WAAO;AAAA,MACL,aAAa,OAAO;AAAA,MACpB;AAAA,MACA,SAAS,aAAa,qBAAqB,KAAK,OAAO,WAAW,UAAU,OAAO;AAAA,MACnF;AAAA,MACA;AAAA,MACA;AAAA,MACA,mBAAmB,OAAO,WAAW;AAAA,IACvC;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defineOperation
3
- } from "./chunk-BKPV47BK.js";
3
+ } from "./chunk-NGOZH7R5.js";
4
4
  import {
5
5
  EngramAccessInputError
6
6
  } from "./chunk-3MUKQQ7A.js";
@@ -71,4 +71,4 @@ defineOperation({
71
71
  })
72
72
  })
73
73
  });
74
- //# sourceMappingURL=chunk-SBBZXDVJ.js.map
74
+ //# sourceMappingURL=chunk-Q6GI7HEC.js.map
@@ -1,3 +1,7 @@
1
+ import {
2
+ searchConversationIndex,
3
+ searchConversationIndexFaissFailOpen
4
+ } from "./chunk-A7Q43EUZ.js";
1
5
  import {
2
6
  failOpenFaissHealth
3
7
  } from "./chunk-F4TWWUMP.js";
@@ -5,10 +9,6 @@ import {
5
9
  rebuildConversationChunksFailOpen,
6
10
  upsertConversationChunksFailOpen
7
11
  } from "./chunk-72A4L5JJ.js";
8
- import {
9
- searchConversationIndex,
10
- searchConversationIndexFaissFailOpen
11
- } from "./chunk-A7Q43EUZ.js";
12
12
 
13
13
  // src/conversation-index/backend.ts
14
14
  function createConversationIndexBackend(options) {
@@ -235,4 +235,4 @@ function createFaissBackend(getFaiss) {
235
235
  export {
236
236
  createConversationIndexBackend
237
237
  };
238
- //# sourceMappingURL=chunk-TFA6HPOA.js.map
238
+ //# sourceMappingURL=chunk-QCP75JGO.js.map
@@ -3,7 +3,7 @@ import {
3
3
  encodeStoragePathSegmentWithHash,
4
4
  isSafeLegacyPathSegment,
5
5
  resolveSafeStoragePath
6
- } from "./chunk-FF4KLI5W.js";
6
+ } from "./chunk-LDPPTPO5.js";
7
7
  import {
8
8
  log
9
9
  } from "./chunk-3WCASNQZ.js";
@@ -369,4 +369,4 @@ var ThreadingManager = class {
369
369
  export {
370
370
  ThreadingManager
371
371
  };
372
- //# sourceMappingURL=chunk-OJP3N7UK.js.map
372
+ //# sourceMappingURL=chunk-R7WYAXPO.js.map
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  encodeStoragePathSegment,
7
7
  resolvePathInsideStorageRoot
8
- } from "./chunk-FF4KLI5W.js";
8
+ } from "./chunk-LDPPTPO5.js";
9
9
 
10
10
  // src/summary-snapshot.ts
11
11
  import { mkdir, readFile, writeFile } from "fs/promises";
@@ -147,4 +147,4 @@ export {
147
147
  writeSummarySnapshot,
148
148
  upsertSummarySnapshot
149
149
  };
150
- //# sourceMappingURL=chunk-6DNMUYEE.js.map
150
+ //# sourceMappingURL=chunk-RIEGCK2W.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-JYG2334B.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-HPEONBM3.js";
10
+ } from "./chunk-6JIHC5AS.js";
11
11
  import {
12
12
  parseContinuityImprovementLoops
13
13
  } from "./chunk-LDXUBPMO.js";
@@ -1283,4 +1283,4 @@ export {
1283
1283
  defaultTierMigrationCycleBudget,
1284
1284
  CompoundingEngine
1285
1285
  };
1286
- //# sourceMappingURL=chunk-BCTDTVSR.js.map
1286
+ //# sourceMappingURL=chunk-RKSGUMVL.js.map
@@ -1,7 +1,13 @@
1
+ import {
2
+ readProjectedMemoryStates
3
+ } from "./chunk-7PZHH4KC.js";
1
4
  import {
2
5
  resolveCueAnchorStoreDir,
3
6
  validateCueAnchor
4
7
  } from "./chunk-BMWN7B3Y.js";
8
+ import {
9
+ StorageManager
10
+ } from "./chunk-6JIHC5AS.js";
5
11
  import {
6
12
  isValidityExpiredNow
7
13
  } from "./chunk-6CIAGZ6X.js";
@@ -31,19 +37,113 @@ import {
31
37
  compareDeterministicStrings
32
38
  } from "./chunk-G73MCJKL.js";
33
39
  import {
40
+ assertSafePathSegment,
34
41
  isRecord
35
42
  } from "./chunk-A2IYSXDQ.js";
36
43
  import {
37
44
  listJsonFilesStrict,
38
45
  readJsonFile
39
46
  } from "./chunk-B6O2YLUR.js";
47
+ import {
48
+ isPathInsideStorageRoot
49
+ } from "./chunk-LDPPTPO5.js";
50
+ import {
51
+ SecureStoreLockedError
52
+ } from "./chunk-MAAL6OZV.js";
53
+ import {
54
+ RECALL_FALLBACK_DIRS
55
+ } from "./chunk-VS2IYZRU.js";
40
56
 
41
57
  // src/harmonic-retrieval.ts
42
58
  import path from "path";
43
- async function readSourceMemories(options) {
59
+ import { existsSync } from "fs";
60
+ import { realpath } from "fs/promises";
61
+ async function readMemoryFile(storage, rootReal, filePath, abortSignal) {
62
+ throwIfAborted(abortSignal, "harmonic retrieval aborted");
63
+ if (!existsSync(filePath)) return null;
64
+ try {
65
+ if (rootReal !== null && !isPathInsideStorageRoot(rootReal, await realpath(filePath))) return null;
66
+ return await storage.readMemoryByPath(filePath);
67
+ } catch (err) {
68
+ throwIfAborted(abortSignal, "harmonic retrieval aborted");
69
+ if (err instanceof SecureStoreLockedError) throw err;
70
+ return null;
71
+ }
72
+ }
73
+ var INDEX_MAX_AGE_MS = 7 * 864e5;
74
+ var DAY_MS = 864e5;
75
+ function utcDaysSince(rebuiltMs, nowMs) {
76
+ const days = [];
77
+ for (let day = Math.floor((rebuiltMs - DAY_MS) / DAY_MS) * DAY_MS; day <= nowMs; day += DAY_MS) {
78
+ days.push(new Date(day).toISOString().slice(0, 10));
79
+ }
80
+ return days;
81
+ }
82
+ var ABSENT_SOURCE_TTL_MS = 10 * 6e4;
83
+ var ABSENT_SOURCE_MAX_ENTRIES = 4096;
84
+ var absentSourceIds = /* @__PURE__ */ new Map();
85
+ function unprojectedCandidatePaths(memoryDir, id, days) {
86
+ const paths = [];
87
+ for (const root of [memoryDir, path.join(memoryDir, "cold")]) {
88
+ for (const dir of RECALL_FALLBACK_DIRS) {
89
+ paths.push(path.join(root, dir, `${id}.md`));
90
+ for (const day of days) paths.push(path.join(root, dir, day, `${id}.md`));
91
+ }
92
+ }
93
+ return paths;
94
+ }
95
+ async function readIndexedSourceMemories(options) {
96
+ const batch = readProjectedMemoryStates(options.memoryDir, options.sourceMemoryIds);
97
+ const rebuiltMs = Date.parse(batch?.rebuiltAt ?? "");
98
+ if (!batch?.complete || !Number.isFinite(rebuiltMs) || options.nowMs - rebuiltMs > INDEX_MAX_AGE_MS) return null;
99
+ const rootReal = await realpath(options.memoryDir).catch(() => null);
100
+ if (rootReal === null) return null;
101
+ const storage = new StorageManager(options.memoryDir);
102
+ const days = utcDaysSince(rebuiltMs, options.nowMs);
103
+ const sourceMemories = /* @__PURE__ */ new Map();
104
+ const pending = [];
105
+ for (const id of options.sourceMemoryIds) {
106
+ const state = batch.states.get(id);
107
+ let safeId = true;
108
+ try {
109
+ assertSafePathSegment(id, "sourceMemoryId");
110
+ } catch {
111
+ safeId = false;
112
+ }
113
+ if (!state && !safeId) return null;
114
+ const candidates = state ? [state.path, path.join(options.memoryDir, "cold", state.pathRel)] : unprojectedCandidatePaths(options.memoryDir, id, days);
115
+ let found = false;
116
+ for (const candidate of candidates) {
117
+ const memory = await readMemoryFile(storage, rootReal, candidate, options.abortSignal);
118
+ if (memory?.frontmatter.id !== id) continue;
119
+ sourceMemories.set(id, memory);
120
+ found = true;
121
+ break;
122
+ }
123
+ const absentKey = `${options.memoryDir}\0${id}`;
124
+ if (!found && safeId && (absentSourceIds.get(absentKey) ?? 0) <= options.nowMs) pending.push(id);
125
+ }
126
+ if (pending.length === 0) return sourceMemories;
127
+ const wanted = new Set(pending);
128
+ const walked = [
129
+ ...await storage.collectActiveMemoryPaths({ abortSignal: options.abortSignal }),
130
+ ...await storage.collectColdMemoryPaths({ abortSignal: options.abortSignal })
131
+ ];
132
+ for (const filePath of walked) {
133
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
134
+ if (!wanted.has(path.basename(filePath, ".md"))) continue;
135
+ const memory = await readMemoryFile(storage, null, filePath, options.abortSignal);
136
+ if (memory && wanted.has(memory.frontmatter.id)) sourceMemories.set(memory.frontmatter.id, memory);
137
+ }
138
+ if (absentSourceIds.size > ABSENT_SOURCE_MAX_ENTRIES) absentSourceIds.clear();
139
+ for (const id of pending) {
140
+ if (!sourceMemories.has(id)) absentSourceIds.set(`${options.memoryDir}\0${id}`, options.nowMs + ABSENT_SOURCE_TTL_MS);
141
+ }
142
+ return sourceMemories;
143
+ }
144
+ async function readCorpusSourceMemories(options) {
44
145
  const sourceMemories = /* @__PURE__ */ new Map();
45
146
  try {
46
- const { StorageManager } = await import("./storage.js");
47
147
  const storage = new StorageManager(options.memoryDir);
48
148
  const [hotMemories, coldMemories] = await Promise.all([
49
149
  storage.readAllMemories({ abortSignal: options.abortSignal }),
@@ -53,12 +153,28 @@ async function readSourceMemories(options) {
53
153
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
54
154
  sourceMemories.set(memory.frontmatter.id, memory);
55
155
  }
56
- } catch {
156
+ } catch (err) {
57
157
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
158
+ if (err instanceof SecureStoreLockedError) return /* @__PURE__ */ new Map();
58
159
  sourceMemories.clear();
59
160
  }
60
161
  return sourceMemories;
61
162
  }
163
+ async function readSourceMemories(options) {
164
+ try {
165
+ const indexed = await readIndexedSourceMemories({
166
+ memoryDir: options.memoryDir,
167
+ abortSignal: options.abortSignal,
168
+ sourceMemoryIds: options.sourceMemoryIds,
169
+ nowMs: options.nowMs ?? Date.now()
170
+ });
171
+ if (indexed) return indexed;
172
+ } catch (err) {
173
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
174
+ if (err instanceof SecureStoreLockedError) return /* @__PURE__ */ new Map();
175
+ }
176
+ return readCorpusSourceMemories(options);
177
+ }
62
178
  function parseSourceMemoryInsertedAt(node) {
63
179
  const insertedAtById = /* @__PURE__ */ new Map();
64
180
  const insertedAtRaw = node.metadata?.[HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY];
@@ -214,8 +330,13 @@ async function readCueAnchors(options) {
214
330
  async function readProjectedHarmonicGraph(options) {
215
331
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
216
332
  const nodes = await readAbstractionNodes(options);
217
- const sourceBacked = nodes.some((node) => (node.sourceMemoryIds?.length ?? 0) > 0);
218
- const sourceMemories = sourceBacked ? await readSourceMemories(options) : /* @__PURE__ */ new Map();
333
+ const sourceMemoryIds = [...new Set(nodes.flatMap((node) => node.sourceMemoryIds ?? []))];
334
+ const sourceMemories = sourceMemoryIds.length > 0 ? await readSourceMemories({
335
+ memoryDir: options.memoryDir,
336
+ abortSignal: options.abortSignal,
337
+ sourceMemoryIds,
338
+ nowMs: options.nowMs
339
+ }) : /* @__PURE__ */ new Map();
219
340
  const nowMs = options.nowMs ?? Date.now();
220
341
  const legacyCompatibleNodeRefs = /* @__PURE__ */ new Set();
221
342
  const projectedNodes = nodes.flatMap((node) => {
@@ -318,4 +439,4 @@ export {
318
439
  readProjectedHarmonicGraph,
319
440
  searchHarmonicRetrieval
320
441
  };
321
- //# sourceMappingURL=chunk-GZRTH3WZ.js.map
442
+ //# sourceMappingURL=chunk-RXT6UB25.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { realpath } from \"node:fs/promises\";\nimport { listJsonFilesStrict, readJsonFile } from \"./json-store.js\";\nimport { throwIfAborted } from \"./abort-error.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 { countRecallTokenOverlap, 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 { isPathInsideStorageRoot } from \"./storage-paths.js\";\n\n\ntype SourceMemoryMap = Map<string, MemoryFile>;\n\n// `rootReal` set: a direct probe, which skips the corpus walk's symlink\n// hardening, so the resolved file must stay inside the memory root. Null: the\n// path came from the contained corpus walk and is already trusted.\nasync function readMemoryFile(\n storage: StorageManager,\n rootReal: string | null,\n filePath: string,\n abortSignal?: AbortSignal,\n): Promise<MemoryFile | null> {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n if (!existsSync(filePath)) return null;\n try {\n if (rootReal !== null && !isPathInsideStorageRoot(rootReal, await realpath(filePath))) return null;\n return await storage.readMemoryByPath(filePath);\n } catch (err) {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) throw err;\n return null;\n }\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// Source ids confirmed absent by a corpus path walk. A node only references a\n// source after the source file exists, so a confirmed absence stays true unless\n// the file is restored later; the short TTL bounds that. Without this, one\n// dangling id (a hard-deleted fact) would force a walk on every recall.\nconst ABSENT_SOURCE_TTL_MS = 10 * 60_000;\nconst ABSENT_SOURCE_MAX_ENTRIES = 4096;\nconst absentSourceIds = new Map<string, number>(); // `${memoryDir}\\0${id}` -> expiry ms\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/**\n * Resolve only the source ids the abstraction nodes reference. Returns null when\n * the projection is absent, unreadable, too old, or not known to cover every\n * active memory (a scoped or pre-`complete` rebuild), so the caller keeps the\n * full-corpus scan. Every file is read from disk, so status, tags and validity\n * are current; the index only says where to look. An id the cheap probes cannot\n * place (an import filed under an old date, a tier root outside the memory dir)\n * is looked up by one contained path-only walk, never a frontmatter parse of the\n * corpus.\n */\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 || !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 for (const id of options.sourceMemoryIds) {\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 // An unprojected id that is not a single path segment cannot be probed or\n // matched by filename, and the scan keys sources by frontmatter id, so only\n // the scan can place it. Rare (legacy/imported ids); worst case is the old cost.\n if (!state && !safeId) return null;\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 : unprojectedCandidatePaths(options.memoryDir, id, days);\n let found = false;\n for (const candidate of candidates) {\n const memory = await readMemoryFile(storage, rootReal, candidate, options.abortSignal);\n if (memory?.frontmatter.id !== id) continue;\n sourceMemories.set(id, memory);\n found = true;\n break;\n }\n const absentKey = `${options.memoryDir}\\0${id}`;\n if (!found && safeId && (absentSourceIds.get(absentKey) ?? 0) <= options.nowMs) pending.push(id);\n }\n if (pending.length === 0) return sourceMemories;\n\n const wanted = new Set(pending);\n const walked = [\n ...(await storage.collectActiveMemoryPaths({ abortSignal: options.abortSignal })),\n ...(await storage.collectColdMemoryPaths({ abortSignal: options.abortSignal })),\n ];\n for (const filePath of walked) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (!wanted.has(path.basename(filePath, \".md\"))) continue;\n const memory = await readMemoryFile(storage, null, filePath, options.abortSignal);\n if (memory && wanted.has(memory.frontmatter.id)) sourceMemories.set(memory.frontmatter.id, memory);\n }\n if (absentSourceIds.size > ABSENT_SOURCE_MAX_ENTRIES) absentSourceIds.clear();\n for (const id of pending) {\n if (!sourceMemories.has(id)) absentSourceIds.set(`${options.memoryDir}\\0${id}`, options.nowMs + ABSENT_SOURCE_TTL_MS);\n }\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(),\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\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 // #2332: a private support-passport record leaves the eligible set the\n // same way a rejected one does — a node title or anchor attribution\n // rebuilt from it would leak governed metadata into the deep-recall\n // frontier (and every other graph reader) before any content check runs.\n !isSupportPassportPrivateMemory(memory) &&\n inferMemoryStatus(memory.frontmatter, toMemoryPathRel(memoryDir, memory.path)) === \"active\" &&\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 scoreNode(node: AbstractionNode, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = countRecallTokenOverlap(queryTokens, node.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = countRecallTokenOverlap(queryTokens, node.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, node.tags?.join(\" \"));\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = countRecallTokenOverlap(queryTokens, node.entityRefs?.join(\" \"));\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = countRecallTokenOverlap(queryTokens, `${node.kind} ${node.abstractionLevel}`);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(\n anchor: CueAnchor,\n queryTokens: Set<string>,\n eligibleNodeTags: readonly string[]\n): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = countRecallTokenOverlap(queryTokens, anchor.anchorValue);\n const normalizedMatches = countRecallTokenOverlap(queryTokens, anchor.normalizedCue);\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 = countRecallTokenOverlap(queryTokens, anchor.anchorType);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, eligibleNodeTags.join(\" \"));\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 nodes: AbstractionNode[] = [];\n for (const filePath of files) {\n try {\n nodes.push(validateAbstractionNode(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return nodes;\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 anchors: CueAnchor[] = [];\n for (const filePath of files) {\n try {\n anchors.push(validateCueAnchor(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return anchors;\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 */\nexport async function readProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\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 // 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: [] };\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 };\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}): 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 { nodes: eligibleNodes, anchors } = await readProjectedHarmonicGraph(options);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const node of eligibleNodes) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const { score, matchedFields } = scoreNode(node, 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 const nodeIndex = new Map(eligibleNodes.map((node) => [node.nodeId, node]));\n for (const anchor of anchors) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n // `nodeRefs` are the projection's surviving references already.\n const eligibleNodeRefs = anchor.nodeRefs;\n const eligibleNodeTags = new Set(eligibleNodeRefs.flatMap((nodeRef) => nodeIndex.get(nodeRef)?.tags ?? []));\n const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];\n const { score, matchedFields } = scoreAnchor(anchor, queryTokens, eligibleAnchorTags);\n if (score <= 0) continue;\n for (const nodeRef of eligibleNodeRefs) {\n const node = nodeIndex.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,kBAAkB;AAC3B,SAAS,gBAAgB;AA8BzB,eAAe,eACb,SACA,UACA,UACA,aAC4B;AAC5B,iBAAe,aAAa,4BAA4B;AACxD,MAAI,CAAC,WAAW,QAAQ,EAAG,QAAO;AAClC,MAAI;AACF,QAAI,aAAa,QAAQ,CAAC,wBAAwB,UAAU,MAAM,SAAS,QAAQ,CAAC,EAAG,QAAO;AAC9F,WAAO,MAAM,QAAQ,iBAAiB,QAAQ;AAAA,EAChD,SAAS,KAAK;AACZ,mBAAe,aAAa,4BAA4B;AACxD,QAAI,eAAe,uBAAwB,OAAM;AACjD,WAAO;AAAA,EACT;AACF;AAIA,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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AAI,KAAK;AACnE,iBAAS,eAAe,IAAI,OAAO,UAAU;AAAA,UAC3C,UAAU,OAAO;AAAA,UACjB,YAAY,OAAO;AAAA,UACnB,aAAa,OAAO;AAAA,QACtB,CAAC;AACD,mBAAW,IAAI,SAAS,QAAQ;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,SAAO,CAAC,GAAG,WAAW,OAAO,CAAC,EAC3B,IAAI,CAAC,cAAc;AAClB,QAAI,QAAQ,UAAU,YAAY,UAAU;AAC5C,QAAI,QAAQ,cAAc,UAAU,KAAK,eAAe,QAAQ,WAAY,UAAS;AACrF,WAAO;AAAA,MACL,MAAM,UAAU;AAAA,MAChB;AAAA,MACA,WAAW,UAAU;AAAA,MACrB,aAAa,UAAU;AAAA,MACvB,eAAe,CAAC,GAAG,UAAU,aAAa,EAAE,KAAK;AAAA,MACjD,gBAAgB,CAAC,GAAG,UAAU,eAAe,OAAO,CAAC,EAAE;AAAA,QACrD,CAAC,MAAM,UACL,KAAK,WAAW,cAAc,MAAM,UAAU,KAAK,KAAK,YAAY,cAAc,MAAM,WAAW;AAAA,MACvG;AAAA,IACF;AAAA,EACF,CAAC,EACA,OAAO,CAAC,WAAW,OAAO,YAAY,KAAK,OAAO,cAAc,CAAC,EACjE;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,6 +1,6 @@
1
1
  import {
2
2
  isValidCapsuleSince
3
- } from "./chunk-7LCGFUMB.js";
3
+ } from "./chunk-KQAFEZQX.js";
4
4
  import {
5
5
  CAPSULE_ID_PATTERN
6
6
  } from "./chunk-WEHSQBFR.js";
@@ -12,7 +12,7 @@ import {
12
12
  import {
13
13
  OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,
14
14
  OFFLINE_SYNC_MAX_MTIME_MS
15
- } from "./chunk-5R4YPRAR.js";
15
+ } from "./chunk-TGF43K66.js";
16
16
  import {
17
17
  validateArchiveRelativePath
18
18
  } from "./chunk-GCGJW34D.js";
@@ -563,4 +563,4 @@ export {
563
563
  actionConfidenceRequestSchema,
564
564
  validateRequest
565
565
  };
566
- //# sourceMappingURL=chunk-47I2EK6G.js.map
566
+ //# sourceMappingURL=chunk-SIYZDT2V.js.map
@@ -9,21 +9,10 @@ import {
9
9
  writeOfflineUploadChunk,
10
10
  writeSafeFileFromUpload
11
11
  } from "./chunk-3E6DGSGZ.js";
12
- import {
13
- OFFLINE_SYNC_FAST_BASE_MTIME_TOLERANCE_MS,
14
- SYNC_INTERNAL_DIR,
15
- assertOfflineSyncMtimeMs,
16
- isEncryptedOfflineSyncFile,
17
- plainFileDigest,
18
- readPlainOfflineSyncFileChunk,
19
- setSafeFileMtime,
20
- sha256OfflineSyncFile,
21
- shouldExcludeOfflineSyncFile
22
- } from "./chunk-EFHNFTWB.js";
23
12
  import {
24
13
  applyChangesetEmbeddingGenerations,
25
14
  normalizeChangesetGenerations
26
- } from "./chunk-DB6XFMOF.js";
15
+ } from "./chunk-VC4J4UTI.js";
27
16
  import {
28
17
  applyIncomingEmbeddingGenerations,
29
18
  assertEmbeddingGenerationStillIncluded,
@@ -32,22 +21,33 @@ import {
32
21
  embeddingGenerationMembership,
33
22
  isEmbeddingGenerationDirPath,
34
23
  isPathInOmittedEmbeddingGeneration
35
- } from "./chunk-GZ2KV2RO.js";
24
+ } from "./chunk-WWLAKRMX.js";
36
25
  import {
37
26
  isEmbeddingGenerationMarkerPath,
38
27
  matchesOfflineSyncDefaultExclude
39
28
  } from "./chunk-63LFM77Z.js";
40
29
  import {
41
- isCanonicalRuntimeStatePath,
42
- shouldDeleteAbsentIncomingOfflineRuntimeFile,
43
- shouldPreferIncomingOfflineRuntimeFile
44
- } from "./chunk-TYT4TEQV.js";
30
+ OFFLINE_SYNC_FAST_BASE_MTIME_TOLERANCE_MS,
31
+ SYNC_INTERNAL_DIR,
32
+ assertOfflineSyncMtimeMs,
33
+ isEncryptedOfflineSyncFile,
34
+ plainFileDigest,
35
+ readPlainOfflineSyncFileChunk,
36
+ setSafeFileMtime,
37
+ sha256OfflineSyncFile,
38
+ shouldExcludeOfflineSyncFile
39
+ } from "./chunk-EFHNFTWB.js";
45
40
  import {
46
41
  prepareSafeArchiveRoot,
47
42
  resolveSafeArchiveTarget,
48
43
  sha256Bytes,
49
44
  validateArchiveRelativePath
50
45
  } from "./chunk-GCGJW34D.js";
46
+ import {
47
+ isCanonicalRuntimeStatePath,
48
+ shouldDeleteAbsentIncomingOfflineRuntimeFile,
49
+ shouldPreferIncomingOfflineRuntimeFile
50
+ } from "./chunk-TYT4TEQV.js";
51
51
  import {
52
52
  withEmbeddingGenerationLock,
53
53
  withEmbeddingGenerationLockIter
@@ -1787,4 +1787,4 @@ export {
1787
1787
  normalizeOfflineSyncState,
1788
1788
  fileStatesFromSnapshot
1789
1789
  };
1790
- //# sourceMappingURL=chunk-5R4YPRAR.js.map
1790
+ //# sourceMappingURL=chunk-TGF43K66.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-HPEONBM3.js";
3
+ } from "./chunk-6JIHC5AS.js";
4
4
  import {
5
5
  composeMemoryEnvelope
6
6
  } from "./chunk-5AYUHSAU.js";
@@ -546,4 +546,4 @@ export {
546
546
  setSemanticRulePromotionTestHooks,
547
547
  promoteSemanticRuleFromMemory
548
548
  };
549
- //# sourceMappingURL=chunk-UP3XXGEN.js.map
549
+ //# sourceMappingURL=chunk-TNVZCLJU.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-A7AISUJI.js";
4
4
  import {
5
5
  deepRecallRequestSchema
6
- } from "./chunk-47I2EK6G.js";
6
+ } from "./chunk-SIYZDT2V.js";
7
7
  import {
8
8
  EngramAccessInputError
9
9
  } from "./chunk-3MUKQQ7A.js";
@@ -40,4 +40,4 @@ async function respondDeepRecall(req, res, respondJson, readJsonBody, service, s
40
40
  export {
41
41
  respondDeepRecall
42
42
  };
43
- //# sourceMappingURL=chunk-RGGXSN5A.js.map
43
+ //# sourceMappingURL=chunk-U6HWKOGD.js.map