@remnic/core 10.0.191 → 10.0.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/abstraction-nodes.js +4 -4
  2. package/dist/access-admin-ops-surface.js +62 -62
  3. package/dist/access-cli.js +62 -62
  4. package/dist/access-extraction-force-flush-preempt.js +62 -62
  5. package/dist/access-extraction-force-flush.js +62 -62
  6. package/dist/access-http-briefing.js +62 -62
  7. package/dist/access-http-query.js +62 -62
  8. package/dist/access-http.js +62 -62
  9. package/dist/access-identity-continuity-surface.js +62 -62
  10. package/dist/access-lcm-surface.js +62 -62
  11. package/dist/access-mcp.js +62 -62
  12. package/dist/access-observe-write-surface.js +62 -62
  13. package/dist/access-operations-batch.js +62 -62
  14. package/dist/access-operations.js +62 -62
  15. package/dist/access-recall-concurrency.js +62 -62
  16. package/dist/access-recall-diagnostics.js +2 -2
  17. package/dist/access-recall-response.js +62 -62
  18. package/dist/access-recall-surface.js +62 -62
  19. package/dist/access-service.js +62 -62
  20. package/dist/active-recall.js +11 -11
  21. package/dist/briefing.js +11 -11
  22. package/dist/buffer-persistence.d.ts +7 -0
  23. package/dist/buffer-persistence.d.ts.map +1 -1
  24. package/dist/buffer-persistence.js +1 -1
  25. package/dist/buffer.d.ts +2 -0
  26. package/dist/buffer.d.ts.map +1 -1
  27. package/dist/buffer.js +6 -6
  28. package/dist/{capsule-merge-BADOICNP.js → capsule-merge-3FARYIHP.js} +5 -5
  29. package/dist/causal-consolidation.js +12 -12
  30. package/dist/{chunk-IMSLPQJB.js → chunk-2QW5HPKU.js} +2 -2
  31. package/dist/{chunk-KNYUEYB6.js → chunk-2YJ2ST23.js} +2 -2
  32. package/dist/{chunk-BZ5VO7KO.js → chunk-3BICT225.js} +2 -2
  33. package/dist/{chunk-UWKHLWUE.js → chunk-3RZ4GDOH.js} +2 -2
  34. package/dist/{chunk-ODIBCZLG.js → chunk-3YID7KZ6.js} +2 -2
  35. package/dist/{chunk-4SUNBSPD.js → chunk-4EAVEDLG.js} +9 -9
  36. package/dist/{chunk-TLRIRISJ.js → chunk-4LCA2GEX.js} +2 -2
  37. package/dist/{chunk-4N33L4HY.js → chunk-5GIYIYJI.js} +2 -2
  38. package/dist/{chunk-JQCEG54G.js → chunk-75K6DRPN.js} +12 -9
  39. package/dist/chunk-75K6DRPN.js.map +1 -0
  40. package/dist/{chunk-ZDLVHGIC.js → chunk-7EP4FURO.js} +2 -2
  41. package/dist/{chunk-CAUADFDM.js → chunk-7SOKOEAZ.js} +2 -2
  42. package/dist/{chunk-7Q74DD2W.js → chunk-7V6GNQC2.js} +2 -2
  43. package/dist/{chunk-C6YKKH73.js → chunk-AALJHIKH.js} +3 -3
  44. package/dist/{chunk-C2UN2CY7.js → chunk-AJ7JHHRY.js} +2 -2
  45. package/dist/{chunk-QSVWIKNY.js → chunk-BDFSVUUZ.js} +9 -7
  46. package/dist/chunk-BDFSVUUZ.js.map +1 -0
  47. package/dist/{chunk-3DADRUGW.js → chunk-BGA7S5EF.js} +3 -3
  48. package/dist/{chunk-7GMOB4FF.js → chunk-CJSTQNE5.js} +2 -2
  49. package/dist/{chunk-6YAQ3AJ5.js → chunk-DYUPSTCV.js} +3 -3
  50. package/dist/{chunk-E5QI6C6C.js → chunk-E3LGAZJC.js} +3 -3
  51. package/dist/{chunk-NL5KFA5N.js → chunk-EEA2RM4B.js} +2 -2
  52. package/dist/{chunk-BL7WULM5.js → chunk-FDO7ITP6.js} +2 -2
  53. package/dist/{chunk-7BIGO6ZL.js → chunk-FGFU6J26.js} +3 -3
  54. package/dist/{chunk-6TIQLG7I.js → chunk-FKHXXL42.js} +2 -2
  55. package/dist/{chunk-QPD7EYGI.js → chunk-G2MS56KM.js} +2 -2
  56. package/dist/{chunk-FFTGLWHI.js → chunk-GH7IKABD.js} +2 -2
  57. package/dist/{chunk-RC2TVYY2.js → chunk-GYCUX3N4.js} +2 -2
  58. package/dist/{chunk-CJYVVVOG.js → chunk-HEJFE3BC.js} +3 -3
  59. package/dist/{chunk-KM4QO4LN.js → chunk-HLQANATZ.js} +2 -2
  60. package/dist/{chunk-RQOUKIFS.js → chunk-J7RQ3RP7.js} +2 -2
  61. package/dist/{chunk-QTHFGP5F.js → chunk-JITK24KX.js} +7 -7
  62. package/dist/{chunk-EJYUAN5F.js → chunk-K6UXWVQ6.js} +2 -2
  63. package/dist/{chunk-3XJITLZQ.js → chunk-KJ65WZHB.js} +2 -2
  64. package/dist/{chunk-JOR4Y326.js → chunk-KOVQZJ27.js} +2 -2
  65. package/dist/{chunk-O6QSBI3U.js → chunk-KZ4BJRGQ.js} +2 -2
  66. package/dist/{chunk-FZPZML67.js → chunk-LR6LWX33.js} +4 -4
  67. package/dist/{chunk-NTS2RCQK.js → chunk-NAULI3EG.js} +2 -2
  68. package/dist/{chunk-V5W67PQV.js → chunk-NOKHMWMW.js} +4 -4
  69. package/dist/{chunk-JGVW6F3Q.js → chunk-ODI4K32P.js} +5 -5
  70. package/dist/{chunk-H7USCTPQ.js → chunk-OLD2GKQJ.js} +3 -3
  71. package/dist/{chunk-D7HOJFDS.js → chunk-ONSEODO2.js} +2 -2
  72. package/dist/{chunk-R3YMWUF3.js → chunk-P3IAZQPS.js} +2 -2
  73. package/dist/{chunk-LL6WEMTC.js → chunk-P3OONWJJ.js} +2 -2
  74. package/dist/chunk-P3OONWJJ.js.map +1 -0
  75. package/dist/{chunk-7KC6LT7U.js → chunk-PSQ347YP.js} +3 -3
  76. package/dist/{chunk-U6OQ7GWU.js → chunk-QFKNIKUF.js} +2 -2
  77. package/dist/{chunk-RFVX4WE7.js → chunk-QIPRDRGM.js} +1 -1
  78. package/dist/chunk-QIPRDRGM.js.map +1 -0
  79. package/dist/{chunk-2DFXIJPZ.js → chunk-QZMGZBTF.js} +2 -2
  80. package/dist/{chunk-NSFHMGOF.js → chunk-SKJM4PKE.js} +2 -2
  81. package/dist/{chunk-T7R42MWB.js → chunk-STSORBX5.js} +2 -2
  82. package/dist/{chunk-ICA5SCIT.js → chunk-T765HQ5U.js} +3 -3
  83. package/dist/{chunk-RFEQ7DQN.js → chunk-TDG5NZAZ.js} +2 -2
  84. package/dist/{chunk-2S6PPGIR.js → chunk-TWYYUMYO.js} +2 -2
  85. package/dist/{chunk-U6JZGQXC.js → chunk-TZ7ZA2LM.js} +2 -2
  86. package/dist/{chunk-AIS7RLTG.js → chunk-UAEJKURK.js} +58 -56
  87. package/dist/{chunk-AIS7RLTG.js.map → chunk-UAEJKURK.js.map} +1 -1
  88. package/dist/{chunk-JIB3UUYV.js → chunk-UH2VY2QQ.js} +3 -3
  89. package/dist/{chunk-X5XK6WWV.js → chunk-VHQNJW4Q.js} +2 -2
  90. package/dist/{chunk-CP6MUXNI.js → chunk-WEI6HEUX.js} +11 -6
  91. package/dist/chunk-WEI6HEUX.js.map +1 -0
  92. package/dist/{chunk-3IA2SUWM.js → chunk-WRVKI6ZO.js} +2 -2
  93. package/dist/{chunk-R5S57GRK.js → chunk-XSRZM6CQ.js} +38 -13
  94. package/dist/chunk-XSRZM6CQ.js.map +1 -0
  95. package/dist/{chunk-2CWCJYT3.js → chunk-XZLCAL5O.js} +2 -2
  96. package/dist/{chunk-7MAMRCZ7.js → chunk-XZMQLON4.js} +430 -292
  97. package/dist/chunk-XZMQLON4.js.map +1 -0
  98. package/dist/{chunk-HL53XYHC.js → chunk-YCJJODER.js} +5 -5
  99. package/dist/chunk-YCJJODER.js.map +1 -0
  100. package/dist/{chunk-W7FZ7ZZE.js → chunk-Z6EFSXU3.js} +2 -2
  101. package/dist/{chunk-GRX5BE73.js → chunk-ZNCCX7P6.js} +2 -2
  102. package/dist/cli.js +62 -62
  103. package/dist/coding/export-okf-codegraph.js +10 -10
  104. package/dist/compounding/engine.js +12 -12
  105. package/dist/config.d.ts.map +1 -1
  106. package/dist/config.js +11 -11
  107. package/dist/connectors/codex-materialize-runner.js +11 -11
  108. package/dist/connectors/index.js +11 -11
  109. package/dist/consolidation-provenance-check.js +5 -5
  110. package/dist/consolidation-undo.js +4 -4
  111. package/dist/contradiction/index.js +3 -3
  112. package/dist/convergence-refresh.js +13 -13
  113. package/dist/corpus-watermark.js +13 -13
  114. package/dist/cue-anchors.js +5 -5
  115. package/dist/{entity-canonical-id-migration-74IDJFPB.js → entity-canonical-id-migration-46EMEXTB.js} +4 -4
  116. package/dist/entity-retrieval.d.ts.map +1 -1
  117. package/dist/entity-retrieval.js +11 -11
  118. package/dist/explicit-capture.js +62 -62
  119. package/dist/extraction.js +15 -15
  120. package/dist/harmonic-construction.js +6 -6
  121. package/dist/harmonic-graph-version.js +3 -3
  122. package/dist/harmonic-retrieval.d.ts +15 -0
  123. package/dist/harmonic-retrieval.d.ts.map +1 -1
  124. package/dist/harmonic-retrieval.js +16 -14
  125. package/dist/index.js +62 -62
  126. package/dist/location/index.js +12 -12
  127. package/dist/maintenance/memory-governance.js +11 -11
  128. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +11 -11
  129. package/dist/maintenance/rebuild-memory-projection-runner.js +13 -13
  130. package/dist/maintenance/rebuild-memory-projection.js +12 -12
  131. package/dist/memory-browse.js +5 -5
  132. package/dist/memory-cache.d.ts +44 -3
  133. package/dist/memory-cache.d.ts.map +1 -1
  134. package/dist/memory-cache.js +9 -1
  135. package/dist/memory-corpus-version.js +2 -2
  136. package/dist/namespaces/migrate.js +12 -12
  137. package/dist/namespaces/search.js +4 -4
  138. package/dist/namespaces/storage.js +11 -11
  139. package/dist/operator-doctor-corpus.js +14 -14
  140. package/dist/operator-toolkit.js +19 -19
  141. package/dist/orchestration/backlog-scheduler.js +63 -63
  142. package/dist/orchestration/buffer-drain-runner.js +63 -63
  143. package/dist/orchestration/maintenance.js +19 -19
  144. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  145. package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
  146. package/dist/orchestrator.js +62 -62
  147. package/dist/page-versioning.js +4 -4
  148. package/dist/qmd.js +2 -2
  149. package/dist/recall-explain-renderer.js +3 -3
  150. package/dist/recall-navigate-access.js +2 -2
  151. package/dist/recall-navigate-disclosure.js +2 -2
  152. package/dist/recall-navigate.js +2 -2
  153. package/dist/recall-navigation.js +62 -62
  154. package/dist/recall-state-view-admission.js +5 -5
  155. package/dist/recall-why-service.js +5 -5
  156. package/dist/recall-xray-cli.js +4 -4
  157. package/dist/recall-xray-renderer.js +3 -3
  158. package/dist/recall-xray.js +2 -2
  159. package/dist/{resolution-RWIGFH2W.js → resolution-4QPPLDEN.js} +4 -4
  160. package/dist/resume-bundles.js +12 -12
  161. package/dist/search/factory.js +3 -3
  162. package/dist/search/index.js +3 -3
  163. package/dist/semantic-consolidation.js +12 -12
  164. package/dist/semantic-rule-promotion.js +11 -11
  165. package/dist/semantic-rule-verifier.js +11 -11
  166. package/dist/source-agent-qualifier.js +14 -14
  167. package/dist/standup/build.js +11 -11
  168. package/dist/storage/entity-listing.d.ts +20 -0
  169. package/dist/storage/entity-listing.d.ts.map +1 -0
  170. package/dist/storage/entity-store.d.ts +5 -0
  171. package/dist/storage/entity-store.d.ts.map +1 -1
  172. package/dist/storage/hot-cache-validation.d.ts +60 -0
  173. package/dist/storage/hot-cache-validation.d.ts.map +1 -0
  174. package/dist/storage.d.ts +2 -0
  175. package/dist/storage.d.ts.map +1 -1
  176. package/dist/storage.js +10 -10
  177. package/dist/transfer/capsule-import.js +5 -5
  178. package/dist/transfer/export-okf.js +11 -11
  179. package/dist/types.d.ts +2 -0
  180. package/dist/types.d.ts.map +1 -1
  181. package/dist/types.js +1 -1
  182. package/dist/verified-recall.js +11 -11
  183. package/dist/who-knows-cli.js +12 -12
  184. package/dist/who-knows.js +11 -11
  185. package/package.json +2 -2
  186. package/src/buffer-large-session-defer.test.ts +81 -0
  187. package/src/buffer-persistence.ts +8 -1
  188. package/src/buffer.ts +9 -4
  189. package/src/config.test.ts +9 -0
  190. package/src/config.ts +3 -6
  191. package/src/entity-recall-hot-cache.test.ts +116 -0
  192. package/src/entity-retrieval.ts +22 -4
  193. package/src/harmonic-graph-cache.test.ts +28 -9
  194. package/src/harmonic-retrieval.ts +20 -4
  195. package/src/memory-cache-hot.test.ts +47 -0
  196. package/src/memory-cache.ts +96 -17
  197. package/src/observe-flush-force-keys.test.ts +130 -0
  198. package/src/orchestration/recall-internal.ts +1 -0
  199. package/src/orchestration/turn-ingestion-buffered.test.ts +6 -2
  200. package/src/orchestration/turn-ingestion-buffered.ts +5 -1
  201. package/src/storage/entity-listing.ts +73 -0
  202. package/src/storage/entity-store.ts +25 -26
  203. package/src/storage/hot-cache-validation.ts +149 -0
  204. package/src/storage-contract/cache-coherence.test.ts +42 -5
  205. package/src/storage-hot-cache-stat-validate.test.ts +112 -0
  206. package/src/storage.ts +58 -44
  207. package/src/types.ts +2 -0
  208. package/dist/chunk-7MAMRCZ7.js.map +0 -1
  209. package/dist/chunk-CP6MUXNI.js.map +0 -1
  210. package/dist/chunk-HL53XYHC.js.map +0 -1
  211. package/dist/chunk-JQCEG54G.js.map +0 -1
  212. package/dist/chunk-LL6WEMTC.js.map +0 -1
  213. package/dist/chunk-QSVWIKNY.js.map +0 -1
  214. package/dist/chunk-R5S57GRK.js.map +0 -1
  215. package/dist/chunk-RFVX4WE7.js.map +0 -1
  216. /package/dist/{capsule-merge-BADOICNP.js.map → capsule-merge-3FARYIHP.js.map} +0 -0
  217. /package/dist/{chunk-IMSLPQJB.js.map → chunk-2QW5HPKU.js.map} +0 -0
  218. /package/dist/{chunk-KNYUEYB6.js.map → chunk-2YJ2ST23.js.map} +0 -0
  219. /package/dist/{chunk-BZ5VO7KO.js.map → chunk-3BICT225.js.map} +0 -0
  220. /package/dist/{chunk-UWKHLWUE.js.map → chunk-3RZ4GDOH.js.map} +0 -0
  221. /package/dist/{chunk-ODIBCZLG.js.map → chunk-3YID7KZ6.js.map} +0 -0
  222. /package/dist/{chunk-4SUNBSPD.js.map → chunk-4EAVEDLG.js.map} +0 -0
  223. /package/dist/{chunk-TLRIRISJ.js.map → chunk-4LCA2GEX.js.map} +0 -0
  224. /package/dist/{chunk-4N33L4HY.js.map → chunk-5GIYIYJI.js.map} +0 -0
  225. /package/dist/{chunk-ZDLVHGIC.js.map → chunk-7EP4FURO.js.map} +0 -0
  226. /package/dist/{chunk-CAUADFDM.js.map → chunk-7SOKOEAZ.js.map} +0 -0
  227. /package/dist/{chunk-7Q74DD2W.js.map → chunk-7V6GNQC2.js.map} +0 -0
  228. /package/dist/{chunk-C6YKKH73.js.map → chunk-AALJHIKH.js.map} +0 -0
  229. /package/dist/{chunk-C2UN2CY7.js.map → chunk-AJ7JHHRY.js.map} +0 -0
  230. /package/dist/{chunk-3DADRUGW.js.map → chunk-BGA7S5EF.js.map} +0 -0
  231. /package/dist/{chunk-7GMOB4FF.js.map → chunk-CJSTQNE5.js.map} +0 -0
  232. /package/dist/{chunk-6YAQ3AJ5.js.map → chunk-DYUPSTCV.js.map} +0 -0
  233. /package/dist/{chunk-E5QI6C6C.js.map → chunk-E3LGAZJC.js.map} +0 -0
  234. /package/dist/{chunk-NL5KFA5N.js.map → chunk-EEA2RM4B.js.map} +0 -0
  235. /package/dist/{chunk-BL7WULM5.js.map → chunk-FDO7ITP6.js.map} +0 -0
  236. /package/dist/{chunk-7BIGO6ZL.js.map → chunk-FGFU6J26.js.map} +0 -0
  237. /package/dist/{chunk-6TIQLG7I.js.map → chunk-FKHXXL42.js.map} +0 -0
  238. /package/dist/{chunk-QPD7EYGI.js.map → chunk-G2MS56KM.js.map} +0 -0
  239. /package/dist/{chunk-FFTGLWHI.js.map → chunk-GH7IKABD.js.map} +0 -0
  240. /package/dist/{chunk-RC2TVYY2.js.map → chunk-GYCUX3N4.js.map} +0 -0
  241. /package/dist/{chunk-CJYVVVOG.js.map → chunk-HEJFE3BC.js.map} +0 -0
  242. /package/dist/{chunk-KM4QO4LN.js.map → chunk-HLQANATZ.js.map} +0 -0
  243. /package/dist/{chunk-RQOUKIFS.js.map → chunk-J7RQ3RP7.js.map} +0 -0
  244. /package/dist/{chunk-QTHFGP5F.js.map → chunk-JITK24KX.js.map} +0 -0
  245. /package/dist/{chunk-EJYUAN5F.js.map → chunk-K6UXWVQ6.js.map} +0 -0
  246. /package/dist/{chunk-3XJITLZQ.js.map → chunk-KJ65WZHB.js.map} +0 -0
  247. /package/dist/{chunk-JOR4Y326.js.map → chunk-KOVQZJ27.js.map} +0 -0
  248. /package/dist/{chunk-O6QSBI3U.js.map → chunk-KZ4BJRGQ.js.map} +0 -0
  249. /package/dist/{chunk-FZPZML67.js.map → chunk-LR6LWX33.js.map} +0 -0
  250. /package/dist/{chunk-NTS2RCQK.js.map → chunk-NAULI3EG.js.map} +0 -0
  251. /package/dist/{chunk-V5W67PQV.js.map → chunk-NOKHMWMW.js.map} +0 -0
  252. /package/dist/{chunk-JGVW6F3Q.js.map → chunk-ODI4K32P.js.map} +0 -0
  253. /package/dist/{chunk-H7USCTPQ.js.map → chunk-OLD2GKQJ.js.map} +0 -0
  254. /package/dist/{chunk-D7HOJFDS.js.map → chunk-ONSEODO2.js.map} +0 -0
  255. /package/dist/{chunk-R3YMWUF3.js.map → chunk-P3IAZQPS.js.map} +0 -0
  256. /package/dist/{chunk-7KC6LT7U.js.map → chunk-PSQ347YP.js.map} +0 -0
  257. /package/dist/{chunk-U6OQ7GWU.js.map → chunk-QFKNIKUF.js.map} +0 -0
  258. /package/dist/{chunk-2DFXIJPZ.js.map → chunk-QZMGZBTF.js.map} +0 -0
  259. /package/dist/{chunk-NSFHMGOF.js.map → chunk-SKJM4PKE.js.map} +0 -0
  260. /package/dist/{chunk-T7R42MWB.js.map → chunk-STSORBX5.js.map} +0 -0
  261. /package/dist/{chunk-ICA5SCIT.js.map → chunk-T765HQ5U.js.map} +0 -0
  262. /package/dist/{chunk-RFEQ7DQN.js.map → chunk-TDG5NZAZ.js.map} +0 -0
  263. /package/dist/{chunk-2S6PPGIR.js.map → chunk-TWYYUMYO.js.map} +0 -0
  264. /package/dist/{chunk-U6JZGQXC.js.map → chunk-TZ7ZA2LM.js.map} +0 -0
  265. /package/dist/{chunk-JIB3UUYV.js.map → chunk-UH2VY2QQ.js.map} +0 -0
  266. /package/dist/{chunk-X5XK6WWV.js.map → chunk-VHQNJW4Q.js.map} +0 -0
  267. /package/dist/{chunk-3IA2SUWM.js.map → chunk-WRVKI6ZO.js.map} +0 -0
  268. /package/dist/{chunk-2CWCJYT3.js.map → chunk-XZLCAL5O.js.map} +0 -0
  269. /package/dist/{chunk-W7FZ7ZZE.js.map → chunk-Z6EFSXU3.js.map} +0 -0
  270. /package/dist/{chunk-GRX5BE73.js.map → chunk-ZNCCX7P6.js.map} +0 -0
  271. /package/dist/{entity-canonical-id-migration-74IDJFPB.js.map → entity-canonical-id-migration-46EMEXTB.js.map} +0 -0
  272. /package/dist/{resolution-RWIGFH2W.js.map → resolution-4QPPLDEN.js.map} +0 -0
@@ -15,8 +15,25 @@ interface CacheEntry {
15
15
  // so the opportunistic sweep can evict abandoned corpora that are never
16
16
  // revisited. 0 = no TTL (never swept by age).
17
17
  ttlMs: number;
18
+ // COS-825: per-file stat snapshot (path -> mtime+size) taken when the entry
19
+ // was read from disk. Lets a version-mismatched entry be validated by
20
+ // metadata instead of a full corpus re-read (the write path patches the
21
+ // entry in place, so its contents are usually already current).
22
+ stats?: HotCacheStatsSnapshot;
18
23
  }
19
24
 
25
+ /** COS-825: one file's entry in a hot-cache stat snapshot. */
26
+ export interface HotCacheStatEntry {
27
+ mtimeMs: number;
28
+ size: number;
29
+ }
30
+
31
+ /** COS-825: per-file stat snapshot carried by a hot-cache entry. */
32
+ export type HotCacheStatsSnapshot = Map<string, HotCacheStatEntry>;
33
+
34
+ /** COS-825 diagnostics for the hot-memories read path. */
35
+ export const hotCacheReadStats = { validatedHits: 0, fullScans: 0 };
36
+
20
37
  // Module-level singleton — shared across all StorageManager instances and sessions
21
38
  const hotCacheByDir = new Map<string, CacheEntry>();
22
39
  const archiveCacheByDir = new Map<string, CacheEntry>();
@@ -77,27 +94,76 @@ export function setCachedMemories(
77
94
  version: number,
78
95
  keyId = "",
79
96
  ttlMs = 0,
97
+ stats?: HotCacheStatsSnapshot,
80
98
  ): void {
81
99
  const map = new Map<string, MemoryFile>();
82
100
  for (const m of memories) map.set(m.path, m);
83
101
  const now = Date.now();
84
- hotCacheByDir.set(baseDir, { memories: map, version, loadedAt: now, keyId, ttlMs });
102
+ hotCacheByDir.set(baseDir, { memories: map, version, loadedAt: now, keyId, ttlMs, stats });
85
103
  // Release abandoned corpora that expired but were never revisited (Codex Medium).
86
104
  sweepExpiredHotEntries(now);
87
105
  }
88
106
 
107
+ /**
108
+ * COS-825: the raw entry for stat validation. Returns the entry only when its
109
+ * secure-store key identity matches AND it carries a stat snapshot; callers
110
+ * validate the snapshot against disk and then promote via
111
+ * {@link promoteHotCacheVersion}.
112
+ */
113
+ export function getHotCacheEntry(
114
+ baseDir: string,
115
+ keyId: string,
116
+ ): {
117
+ memories: ReadonlyMap<string, MemoryFile>;
118
+ stats: HotCacheStatsSnapshot;
119
+ loadedAt: number;
120
+ } | null {
121
+ const entry = hotCacheByDir.get(baseDir);
122
+ if (!entry || entry.keyId !== keyId || !entry.stats) return null;
123
+ return { memories: entry.memories, stats: entry.stats, loadedAt: entry.loadedAt };
124
+ }
125
+
126
+ /**
127
+ * COS-825: after stat validation passes, re-key the patched entry to the
128
+ * current corpus version and serve it — the equivalent of a fresh full read
129
+ * without the read. Counts as a validated hit.
130
+ */
131
+ export function promoteHotCacheVersion(baseDir: string, version: number, keyId: string): MemoryFile[] | null {
132
+ const entry = hotCacheByDir.get(baseDir);
133
+ if (!entry || entry.keyId !== keyId || version === 0) return null;
134
+ entry.version = version;
135
+ // loadedAt is deliberately NOT refreshed: the TTL is the recovery bound for
136
+ // edits that preserve size and mtime, and resetting it here would let
137
+ // repeated version churn defer that fresh scan indefinitely (COS-825 review
138
+ // round 3).
139
+ hotCacheReadStats.validatedHits++;
140
+ return [...entry.memories.values()];
141
+ }
142
+
89
143
  export function updateCacheOnWrite(baseDir: string, memory: MemoryFile, keyId = ""): void {
90
144
  const entry = hotCacheByDir.get(baseDir);
91
145
  // Only mutate an entry that belongs to THIS key identity (issue #1902, Codex
92
146
  // Medium). A concurrent differently-keyed manager may have replaced the
93
147
  // single hotCacheByDir slot during an awaited parse; inserting our decrypted
94
148
  // MemoryFile into its entry would leak plaintext across the key boundary.
95
- if (entry && entry.keyId === keyId) entry.memories.set(memory.path, memory);
149
+ if (entry && entry.keyId === keyId) {
150
+ entry.memories.set(memory.path, memory);
151
+ // COS-825 review: a peer can rewrite the same path between our content
152
+ // write and any stat we take, which would let the snapshot vouch the
153
+ // peer's bytes for our content on every later validation. Drop the
154
+ // snapshot instead: the entry keeps serving at its current version, and
155
+ // the next version churn costs the same full re-read as before this
156
+ // optimization. Never a false pass.
157
+ entry.stats = undefined;
158
+ }
96
159
  }
97
160
 
98
161
  export function updateCacheOnDelete(baseDir: string, filePath: string, keyId = ""): void {
99
162
  const entry = hotCacheByDir.get(baseDir);
100
- if (entry && entry.keyId === keyId) entry.memories.delete(filePath);
163
+ if (entry && entry.keyId === keyId) {
164
+ entry.memories.delete(filePath);
165
+ entry.stats?.delete(filePath);
166
+ }
101
167
  }
102
168
  // Archive cache — same pattern, separate store
103
169
  export function getCachedArchivedMemories(
@@ -125,7 +191,23 @@ export function setCachedArchivedMemories(
125
191
  }
126
192
 
127
193
  // Entity cache — same pattern as memory cache, but keyed by schema-aware parse inputs.
128
- const entityCacheByDir = new Map<string, { entities: EntityFile[]; version: number; loadedAt: number }>();
194
+ // COS-825: validity is the entities-dir listing snapshot (name, mtime, size)
195
+ // carried by the entry, NOT the memory-status version — status churns with
196
+ // unrelated memory lifecycle writes (supersede/archive/cleanup) and used to
197
+ // bust this cache on every recall under observe traffic. Entity-file changes
198
+ // always change the listing (and bump the entity-mutation version, which is
199
+ // part of the caller's cache key).
200
+ interface EntityCacheEntry {
201
+ entities: EntityFile[];
202
+ loadedAt: number;
203
+ /** Snapshot of the entities dir at build time: name -> `${mtimeMs}:${size}`. */
204
+ listing: ReadonlyMap<string, string>;
205
+ }
206
+
207
+ const entityCacheByDir = new Map<string, EntityCacheEntry>();
208
+
209
+ /** COS-825 diagnostics: a hit is a served cache entry whose listing validated. */
210
+ export const entityCacheStats = { hits: 0, rebuilds: 0 };
129
211
 
130
212
  /**
131
213
  * Single normalization point for the entity-cache schema key (issue #1535).
@@ -146,26 +228,19 @@ function buildEntityCacheKey(baseDir: string, schemaKey?: string): string {
146
228
  return `${entityCacheKeyPrefix(baseDir)}${normalizeEntitySchemaKey(schemaKey)}`;
147
229
  }
148
230
 
149
- export function getCachedEntities(
150
- baseDir: string,
151
- currentVersion: number,
152
- schemaKey: string = "",
153
- ): EntityFile[] | null {
154
- if (currentVersion === 0) return null;
155
- const entry = entityCacheByDir.get(buildEntityCacheKey(baseDir, schemaKey));
156
- if (!entry || entry.version !== currentVersion) return null;
157
- return entry.entities;
231
+ export function getCachedEntities(baseDir: string, cacheKey: string): EntityCacheEntry | null {
232
+ return entityCacheByDir.get(buildEntityCacheKey(baseDir, cacheKey)) ?? null;
158
233
  }
159
234
 
160
235
  export function setCachedEntities(
161
236
  baseDir: string,
162
237
  entities: EntityFile[],
163
- version: number,
164
- schemaKey: string = "",
238
+ cacheKey: string,
239
+ listing: ReadonlyMap<string, string>,
165
240
  ): void {
166
- entityCacheByDir.set(buildEntityCacheKey(baseDir, schemaKey), {
241
+ entityCacheByDir.set(buildEntityCacheKey(baseDir, cacheKey), {
167
242
  entities,
168
- version,
243
+ listing,
169
244
  loadedAt: Date.now(),
170
245
  });
171
246
  }
@@ -491,6 +566,10 @@ export function clearMemoryCache(baseDir?: string): void {
491
566
  for (const layer of ALL_CACHE_LAYERS) {
492
567
  layer.clearAll();
493
568
  }
569
+ hotCacheReadStats.validatedHits = 0;
570
+ hotCacheReadStats.fullScans = 0;
571
+ entityCacheStats.hits = 0;
572
+ entityCacheStats.rebuilds = 0;
494
573
  }
495
574
 
496
575
  /**
@@ -0,0 +1,130 @@
1
+ /**
2
+ * COS-825 — the observe durable-buffer flush is a subset barrier.
3
+ *
4
+ * `ingestReplayBatchBuffered` used to end with a full durability barrier
5
+ * (`flushPendingSave({ throwOnFailure: true })` with no `allowDeferral`), so
6
+ * every observe force-rewrote EVERY dirty session — including large sessions
7
+ * rate-limited by #3389 — and forced the ~1.16 MB admission-idempotency file
8
+ * past its coalescing interval. Under observe traffic that made the
9
+ * durable-buffer stage 10-16 s per request.
10
+ *
11
+ * The fix: the flush forces exactly the sessions this observe admitted (their
12
+ * turns must be durable before the 202) and lets everything else keep its
13
+ * steady-state deferral with the armed retry.
14
+ */
15
+ import test from "node:test";
16
+ import assert from "node:assert/strict";
17
+
18
+ import { ingestReplayBatchBuffered } from "./orchestration/turn-ingestion-buffered.js";
19
+ import { SmartBuffer } from "./buffer.js";
20
+ import { parseConfig } from "./config.js";
21
+ import { BUFFER_SESSION_DEFER_MIN_BYTES } from "./buffer-persistence.js";
22
+ import type { BufferEntryState, BufferState, BufferTurn } from "./types.js";
23
+
24
+ const BIG_CONTENT = "x".repeat(BUFFER_SESSION_DEFER_MIN_BYTES);
25
+
26
+ function makeTurn(sessionKey: string, content: string): BufferTurn {
27
+ return { role: "user", content, timestamp: "2026-12-02T12:00:00.000Z", sessionKey };
28
+ }
29
+
30
+ function bigEntry(): BufferEntryState {
31
+ return { turns: [makeTurn("big", BIG_CONTENT)], lastExtractionAt: null, extractionCount: 0 };
32
+ }
33
+
34
+ function emptyState(): BufferState {
35
+ return { turns: [], lastExtractionAt: null, extractionCount: 0 };
36
+ }
37
+
38
+ class CountingStorage {
39
+ readonly writes = new Map<string, number>();
40
+ private initial: BufferState;
41
+
42
+ constructor(initial: BufferState) {
43
+ this.initial = initial;
44
+ }
45
+
46
+ async loadBuffer(): Promise<BufferState> {
47
+ return structuredClone(this.initial);
48
+ }
49
+
50
+ async saveBuffer(state: BufferState): Promise<void> {
51
+ this.initial = structuredClone(state);
52
+ }
53
+
54
+ async saveBufferSession(key: string, _entry: BufferEntryState): Promise<void> {
55
+ this.writes.set(key, (this.writes.get(key) ?? 0) + 1);
56
+ }
57
+
58
+ async deleteBufferSession(): Promise<void> {}
59
+
60
+ isBufferSessionClaimed(): boolean {
61
+ return false;
62
+ }
63
+
64
+ writeCount(key: string): number {
65
+ return this.writes.get(key) ?? 0;
66
+ }
67
+ }
68
+
69
+ test("COS-825 the observe ingest does not force unrelated deferred sessions", async () => {
70
+ const state = emptyState();
71
+ state.entries = { big: bigEntry() };
72
+ const storage = new CountingStorage(state);
73
+ const buffer = new SmartBuffer(
74
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 0 }),
75
+ storage,
76
+ );
77
+
78
+ await buffer.addTurn("big", makeTurn("big", "more")); // first write lands
79
+ await buffer.addTurn("big", makeTurn("big", "more")); // large + recent: deferred
80
+ assert.equal(storage.writeCount("big"), 1);
81
+
82
+ await ingestReplayBatchBuffered(
83
+ {
84
+ config: parseConfig({ memoryDir: "/tmp/remnic-observe-flush" }),
85
+ buffer,
86
+ lcmEngine: null,
87
+ queueBufferedExtraction: async () => {},
88
+ },
89
+ new Map([["small", [makeTurn("small", "tiny observe turn")]]]),
90
+ { archiveLcm: false, writeNamespaceOverride: "test-ns" },
91
+ );
92
+
93
+ assert.ok(storage.writeCount("small") >= 1, "the admitted session is durable before the ack");
94
+ assert.equal(storage.writeCount("big"), 1, "the unrelated large session was not forced by the observe");
95
+
96
+ // The deferred tail still lands on a real barrier.
97
+ await buffer.save();
98
+ assert.equal(storage.writeCount("big"), 2, "a full barrier flushes the deferred session");
99
+ });
100
+
101
+ test("COS-825 the observe flush forces a recently-persisted large admitted session", async () => {
102
+ // The review finding: deferral requires lastPersistedAt, so a never-persisted
103
+ // admitted session always writes regardless of forceKeys. Admit into a large
104
+ // session that WAS persisted within the defer interval — the forced path is
105
+ // the only thing keeping its turns durable before the ack.
106
+ const state = emptyState();
107
+ state.entries = { hot: bigEntry() };
108
+ const storage = new CountingStorage(state);
109
+ const buffer = new SmartBuffer(
110
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 0 }),
111
+ storage,
112
+ );
113
+
114
+ await buffer.addTurn("hot", makeTurn("hot", "more")); // first write lands (lastPersistedAt set)
115
+ await buffer.addTurn("hot", makeTurn("hot", "more")); // large + recent: deferred, stays dirty
116
+ assert.equal(storage.writeCount("hot"), 1);
117
+
118
+ await ingestReplayBatchBuffered(
119
+ {
120
+ config: parseConfig({ memoryDir: "/tmp/remnic-observe-flush" }),
121
+ buffer,
122
+ lcmEngine: null,
123
+ queueBufferedExtraction: async () => {},
124
+ },
125
+ new Map([["hot", [makeTurn("hot", "more observe turn")]]]),
126
+ { archiveLcm: false, writeNamespaceOverride: "test-ns" },
127
+ );
128
+
129
+ assert.equal(storage.writeCount("hot"), 2, "the admitted turns of a large recent session are durable before the ack");
130
+ });
@@ -1504,6 +1504,7 @@ export class RecallInternalCoordinator {
1504
1504
  anchorsEnabled: resolveConsolidationCapabilities(this.deps.config).abstractionAnchors,
1505
1505
  temporalExpiredInInjection: this.deps.config.temporalExpiredInInjection,
1506
1506
  abortSignal: harmonicRetrievalAbort.signal, useGraphCache: true,
1507
+ graphCacheTtlMs: this.deps.config.harmonicGraphCacheTtlMs,
1507
1508
  }),
1508
1509
  ),
1509
1510
  );
@@ -22,7 +22,7 @@ interface StubBuffer {
22
22
  batches: readonly { bufferKey: string; turns: readonly BufferTurn[] }[],
23
23
  admissionKey: string,
24
24
  ): Promise<OutcomeRow[] | null | "duplicate">;
25
- flushPendingSave(opts?: { throwOnFailure?: boolean }): Promise<void>;
25
+ flushPendingSave(opts?: { throwOnFailure?: boolean; allowDeferral?: boolean; forceKeys?: ReadonlySet<string> }): Promise<void>;
26
26
  }
27
27
 
28
28
  function turn(content: string): BufferTurn {
@@ -174,7 +174,11 @@ test("buffered ingest: accepted batches flush the pending save and queue non-buf
174
174
 
175
175
  await ingestReplayBatchBuffered(deps, new Map([["s1", [turn("a")]]]), { writeNamespaceOverride: "ns-work" });
176
176
 
177
- assert.deepEqual(calls.flushArgs, [{ throwOnFailure: true }]);
177
+ assert.deepEqual(calls.flushArgs, [{
178
+ throwOnFailure: true,
179
+ allowDeferral: true,
180
+ forceKeys: new Set(["s1"]),
181
+ }]);
178
182
  assert.equal(queued.length, 1);
179
183
  assert.deepEqual(queued[0]?.turns, [extractionTurn]);
180
184
  assert.equal(queued[0]?.opts.bufferKey, "s1");
@@ -49,7 +49,11 @@ export async function ingestReplayBatchBuffered(
49
49
  if (outcomes === "duplicate") return;
50
50
  if (outcomes === null) throw replayRefusal(refusal, batches);
51
51
 
52
- await deps.buffer.flushPendingSave({ throwOnFailure: true });
52
+ // COS-825 subset barrier: the sessions THIS observe admitted must be durable
53
+ // before the ack, but other dirty sessions keep their #3389 steady-state
54
+ // deferral (armed retry lands the tail) instead of being forced per observe.
55
+ const forceKeys = new Set(outcomes.map(({ bufferKey }) => bufferKey));
56
+ await deps.buffer.flushPendingSave({ throwOnFailure: true, allowDeferral: true, forceKeys });
53
57
 
54
58
  if (options.archiveLcm !== false && deps.lcmEngine?.enabled) {
55
59
  for (const [bufferKey, sessionTurns] of bySession) {
@@ -0,0 +1,73 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import { checkCorpusReadAbort, type CorpusReadOptions } from "../corpus-read-cancellation.js";
3
+ import path from "node:path";
4
+ import { isTrustedEntitiesRoot } from "./entity-migration-completion-cache.js";
5
+ import { log } from "../logger.js";
6
+ import {
7
+ warnIgnoredMacOsReplicationJunk,
8
+ withoutMacOsReplicationJunk,
9
+ } from "../utils/macos-replication-junk.js";
10
+
11
+ /** The slice of the entity store the listing scan needs. */
12
+ export interface EntityListingDeps {
13
+ baseDir: string;
14
+ entitiesDir: string;
15
+ }
16
+
17
+ /**
18
+ * COS-825: one readdir + stat pass over the entities dir. `warn` is true on
19
+ * the rebuild path (junk entries log once per rebuild); validation passes
20
+ * quietly so cache reads never spam. Returns null when the root is untrusted
21
+ * (#3207: resolve empty) or the directory cannot be listed. Honors
22
+ * cancellation at each batch boundary (#2291 class).
23
+ */
24
+ export async function scanEntitiesDir(
25
+ deps: EntityListingDeps,
26
+ warn: boolean,
27
+ options?: CorpusReadOptions,
28
+ ): Promise<{ names: string[]; listing: Map<string, string> } | null> {
29
+ if (!(await isTrustedEntitiesRoot(deps.baseDir, deps.entitiesDir))) return null;
30
+ let listed: string[];
31
+ try {
32
+ listed = await readdir(deps.entitiesDir);
33
+ } catch {
34
+ return null;
35
+ }
36
+ const { kept: names, ignored } = withoutMacOsReplicationJunk(listed, (name) => name);
37
+ if (warn) {
38
+ warnIgnoredMacOsReplicationJunk(deps.entitiesDir, ignored, (message) => {
39
+ log.warn(`entity load ${message}`);
40
+ });
41
+ }
42
+ const listing = new Map<string, string>();
43
+ const BATCH = 200;
44
+ for (let i = 0; i < names.length; i += BATCH) {
45
+ checkCorpusReadAbort(options);
46
+ await Promise.all(names.slice(i, i + BATCH).map(async (name) => {
47
+ try {
48
+ const st = await stat(path.join(deps.entitiesDir, name));
49
+ listing.set(name, `${st.mtimeMs}:${st.size}`);
50
+ } catch {
51
+ // A racing rename/delete: mark unreadable so any mismatch against a
52
+ // stored snapshot forces a rebuild — never a false validation pass.
53
+ listing.set(name, "missing");
54
+ }
55
+ }));
56
+ }
57
+ return { names, listing };
58
+ }
59
+
60
+ /** COS-825: does a fresh listing scan match the cached snapshot exactly? */
61
+ export async function entitiesListingUnchanged(
62
+ deps: EntityListingDeps,
63
+ listing: ReadonlyMap<string, string>,
64
+ options?: CorpusReadOptions,
65
+ ): Promise<boolean> {
66
+ const scanned = await scanEntitiesDir(deps, /* warn */ false, options);
67
+ if (!scanned || scanned.listing.size !== listing.size) return false;
68
+ checkCorpusReadAbort(options);
69
+ for (const [name, token] of listing) {
70
+ if (scanned.listing.get(name) !== token) return false;
71
+ }
72
+ return true;
73
+ }
@@ -10,24 +10,20 @@
10
10
  * - fragmented-entity merge (consolidation)
11
11
  */
12
12
 
13
- import { lstat, readdir, unlink } from "node:fs/promises";
13
+ import { lstat, unlink } from "node:fs/promises";
14
14
  import path from "node:path";
15
15
  import { checkCorpusReadAbort, type CorpusReadOptions } from "../corpus-read-cancellation.js";
16
16
  import { normalizeEntityStructuredSection, sortStructuredSectionsBySchema } from "../entity-schema.js";
17
17
  import { withEntityCanonicalMutationLock } from "./entity-canonical-id-lock.js";
18
18
  import { assertSafeEntityId } from "./entity-id-safety.js";
19
+ import { entitiesListingUnchanged, scanEntitiesDir } from "./entity-listing.js";
19
20
  import {
20
21
  EntityMigrationCompletionCache,
21
- isTrustedEntitiesRoot,
22
22
  readEntityFileResolvingRename,
23
23
  } from "./entity-migration-completion-cache.js";
24
24
  import { isMalformedEntityRecord } from "../utils/malformed-entity-record.js";
25
25
  import { log } from "../logger.js";
26
- import {
27
- warnIgnoredMacOsReplicationJunk,
28
- withoutMacOsReplicationJunk,
29
- } from "../utils/macos-replication-junk.js";
30
- import { getCachedEntities, setCachedEntities } from "../memory-cache.js";
26
+ import { entityCacheStats, getCachedEntities, setCachedEntities } from "../memory-cache.js";
31
27
  import type { VersionTrigger } from "../page-versioning.js";
32
28
  import { SecureStoreDecryptError, SecureStoreLockedError } from "../secure-store/secure-fs.js";
33
29
  import type {
@@ -431,13 +427,8 @@ export class EntityStore {
431
427
  * A symlinked entities root yields an empty list and is not read.
432
428
  */
433
429
  private async readEntityDirectoryNames(): Promise<string[]> {
434
- if (!(await isTrustedEntitiesRoot(this.deps.baseDir, this.deps.entitiesDir))) return [];
435
- const entries = await readdir(this.deps.entitiesDir);
436
- const { kept, ignored } = withoutMacOsReplicationJunk(entries, (name) => name);
437
- warnIgnoredMacOsReplicationJunk(this.deps.entitiesDir, ignored, (message) => {
438
- log.warn(`entity load ${message}`);
439
- });
440
- return kept;
430
+ const scanned = await scanEntitiesDir(this.deps, /* warn */ true);
431
+ return scanned?.names ?? [];
441
432
  }
442
433
 
443
434
  /**
@@ -675,31 +666,39 @@ export class EntityStore {
675
666
  /**
676
667
  * Read all entity files and return lightweight EntityFile objects.
677
668
  * Parsing is fast (~50-100ms for ~1,800 files) since entity files are small.
669
+ *
670
+ * COS-825: the parsed cache is validated by an entities-dir listing snapshot
671
+ * (name, mtime, size) plus the entity-mutation version — NOT the memory-status
672
+ * version, which churns with unrelated memory lifecycle writes and used to
673
+ * force a full re-read on every recall under observe traffic.
678
674
  */
679
675
  async readAllEntityFiles(options?: CorpusReadOptions): Promise<EntityFile[]> {
680
676
  checkCorpusReadAbort(options);
681
- const currentVersion = this.deps.getMemoryStatusVersion();
682
677
  const cacheKey = [
683
678
  this.deps.getEntityCacheSecureStoreKey(),
684
679
  buildEntitySchemaCacheKey(this.deps.entitySchemas),
685
680
  this.deps.getEntityMutationVersion(),
686
681
  ].join("\u0000");
687
- const cached = getCachedEntities(this.deps.baseDir, currentVersion, cacheKey);
688
- if (cached) return cached;
682
+ const cached = getCachedEntities(this.deps.baseDir, cacheKey);
683
+ if (cached && (await entitiesListingUnchanged(this.deps, cached.listing, options))) {
684
+ entityCacheStats.hits++;
685
+ return cached.entities;
686
+ }
687
+ entityCacheStats.rebuilds++;
689
688
 
690
689
  try {
690
+ const scanned = await scanEntitiesDir(this.deps, /* warn */ true, options);
691
+ checkCorpusReadAbort(options);
691
692
  // A symlinked/replaced entities root has no readable entries (merged
692
693
  // #3207 semantics): resolve empty rather than following it. Within a
693
694
  // trusted root, readdir directly so planted entries reach the secure
694
695
  // read instead of being swallowed by the listing guards.
695
- if (!(await isTrustedEntitiesRoot(this.deps.baseDir, this.deps.entitiesDir))) return [];
696
- const listed = await readdir(this.deps.entitiesDir);
697
- const { kept: entries, ignored } = withoutMacOsReplicationJunk(listed, (name) => name);
698
- warnIgnoredMacOsReplicationJunk(this.deps.entitiesDir, ignored, (message) => {
699
- log.warn(`entity load ${message}`);
700
- });
701
- const mdFiles = entries.filter((e) => e.endsWith(".md"));
702
- if (mdFiles.length === 0) return [];
696
+ if (!scanned) return [];
697
+ const mdFiles = scanned.names.filter((e) => e.endsWith(".md"));
698
+ if (mdFiles.length === 0) {
699
+ setCachedEntities(this.deps.baseDir, [], cacheKey, scanned.listing);
700
+ return [];
701
+ }
703
702
 
704
703
  const historicalIds = this.deps.currentHistoricalIds();
705
704
  const seen = new Map<string, Set<string>>();
@@ -756,7 +755,7 @@ export class EntityStore {
756
755
  // A signal that fired during the last batch's await would otherwise publish
757
756
  // and return as if uncancelled (issue #2307 review).
758
757
  checkCorpusReadAbort(options);
759
- setCachedEntities(this.deps.baseDir, entities, currentVersion, cacheKey);
758
+ setCachedEntities(this.deps.baseDir, entities, cacheKey, scanned.listing);
760
759
  return entities;
761
760
  } catch (err) {
762
761
  if (err instanceof SecureStoreLockedError || !isErrnoCode(err, "ENOENT")) throw err;
@@ -0,0 +1,149 @@
1
+ import { stat } from "node:fs/promises";
2
+ import {
3
+ getCachedMemories,
4
+ getHotCacheEntry,
5
+ hotCacheReadStats,
6
+ promoteHotCacheVersion,
7
+ setCachedMemories,
8
+ type HotCacheStatEntry,
9
+ type HotCacheStatsSnapshot,
10
+ } from "../memory-cache.js";
11
+ import type { MemoryFile } from "../types.js";
12
+
13
+ /**
14
+ * The slice of StorageManager the hot-cache read path needs. Structural, so
15
+ * test doubles and Object.create prototypes keep working (#1526 playbook).
16
+ */
17
+ export interface HotCacheHost {
18
+ /** Public alias of the storage root. */
19
+ dir: string;
20
+ isHotCacheEnabled(): boolean;
21
+ hotCacheKeyId(): string;
22
+ hotCacheTtlMs(): number;
23
+ getMemoryCorpusVersion(): number;
24
+ collectActiveMemoryPaths(options?: { abortSignal?: AbortSignal }): Promise<string[]>;
25
+ }
26
+
27
+ /**
28
+ * COS-825: per-file stat snapshot for the hot-memories cache. The snapshot is
29
+ * captured by the scan itself (stat before and after each file's read), so a
30
+ * peer write that straddled a read omits that file and validation later
31
+ * misses — a snapshot can only vouch bytes actually read. Fail closed; an edit that
32
+ * preserves size and mtime is outside what file metadata can observe.
33
+ */
34
+
35
+ /**
36
+ * COS-825: publish a freshly scanned corpus with its scan-collected stat
37
+ * snapshot. Counts one disk scan. The #1902 publish guards (version and key
38
+ * identity unchanged through the scan) live here: the version guard prevents
39
+ * clobbering a newer patched + re-keyed entry, the keyId guard prevents
40
+ * publishing this key's decrypted corpus under a since-changed identity
41
+ * (#1902 Codex Medium), and a cancelled scan never reaches this at all — the
42
+ * checkpoints throw — so a partial corpus is never published.
43
+ */
44
+ export async function publishCorpusAfterScan(
45
+ host: HotCacheHost,
46
+ memories: MemoryFile[],
47
+ version: number,
48
+ keyId: string,
49
+ snapshot?: HotCacheStatsSnapshot,
50
+ ): Promise<void> {
51
+ hotCacheReadStats.fullScans++;
52
+ if (
53
+ !host.isHotCacheEnabled() ||
54
+ host.getMemoryCorpusVersion() !== version ||
55
+ host.hotCacheKeyId() !== keyId
56
+ ) {
57
+ return;
58
+ }
59
+ setCachedMemories(host.dir, memories, version, keyId, host.hotCacheTtlMs(), snapshot);
60
+ }
61
+
62
+ /**
63
+ * COS-825: read one memory file for a snapshot-bearing scan. Stats before and
64
+ * after the read: only a read that no write straddled yields a stat entry for
65
+ * the caller to record — a straddled write or a vanished file yields null, so
66
+ * a snapshot can only vouch bytes actually read. The entry is recorded by the
67
+ * CALLER after parsing succeeds, so malformed files never enter a snapshot.
68
+ */
69
+ export async function readWithStableStat(
70
+ fullPath: string,
71
+ snapshot: HotCacheStatsSnapshot | undefined,
72
+ read: () => Promise<string>,
73
+ ): Promise<{ raw: string; stat: { mtimeMs: number; size: number } } | null> {
74
+ if (!snapshot) return { raw: await read(), stat: { mtimeMs: 0, size: 0 } };
75
+ // One retry when a write straddled the read: the retried read pairs fresh
76
+ // content with a fresh stat, so the file stays in the corpus instead of
77
+ // being dropped from recall until the next full scan. A second straddle
78
+ // skips the file entirely — fail closed (COS-825 review round 4).
79
+ for (let attempt = 0; attempt < 2; attempt++) {
80
+ let before: HotCacheStatEntry;
81
+ try {
82
+ const st = await stat(fullPath);
83
+ before = { mtimeMs: st.mtimeMs, size: st.size };
84
+ } catch {
85
+ return null;
86
+ }
87
+ const raw = await read();
88
+ try {
89
+ const st = await stat(fullPath);
90
+ if (st.mtimeMs === before.mtimeMs && st.size === before.size) {
91
+ return { raw, stat: before };
92
+ }
93
+ } catch {
94
+ // The file vanished after a successful read: skip it entirely so
95
+ // validation misses instead of promoting.
96
+ return null;
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+
102
+ /**
103
+ * COS-825: serve readAllMemories from the hot cache; null means the caller
104
+ * must scan disk. The fast path is the version-keyed hit (#1902). On a
105
+ * version mismatch this process's own writes have usually patched the entry
106
+ * in place, and peer sentinel bumps (other daemons, CLI runs, converge sync)
107
+ * leave the disk unchanged — so the entry is validated against its per-file
108
+ * stat snapshot and promoted instead of re-reading the corpus. Any provable
109
+ * disk change (out-of-band edit, delete, add), or an inability to prove
110
+ * freshness (missing snapshot, unreadable file), returns null.
111
+ */
112
+ export async function serveHotMemoriesValidated(host: HotCacheHost, abortSignal?: AbortSignal): Promise<MemoryFile[] | null> {
113
+ if (!host.isHotCacheEnabled()) return null;
114
+ const keyId = host.hotCacheKeyId();
115
+ const cached = getCachedMemories(host.dir, host.getMemoryCorpusVersion(), keyId, host.hotCacheTtlMs());
116
+ if (cached !== null) return cached;
117
+ const entry = getHotCacheEntry(host.dir, keyId);
118
+ if (!entry) return null;
119
+ // The TTL is the recovery bound for edits that preserve size and mtime: an
120
+ // expired entry is never validated, it forces the full scan that re-arms a
121
+ // fresh snapshot (COS-825 review round 4).
122
+ const ttlMs = host.hotCacheTtlMs();
123
+ if (ttlMs > 0 && Date.now() - entry.loadedAt > ttlMs) return null;
124
+ // A peer write during this walk must not be promoted over: capture the
125
+ // version now and refuse promotion if it moved (the caller's scan path
126
+ // handles the changed corpus instead).
127
+ const versionAtStart = host.getMemoryCorpusVersion();
128
+ let paths: string[];
129
+ try {
130
+ paths = await host.collectActiveMemoryPaths({ abortSignal });
131
+ } catch {
132
+ return null;
133
+ }
134
+ if (paths.length !== entry.memories.size) return null;
135
+ const pathSet = new Set(paths);
136
+ for (const cachedPath of pathSet) {
137
+ const snap = entry.stats.get(cachedPath);
138
+ if (!snap) return null;
139
+ try {
140
+ const st = await stat(cachedPath);
141
+ if (st.mtimeMs !== snap.mtimeMs || st.size !== snap.size) return null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ }
146
+ if (host.getMemoryCorpusVersion() !== versionAtStart) return null;
147
+ return promoteHotCacheVersion(host.dir, versionAtStart, keyId);
148
+ }
149
+