@remnic/core 10.0.128 → 10.0.130

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 (243) hide show
  1. package/dist/access-admin-ops-surface.js +104 -103
  2. package/dist/access-cli.js +104 -103
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-extraction-force-flush.js +104 -103
  5. package/dist/access-health-types.d.ts +8 -0
  6. package/dist/access-health-types.d.ts.map +1 -1
  7. package/dist/access-http-briefing.js +104 -103
  8. package/dist/access-http-query.js +104 -103
  9. package/dist/access-http.js +104 -103
  10. package/dist/access-identity-continuity-surface.js +104 -103
  11. package/dist/access-lcm-surface.js +104 -103
  12. package/dist/access-mcp.js +104 -103
  13. package/dist/access-observe-write-category.js +6 -6
  14. package/dist/access-observe-write-surface.js +104 -103
  15. package/dist/access-offline-manifest.js +5 -5
  16. package/dist/access-operations-batch.js +104 -103
  17. package/dist/access-operations.js +104 -103
  18. package/dist/access-recall-concurrency.js +104 -103
  19. package/dist/access-recall-response.js +104 -103
  20. package/dist/access-recall-surface.js +104 -103
  21. package/dist/access-schema.js +5 -5
  22. package/dist/access-service.d.ts.map +1 -1
  23. package/dist/access-service.js +104 -103
  24. package/dist/active-recall.js +13 -13
  25. package/dist/adapters/agy.d.ts +22 -0
  26. package/dist/adapters/agy.d.ts.map +1 -0
  27. package/dist/adapters/index.js +4 -4
  28. package/dist/adapters/registry.d.ts.map +1 -1
  29. package/dist/adapters/registry.js +2 -2
  30. package/dist/briefing.js +6 -6
  31. package/dist/buffer-ingress-counters.d.ts +100 -0
  32. package/dist/buffer-ingress-counters.d.ts.map +1 -0
  33. package/dist/buffer-ingress-counters.js +11 -0
  34. package/dist/buffer-turn-helpers.d.ts +6 -0
  35. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  36. package/dist/buffer-turn-helpers.js +3 -1
  37. package/dist/buffer.d.ts +8 -1
  38. package/dist/buffer.d.ts.map +1 -1
  39. package/dist/buffer.js +3 -2
  40. package/dist/calibration.js +2 -2
  41. package/dist/causal-behavior.js +2 -2
  42. package/dist/causal-chain.js +2 -2
  43. package/dist/causal-consolidation.js +9 -9
  44. package/dist/causal-retrieval.js +2 -2
  45. package/dist/causal-trajectory-graph.js +2 -2
  46. package/dist/causal-trajectory.js +1 -1
  47. package/dist/{chunk-ID65XTF3.js → chunk-2JAT4S7N.js} +2 -2
  48. package/dist/{chunk-BR7CZVMO.js → chunk-2UW3EM3U.js} +6 -1
  49. package/dist/chunk-2UW3EM3U.js.map +1 -0
  50. package/dist/{chunk-ORMJT23N.js → chunk-3OT6JDMD.js} +8 -8
  51. package/dist/{chunk-SU42FIJ7.js → chunk-3RW5ZCYO.js} +2 -2
  52. package/dist/{chunk-TJJPT2OV.js → chunk-3S7BUGYC.js} +2 -2
  53. package/dist/{chunk-7TC2PWKH.js → chunk-4KWR7M3Q.js} +2 -2
  54. package/dist/{chunk-WRGW76LI.js → chunk-5BE3FLKL.js} +6 -6
  55. package/dist/{chunk-JK2IVISS.js → chunk-5FWPLAKP.js} +2 -2
  56. package/dist/{chunk-PPPY2PCU.js → chunk-5OW73TEG.js} +2 -2
  57. package/dist/{chunk-DTTDMK7Q.js → chunk-5RONA5FF.js} +4 -4
  58. package/dist/{chunk-6FPJPSQK.js → chunk-6P5PIOWW.js} +2 -2
  59. package/dist/{chunk-HJ7M322C.js → chunk-6PQVAYQJ.js} +2 -2
  60. package/dist/{chunk-QKYOMKRG.js → chunk-7C7M2P43.js} +2 -2
  61. package/dist/{chunk-XMKUABIG.js → chunk-AAV726HQ.js} +3 -3
  62. package/dist/{chunk-ASINXIKX.js → chunk-AWKD2A73.js} +12 -12
  63. package/dist/{chunk-XUWDB53W.js → chunk-BAKCGJRQ.js} +3 -3
  64. package/dist/{chunk-ALLI23GW.js → chunk-BE5F6KFG.js} +2 -2
  65. package/dist/{chunk-MGCV3VGC.js → chunk-BOK5D46I.js} +2 -2
  66. package/dist/{chunk-FBXU7X27.js → chunk-BTY6DUFW.js} +2 -2
  67. package/dist/{chunk-FPBFDQZZ.js → chunk-CFJBSE7J.js} +11 -11
  68. package/dist/{chunk-WYABF2WA.js → chunk-CLVILSBR.js} +3 -3
  69. package/dist/{chunk-BFBS7OFQ.js → chunk-DC55RIEZ.js} +4 -4
  70. package/dist/{chunk-NYZ6ZNFO.js → chunk-FCW4FUF2.js} +5 -5
  71. package/dist/{chunk-7QDB7P3V.js → chunk-FMFCQRDM.js} +3 -3
  72. package/dist/{chunk-CUKYV5O3.js → chunk-GCHM5BYL.js} +30 -4
  73. package/dist/chunk-GCHM5BYL.js.map +1 -0
  74. package/dist/{chunk-K36RMINQ.js → chunk-GOZXQNIM.js} +3 -3
  75. package/dist/{chunk-YFUHFPV6.js → chunk-HILGHLPA.js} +10 -10
  76. package/dist/{chunk-EFHM4VDG.js → chunk-HLWXCDUQ.js} +2 -2
  77. package/dist/{chunk-JCPEXUNP.js → chunk-IUVTFQWY.js} +2 -2
  78. package/dist/{chunk-YPE3O5VH.js → chunk-JHKCS6EN.js} +2 -2
  79. package/dist/{chunk-UWU6KEZU.js → chunk-JVQNRSWO.js} +2 -2
  80. package/dist/{chunk-PAGVXEWG.js → chunk-KLUCX6OH.js} +2 -2
  81. package/dist/{chunk-ELBZT6RU.js → chunk-KVCFAWBZ.js} +2 -2
  82. package/dist/{chunk-W4Q65VJL.js → chunk-MZCGHPIJ.js} +2 -2
  83. package/dist/{chunk-2BBCM2PX.js → chunk-N36J3MIB.js} +2 -2
  84. package/dist/{chunk-AYBRQJXP.js → chunk-NVKWV4W3.js} +2 -2
  85. package/dist/{chunk-ZUMHQEW4.js → chunk-QHDBKC5Z.js} +4 -4
  86. package/dist/chunk-RADARJEC.js +156 -0
  87. package/dist/chunk-RADARJEC.js.map +1 -0
  88. package/dist/{chunk-3OLHDECL.js → chunk-RMU3O74L.js} +157 -150
  89. package/dist/chunk-RMU3O74L.js.map +1 -0
  90. package/dist/{chunk-MCTGYIYN.js → chunk-RXD46MY6.js} +2 -2
  91. package/dist/{chunk-TJY6AKWV.js → chunk-SULNVNTU.js} +2 -2
  92. package/dist/{chunk-34YQ7CVE.js → chunk-TL6QIZT7.js} +18 -14
  93. package/dist/chunk-TL6QIZT7.js.map +1 -0
  94. package/dist/{chunk-7T7I5D3F.js → chunk-TSJQ7C2T.js} +6 -6
  95. package/dist/{chunk-HQPFACXO.js → chunk-UH3FPX3L.js} +2 -2
  96. package/dist/{chunk-6SRYCJ5I.js → chunk-V6JECHY6.js} +5 -5
  97. package/dist/{chunk-YCJRYM3Q.js → chunk-VAMCJPJT.js} +3 -3
  98. package/dist/{chunk-QC2MHZDD.js → chunk-VEFGHRKV.js} +1 -1
  99. package/dist/{chunk-O62MMJWV.js → chunk-VO3HCFSR.js} +2 -2
  100. package/dist/{chunk-4DJSDH2M.js → chunk-W5GGKQVS.js} +5 -5
  101. package/dist/{chunk-TQ5NOVMT.js → chunk-X7EAMNKR.js} +2 -2
  102. package/dist/{chunk-G53I363P.js → chunk-XF2QQQXO.js} +2 -2
  103. package/dist/{chunk-GWFL6LUU.js → chunk-XUS2UQOO.js} +2 -2
  104. package/dist/{chunk-FZVROZKC.js → chunk-XVZA6VXC.js} +4 -4
  105. package/dist/{chunk-VPEIWMUT.js → chunk-YLTU2DC4.js} +2 -2
  106. package/dist/{chunk-PXZLVFNC.js → chunk-YQXD57ZS.js} +2 -2
  107. package/dist/{chunk-LR2X3FJM.js → chunk-YW63C4FO.js} +9 -9
  108. package/dist/{chunk-LU2GQ4Q4.js → chunk-YYHBB565.js} +2 -2
  109. package/dist/{chunk-2G72JBQB.js → chunk-ZCXZNK4G.js} +2 -2
  110. package/dist/{chunk-ZO377APE.js → chunk-ZMDXISMQ.js} +3 -3
  111. package/dist/cli.js +104 -103
  112. package/dist/coding/export-okf-codegraph.js +5 -5
  113. package/dist/coding/pre-action-gate.js +2 -2
  114. package/dist/compounding/engine.js +7 -7
  115. package/dist/config.js +13 -13
  116. package/dist/connectors/codex-materialize-runner.js +6 -6
  117. package/dist/connectors/index.js +6 -6
  118. package/dist/consolidation-provenance-check.js +2 -2
  119. package/dist/convergence-refresh.js +8 -8
  120. package/dist/corpus-watermark.js +8 -8
  121. package/dist/deep-recall-http-glue.js +6 -6
  122. package/dist/embedding-fallback.js +2 -2
  123. package/dist/entity-retrieval.js +8 -8
  124. package/dist/explicit-capture.js +104 -103
  125. package/dist/extraction-span-materialize.js +2 -2
  126. package/dist/extraction.js +13 -13
  127. package/dist/{graph-edge-decay-CXTNJ7IQ.js → graph-edge-decay-EKWXRBWF.js} +5 -5
  128. package/dist/graph-edge-decay-EKWXRBWF.js.map +1 -0
  129. package/dist/graph-jsonl.js +3 -3
  130. package/dist/graph-snapshot.js +3 -3
  131. package/dist/graph.js +2 -2
  132. package/dist/harmonic-retrieval.js +6 -6
  133. package/dist/index.js +167 -166
  134. package/dist/lcm/index.js +3 -3
  135. package/dist/local-llm.js +2 -2
  136. package/dist/location/index.js +7 -7
  137. package/dist/maintenance/memory-governance.js +6 -6
  138. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +6 -6
  139. package/dist/maintenance/rebuild-memory-projection-runner.js +8 -8
  140. package/dist/maintenance/rebuild-memory-projection.js +7 -7
  141. package/dist/namespaces/migrate.js +7 -7
  142. package/dist/namespaces/storage.js +6 -6
  143. package/dist/offline-sync-changeset-generations.js +3 -3
  144. package/dist/offline-sync-embedding-generation.js +2 -2
  145. package/dist/offline-sync-snapshot-stream.js +5 -5
  146. package/dist/offline-sync.js +4 -4
  147. package/dist/operator-doctor-corpus.js +9 -9
  148. package/dist/operator-toolkit.js +23 -23
  149. package/dist/orchestration/backlog-scheduler.js +105 -104
  150. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  151. package/dist/orchestration/buffer-drain-runner.js +105 -104
  152. package/dist/orchestration/maintenance.js +16 -16
  153. package/dist/orchestrator.js +104 -103
  154. package/dist/recall-navigation.js +104 -103
  155. package/dist/resume-bundles.js +16 -16
  156. package/dist/semantic-consolidation.js +10 -10
  157. package/dist/semantic-rule-promotion.js +6 -6
  158. package/dist/semantic-rule-verifier.js +6 -6
  159. package/dist/source-agent-qualifier.js +6 -6
  160. package/dist/standup/build.js +6 -6
  161. package/dist/storage/buffer-drain-claims.js +2 -2
  162. package/dist/storage/buffer-session-files.js +2 -2
  163. package/dist/storage.js +5 -5
  164. package/dist/summarizer.js +3 -3
  165. package/dist/support-passport/index.js +3 -3
  166. package/dist/transcript.js +2 -2
  167. package/dist/transfer/export-okf.js +6 -6
  168. package/dist/verified-recall.js +6 -6
  169. package/dist/who-knows-cli.js +7 -7
  170. package/dist/who-knows.js +6 -6
  171. package/package.json +2 -2
  172. package/src/access-health-types.ts +8 -0
  173. package/src/access-http.test.ts +18 -0
  174. package/src/access-service-health-ingress.test.ts +113 -0
  175. package/src/access-service.ts +14 -7
  176. package/src/adapters/agy.test.ts +75 -0
  177. package/src/adapters/agy.ts +45 -0
  178. package/src/adapters/grok-opencode.test.ts +1 -0
  179. package/src/adapters/registry.ts +2 -0
  180. package/src/buffer-ingress-counters.test.ts +310 -0
  181. package/src/buffer-ingress-counters.ts +278 -0
  182. package/src/buffer-ingress-invariant.test.ts +290 -0
  183. package/src/buffer-turn-helpers.ts +10 -0
  184. package/src/buffer.ts +19 -21
  185. package/dist/chunk-34YQ7CVE.js.map +0 -1
  186. package/dist/chunk-3OLHDECL.js.map +0 -1
  187. package/dist/chunk-BR7CZVMO.js.map +0 -1
  188. package/dist/chunk-CUKYV5O3.js.map +0 -1
  189. /package/dist/{graph-edge-decay-CXTNJ7IQ.js.map → buffer-ingress-counters.js.map} +0 -0
  190. /package/dist/{chunk-ID65XTF3.js.map → chunk-2JAT4S7N.js.map} +0 -0
  191. /package/dist/{chunk-ORMJT23N.js.map → chunk-3OT6JDMD.js.map} +0 -0
  192. /package/dist/{chunk-SU42FIJ7.js.map → chunk-3RW5ZCYO.js.map} +0 -0
  193. /package/dist/{chunk-TJJPT2OV.js.map → chunk-3S7BUGYC.js.map} +0 -0
  194. /package/dist/{chunk-7TC2PWKH.js.map → chunk-4KWR7M3Q.js.map} +0 -0
  195. /package/dist/{chunk-WRGW76LI.js.map → chunk-5BE3FLKL.js.map} +0 -0
  196. /package/dist/{chunk-JK2IVISS.js.map → chunk-5FWPLAKP.js.map} +0 -0
  197. /package/dist/{chunk-PPPY2PCU.js.map → chunk-5OW73TEG.js.map} +0 -0
  198. /package/dist/{chunk-DTTDMK7Q.js.map → chunk-5RONA5FF.js.map} +0 -0
  199. /package/dist/{chunk-6FPJPSQK.js.map → chunk-6P5PIOWW.js.map} +0 -0
  200. /package/dist/{chunk-HJ7M322C.js.map → chunk-6PQVAYQJ.js.map} +0 -0
  201. /package/dist/{chunk-QKYOMKRG.js.map → chunk-7C7M2P43.js.map} +0 -0
  202. /package/dist/{chunk-XMKUABIG.js.map → chunk-AAV726HQ.js.map} +0 -0
  203. /package/dist/{chunk-ASINXIKX.js.map → chunk-AWKD2A73.js.map} +0 -0
  204. /package/dist/{chunk-XUWDB53W.js.map → chunk-BAKCGJRQ.js.map} +0 -0
  205. /package/dist/{chunk-ALLI23GW.js.map → chunk-BE5F6KFG.js.map} +0 -0
  206. /package/dist/{chunk-MGCV3VGC.js.map → chunk-BOK5D46I.js.map} +0 -0
  207. /package/dist/{chunk-FBXU7X27.js.map → chunk-BTY6DUFW.js.map} +0 -0
  208. /package/dist/{chunk-FPBFDQZZ.js.map → chunk-CFJBSE7J.js.map} +0 -0
  209. /package/dist/{chunk-WYABF2WA.js.map → chunk-CLVILSBR.js.map} +0 -0
  210. /package/dist/{chunk-BFBS7OFQ.js.map → chunk-DC55RIEZ.js.map} +0 -0
  211. /package/dist/{chunk-NYZ6ZNFO.js.map → chunk-FCW4FUF2.js.map} +0 -0
  212. /package/dist/{chunk-7QDB7P3V.js.map → chunk-FMFCQRDM.js.map} +0 -0
  213. /package/dist/{chunk-K36RMINQ.js.map → chunk-GOZXQNIM.js.map} +0 -0
  214. /package/dist/{chunk-YFUHFPV6.js.map → chunk-HILGHLPA.js.map} +0 -0
  215. /package/dist/{chunk-EFHM4VDG.js.map → chunk-HLWXCDUQ.js.map} +0 -0
  216. /package/dist/{chunk-JCPEXUNP.js.map → chunk-IUVTFQWY.js.map} +0 -0
  217. /package/dist/{chunk-YPE3O5VH.js.map → chunk-JHKCS6EN.js.map} +0 -0
  218. /package/dist/{chunk-UWU6KEZU.js.map → chunk-JVQNRSWO.js.map} +0 -0
  219. /package/dist/{chunk-PAGVXEWG.js.map → chunk-KLUCX6OH.js.map} +0 -0
  220. /package/dist/{chunk-ELBZT6RU.js.map → chunk-KVCFAWBZ.js.map} +0 -0
  221. /package/dist/{chunk-W4Q65VJL.js.map → chunk-MZCGHPIJ.js.map} +0 -0
  222. /package/dist/{chunk-2BBCM2PX.js.map → chunk-N36J3MIB.js.map} +0 -0
  223. /package/dist/{chunk-AYBRQJXP.js.map → chunk-NVKWV4W3.js.map} +0 -0
  224. /package/dist/{chunk-ZUMHQEW4.js.map → chunk-QHDBKC5Z.js.map} +0 -0
  225. /package/dist/{chunk-MCTGYIYN.js.map → chunk-RXD46MY6.js.map} +0 -0
  226. /package/dist/{chunk-TJY6AKWV.js.map → chunk-SULNVNTU.js.map} +0 -0
  227. /package/dist/{chunk-7T7I5D3F.js.map → chunk-TSJQ7C2T.js.map} +0 -0
  228. /package/dist/{chunk-HQPFACXO.js.map → chunk-UH3FPX3L.js.map} +0 -0
  229. /package/dist/{chunk-6SRYCJ5I.js.map → chunk-V6JECHY6.js.map} +0 -0
  230. /package/dist/{chunk-YCJRYM3Q.js.map → chunk-VAMCJPJT.js.map} +0 -0
  231. /package/dist/{chunk-QC2MHZDD.js.map → chunk-VEFGHRKV.js.map} +0 -0
  232. /package/dist/{chunk-O62MMJWV.js.map → chunk-VO3HCFSR.js.map} +0 -0
  233. /package/dist/{chunk-4DJSDH2M.js.map → chunk-W5GGKQVS.js.map} +0 -0
  234. /package/dist/{chunk-TQ5NOVMT.js.map → chunk-X7EAMNKR.js.map} +0 -0
  235. /package/dist/{chunk-G53I363P.js.map → chunk-XF2QQQXO.js.map} +0 -0
  236. /package/dist/{chunk-GWFL6LUU.js.map → chunk-XUS2UQOO.js.map} +0 -0
  237. /package/dist/{chunk-FZVROZKC.js.map → chunk-XVZA6VXC.js.map} +0 -0
  238. /package/dist/{chunk-VPEIWMUT.js.map → chunk-YLTU2DC4.js.map} +0 -0
  239. /package/dist/{chunk-PXZLVFNC.js.map → chunk-YQXD57ZS.js.map} +0 -0
  240. /package/dist/{chunk-LR2X3FJM.js.map → chunk-YW63C4FO.js.map} +0 -0
  241. /package/dist/{chunk-LU2GQ4Q4.js.map → chunk-YYHBB565.js.map} +0 -0
  242. /package/dist/{chunk-2G72JBQB.js.map → chunk-ZCXZNK4G.js.map} +0 -0
  243. /package/dist/{chunk-ZO377APE.js.map → chunk-ZMDXISMQ.js.map} +0 -0
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Buffer-ingress counters (issue #3444) — OBSERVATION ONLY.
3
+ *
4
+ * Counts what the SmartBuffer add path already does, per offered turn, in
5
+ * turns and characters:
6
+ * - accepted: the turn was appended to a buffer entry (always the case for
7
+ * non-refused offers; this layer invents no filtering),
8
+ * - acceptedExactDuplicate: observational SUB-COUNT of accepted — the
9
+ * appended turn's role+content exactly matches a turn already in that
10
+ * session's buffer entry (live turns or deferred-retained copies). This
11
+ * is the duplicate rate at ingress that #3443 needs; it changes nothing,
12
+ * - filtered: reserved for turns existing code drops before/at the buffer.
13
+ * The SmartBuffer add path itself drops nothing, so it is always 0 at
14
+ * this layer; upstream filters (captureMode=explicit skips in
15
+ * processTurn/ingestReplayBatch, the observe funnel's empty-content and
16
+ * fingerprint dedup) live outside the buffer add,
17
+ * - refused: capacity refusal (existing null-return and throw sites).
18
+ *
19
+ * Invariant: accepted + filtered + refused == turns offered.
20
+ * acceptedExactDuplicate <= accepted (it is a sub-count, not a partition).
21
+ *
22
+ * Counters are process-local and instance-owned (one instance per
23
+ * SmartBuffer, no module state), feed a 24-hour hourly ring with ONE
24
+ * aggregate info log line per hour (counts only: no content, no session
25
+ * ids, silent idle hours), and take an injectable clock for tests.
26
+ *
27
+ * Memory: duplicate detection hashes role+content to a sha256 digest (same
28
+ * scheme as the drain hand-in memo) — turn content is never retained. The
29
+ * per-entry digest set mirrors the entry's own turns (so it is bounded by
30
+ * the session turn cap) and additionally enforces a hard FIFO cap of
31
+ * DUPLICATE_DIGEST_CAP digests; beyond the cap the oldest digest is
32
+ * evicted, so very old unique contents stop being recognized as
33
+ * duplicates until the next rebuild (metric under-count, never a buffer
34
+ * change).
35
+ *
36
+ * O(1) amortized per turn: memo validity is the entry's array references,
37
+ * so any mutation that removes or replaces turns (all of them reassign a
38
+ * fresh array) self-invalidates the memo without epoch bookkeeping.
39
+ */
40
+
41
+ import { createHash } from "node:crypto";
42
+ import { log } from "./logger.js";
43
+ import type { BufferEntryState, BufferTurn } from "./types.js";
44
+
45
+ export type BufferIngressOutcome = "accepted" | "acceptedExactDuplicate" | "filtered" | "refused";
46
+
47
+ export interface BufferIngressOutcomeCount {
48
+ turns: number;
49
+ chars: number;
50
+ }
51
+
52
+ export interface BufferIngressHour {
53
+ hourStart: string;
54
+ accepted: BufferIngressOutcomeCount;
55
+ acceptedExactDuplicate: BufferIngressOutcomeCount;
56
+ filtered: BufferIngressOutcomeCount;
57
+ refused: BufferIngressOutcomeCount;
58
+ }
59
+
60
+ export interface BufferIngressSnapshot {
61
+ totals: Record<BufferIngressOutcome, BufferIngressOutcomeCount>;
62
+ hours: BufferIngressHour[];
63
+ }
64
+
65
+ export const EMPTY_BUFFER_INGRESS_SNAPSHOT: BufferIngressSnapshot = {
66
+ totals: {
67
+ accepted: { turns: 0, chars: 0 },
68
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
69
+ filtered: { turns: 0, chars: 0 },
70
+ refused: { turns: 0, chars: 0 },
71
+ },
72
+ hours: [],
73
+ };
74
+
75
+ const HOUR_MS = 3_600_000;
76
+ const RING_SLOTS = 24;
77
+ /**
78
+ * Hard cap on the per-entry duplicate-digest set (defense against configs
79
+ * with very large session caps). Beyond the cap the oldest digest is
80
+ * FIFO-evicted: recognition of the oldest unique contents degrades to
81
+ * "not a duplicate" (an under-count of acceptedExactDuplicate), never a
82
+ * behavioral change.
83
+ */
84
+ const DUPLICATE_DIGEST_CAP = 4096;
85
+
86
+ const OUTCOMES: readonly BufferIngressOutcome[] = ["accepted", "acceptedExactDuplicate", "filtered", "refused"];
87
+
88
+ function zeroCounts() {
89
+ return {
90
+ accepted: { turns: 0, chars: 0 },
91
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
92
+ filtered: { turns: 0, chars: 0 },
93
+ refused: { turns: 0, chars: 0 },
94
+ } satisfies Record<BufferIngressOutcome, BufferIngressOutcomeCount>;
95
+ }
96
+
97
+ function contentDigest(turn: BufferTurn): string {
98
+ return createHash("sha256").update(`${turn.role}\u0000${turn.content}`).digest("base64");
99
+ }
100
+
101
+ interface RingSlot {
102
+ hourStartMs: number;
103
+ counts: Record<BufferIngressOutcome, BufferIngressOutcomeCount>;
104
+ }
105
+
106
+ /** Test-visible view of a per-entry digest memo: digest set only. The validity
107
+ * refs (WeakRefs over entry arrays) stay private; tests assert rebuild
108
+ * identity through the map plus the observable counts, never the refs. */
109
+ export interface BufferIngressMemoView {
110
+ digests: Set<string>;
111
+ }
112
+
113
+ interface EntryDigestMemo {
114
+ // WeakRefs: after clearAfterExtraction replaces the entry arrays, the old
115
+ // arrays must not stay reachable through the memo. Deref-compare keeps the
116
+ // validity check exact without retaining evicted turn content.
117
+ turnsRef: WeakRef<BufferTurn[]>;
118
+ retainedRef: WeakRef<BufferTurn[]> | undefined;
119
+ digests: Set<string>;
120
+ }
121
+
122
+ export class BufferIngressCounters {
123
+ private readonly ring: (RingSlot | null)[] = Array.from({ length: RING_SLOTS }, () => null);
124
+ private readonly totals: Record<BufferIngressOutcome, BufferIngressOutcomeCount> = zeroCounts();
125
+ private readonly memos = new WeakMap<BufferEntryState, EntryDigestMemo>();
126
+ /** Test-only: the digest set cached for an entry, or undefined when no
127
+ * memo was built yet. Exposes digests only — never the validity refs. */
128
+ memoForTest(entry: BufferEntryState): BufferIngressMemoView | undefined {
129
+ return this.memos.get(entry);
130
+ }
131
+ private lastActiveHourMs: number | null = null;
132
+
133
+ constructor(
134
+ private readonly now: () => number = Date.now,
135
+ /** Test seam: the disabled control proves counting does not touch the buffer. */
136
+ private readonly enabled = true,
137
+ ) {}
138
+
139
+ /**
140
+ * Observe an offered turn (called BEFORE the buffer pushes it, so a lazily
141
+ * rebuilt digest memo sees only turns already in the entry). Counts
142
+ * `accepted` and, when an identical role+content digest is already tracked
143
+ * for this entry, the `acceptedExactDuplicate` sub-count. Returns nothing;
144
+ * the buffer behaves identically either way.
145
+ */
146
+ noteAppendedTurn(entry: BufferEntryState, turn: BufferTurn): void {
147
+ if (!this.enabled) return;
148
+ // One hour per offer: the two records below must land in the same
149
+ // bucket even if the clock crosses an hour between them.
150
+ const hourStartMs = Math.floor(this.now() / HOUR_MS) * HOUR_MS;
151
+ const chars = turn.content.length;
152
+ this.record("accepted", chars, hourStartMs);
153
+ // The offered turn is counted, then added to the memo: a later re-offer
154
+ // of identical content is recognised as a duplicate of an already-seen
155
+ // turn. Set semantics dedupe — no double count.
156
+ const memo = this.memoFor(entry);
157
+ const digest = contentDigest(turn);
158
+ if (memo.digests.has(digest)) this.record("acceptedExactDuplicate", chars, hourStartMs);
159
+ memo.digests.add(digest);
160
+ if (memo.digests.size > DUPLICATE_DIGEST_CAP) {
161
+ for (const oldest of memo.digests) {
162
+ memo.digests.delete(oldest);
163
+ break;
164
+ }
165
+ }
166
+ }
167
+
168
+ /** Count a single capacity-refused turn; returns null for `return` sites. */
169
+ refuseOne(turn: BufferTurn): null {
170
+ if (!this.enabled) return null;
171
+ this.record("refused", turn.content.length);
172
+ return null;
173
+ }
174
+
175
+ /** Count a refused ERROR for `throw` sites; the error propagates unchanged. */
176
+ refuseThrow(turn: BufferTurn, error: Error): Error {
177
+ this.refuseOne(turn);
178
+ return error;
179
+ }
180
+
181
+ /** Count a WHOLE-BATCH refusal (every offered turn is dropped). */
182
+ refuseAll(offered: readonly { turn: BufferTurn }[]): null {
183
+ for (const { turn } of offered) this.refuseOne(turn);
184
+ return null;
185
+ }
186
+
187
+ snapshot(): BufferIngressSnapshot {
188
+ const nowHourMs = Math.floor(this.now() / HOUR_MS) * HOUR_MS;
189
+ const hours = this.ring
190
+ .filter((slot): slot is RingSlot => slot !== null && nowHourMs - slot.hourStartMs < HOUR_MS * RING_SLOTS)
191
+ .sort((a, b) => a.hourStartMs - b.hourStartMs)
192
+ .map((slot) => ({
193
+ hourStart: new Date(slot.hourStartMs).toISOString(),
194
+ accepted: { ...slot.counts.accepted },
195
+ acceptedExactDuplicate: { ...slot.counts.acceptedExactDuplicate },
196
+ filtered: { ...slot.counts.filtered },
197
+ refused: { ...slot.counts.refused },
198
+ }));
199
+ return {
200
+ totals: {
201
+ accepted: { ...this.totals.accepted },
202
+ acceptedExactDuplicate: { ...this.totals.acceptedExactDuplicate },
203
+ filtered: { ...this.totals.filtered },
204
+ refused: { ...this.totals.refused },
205
+ },
206
+ hours,
207
+ };
208
+ }
209
+
210
+ private record(outcome: BufferIngressOutcome, chars: number, hourStartMs = Math.floor(this.now() / HOUR_MS) * HOUR_MS): void {
211
+ if (hourStartMs !== this.lastActiveHourMs) {
212
+ if (this.lastActiveHourMs !== null) this.logHourBucket(this.lastActiveHourMs);
213
+ this.lastActiveHourMs = hourStartMs;
214
+ }
215
+ const slotIndex = (hourStartMs / HOUR_MS) % RING_SLOTS;
216
+ const slot = this.ring[slotIndex];
217
+ if (slot !== null && slot.hourStartMs === hourStartMs) {
218
+ slot.counts[outcome].turns += 1;
219
+ slot.counts[outcome].chars += chars;
220
+ } else {
221
+ // Slot reuse after 24h: the stale bucket was logged when its own hour
222
+ // ended, so eviction here is silent.
223
+ const counts = {
224
+ ...zeroCounts(),
225
+ [outcome]: { turns: 1, chars },
226
+ } satisfies Record<BufferIngressOutcome, BufferIngressOutcomeCount>;
227
+ this.ring[slotIndex] = { hourStartMs, counts };
228
+ }
229
+ this.totals[outcome].turns += 1;
230
+ this.totals[outcome].chars += chars;
231
+ }
232
+
233
+ /** ONE aggregate line per hour, at roll time, describing the ending hour. */
234
+ private logHourBucket(hourStartMs: number): void {
235
+ const slot = this.ring[(hourStartMs / HOUR_MS) % RING_SLOTS];
236
+ if (slot === null || slot.hourStartMs !== hourStartMs) return;
237
+ const counts = slot.counts;
238
+ if (OUTCOMES.every((outcome) => counts[outcome].turns === 0)) return; // zero-noise: silent idle hours
239
+ log.info(
240
+ `buffer ingress ${new Date(hourStartMs).toISOString()}: ${OUTCOMES.map((outcome) => `${outcome}=${counts[outcome].turns}/${counts[outcome].chars}c`).join(" ")}`,
241
+ );
242
+ }
243
+
244
+ private memoFor(entry: BufferEntryState): EntryDigestMemo {
245
+ const retained = entry.retainedTurns;
246
+ const memo = this.memos.get(entry);
247
+ // --- Fix 3: bound the rebuild to the digest cap. A restored entry can
248
+ // hold more unique turns than DUPLICATE_DIGEST_CAP; inserting all of them
249
+ // would leave the set permanently above the cap (later appends evict one
250
+ // each). Keep the most recent turns, matching the FIFO order of the
251
+ // steady-state path, so recognition degrades to "not a duplicate".
252
+ // Distinguish "built with no retained array" (retainedRef undefined) from
253
+ // "built with one that was since collected" (deref undefined but the entry
254
+ // still has none... no: if the entry has none NOW and the memo was built
255
+ // with one, the entry changed shape -> rebuild). Reuse only when both sides
256
+ // agree on presence AND identity.
257
+ // Reuse only when both sides agree on presence AND identity: a memo built
258
+ // with a retained array that the buffer later deleted (entry.retainedTurns
259
+ // now undefined) must rebuild, and a collected WeakRef must never read as
260
+ // "absent" (that would reuse a memo whose digests still include removed
261
+ // content). Any memo built with a retained array therefore requires a
262
+ // live identical array now; a memo built without one requires none now.
263
+ const retainedMatch =
264
+ memo?.retainedRef === undefined
265
+ ? memo !== undefined && retained === undefined
266
+ : memo.retainedRef.deref() !== undefined && memo.retainedRef.deref() === retained;
267
+ if (memo && memo.turnsRef.deref() === entry.turns && retainedMatch) return memo;
268
+ const ordered = [...entry.turns, ...(retained ?? [])];
269
+ const bounded = ordered.length > DUPLICATE_DIGEST_CAP ? ordered.slice(ordered.length - DUPLICATE_DIGEST_CAP) : ordered;
270
+ const fresh: EntryDigestMemo = {
271
+ turnsRef: new WeakRef(entry.turns),
272
+ retainedRef: retained ? new WeakRef(retained) : undefined,
273
+ digests: new Set(bounded.map(contentDigest)),
274
+ };
275
+ this.memos.set(entry, fresh);
276
+ return fresh;
277
+ }
278
+ }
@@ -0,0 +1,290 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+
7
+ import { SmartBuffer } from "./buffer.js";
8
+ import { SessionObserverState } from "./session-observer-state.js";
9
+ import { TranscriptManager } from "./transcript.js";
10
+ import { ExtractionQueueCoordinator } from "./orchestration/extraction-queue-coordinator.js";
11
+ import { TurnIngestionCoordinator, type TurnIngestionDeps } from "./orchestration/turn-ingestion.js";
12
+ import { parseConfig } from "./config.js";
13
+ import type { BufferState, BufferTurn, PluginConfig } from "./types.js";
14
+ import type { ReplayTurn } from "./replay/types.js";
15
+
16
+ /**
17
+ * Issue #3444, observation-only contract: the counters change NOTHING the
18
+ * buffer does. Two guarantees are pinned here:
19
+ *
20
+ * 1. Partition: accepted + filtered + refused == turns offered (in turns and
21
+ * in characters). The SmartBuffer add path drops nothing, so `filtered`
22
+ * is always 0 at this layer; upstream filters (captureMode=explicit
23
+ * skips in processTurn/ingestReplayBatch; the observe funnel's
24
+ * empty-content guard and fingerprint dedup) live outside this boundary.
25
+ * 2. Differential: the exact same mixed sequence of offers run against a
26
+ * counters-enabled buffer and a counters-disabled control produces
27
+ * identical buffer state, identical mutation results and identical
28
+ * refusal errors.
29
+ *
30
+ * `acceptedExactDuplicate` is a sub-count of accepted (appended AND counted),
31
+ * giving #3443 the true duplicate rate at ingress.
32
+ */
33
+
34
+ class FakeStorage {
35
+ public saved: BufferState | null = null;
36
+ async loadBuffer(): Promise<BufferState> {
37
+ return structuredClone(this.saved ?? { turns: [], lastExtractionAt: null, extractionCount: 0 });
38
+ }
39
+ async saveBuffer(state: BufferState): Promise<void> {
40
+ this.saved = structuredClone(state);
41
+ }
42
+ }
43
+
44
+ function makeConfig(memoryDir: string, overrides: Partial<PluginConfig> = {}): PluginConfig {
45
+ return parseConfig({
46
+ memoryDir,
47
+ bufferSaveDebounceMs: 0,
48
+ bufferMaxSessions: 8,
49
+ bufferMaxTurnsPerSession: 6,
50
+ ...overrides,
51
+ });
52
+ }
53
+
54
+ function turn(content: string, overrides: Partial<BufferTurn> = {}): BufferTurn {
55
+ return {
56
+ role: "user",
57
+ content,
58
+ timestamp: "2026-11-15T12:00:00.000Z",
59
+ sessionKey: "kA",
60
+ ...overrides,
61
+ };
62
+ }
63
+
64
+ function charsOf(turns: readonly BufferTurn[]): number {
65
+ return turns.reduce((sum, t) => sum + t.content.length, 0);
66
+ }
67
+
68
+ interface RunTrace {
69
+ /** Whole persisted buffer state after the sequence. */
70
+ saved: BufferState | null;
71
+ /** Live turns per buffer key, in order. */
72
+ turns: Record<string, string[]>;
73
+ /** Trigger decisions per addTurnsBounded outcome entry. */
74
+ decisions: string[];
75
+ /** Per-key turn counts reported by each batch outcome entry. */
76
+ batchCounts: number[];
77
+ /** Names of refusal errors thrown, in order. */
78
+ refusalErrors: string[];
79
+ /** addTurnsBounded null (refused) returns, in order. */
80
+ batchNulls: boolean[];
81
+ }
82
+
83
+ async function runMixedSequence(memoryDir: string, countIngress: boolean): Promise<RunTrace> {
84
+ const storage = new FakeStorage();
85
+ const buffer = new SmartBuffer(makeConfig(memoryDir), storage, null, { countIngress });
86
+ const trace: RunTrace = { saved: null, turns: {}, decisions: [], batchCounts: [], refusalErrors: [], batchNulls: [] };
87
+
88
+ // Multi-session batch: uniques, exact in-batch duplicate, empty, whitespace.
89
+ const batchA = [turn("alpha memory"), turn("alpha memory"), turn(""), turn(" \n\t ")];
90
+ const batchB = [turn("beta memory", { sessionKey: "kB", timestamp: "2026-11-15T12:00:01.000Z" })];
91
+ const batchC = [turn("beta memory", { sessionKey: "kC", timestamp: "2026-11-15T12:00:02.000Z" })];
92
+ const outcomes = await buffer.addTurnsBounded([
93
+ { bufferKey: "kA", turns: batchA },
94
+ { bufferKey: "kB", turns: batchB },
95
+ { bufferKey: "kC", turns: batchC },
96
+ ]);
97
+ assert.ok(outcomes);
98
+ trace.decisions.push(...outcomes.map((o) => o.outcome.decision));
99
+ trace.batchCounts.push(...outcomes.map((o) => o.outcome.extractionTurns?.length ?? -1));
100
+
101
+ // Sequential adds: exact re-offer of a buffered turn, then a fresh one.
102
+ await buffer.addTurn("kA", turn("alpha memory"));
103
+ await buffer.addTurn("kA", turn("gamma memory"));
104
+
105
+ // Retained-turn re-offer: still appended (observation only).
106
+ await buffer.retainDeferredTurns("kA", [turn("gamma memory")], 10);
107
+ await buffer.clearAfterExtraction("kA");
108
+ await buffer.addTurn("kA", turn("gamma memory"));
109
+
110
+ // Refusal: per-session turn cap — a 7-turn batch is refused whole.
111
+ const overCap = [0, 1, 2, 3, 4, 5, 6].map((i) => turn(`over ${i}`, { sessionKey: "kF" }));
112
+ trace.batchNulls.push((await buffer.addTurnsBounded([{ bufferKey: "kF", turns: overCap }])) === null);
113
+
114
+ // Refusal: session-entry cap — accepted-capture entries are pinned, so a
115
+ // new live session beyond the cap throws (the implicit "default" entry is
116
+ // protected too, hence cap 3 for 2 pins).
117
+ const pinnedBuffer = new SmartBuffer(makeConfig(memoryDir, { bufferMaxSessions: 3 }), new FakeStorage(), null, { countIngress });
118
+ for (const key of ["p1", "p2"]) {
119
+ await pinnedBuffer.addTurnsBounded([{ bufferKey: key, turns: [turn("pin", { sessionKey: key, acceptedCapture: true })] }]);
120
+ }
121
+ try {
122
+ await pinnedBuffer.addTurn("p3", turn("beyond the entry cap"));
123
+ } catch (error) {
124
+ // `error` is `unknown`; the add path only throws Errors, so a non-Error would be a bug worth surfacing.
125
+ if (!(error instanceof Error)) throw error;
126
+ trace.refusalErrors.push(`${error.name}: ${error.message}`);
127
+ }
128
+
129
+ // Buffered replay: identity duplicate and content duplicate are appended.
130
+ const unreachable = (name: string): never => {
131
+ throw new Error(`TurnIngestionDeps.${name} is unreachable in the replay-capacity fixture`);
132
+ };
133
+ const deps: TurnIngestionDeps = {
134
+ buffer,
135
+ config: makeConfig(memoryDir),
136
+ bulkImportWriteNamespace: () => unreachable("bulkImportWriteNamespace"),
137
+ extractionQueueCoordinator: new ExtractionQueueCoordinator(),
138
+ getStorage: async () => unreachable("getStorage"),
139
+ heartbeatObserverChains: new Map(),
140
+ lcmEngine: null,
141
+ passiveCorrectionDedup: new Set(),
142
+ // SAFETY: the fixture never drains or corrects, so a call here would mean the
143
+ // fixture itself changed shape; fail loud rather than silently stub.
144
+ passiveCorrectionService: () => unreachable("passiveCorrectionService"),
145
+ passiveCorrectionTelemetry: { detected: 0, queued: 0, autoApplied: 0, suppressedReasonCounts: {} },
146
+ queueBufferedExtraction: async () => {},
147
+ resolveMemoryIdOrHandle: (ref: string) => ref,
148
+ runExtraction: () => unreachable("runExtraction"),
149
+ // Disabled observer: no bands means `observe` never triggers, so the fixture's
150
+ // replay path never consults persisted state.
151
+ sessionObserver: new SessionObserverState({ memoryDir, debounceMs: 0, bands: [] }),
152
+ shouldQueueExtraction: () => false,
153
+ transcript: new TranscriptManager(makeConfig(memoryDir)),
154
+ };
155
+ const coordinator = new TurnIngestionCoordinator(deps);
156
+ const replay = (sessionKey: string, content: string, timestamp: string): ReplayTurn => ({
157
+ source: "openclaw",
158
+ sessionKey,
159
+ role: "user",
160
+ content,
161
+ timestamp,
162
+ });
163
+ await coordinator.ingestReplayBatch(
164
+ [
165
+ replay("s1", "replay unique one", "2026-11-15T13:00:00.000Z"),
166
+ replay("s1", "replay unique one", "2026-11-15T13:00:05.000Z"),
167
+ replay("s2", "replay unique two", "2026-11-15T13:00:01.000Z"),
168
+ replay("s2", "replay unique two", "2026-11-15T13:00:01.000Z"),
169
+ ],
170
+ { archiveLcm: false, extractionMode: "buffered" },
171
+ );
172
+
173
+ // Normalize wall-clock stamps the buffer itself writes (lastExtractionAt)
174
+ // so the two runs differ only where counters could possibly matter.
175
+ if (storage.saved) {
176
+ storage.saved.lastExtractionAt = null;
177
+ for (const entry of Object.values(storage.saved.entries ?? {})) entry.lastExtractionAt = null;
178
+ }
179
+ trace.saved = storage.saved;
180
+ for (const key of ["kA", "kB", "kC", "s1", "s2"]) {
181
+ trace.turns[key] = (await buffer.getTurns(key)).map((t) => `${t.role}:${t.timestamp}:${t.content}`);
182
+ }
183
+ return trace;
184
+ }
185
+
186
+ test("differential: counters on vs off — identical state, results and refusals", async () => {
187
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-ingress-diff-"));
188
+ try {
189
+ const enabled = await runMixedSequence(memoryDir, true);
190
+ const control = await runMixedSequence(memoryDir, false);
191
+ assert.deepEqual(enabled, control, "counters must not change any buffer behavior");
192
+ assert.equal(enabled.refusalErrors.length, 1, "the entry-cap refusal still refuses");
193
+ assert.match(enabled.refusalErrors[0], /session-entry cap/);
194
+ assert.ok(enabled.batchNulls.every((isNull) => isNull), "the over-cap batch is still refused whole");
195
+ // Appended duplicates really are in the buffer (observation, not skip):
196
+ // kC holds the batch's cross-session beta duplicate, kA was cleared by the
197
+ // extraction clear and holds only the re-appended retained content, and
198
+ // both replay duplicates were appended.
199
+ assert.deepEqual(enabled.turns.kC.length, 1);
200
+ assert.ok(enabled.turns.kC[0].endsWith("beta memory"));
201
+ assert.deepEqual(enabled.turns.kA, [
202
+ "user:2026-11-15T12:00:00.000Z:gamma memory", // retained copy
203
+ "user:2026-11-15T12:00:00.000Z:gamma memory", // re-appended offer
204
+ ]);
205
+ assert.equal(enabled.turns.s1.length, 2, "replay content duplicate is appended");
206
+ assert.equal(enabled.turns.s2.length, 2, "replay identity duplicate is appended");
207
+ } finally {
208
+ await rm(memoryDir, { recursive: true, force: true });
209
+ }
210
+ });
211
+
212
+ test("partition: accepted + filtered + refused equals turns offered; duplicates are a sub-count", async () => {
213
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-ingress-partition-"));
214
+ try {
215
+ const buffer = new SmartBuffer(makeConfig(memoryDir), new FakeStorage());
216
+ const snap = () => buffer.ingress.snapshot();
217
+ let offered = 0;
218
+ let offeredChars = 0;
219
+ const offer = (turns: readonly BufferTurn[]) => {
220
+ offered += turns.length;
221
+ offeredChars += charsOf(turns);
222
+ };
223
+
224
+ const batchA = [turn("alpha memory"), turn("alpha memory"), turn(""), turn(" \n\t ")];
225
+ const batchB = [turn("beta memory", { sessionKey: "kB", timestamp: "2026-11-15T12:00:01.000Z" })];
226
+ offer([...batchA, ...batchB]);
227
+ await buffer.addTurnsBounded([
228
+ { bufferKey: "kA", turns: batchA },
229
+ { bufferKey: "kB", turns: batchB },
230
+ ]);
231
+ const replayed = turn("alpha memory");
232
+ const fresh = turn("gamma memory");
233
+ offer([replayed, fresh]);
234
+ await buffer.addTurn("kA", replayed);
235
+ await buffer.addTurn("kA", fresh);
236
+
237
+ let s = snap();
238
+ // filtered is structurally 0 here: the add path drops nothing.
239
+ assert.deepEqual(s.totals.filtered, { turns: 0, chars: 0 });
240
+ // accepted: 6 appended (alpha, alpha-dup, "", ws, beta, then replayed+fresh = 7).
241
+ assert.deepEqual(s.totals.accepted, { turns: 7, chars: charsOf([...batchA, ...batchB, replayed, fresh]) });
242
+ // exact duplicates: in-batch alpha, re-offered alpha — still appended.
243
+ assert.deepEqual(s.totals.acceptedExactDuplicate, { turns: 2, chars: 2 * charsOf([turn("alpha memory")]) });
244
+ assert.ok(s.totals.acceptedExactDuplicate.turns <= s.totals.accepted.turns);
245
+ assert.equal(s.totals.accepted.turns + s.totals.filtered.turns + s.totals.refused.turns, offered);
246
+ assert.equal(
247
+ s.totals.accepted.chars + s.totals.filtered.chars + s.totals.refused.chars,
248
+ offeredChars,
249
+ );
250
+
251
+ // Refusals enter the partition: per-session cap refuses a whole 7-turn batch.
252
+ const overCap = [0, 1, 2, 3, 4, 5, 6].map((i) => turn(`over ${i}`, { sessionKey: "kF" }));
253
+ offer(overCap);
254
+ assert.equal(await buffer.addTurnsBounded([{ bufferKey: "kF", turns: overCap }]), null);
255
+ s = snap();
256
+ assert.deepEqual(s.totals.refused, { turns: 7, chars: charsOf(overCap) });
257
+ assert.equal(s.totals.accepted.turns + s.totals.filtered.turns + s.totals.refused.turns, offered);
258
+ assert.equal(
259
+ s.totals.accepted.chars + s.totals.filtered.chars + s.totals.refused.chars,
260
+ offeredChars,
261
+ );
262
+ } finally {
263
+ await rm(memoryDir, { recursive: true, force: true });
264
+ }
265
+ });
266
+
267
+ test("duplicate digests are memory-bounded (FIFO cap) and never retain content", async () => {
268
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-ingress-cap-"));
269
+ try {
270
+ // No-save storage: this test only observes counting, not persistence.
271
+ // SAFETY: FakeStorage implements BufferStorage; nothing is saved because saveBuffer writes only to memory here.
272
+ const buffer = new SmartBuffer(makeConfig(memoryDir, { bufferMaxTurnsPerSession: 10_000 }), new FakeStorage());
273
+ const unique = (i: number) => turn(`unique-${i}`);
274
+ // Fill the digest set to its 4,096 cap.
275
+ for (let i = 0; i < 4_096; i += 1) await buffer.addTurn("kA", unique(i));
276
+ // A new unique content FIFO-evicts the oldest digest…
277
+ await buffer.addTurn("kA", turn("brand-new"));
278
+ // …so re-offering the very first content is no longer recognized, while
279
+ // the still-tracked recent one is — an under-count, never a behavior change.
280
+ await buffer.addTurn("kA", unique(0));
281
+ await buffer.addTurn("kA", turn("brand-new"));
282
+ const s = buffer.ingress.snapshot().totals;
283
+ assert.equal(s.accepted.turns, 4_099);
284
+ assert.deepEqual(s.acceptedExactDuplicate, { turns: 1, chars: turn("brand-new").content.length });
285
+ // All offered turns were appended: nothing was dropped.
286
+ assert.equal((await buffer.getTurns("kA")).length, 4_099);
287
+ } finally {
288
+ await rm(memoryDir, { recursive: true, force: true });
289
+ }
290
+ });
@@ -1,4 +1,14 @@
1
1
  import type { BufferEntryState, BufferState, BufferTurn } from "./types.js";
2
+ import type { BufferEvictionHooks } from "./buffer-eviction.js";
3
+
4
+ /**
5
+ * Eviction hooks are pure functions of an entry; one shared instance serves
6
+ * pruneEntries, the admission probe and the batch preflight.
7
+ */
8
+ export const EVICTION_HOOKS: BufferEvictionHooks = {
9
+ activityAt: entryActivityAt,
10
+ holdsAcceptedCapture: entryHoldsAcceptedCapture,
11
+ };
2
12
 
3
13
  /** Extracted identities retain whether they came from active or retained turns. */
4
14
  export interface DrainedTurnSets {