@remnic/core 10.0.128 → 10.0.129

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 (235) 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/index.js +4 -4
  26. package/dist/adapters/registry.js +2 -2
  27. package/dist/briefing.js +6 -6
  28. package/dist/buffer-ingress-counters.d.ts +100 -0
  29. package/dist/buffer-ingress-counters.d.ts.map +1 -0
  30. package/dist/buffer-ingress-counters.js +11 -0
  31. package/dist/buffer-turn-helpers.d.ts +6 -0
  32. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  33. package/dist/buffer-turn-helpers.js +3 -1
  34. package/dist/buffer.d.ts +8 -1
  35. package/dist/buffer.d.ts.map +1 -1
  36. package/dist/buffer.js +3 -2
  37. package/dist/calibration.js +2 -2
  38. package/dist/causal-behavior.js +2 -2
  39. package/dist/causal-chain.js +2 -2
  40. package/dist/causal-consolidation.js +9 -9
  41. package/dist/causal-retrieval.js +2 -2
  42. package/dist/causal-trajectory-graph.js +2 -2
  43. package/dist/causal-trajectory.js +1 -1
  44. package/dist/{chunk-ID65XTF3.js → chunk-2JAT4S7N.js} +2 -2
  45. package/dist/{chunk-BR7CZVMO.js → chunk-2UW3EM3U.js} +6 -1
  46. package/dist/chunk-2UW3EM3U.js.map +1 -0
  47. package/dist/{chunk-ORMJT23N.js → chunk-3OT6JDMD.js} +8 -8
  48. package/dist/{chunk-SU42FIJ7.js → chunk-3RW5ZCYO.js} +2 -2
  49. package/dist/{chunk-TJJPT2OV.js → chunk-3S7BUGYC.js} +2 -2
  50. package/dist/{chunk-7TC2PWKH.js → chunk-4KWR7M3Q.js} +2 -2
  51. package/dist/{chunk-WRGW76LI.js → chunk-5BE3FLKL.js} +6 -6
  52. package/dist/{chunk-JK2IVISS.js → chunk-5FWPLAKP.js} +2 -2
  53. package/dist/{chunk-PPPY2PCU.js → chunk-5OW73TEG.js} +2 -2
  54. package/dist/{chunk-DTTDMK7Q.js → chunk-5RONA5FF.js} +4 -4
  55. package/dist/{chunk-6FPJPSQK.js → chunk-6P5PIOWW.js} +2 -2
  56. package/dist/{chunk-HJ7M322C.js → chunk-6PQVAYQJ.js} +2 -2
  57. package/dist/{chunk-QKYOMKRG.js → chunk-7C7M2P43.js} +2 -2
  58. package/dist/{chunk-XMKUABIG.js → chunk-AAV726HQ.js} +3 -3
  59. package/dist/{chunk-ASINXIKX.js → chunk-AWKD2A73.js} +12 -12
  60. package/dist/{chunk-XUWDB53W.js → chunk-BAKCGJRQ.js} +3 -3
  61. package/dist/{chunk-ALLI23GW.js → chunk-BE5F6KFG.js} +2 -2
  62. package/dist/{chunk-MGCV3VGC.js → chunk-BOK5D46I.js} +2 -2
  63. package/dist/{chunk-FBXU7X27.js → chunk-BTY6DUFW.js} +2 -2
  64. package/dist/{chunk-FPBFDQZZ.js → chunk-CFJBSE7J.js} +11 -11
  65. package/dist/{chunk-WYABF2WA.js → chunk-CLVILSBR.js} +3 -3
  66. package/dist/{chunk-BFBS7OFQ.js → chunk-DC55RIEZ.js} +4 -4
  67. package/dist/{chunk-NYZ6ZNFO.js → chunk-FCW4FUF2.js} +5 -5
  68. package/dist/{chunk-7QDB7P3V.js → chunk-FMFCQRDM.js} +3 -3
  69. package/dist/{chunk-K36RMINQ.js → chunk-GOZXQNIM.js} +3 -3
  70. package/dist/{chunk-YFUHFPV6.js → chunk-HILGHLPA.js} +10 -10
  71. package/dist/{chunk-EFHM4VDG.js → chunk-HLWXCDUQ.js} +2 -2
  72. package/dist/{chunk-JCPEXUNP.js → chunk-IUVTFQWY.js} +2 -2
  73. package/dist/{chunk-YPE3O5VH.js → chunk-JHKCS6EN.js} +2 -2
  74. package/dist/{chunk-UWU6KEZU.js → chunk-JVQNRSWO.js} +2 -2
  75. package/dist/{chunk-PAGVXEWG.js → chunk-KLUCX6OH.js} +2 -2
  76. package/dist/{chunk-ELBZT6RU.js → chunk-KVCFAWBZ.js} +2 -2
  77. package/dist/{chunk-W4Q65VJL.js → chunk-MZCGHPIJ.js} +2 -2
  78. package/dist/{chunk-2BBCM2PX.js → chunk-N36J3MIB.js} +2 -2
  79. package/dist/{chunk-AYBRQJXP.js → chunk-NVKWV4W3.js} +2 -2
  80. package/dist/{chunk-CUKYV5O3.js → chunk-OEP5XRTB.js} +4 -4
  81. package/dist/{chunk-3OLHDECL.js → chunk-OWNMYYG3.js} +157 -150
  82. package/dist/chunk-OWNMYYG3.js.map +1 -0
  83. package/dist/{chunk-ZUMHQEW4.js → chunk-QHDBKC5Z.js} +4 -4
  84. package/dist/chunk-RADARJEC.js +156 -0
  85. package/dist/chunk-RADARJEC.js.map +1 -0
  86. package/dist/{chunk-MCTGYIYN.js → chunk-RXD46MY6.js} +2 -2
  87. package/dist/{chunk-TJY6AKWV.js → chunk-SULNVNTU.js} +2 -2
  88. package/dist/{chunk-34YQ7CVE.js → chunk-TL6QIZT7.js} +18 -14
  89. package/dist/chunk-TL6QIZT7.js.map +1 -0
  90. package/dist/{chunk-7T7I5D3F.js → chunk-TSJQ7C2T.js} +6 -6
  91. package/dist/{chunk-HQPFACXO.js → chunk-UH3FPX3L.js} +2 -2
  92. package/dist/{chunk-6SRYCJ5I.js → chunk-V6JECHY6.js} +5 -5
  93. package/dist/{chunk-YCJRYM3Q.js → chunk-VAMCJPJT.js} +3 -3
  94. package/dist/{chunk-QC2MHZDD.js → chunk-VEFGHRKV.js} +1 -1
  95. package/dist/{chunk-O62MMJWV.js → chunk-VO3HCFSR.js} +2 -2
  96. package/dist/{chunk-TQ5NOVMT.js → chunk-X7EAMNKR.js} +2 -2
  97. package/dist/{chunk-G53I363P.js → chunk-XF2QQQXO.js} +2 -2
  98. package/dist/{chunk-GWFL6LUU.js → chunk-XUS2UQOO.js} +2 -2
  99. package/dist/{chunk-FZVROZKC.js → chunk-XVZA6VXC.js} +4 -4
  100. package/dist/{chunk-VPEIWMUT.js → chunk-YLTU2DC4.js} +2 -2
  101. package/dist/{chunk-PXZLVFNC.js → chunk-YQXD57ZS.js} +2 -2
  102. package/dist/{chunk-LR2X3FJM.js → chunk-YW63C4FO.js} +9 -9
  103. package/dist/{chunk-LU2GQ4Q4.js → chunk-YYHBB565.js} +2 -2
  104. package/dist/{chunk-2G72JBQB.js → chunk-ZCXZNK4G.js} +2 -2
  105. package/dist/{chunk-ZO377APE.js → chunk-ZMDXISMQ.js} +3 -3
  106. package/dist/{chunk-4DJSDH2M.js → chunk-ZT7EJUNT.js} +5 -5
  107. package/dist/cli.js +104 -103
  108. package/dist/coding/export-okf-codegraph.js +5 -5
  109. package/dist/coding/pre-action-gate.js +2 -2
  110. package/dist/compounding/engine.js +7 -7
  111. package/dist/config.js +13 -13
  112. package/dist/connectors/codex-materialize-runner.js +6 -6
  113. package/dist/connectors/index.js +6 -6
  114. package/dist/consolidation-provenance-check.js +2 -2
  115. package/dist/convergence-refresh.js +8 -8
  116. package/dist/corpus-watermark.js +8 -8
  117. package/dist/deep-recall-http-glue.js +6 -6
  118. package/dist/embedding-fallback.js +2 -2
  119. package/dist/entity-retrieval.js +8 -8
  120. package/dist/explicit-capture.js +104 -103
  121. package/dist/extraction-span-materialize.js +2 -2
  122. package/dist/extraction.js +13 -13
  123. package/dist/{graph-edge-decay-CXTNJ7IQ.js → graph-edge-decay-EKWXRBWF.js} +5 -5
  124. package/dist/graph-edge-decay-EKWXRBWF.js.map +1 -0
  125. package/dist/graph-jsonl.js +3 -3
  126. package/dist/graph-snapshot.js +3 -3
  127. package/dist/graph.js +2 -2
  128. package/dist/harmonic-retrieval.js +6 -6
  129. package/dist/index.js +167 -166
  130. package/dist/lcm/index.js +3 -3
  131. package/dist/local-llm.js +2 -2
  132. package/dist/location/index.js +7 -7
  133. package/dist/maintenance/memory-governance.js +6 -6
  134. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +6 -6
  135. package/dist/maintenance/rebuild-memory-projection-runner.js +8 -8
  136. package/dist/maintenance/rebuild-memory-projection.js +7 -7
  137. package/dist/namespaces/migrate.js +7 -7
  138. package/dist/namespaces/storage.js +6 -6
  139. package/dist/offline-sync-changeset-generations.js +3 -3
  140. package/dist/offline-sync-embedding-generation.js +2 -2
  141. package/dist/offline-sync-snapshot-stream.js +5 -5
  142. package/dist/offline-sync.js +4 -4
  143. package/dist/operator-doctor-corpus.js +9 -9
  144. package/dist/operator-toolkit.js +23 -23
  145. package/dist/orchestration/backlog-scheduler.js +105 -104
  146. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  147. package/dist/orchestration/buffer-drain-runner.js +105 -104
  148. package/dist/orchestration/maintenance.js +16 -16
  149. package/dist/orchestrator.js +104 -103
  150. package/dist/recall-navigation.js +104 -103
  151. package/dist/resume-bundles.js +16 -16
  152. package/dist/semantic-consolidation.js +10 -10
  153. package/dist/semantic-rule-promotion.js +6 -6
  154. package/dist/semantic-rule-verifier.js +6 -6
  155. package/dist/source-agent-qualifier.js +6 -6
  156. package/dist/standup/build.js +6 -6
  157. package/dist/storage/buffer-drain-claims.js +2 -2
  158. package/dist/storage/buffer-session-files.js +2 -2
  159. package/dist/storage.js +5 -5
  160. package/dist/summarizer.js +3 -3
  161. package/dist/support-passport/index.js +3 -3
  162. package/dist/transcript.js +2 -2
  163. package/dist/transfer/export-okf.js +6 -6
  164. package/dist/verified-recall.js +6 -6
  165. package/dist/who-knows-cli.js +7 -7
  166. package/dist/who-knows.js +6 -6
  167. package/package.json +2 -2
  168. package/src/access-health-types.ts +8 -0
  169. package/src/access-http.test.ts +18 -0
  170. package/src/access-service-health-ingress.test.ts +113 -0
  171. package/src/access-service.ts +14 -7
  172. package/src/buffer-ingress-counters.test.ts +310 -0
  173. package/src/buffer-ingress-counters.ts +278 -0
  174. package/src/buffer-ingress-invariant.test.ts +290 -0
  175. package/src/buffer-turn-helpers.ts +10 -0
  176. package/src/buffer.ts +19 -21
  177. package/dist/chunk-34YQ7CVE.js.map +0 -1
  178. package/dist/chunk-3OLHDECL.js.map +0 -1
  179. package/dist/chunk-BR7CZVMO.js.map +0 -1
  180. /package/dist/{graph-edge-decay-CXTNJ7IQ.js.map → buffer-ingress-counters.js.map} +0 -0
  181. /package/dist/{chunk-ID65XTF3.js.map → chunk-2JAT4S7N.js.map} +0 -0
  182. /package/dist/{chunk-ORMJT23N.js.map → chunk-3OT6JDMD.js.map} +0 -0
  183. /package/dist/{chunk-SU42FIJ7.js.map → chunk-3RW5ZCYO.js.map} +0 -0
  184. /package/dist/{chunk-TJJPT2OV.js.map → chunk-3S7BUGYC.js.map} +0 -0
  185. /package/dist/{chunk-7TC2PWKH.js.map → chunk-4KWR7M3Q.js.map} +0 -0
  186. /package/dist/{chunk-WRGW76LI.js.map → chunk-5BE3FLKL.js.map} +0 -0
  187. /package/dist/{chunk-JK2IVISS.js.map → chunk-5FWPLAKP.js.map} +0 -0
  188. /package/dist/{chunk-PPPY2PCU.js.map → chunk-5OW73TEG.js.map} +0 -0
  189. /package/dist/{chunk-DTTDMK7Q.js.map → chunk-5RONA5FF.js.map} +0 -0
  190. /package/dist/{chunk-6FPJPSQK.js.map → chunk-6P5PIOWW.js.map} +0 -0
  191. /package/dist/{chunk-HJ7M322C.js.map → chunk-6PQVAYQJ.js.map} +0 -0
  192. /package/dist/{chunk-QKYOMKRG.js.map → chunk-7C7M2P43.js.map} +0 -0
  193. /package/dist/{chunk-XMKUABIG.js.map → chunk-AAV726HQ.js.map} +0 -0
  194. /package/dist/{chunk-ASINXIKX.js.map → chunk-AWKD2A73.js.map} +0 -0
  195. /package/dist/{chunk-XUWDB53W.js.map → chunk-BAKCGJRQ.js.map} +0 -0
  196. /package/dist/{chunk-ALLI23GW.js.map → chunk-BE5F6KFG.js.map} +0 -0
  197. /package/dist/{chunk-MGCV3VGC.js.map → chunk-BOK5D46I.js.map} +0 -0
  198. /package/dist/{chunk-FBXU7X27.js.map → chunk-BTY6DUFW.js.map} +0 -0
  199. /package/dist/{chunk-FPBFDQZZ.js.map → chunk-CFJBSE7J.js.map} +0 -0
  200. /package/dist/{chunk-WYABF2WA.js.map → chunk-CLVILSBR.js.map} +0 -0
  201. /package/dist/{chunk-BFBS7OFQ.js.map → chunk-DC55RIEZ.js.map} +0 -0
  202. /package/dist/{chunk-NYZ6ZNFO.js.map → chunk-FCW4FUF2.js.map} +0 -0
  203. /package/dist/{chunk-7QDB7P3V.js.map → chunk-FMFCQRDM.js.map} +0 -0
  204. /package/dist/{chunk-K36RMINQ.js.map → chunk-GOZXQNIM.js.map} +0 -0
  205. /package/dist/{chunk-YFUHFPV6.js.map → chunk-HILGHLPA.js.map} +0 -0
  206. /package/dist/{chunk-EFHM4VDG.js.map → chunk-HLWXCDUQ.js.map} +0 -0
  207. /package/dist/{chunk-JCPEXUNP.js.map → chunk-IUVTFQWY.js.map} +0 -0
  208. /package/dist/{chunk-YPE3O5VH.js.map → chunk-JHKCS6EN.js.map} +0 -0
  209. /package/dist/{chunk-UWU6KEZU.js.map → chunk-JVQNRSWO.js.map} +0 -0
  210. /package/dist/{chunk-PAGVXEWG.js.map → chunk-KLUCX6OH.js.map} +0 -0
  211. /package/dist/{chunk-ELBZT6RU.js.map → chunk-KVCFAWBZ.js.map} +0 -0
  212. /package/dist/{chunk-W4Q65VJL.js.map → chunk-MZCGHPIJ.js.map} +0 -0
  213. /package/dist/{chunk-2BBCM2PX.js.map → chunk-N36J3MIB.js.map} +0 -0
  214. /package/dist/{chunk-AYBRQJXP.js.map → chunk-NVKWV4W3.js.map} +0 -0
  215. /package/dist/{chunk-CUKYV5O3.js.map → chunk-OEP5XRTB.js.map} +0 -0
  216. /package/dist/{chunk-ZUMHQEW4.js.map → chunk-QHDBKC5Z.js.map} +0 -0
  217. /package/dist/{chunk-MCTGYIYN.js.map → chunk-RXD46MY6.js.map} +0 -0
  218. /package/dist/{chunk-TJY6AKWV.js.map → chunk-SULNVNTU.js.map} +0 -0
  219. /package/dist/{chunk-7T7I5D3F.js.map → chunk-TSJQ7C2T.js.map} +0 -0
  220. /package/dist/{chunk-HQPFACXO.js.map → chunk-UH3FPX3L.js.map} +0 -0
  221. /package/dist/{chunk-6SRYCJ5I.js.map → chunk-V6JECHY6.js.map} +0 -0
  222. /package/dist/{chunk-YCJRYM3Q.js.map → chunk-VAMCJPJT.js.map} +0 -0
  223. /package/dist/{chunk-QC2MHZDD.js.map → chunk-VEFGHRKV.js.map} +0 -0
  224. /package/dist/{chunk-O62MMJWV.js.map → chunk-VO3HCFSR.js.map} +0 -0
  225. /package/dist/{chunk-TQ5NOVMT.js.map → chunk-X7EAMNKR.js.map} +0 -0
  226. /package/dist/{chunk-G53I363P.js.map → chunk-XF2QQQXO.js.map} +0 -0
  227. /package/dist/{chunk-GWFL6LUU.js.map → chunk-XUS2UQOO.js.map} +0 -0
  228. /package/dist/{chunk-FZVROZKC.js.map → chunk-XVZA6VXC.js.map} +0 -0
  229. /package/dist/{chunk-VPEIWMUT.js.map → chunk-YLTU2DC4.js.map} +0 -0
  230. /package/dist/{chunk-PXZLVFNC.js.map → chunk-YQXD57ZS.js.map} +0 -0
  231. /package/dist/{chunk-LR2X3FJM.js.map → chunk-YW63C4FO.js.map} +0 -0
  232. /package/dist/{chunk-LU2GQ4Q4.js.map → chunk-YYHBB565.js.map} +0 -0
  233. /package/dist/{chunk-2G72JBQB.js.map → chunk-ZCXZNK4G.js.map} +0 -0
  234. /package/dist/{chunk-ZO377APE.js.map → chunk-ZMDXISMQ.js.map} +0 -0
  235. /package/dist/{chunk-4DJSDH2M.js.map → chunk-ZT7EJUNT.js.map} +0 -0
@@ -2368,13 +2368,10 @@ export class EngramAccessService extends SupportPassportAccessServiceBase {
2368
2368
  cache: this.corpusWatermarkCache,
2369
2369
  caps,
2370
2370
  });
2371
- let projectionAvailable = false;
2372
- try {
2373
- await stat(getMemoryProjectionPath(storage.dir));
2374
- projectionAvailable = true;
2375
- } catch {
2376
- projectionAvailable = false;
2377
- }
2371
+ const projectionAvailable = await stat(getMemoryProjectionPath(storage.dir)).then(
2372
+ () => true,
2373
+ () => false,
2374
+ );
2378
2375
 
2379
2376
  return {
2380
2377
  ok: true,
@@ -2391,6 +2388,16 @@ export class EngramAccessService extends SupportPassportAccessServiceBase {
2391
2388
  ),
2392
2389
  nativeKnowledgeEnabled: this.orchestrator.config.nativeKnowledge?.enabled === true,
2393
2390
  projectionAvailable,
2391
+ // #3444: process-local buffer add-path counters, TOP LEVEL (not inside `extraction`).
2392
+ bufferIngress: this.orchestrator.buffer?.ingress?.snapshot() ?? {
2393
+ totals: {
2394
+ accepted: { turns: 0, chars: 0 },
2395
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
2396
+ filtered: { turns: 0, chars: 0 },
2397
+ refused: { turns: 0, chars: 0 },
2398
+ },
2399
+ hours: [],
2400
+ },
2394
2401
  extraction: visibleExtraction,
2395
2402
  corpus: corpusCensus.watermarks,
2396
2403
  // Describes THIS response's array (round 8): a separate scan could report
@@ -0,0 +1,310 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { createHash } from "node:crypto";
5
+
6
+ import {
7
+ BufferIngressCounters,
8
+ type BufferIngressSnapshot,
9
+ EMPTY_BUFFER_INGRESS_SNAPSHOT,
10
+ } from "./buffer-ingress-counters.js";
11
+ import { initLogger, resetLogger } from "./logger.js";
12
+ import type { BufferEntryState, BufferTurn } from "./types.js";
13
+
14
+ const HOUR_MS = 3_600_000;
15
+
16
+ function captureInfo() {
17
+ // SAFETY: implements LoggerBackend for log capture; error is a no-op because these tests never log errors.
18
+ const lines: string[] = [];
19
+ initLogger({
20
+ info: (msg: string) => lines.push(msg),
21
+ warn: () => {},
22
+ error: () => {},
23
+ debug: () => {},
24
+ });
25
+ return { lines, restore: resetLogger };
26
+ }
27
+
28
+ function fakeEntry(turns: BufferTurn[] = []): BufferEntryState {
29
+ return { turns, lastExtractionAt: null, extractionCount: 0 };
30
+ }
31
+
32
+ function turn(content: string): BufferTurn {
33
+ return { role: "user", content, timestamp: "2026-04-12T12:00:00.000Z", sessionKey: "kA" };
34
+ }
35
+
36
+ test("aggregates accepted, its exact-duplicate sub-count and refusals in turns and chars", () => {
37
+ const counters = new BufferIngressCounters();
38
+ const entry = fakeEntry();
39
+ counters.noteAppendedTurn(entry, turn("alpha memory"));
40
+ counters.noteAppendedTurn(entry, turn("beta memory"));
41
+ counters.noteAppendedTurn(entry, turn("alpha memory")); // exact duplicate, still appended
42
+ counters.refuseOne(turn("refused offer"));
43
+
44
+ const snapshot = counters.snapshot();
45
+ assert.deepEqual(snapshot.totals.accepted, { turns: 3, chars: 35 });
46
+ assert.deepEqual(snapshot.totals.acceptedExactDuplicate, { turns: 1, chars: 12 });
47
+ assert.deepEqual(snapshot.totals.filtered, { turns: 0, chars: 0 });
48
+ assert.deepEqual(snapshot.totals.refused, { turns: 1, chars: 13 });
49
+ });
50
+
51
+ test("refuseThrow counts and returns the original error; refuseAll counts every turn", () => {
52
+ const counters = new BufferIngressCounters();
53
+ const original = new Error("cap");
54
+ const returned = counters.refuseThrow(turn("x"), original);
55
+ assert.equal(returned, original);
56
+ const batch = [turn("a"), turn("bb")];
57
+ assert.equal(counters.refuseAll(batch.map((t) => ({ turn: t }))), null);
58
+ const snapshot = counters.snapshot();
59
+ assert.deepEqual(snapshot.totals.refused, { turns: 3, chars: 1 + 1 + 2 });
60
+ });
61
+
62
+ test("the duplicate digest set follows the entry's turns (self-invalidating memo)", () => {
63
+ const counters = new BufferIngressCounters();
64
+ const entry = fakeEntry([turn("seeded")]);
65
+ counters.noteAppendedTurn(entry, turn("seeded")); // matches the seeded turn
66
+ assert.equal(counters.snapshot().totals.acceptedExactDuplicate.turns, 1);
67
+ // A drain reassigns the array: the old content is no longer tracked.
68
+ entry.turns = [turn("fresh")];
69
+ counters.noteAppendedTurn(entry, turn("seeded"));
70
+ assert.equal(counters.snapshot().totals.acceptedExactDuplicate.turns, 1);
71
+ // Retained turns participate too.
72
+ entry.turns = [];
73
+ entry.retainedTurns = [turn("kept")];
74
+ counters.noteAppendedTurn(entry, turn("kept"));
75
+ assert.equal(counters.snapshot().totals.acceptedExactDuplicate.turns, 2);
76
+ });
77
+
78
+ test("counters-disabled control records nothing (differential seam)", () => {
79
+ const counters = new BufferIngressCounters(undefined, false);
80
+ const entry = fakeEntry();
81
+ counters.noteAppendedTurn(entry, turn("anything"));
82
+ assert.equal(counters.refuseOne(turn("anything")), null);
83
+ assert.deepEqual(counters.snapshot(), EMPTY_BUFFER_INGRESS_SNAPSHOT);
84
+ });
85
+
86
+ test("snapshot drops hour buckets older than 24h while totals stay cumulative", () => {
87
+ let t = Date.parse("2026-04-12T12:00:00.000Z");
88
+ const counters = new BufferIngressCounters(() => t);
89
+ const entry = fakeEntry();
90
+ counters.noteAppendedTurn(entry, turn("old"));
91
+ assert.equal(counters.snapshot().hours.length, 1);
92
+ t += 30 * HOUR_MS; // 30 h later
93
+ counters.noteAppendedTurn(entry, turn("new"));
94
+ const snapshot = counters.snapshot();
95
+ assert.equal(snapshot.hours.length, 1);
96
+ assert.equal(snapshot.hours[0].accepted.turns, 1);
97
+ assert.equal(snapshot.totals.accepted.turns, 2);
98
+ });
99
+
100
+ test("snapshot is a fresh read-only structure and never aliases internals", () => {
101
+ const counters = new BufferIngressCounters();
102
+ const entry = fakeEntry();
103
+ counters.noteAppendedTurn(entry, turn("note"));
104
+ const first = counters.snapshot();
105
+ first.totals.accepted.turns = 99;
106
+ first.hours.push({
107
+ hourStart: "tampered",
108
+ accepted: { turns: 0, chars: 0 },
109
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
110
+ filtered: { turns: 0, chars: 0 },
111
+ refused: { turns: 0, chars: 0 },
112
+ });
113
+ const second = counters.snapshot();
114
+ assert.equal(second.totals.accepted.turns, 1);
115
+ assert.equal(second.hours.length, 1);
116
+ });
117
+
118
+ test("hourly ring rolls with an injected clock and keeps the last 24 hours", () => {
119
+ let nowMs = 1_700_000_000_000;
120
+ const counters = new BufferIngressCounters(() => nowMs);
121
+ const entry = fakeEntry();
122
+
123
+ counters.noteAppendedTurn(entry, turn("a"));
124
+ const hourZero = Math.floor(nowMs / HOUR_MS) * HOUR_MS;
125
+ assert.deepEqual(counters.snapshot().hours, [
126
+ {
127
+ hourStart: new Date(hourZero).toISOString(),
128
+ accepted: { turns: 1, chars: 1 },
129
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
130
+ filtered: { turns: 0, chars: 0 },
131
+ refused: { turns: 0, chars: 0 },
132
+ },
133
+ ]);
134
+
135
+ // Same hour: counts land in the same bucket.
136
+ counters.noteAppendedTurn(entry, turn("b"));
137
+ assert.equal(counters.snapshot().hours.length, 1);
138
+
139
+ // Next hour: a second bucket appears, the first is preserved.
140
+ nowMs += HOUR_MS;
141
+ counters.refuseOne(turn("c"));
142
+ const hours = counters.snapshot().hours;
143
+ assert.equal(hours.length, 2);
144
+ assert.equal(hours[0].accepted.turns, 2);
145
+ assert.equal(hours[1].refused.turns, 1);
146
+
147
+ // Fill the ring: 24 distinct hours hold exactly 24 buckets, oldest first.
148
+ for (let i = 2; i <= 23; i += 1) {
149
+ nowMs += HOUR_MS;
150
+ counters.noteAppendedTurn(entry, turn(String(i)));
151
+ }
152
+ const full = counters.snapshot().hours;
153
+ assert.equal(full.length, 24);
154
+ assert.equal(new Date(full[0].hourStart).getTime(), hourZero);
155
+
156
+ // One more hour evicts the oldest bucket; the ring never exceeds 24.
157
+ nowMs += HOUR_MS;
158
+ counters.refuseOne(turn("d"));
159
+ const rolled = counters.snapshot().hours;
160
+ assert.equal(rolled.length, 24);
161
+ assert.ok(!rolled.some((hour) => hour.hourStart === new Date(hourZero).toISOString()));
162
+ const newest = rolled.at(-1);
163
+ assert.ok(newest !== undefined, "the ring keeps the newest hour after eviction");
164
+ assert.equal(newest.refused.turns, 1);
165
+ });
166
+
167
+ test("totals survive hourly eviction (process-lifetime sums, not the ring)", () => {
168
+ let nowMs = 1_700_000_000_000;
169
+ const counters = new BufferIngressCounters(() => nowMs);
170
+ const entry = fakeEntry();
171
+ counters.noteAppendedTurn(entry, turn("a"));
172
+ nowMs += 30 * HOUR_MS;
173
+ counters.noteAppendedTurn(entry, turn("bb"));
174
+ assert.deepEqual(counters.snapshot().totals.accepted, { turns: 2, chars: 3 });
175
+ });
176
+
177
+ test("exactly one aggregate info line per hour, counts only", () => {
178
+ let nowMs = 1_700_000_000_000;
179
+ const counters = new BufferIngressCounters(() => nowMs);
180
+ const entry = fakeEntry();
181
+ const { lines, restore } = captureInfo();
182
+ try {
183
+ // First hour of the process: nothing to log yet (empty bucket).
184
+ counters.noteAppendedTurn(entry, turn("a"));
185
+ assert.equal(lines.length, 0);
186
+
187
+ // Hour rolls: ONE line describing the previous hour.
188
+ nowMs += HOUR_MS;
189
+ counters.refuseOne(turn("b"));
190
+ assert.equal(lines.length, 1);
191
+ assert.match(lines[0], /buffer ingress/);
192
+ assert.match(lines[0], /accepted=1\//);
193
+ assert.match(lines[0], /refused=0\//);
194
+
195
+ // No further log within the same hour, even with more records.
196
+ counters.noteAppendedTurn(entry, turn("c"));
197
+ assert.equal(lines.length, 1);
198
+
199
+ // Empty hours produce no log line (zero-noise): jump forward 3 hours.
200
+ nowMs += 3 * HOUR_MS;
201
+ counters.refuseOne(turn("d"));
202
+ assert.equal(lines.length, 2);
203
+ assert.match(lines[1], /refused=1\//);
204
+ } finally {
205
+ restore();
206
+ }
207
+ });
208
+
209
+ test("log lines carry no content or session identifiers", () => {
210
+ let nowMs = 1_700_000_000_000;
211
+ const counters = new BufferIngressCounters(() => nowMs);
212
+ const entry = fakeEntry();
213
+ const { lines, restore } = captureInfo();
214
+ try {
215
+ counters.noteAppendedTurn(entry, turn("secret-session-kaze"));
216
+ nowMs += HOUR_MS;
217
+ counters.noteAppendedTurn(entry, turn("secret memory content"));
218
+ assert.equal(lines.length, 1);
219
+ assert.ok(!lines[0].includes("secret-session-kaze"));
220
+ assert.ok(!lines[0].includes("secret memory content"));
221
+ } finally {
222
+ restore();
223
+ }
224
+ });
225
+
226
+ test("EMPTY_BUFFER_INGRESS_SNAPSHOT is the zero snapshot for hosts without a buffer", () => {
227
+ const empty: BufferIngressSnapshot = EMPTY_BUFFER_INGRESS_SNAPSHOT;
228
+ assert.deepEqual(empty.totals, {
229
+ accepted: { turns: 0, chars: 0 },
230
+ acceptedExactDuplicate: { turns: 0, chars: 0 },
231
+ filtered: { turns: 0, chars: 0 },
232
+ refused: { turns: 0, chars: 0 },
233
+ });
234
+ assert.deepEqual(empty.hours, []);
235
+ });
236
+
237
+ test("accepted and its exact-duplicate sub-count share one bucket when the hour rolls over mid-offer", () => {
238
+ // Scripted clock: the first now() call (accepted) lands at the end of hour
239
+ // H, the second (duplicate check path) in hour H+1. Before the fix each
240
+ // record() read the clock itself and the two counts split across buckets.
241
+ const h0 = 1_700_000_000_000 - (1_700_000_000_000 % HOUR_MS);
242
+ // now() is read once per offer (the duplicate check itself never reads the
243
+ // clock): first offer at the end of hour H, second offer in hour H+1.
244
+ const stamps = [h0 + HOUR_MS - 1, h0 + HOUR_MS - 1, h0 + HOUR_MS, h0 + HOUR_MS];
245
+ let calls = 0;
246
+ const clock = () => stamps[Math.min(calls++, stamps.length - 1)];
247
+ const counters = new BufferIngressCounters(clock);
248
+ const entry = fakeEntry();
249
+ counters.noteAppendedTurn(entry, turn("once"));
250
+ counters.noteAppendedTurn(entry, turn("once")); // duplicate, hour has rolled
251
+ const hours = counters.snapshot().hours;
252
+ const dup = hours.find((h) => h.acceptedExactDuplicate.turns === 1);
253
+ assert.ok(dup, "the duplicate sub-count must be recorded");
254
+ assert.equal(dup.accepted.turns, 2, "both accepted turns share the duplicate's bucket");
255
+ });
256
+
257
+ test("rebuilding the memo from a restored entry respects the digest cap", () => {
258
+ // A restored entry can hold more unique turns than DUPLICATE_DIGEST_CAP.
259
+ // The rebuild must keep only the most recent 4,096, so a re-offer of the
260
+ // oldest content is NOT recognised as a duplicate (bounded memory).
261
+ const counters = new BufferIngressCounters();
262
+ const many = Array.from({ length: 6_000 }, (_, i) => turn(`restored-${i}`));
263
+ const entry = fakeEntry(many);
264
+ counters.noteAppendedTurn(entry, turn("restored-0")); // re-offer of the oldest
265
+ const snapshot = counters.snapshot();
266
+ assert.equal(snapshot.totals.accepted.turns, 1);
267
+ assert.equal(snapshot.totals.acceptedExactDuplicate.turns, 0, "oldest digest evicted at rebuild");
268
+ counters.noteAppendedTurn(entry, turn("restored-5999")); // re-offer of the newest
269
+ assert.equal(counters.snapshot().totals.acceptedExactDuplicate.turns, 1, "newest digest retained");
270
+ });
271
+
272
+ // NOTE (not a test): an "offered turn missing from entry.turns" case cannot be
273
+ // constructed against the real contract — the buffer appends before counting,
274
+ // and fakeEntry arrays are caller-owned. The earlier draft of this file had
275
+ // such a test; it failed because the premise contradicts the layer's only
276
+ // valid input shape, not because counting was wrong. Memo validity therefore
277
+ // rests on entry-array identity (WeakRef-compared), covered by the
278
+ // self-invalidating-memo and retained-deletion tests below.
279
+
280
+ test("deleting retainedTurns invalidates the memo even when turns keep their identity", () => {
281
+ // The buffer observes BEFORE pushing (recordTurnUnlocked calls
282
+ // noteAppendedTurn, then pushes), so the offered turn is NOT in
283
+ // entry.turns at count time. Re-offering content that only exists in a
284
+ // deleted retained array must not count as a duplicate.
285
+ const counters = new BufferIngressCounters();
286
+ const entry = fakeEntry([turn("live")]);
287
+ entry.retainedTurns = [turn("kept-elsewhere")];
288
+ // Novel content: the first offer is not itself a duplicate, so the
289
+ // duplicate sub-count starts at zero and the probe is the only candidate.
290
+ const offered = turn("something-new");
291
+ counters.noteAppendedTurn(entry, offered); // builds memo with retained
292
+ entry.turns.push(offered);
293
+ // White-box through the layer's own test seam: memoForTest exposes the
294
+ // digest set only, never the validity refs.
295
+ const memoBefore = counters.memoForTest(entry);
296
+ assert.ok(memoBefore !== undefined && memoBefore.digests instanceof Set, "memo exists after first offer");
297
+ const d = (c: string) => createHash("sha256").update("user\0" + c).digest("base64");
298
+ assert.ok(memoBefore.digests.has(d("kept-elsewhere")), "memo covers retained content before deletion");
299
+ const sizeBefore = memoBefore.digests.size;
300
+ delete entry.retainedTurns;
301
+ const probe = turn("kept-elsewhere");
302
+ counters.noteAppendedTurn(entry, probe); // matches only removed content
303
+ entry.turns.push(probe);
304
+ // Same seam; identity compared, then dropped.
305
+ const memoAfter = counters.memoForTest(entry);
306
+ assert.notEqual(memoAfter, memoBefore, "memo rebuilt after retainedTurns deletion");
307
+ // The re-offered probe matches only removed content, so the duplicate
308
+ // sub-count stays at zero — the observable behavior the fix protects.
309
+ assert.equal(counters.snapshot().totals.acceptedExactDuplicate.turns, 0, "removed content is not a duplicate");
310
+ });
@@ -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
+ }