@remnic/core 10.0.125 → 10.0.127

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 (178) hide show
  1. package/dist/access-admin-ops-surface.js +38 -38
  2. package/dist/access-cli.js +38 -38
  3. package/dist/access-extraction-force-flush.js +38 -38
  4. package/dist/access-http-briefing.js +38 -38
  5. package/dist/access-http-query.js +38 -38
  6. package/dist/access-http.js +38 -38
  7. package/dist/access-identity-continuity-surface.js +38 -38
  8. package/dist/access-lcm-surface.js +38 -38
  9. package/dist/access-mcp.js +38 -38
  10. package/dist/access-observe-write-surface.js +38 -38
  11. package/dist/access-operations-batch.js +38 -38
  12. package/dist/access-operations.js +38 -38
  13. package/dist/access-recall-concurrency.js +38 -38
  14. package/dist/access-recall-response.js +38 -38
  15. package/dist/access-recall-surface.js +38 -38
  16. package/dist/access-service.d.ts.map +1 -1
  17. package/dist/access-service.js +38 -38
  18. package/dist/active-recall.js +6 -6
  19. package/dist/briefing.js +4 -4
  20. package/dist/buffer-turn-helpers.d.ts +7 -0
  21. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  22. package/dist/buffer-turn-helpers.js +3 -1
  23. package/dist/buffer-turn.d.ts +10 -0
  24. package/dist/buffer-turn.d.ts.map +1 -1
  25. package/dist/buffer.js +3 -3
  26. package/dist/causal-consolidation.js +5 -5
  27. package/dist/{chunk-BNRKSJMO.js → chunk-2BBCM2PX.js} +2 -2
  28. package/dist/{chunk-2GSPNTOU.js → chunk-2G72JBQB.js} +2 -2
  29. package/dist/{chunk-IDCZEKK6.js → chunk-34YQ7CVE.js} +3 -3
  30. package/dist/{chunk-AYWW6JEH.js → chunk-3OLHDECL.js} +115 -41
  31. package/dist/chunk-3OLHDECL.js.map +1 -0
  32. package/dist/{chunk-4VWZ4HPL.js → chunk-4DJSDH2M.js} +6 -6
  33. package/dist/{chunk-YJEOQ72B.js → chunk-6FPJPSQK.js} +2 -2
  34. package/dist/{chunk-YKUW2EZF.js → chunk-7T7I5D3F.js} +2 -2
  35. package/dist/{chunk-ERR7ZFPJ.js → chunk-7TC2PWKH.js} +2 -2
  36. package/dist/{chunk-DH2CDGAE.js → chunk-ALLI23GW.js} +2 -2
  37. package/dist/{chunk-RTIHO7AJ.js → chunk-AYBRQJXP.js} +2 -2
  38. package/dist/{chunk-UXXK523X.js → chunk-BR7CZVMO.js} +20 -16
  39. package/dist/chunk-BR7CZVMO.js.map +1 -0
  40. package/dist/{chunk-AWD36R4D.js → chunk-DURQZFVJ.js} +36 -6
  41. package/dist/chunk-DURQZFVJ.js.map +1 -0
  42. package/dist/{chunk-C7BTGSCY.js → chunk-FPBFDQZZ.js} +9 -9
  43. package/dist/{chunk-5DCCVEKT.js → chunk-GWFL6LUU.js} +2 -2
  44. package/dist/{chunk-JTY3NA3I.js → chunk-HJ7M322C.js} +2 -2
  45. package/dist/{chunk-HURBXNNB.js → chunk-JCPEXUNP.js} +2 -2
  46. package/dist/{chunk-LKGTTX74.js → chunk-JK2IVISS.js} +2 -2
  47. package/dist/{chunk-7XG7KMIW.js → chunk-LNQQEFKH.js} +2 -2
  48. package/dist/{chunk-IB4TDPCC.js → chunk-LR2X3FJM.js} +2 -2
  49. package/dist/{chunk-6IRJWKR5.js → chunk-LU2GQ4Q4.js} +2 -2
  50. package/dist/{chunk-4VCASS3Q.js → chunk-MCTGYIYN.js} +2 -2
  51. package/dist/{chunk-XN43HAIV.js → chunk-MGCV3VGC.js} +2 -2
  52. package/dist/{chunk-KWVGRNKL.js → chunk-NYZ6ZNFO.js} +2 -2
  53. package/dist/{chunk-6VAN7VZR.js → chunk-ORMJT23N.js} +7 -7
  54. package/dist/{chunk-DL7K5PMQ.js → chunk-PPPY2PCU.js} +2 -2
  55. package/dist/{chunk-5DP4GVKR.js → chunk-PXZLVFNC.js} +2 -2
  56. package/dist/{chunk-GSCIRMPR.js → chunk-QKYOMKRG.js} +2 -2
  57. package/dist/{chunk-QF64W4YM.js → chunk-QRZNVNNS.js} +2 -2
  58. package/dist/{chunk-CQMH65IP.js → chunk-TJJPT2OV.js} +2 -2
  59. package/dist/{chunk-2AVPRUML.js → chunk-TJY6AKWV.js} +2 -2
  60. package/dist/{chunk-RRHLI6VU.js → chunk-TQ5NOVMT.js} +2 -2
  61. package/dist/{chunk-KNT3BZZH.js → chunk-UWU6KEZU.js} +185 -59
  62. package/dist/chunk-UWU6KEZU.js.map +1 -0
  63. package/dist/{chunk-PUKLCFCU.js → chunk-VY3DHUL7.js} +2 -2
  64. package/dist/chunk-VY3DHUL7.js.map +1 -0
  65. package/dist/{chunk-47W3ALIS.js → chunk-XMKUABIG.js} +3 -3
  66. package/dist/{chunk-UGCLNASV.js → chunk-XUWDB53W.js} +3 -3
  67. package/dist/{chunk-XLHLZALR.js → chunk-YCJRYM3Q.js} +3 -3
  68. package/dist/{chunk-DB4THCGN.js → chunk-YFUHFPV6.js} +2 -2
  69. package/dist/{chunk-42JE2CF4.js → chunk-YPE3O5VH.js} +2 -2
  70. package/dist/{chunk-7TJMXZPO.js → chunk-ZO377APE.js} +2 -2
  71. package/dist/cli.js +38 -38
  72. package/dist/coding/export-okf-codegraph.js +3 -3
  73. package/dist/compounding/engine.js +5 -5
  74. package/dist/config.js +6 -6
  75. package/dist/connectors/codex-materialize-runner.js +4 -4
  76. package/dist/connectors/index.js +4 -4
  77. package/dist/convergence-refresh.js +6 -6
  78. package/dist/corpus-watermark.js +6 -6
  79. package/dist/entity-retrieval.js +4 -4
  80. package/dist/explicit-capture.js +38 -38
  81. package/dist/extraction-liveness.d.ts +54 -5
  82. package/dist/extraction-liveness.d.ts.map +1 -1
  83. package/dist/extraction-liveness.js +1 -1
  84. package/dist/extraction-span-config.js +2 -2
  85. package/dist/extraction.js +7 -7
  86. package/dist/harmonic-retrieval.js +4 -4
  87. package/dist/index.js +38 -38
  88. package/dist/location/index.js +5 -5
  89. package/dist/maintenance/memory-governance.js +4 -4
  90. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +4 -4
  91. package/dist/maintenance/rebuild-memory-projection-runner.js +6 -6
  92. package/dist/maintenance/rebuild-memory-projection.js +5 -5
  93. package/dist/namespaces/migrate.js +5 -5
  94. package/dist/namespaces/storage.js +4 -4
  95. package/dist/operator-doctor-corpus.js +7 -7
  96. package/dist/operator-toolkit.js +13 -13
  97. package/dist/orchestration/backlog-scheduler.js +39 -39
  98. package/dist/orchestration/buffer-drain-runner.js +39 -39
  99. package/dist/orchestration/extraction-dedupe.d.ts +46 -0
  100. package/dist/orchestration/extraction-dedupe.d.ts.map +1 -0
  101. package/dist/orchestration/extraction-drain.d.ts +12 -1
  102. package/dist/orchestration/extraction-drain.d.ts.map +1 -1
  103. package/dist/orchestration/extraction-run.d.ts.map +1 -1
  104. package/dist/orchestration/maintenance.js +12 -12
  105. package/dist/orchestrator.js +38 -38
  106. package/dist/recall-navigation.js +38 -38
  107. package/dist/resume-bundles.js +7 -7
  108. package/dist/semantic-consolidation.js +5 -5
  109. package/dist/semantic-rule-promotion.js +4 -4
  110. package/dist/semantic-rule-verifier.js +4 -4
  111. package/dist/source-agent-qualifier.js +6 -6
  112. package/dist/standup/build.js +4 -4
  113. package/dist/storage/buffer-drain-claims.d.ts +19 -4
  114. package/dist/storage/buffer-drain-claims.d.ts.map +1 -1
  115. package/dist/storage/buffer-drain-claims.js +2 -2
  116. package/dist/storage/buffer-session-files.js +2 -2
  117. package/dist/storage/drain-claim-totals.d.ts +54 -0
  118. package/dist/storage/drain-claim-totals.d.ts.map +1 -0
  119. package/dist/storage.js +3 -3
  120. package/dist/transfer/export-okf.js +4 -4
  121. package/dist/verified-recall.js +4 -4
  122. package/dist/who-knows-cli.js +5 -5
  123. package/dist/who-knows.js +4 -4
  124. package/package.json +2 -2
  125. package/src/access-service-health.test.ts +102 -1
  126. package/src/access-service.ts +10 -1
  127. package/src/buffer-turn-helpers.ts +25 -15
  128. package/src/buffer-turn.ts +10 -0
  129. package/src/extraction-liveness.test.ts +229 -0
  130. package/src/extraction-liveness.ts +89 -6
  131. package/src/orchestration/extraction-dedupe.test.ts +101 -0
  132. package/src/orchestration/extraction-dedupe.ts +80 -0
  133. package/src/orchestration/extraction-drain-dedupe.test.ts +477 -0
  134. package/src/orchestration/extraction-drain.ts +69 -9
  135. package/src/orchestration/extraction-run.ts +2 -0
  136. package/src/storage/buffer-drain-claims.test.ts +66 -0
  137. package/src/storage/buffer-drain-claims.ts +49 -4
  138. package/src/storage/drain-claim-totals.test.ts +356 -0
  139. package/src/storage/drain-claim-totals.ts +175 -0
  140. package/dist/chunk-AWD36R4D.js.map +0 -1
  141. package/dist/chunk-AYWW6JEH.js.map +0 -1
  142. package/dist/chunk-KNT3BZZH.js.map +0 -1
  143. package/dist/chunk-PUKLCFCU.js.map +0 -1
  144. package/dist/chunk-UXXK523X.js.map +0 -1
  145. /package/dist/{chunk-BNRKSJMO.js.map → chunk-2BBCM2PX.js.map} +0 -0
  146. /package/dist/{chunk-2GSPNTOU.js.map → chunk-2G72JBQB.js.map} +0 -0
  147. /package/dist/{chunk-IDCZEKK6.js.map → chunk-34YQ7CVE.js.map} +0 -0
  148. /package/dist/{chunk-4VWZ4HPL.js.map → chunk-4DJSDH2M.js.map} +0 -0
  149. /package/dist/{chunk-YJEOQ72B.js.map → chunk-6FPJPSQK.js.map} +0 -0
  150. /package/dist/{chunk-YKUW2EZF.js.map → chunk-7T7I5D3F.js.map} +0 -0
  151. /package/dist/{chunk-ERR7ZFPJ.js.map → chunk-7TC2PWKH.js.map} +0 -0
  152. /package/dist/{chunk-DH2CDGAE.js.map → chunk-ALLI23GW.js.map} +0 -0
  153. /package/dist/{chunk-RTIHO7AJ.js.map → chunk-AYBRQJXP.js.map} +0 -0
  154. /package/dist/{chunk-C7BTGSCY.js.map → chunk-FPBFDQZZ.js.map} +0 -0
  155. /package/dist/{chunk-5DCCVEKT.js.map → chunk-GWFL6LUU.js.map} +0 -0
  156. /package/dist/{chunk-JTY3NA3I.js.map → chunk-HJ7M322C.js.map} +0 -0
  157. /package/dist/{chunk-HURBXNNB.js.map → chunk-JCPEXUNP.js.map} +0 -0
  158. /package/dist/{chunk-LKGTTX74.js.map → chunk-JK2IVISS.js.map} +0 -0
  159. /package/dist/{chunk-7XG7KMIW.js.map → chunk-LNQQEFKH.js.map} +0 -0
  160. /package/dist/{chunk-IB4TDPCC.js.map → chunk-LR2X3FJM.js.map} +0 -0
  161. /package/dist/{chunk-6IRJWKR5.js.map → chunk-LU2GQ4Q4.js.map} +0 -0
  162. /package/dist/{chunk-4VCASS3Q.js.map → chunk-MCTGYIYN.js.map} +0 -0
  163. /package/dist/{chunk-XN43HAIV.js.map → chunk-MGCV3VGC.js.map} +0 -0
  164. /package/dist/{chunk-KWVGRNKL.js.map → chunk-NYZ6ZNFO.js.map} +0 -0
  165. /package/dist/{chunk-6VAN7VZR.js.map → chunk-ORMJT23N.js.map} +0 -0
  166. /package/dist/{chunk-DL7K5PMQ.js.map → chunk-PPPY2PCU.js.map} +0 -0
  167. /package/dist/{chunk-5DP4GVKR.js.map → chunk-PXZLVFNC.js.map} +0 -0
  168. /package/dist/{chunk-GSCIRMPR.js.map → chunk-QKYOMKRG.js.map} +0 -0
  169. /package/dist/{chunk-QF64W4YM.js.map → chunk-QRZNVNNS.js.map} +0 -0
  170. /package/dist/{chunk-CQMH65IP.js.map → chunk-TJJPT2OV.js.map} +0 -0
  171. /package/dist/{chunk-2AVPRUML.js.map → chunk-TJY6AKWV.js.map} +0 -0
  172. /package/dist/{chunk-RRHLI6VU.js.map → chunk-TQ5NOVMT.js.map} +0 -0
  173. /package/dist/{chunk-47W3ALIS.js.map → chunk-XMKUABIG.js.map} +0 -0
  174. /package/dist/{chunk-UGCLNASV.js.map → chunk-XUWDB53W.js.map} +0 -0
  175. /package/dist/{chunk-XLHLZALR.js.map → chunk-YCJRYM3Q.js.map} +0 -0
  176. /package/dist/{chunk-DB4THCGN.js.map → chunk-YFUHFPV6.js.map} +0 -0
  177. /package/dist/{chunk-42JE2CF4.js.map → chunk-YPE3O5VH.js.map} +0 -0
  178. /package/dist/{chunk-7TJMXZPO.js.map → chunk-ZO377APE.js.map} +0 -0
@@ -0,0 +1,477 @@
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
+ import { SmartBuffer } from "../buffer.js";
7
+ import { parseConfig } from "../config.js";
8
+ import { StorageManager } from "../storage.js";
9
+ import type { BufferTurn } from "../types.js";
10
+ import { ExtractionDrain, type DrainRunOptions } from "./extraction-drain.js";
11
+ import type { ExtractionRunResult } from "./extraction-run.js";
12
+
13
+ function makeTurn(content: string, overrides: Partial<BufferTurn> = {}): BufferTurn {
14
+ return { role: "user", content, timestamp: "2026-11-16T12:00:00.000Z", sessionKey: "s1", ...overrides };
15
+ }
16
+
17
+ const DONE: ExtractionRunResult = { status: "completed", persistedCount: 1, durableOutputCount: 1 };
18
+ const FAILED: ExtractionRunResult = {
19
+ status: "skipped",
20
+ reason: "empty_extraction_result",
21
+ retainedBuffer: true,
22
+ failureClass: "parse_empty",
23
+ persistedCount: 0,
24
+ durableOutputCount: 0,
25
+ };
26
+
27
+ /** What an extraction run keeps for the model: the chunk minus marked duplicate copies. */
28
+ function modelTurnsOf(call: { turns: BufferTurn[] }): BufferTurn[] {
29
+ return call.turns.filter((seen) => seen.extractionDuplicateOf !== true);
30
+ }
31
+
32
+ interface RunSpy {
33
+ calls: { turns: BufferTurn[]; options: Partial<DrainRunOptions> }[];
34
+ /** role+content the model sees, in arrival order */
35
+ modelRoleContent(): string[];
36
+ modelTurnCount(): number;
37
+ /** repeated role+content pairs within any single chunk's model-visible set (must stay 0) */
38
+ modelDuplicates(): number;
39
+ /** marked copies whose representative is missing from the same call (must stay 0) */
40
+ uncoveredShadows(): number;
41
+ }
42
+
43
+ function createSpy(): RunSpy {
44
+ const calls: { turns: BufferTurn[]; options: DrainRunOptions }[] = [];
45
+ return {
46
+ calls,
47
+ modelRoleContent() {
48
+ return calls.flatMap((call) => modelTurnsOf(call).map((seen) => `${seen.role}\u0000${seen.content}`));
49
+ },
50
+ modelTurnCount() {
51
+ return calls.reduce((total, call) => total + modelTurnsOf(call).length, 0);
52
+ },
53
+ modelDuplicates() {
54
+ return Math.max(
55
+ 0,
56
+ ...calls.map((call) => {
57
+ const seen = modelTurnsOf(call).map((turn) => `${turn.role}\u0000${turn.content}`);
58
+ return seen.length - new Set(seen).size;
59
+ }),
60
+ );
61
+ },
62
+ uncoveredShadows() {
63
+ return calls.filter((call) => {
64
+ const representatives = new Set(
65
+ modelTurnsOf(call).map((seen) => `${seen.role}\u0000${seen.content}`),
66
+ );
67
+ return call.turns.some(
68
+ (seen) => seen.extractionDuplicateOf === true && !representatives.has(`${seen.role}\u0000${seen.content}`),
69
+ );
70
+ }).length;
71
+ },
72
+ };
73
+ }
74
+
75
+ interface DrainOptions {
76
+ /** Turns loaded into the buffer AND handed to `run` as the drain window. */
77
+ turns: BufferTurn[];
78
+ results: ExtractionRunResult[];
79
+ budgetChars?: number;
80
+ minChars?: number;
81
+ dropAfter?: number;
82
+ saveCopy?: (bufferKey: string, reason: string, turns: readonly BufferTurn[]) => Promise<string>;
83
+ }
84
+
85
+ /**
86
+ * A real buffer on real storage, drained with a stub runExtraction that clears like the
87
+ * coordinator does for a `clearMatchingTurns` drain: by identity, from the turns it received.
88
+ */
89
+ async function withDrain(
90
+ opts: DrainOptions,
91
+ run: (
92
+ drain: ExtractionDrain,
93
+ spy: RunSpy,
94
+ window: BufferTurn[],
95
+ buffer: SmartBuffer,
96
+ ) => Promise<ExtractionRunResult | void>,
97
+ ): Promise<{ spy: RunSpy; buffer: SmartBuffer }> {
98
+ const root = await mkdtemp(path.join(os.tmpdir(), "remnic-dedup-drain-"));
99
+ const spy = createSpy();
100
+ const buffer = new SmartBuffer(
101
+ parseConfig({ memoryDir: root, bufferMaxTurnsPerSession: 2000 }),
102
+ new StorageManager(root),
103
+ );
104
+ try {
105
+ for (const entry of opts.turns) await buffer.addTurn("s1", entry);
106
+ await buffer.flushPendingSave();
107
+ const drain = new ExtractionDrain({
108
+ config: {
109
+ extractionMinUserTurns: 1,
110
+ extractionMinChars: opts.minChars ?? 0,
111
+ extractionMaxTurnChars: 100_000,
112
+ extractionChunkDropAfterFailures: opts.dropAfter ?? 3,
113
+ },
114
+ extractionWindowBudgetChars: () => opts.budgetChars ?? Number.POSITIVE_INFINITY,
115
+ measureRenderedTurns: (turns) => turns.reduce((total, seen) => total + seen.content.length, 0),
116
+ runExtraction: async (turns, options) => {
117
+ spy.calls.push({ turns: [...turns], options: options ?? {} });
118
+ const result = opts.results.shift() ?? DONE;
119
+ // A successful run clears its chunk the way the coordinator does: by identity.
120
+ if (result.status === "completed") {
121
+ await buffer.clearAfterExtraction(
122
+ "s1",
123
+ turns,
124
+ options?.clearMatchingTurns === true ? { allowNonPrefix: true } : undefined,
125
+ );
126
+ }
127
+ return result;
128
+ },
129
+ getStorage: async () => ({
130
+ saveDroppedExtractionChunk:
131
+ opts.saveCopy ?? (async (_bufferKey, _reason, turns) => `/recovery/${turns.length}.json`),
132
+ }),
133
+ buffer: {
134
+ dropExtractionChunk: (bufferKey, turns, dropOptions) =>
135
+ buffer.dropExtractionChunk(bufferKey, turns, dropOptions),
136
+ },
137
+ });
138
+ const options: DrainRunOptions = {
139
+ bufferKey: "s1",
140
+ clearBufferAfterExtraction: true,
141
+ clearMatchingTurns: true,
142
+ skipUserTurnThreshold: false,
143
+ failOnExtractionFailure: false,
144
+ forceExtractionAttempt: false,
145
+ };
146
+ await run(drain, spy, opts.turns, buffer);
147
+ return { spy, buffer };
148
+ } finally {
149
+ await rm(root, { recursive: true, force: true });
150
+ }
151
+ }
152
+
153
+ const SINGLE_RUN = (): DrainRunOptions => ({
154
+ bufferKey: "s1",
155
+ clearBufferAfterExtraction: true,
156
+ clearMatchingTurns: true,
157
+ skipUserTurnThreshold: false,
158
+ failOnExtractionFailure: false,
159
+ forceExtractionAttempt: false,
160
+ });
161
+
162
+ test("the model sees each turn once and every identity drains with its representative", async () => {
163
+ const first = makeTurn("repeat me");
164
+ const duplicate = makeTurn("repeat me", { timestamp: "2026-11-16T12:00:02.000Z" });
165
+ const last = makeTurn("final word", { timestamp: "2026-11-16T12:00:03.000Z" });
166
+ const { spy, buffer } = await withDrain(
167
+ { turns: [first, duplicate, last], results: [DONE] },
168
+ async (drain, _spy, window) => {
169
+ return await drain.run(window, SINGLE_RUN());
170
+ },
171
+ );
172
+ assert.equal(spy.calls.length, 1, "one chunk");
173
+ assert.equal(spy.modelDuplicates(), 0, "the model never receives a duplicate");
174
+ assert.deepEqual(spy.modelRoleContent(), ["user\u0000repeat me", "user\u0000final word"], "representatives only");
175
+ assert.equal(spy.uncoveredShadows(), 0, "each duplicate copy rides with its representative");
176
+ assert.deepEqual(
177
+ buffer.getTurns("s1").map((seen) => seen.content),
178
+ [],
179
+ "on success the duplicate drains together with its representative — nothing left behind",
180
+ );
181
+ });
182
+
183
+ test("the raw buffered turns are never altered by the marker", async () => {
184
+ const first = makeTurn("repeat me");
185
+ const duplicate = makeTurn("repeat me", { timestamp: "2026-11-16T12:00:02.000Z" });
186
+ await withDrain({ turns: [first, duplicate], results: [DONE] }, async (drain, _spy, window) => {
187
+ return await drain.run(window, SINGLE_RUN());
188
+ });
189
+ assert.equal(duplicate.extractionDuplicateOf, undefined, "the raw duplicate object carries no marker");
190
+ assert.equal(first.extractionDuplicateOf, undefined);
191
+ });
192
+
193
+ test("a failed chunk retains its duplicates together with its representative", async () => {
194
+ const first = makeTurn("repeat me");
195
+ const duplicate = makeTurn("repeat me", { timestamp: "2026-11-16T12:00:02.000Z" });
196
+ const { spy, buffer } = await withDrain(
197
+ { turns: [first, duplicate], results: [FAILED, DONE] },
198
+ async (drain, _spy, window, liveBuffer) => {
199
+ const failed = await drain.run(window, SINGLE_RUN());
200
+ assert.equal(failed.status, "skipped", "the first pass fails and retains");
201
+ assert.deepEqual(
202
+ liveBuffer.getTurns("s1").map((seen) => seen.timestamp),
203
+ [first.timestamp, duplicate.timestamp],
204
+ "after the failure both identities are still buffered",
205
+ );
206
+ return await drain.run(window, SINGLE_RUN());
207
+ },
208
+ );
209
+ assert.deepEqual(buffer.getTurns("s1"), [], "the retry drains both identities");
210
+ assert.equal(spy.modelDuplicates(), 0);
211
+ });
212
+
213
+ test("different write scopes are never collapsed, even with identical text", async () => {
214
+ const namespaceA = makeTurn("same text", { writeNamespaceOverride: "ns-a" });
215
+ const namespaceB = makeTurn("same text", { writeNamespaceOverride: "ns-b" });
216
+ const { spy } = await withDrain(
217
+ { turns: [namespaceA, namespaceB], results: [DONE] },
218
+ async (drain, _spy, window) => {
219
+ return await drain.run(window, SINGLE_RUN());
220
+ },
221
+ );
222
+ assert.equal(spy.modelTurnCount(), 2, "both scope copies reach the model");
223
+ assert.deepEqual(
224
+ spy.calls[0]?.turns.map((seen) => [seen.content, seen.extractionDuplicateOf]),
225
+ [
226
+ ["same text", undefined],
227
+ ["same text", undefined],
228
+ ],
229
+ "identical text under different scope pins is never collapsed or marked",
230
+ );
231
+ });
232
+
233
+ test("duplicate-heavy windows need fewer chunks", async () => {
234
+ // Six unique turns of 40 chars, every turn repeated twice, 120-char budget:
235
+ // raw packing needs six chunks; deduped packing needs two of three representatives.
236
+ const unique = Array.from({ length: 6 }, (_, index) => makeTurn(`u${index} `.padEnd(40, "x")));
237
+ const window = unique.flatMap((entry) => [
238
+ entry,
239
+ makeTurn(entry.content, { timestamp: "2026-11-16T12:00:01.000Z" }),
240
+ ]);
241
+ const { spy } = await withDrain(
242
+ { turns: window, results: [DONE, DONE, DONE], budgetChars: 120 },
243
+ async (drain, _spy, drainWindow) => {
244
+ return await drain.run(drainWindow, SINGLE_RUN());
245
+ },
246
+ );
247
+ assert.equal(spy.calls.length, 2, "chunks pack unique turns: two chunks, not four");
248
+ for (const call of spy.calls) {
249
+ assert.ok(modelTurnsOf(call).length <= 3, "each chunk holds at most its budget in representatives");
250
+ }
251
+ assert.equal(spy.modelDuplicates(), 0);
252
+ assert.equal(spy.uncoveredShadows(), 0);
253
+ });
254
+
255
+ test("a window that is 17.6% duplicates sends 17.6% fewer turns", async () => {
256
+ // 1000 turns, 176 of them exact duplicates of an earlier turn (the measured backlog rate).
257
+ const window: BufferTurn[] = [];
258
+ let stamp = 0;
259
+ const nextTimestamp = (): string => {
260
+ const current = `2026-11-16T12:${String(Math.floor(stamp / 60) % 60).padStart(2, "0")}:${String(stamp % 60).padStart(2, "0")}.${String(stamp % 1000).padStart(3, "0")}Z`;
261
+ stamp += 1;
262
+ return current;
263
+ };
264
+ for (let index = 0; index < 1000; index++) {
265
+ if (index % 100 < 18 && (index >= 100 || index >= 4)) {
266
+ window.push(
267
+ makeTurn(window[index >= 100 ? index - 100 : index - 4]!.content, { timestamp: nextTimestamp() }),
268
+ );
269
+ } else {
270
+ window.push(makeTurn(`unique content ${index}`, { timestamp: nextTimestamp() }));
271
+ }
272
+ }
273
+ const identity = (entry: BufferTurn): string => `${entry.role}\u0000${entry.content}`;
274
+ const duplicates = window.length - new Set(window.map(identity)).size;
275
+ assert.equal(duplicates, 176, "fixture sanity: 17.6% exact duplicates");
276
+ const { spy } = await withDrain({ turns: window, results: [DONE] }, async (drain, _spy, drainWindow) => {
277
+ return await drain.run(drainWindow, SINGLE_RUN());
278
+ });
279
+ assert.equal(spy.modelTurnCount(), 824, "exactly the unique turns reach the model: 17.6% fewer");
280
+ assert.equal(spy.modelDuplicates(), 0, "and no text repeats");
281
+ assert.equal(spy.uncoveredShadows(), 0);
282
+ });
283
+
284
+ test("a below-threshold window keeps today's raw skip path", async () => {
285
+ const first = makeTurn("short");
286
+ const duplicate = makeTurn("short", { timestamp: "2026-11-16T12:00:02.000Z" });
287
+ const { spy } = await withDrain(
288
+ { turns: [first, duplicate], results: [DONE], minChars: 10_000 },
289
+ async (drain, _spy, window) => {
290
+ return await drain.run(window, SINGLE_RUN());
291
+ },
292
+ );
293
+ assert.deepEqual(
294
+ spy.calls[0]?.turns.map((seen) => [seen.content, seen.extractionDuplicateOf]),
295
+ [
296
+ ["short", undefined],
297
+ ["short", undefined],
298
+ ],
299
+ "the raw window goes through unmarked — eligibility and skip/clear judge every identity as before",
300
+ );
301
+ });
302
+
303
+ test("a dropped chunk drops its duplicates too, and the recovery copy holds every identity", async () => {
304
+ const first = makeTurn("aaaa");
305
+ const duplicate = makeTurn("aaaa", { timestamp: "2026-11-16T12:00:02.000Z" });
306
+ const second = makeTurn("bbbb", { timestamp: "2026-11-16T12:00:03.000Z" });
307
+ const tail = makeTurn("cccc", { timestamp: "2026-11-16T12:00:04.000Z" });
308
+ let copied: readonly BufferTurn[] = [];
309
+ const { spy, buffer } = await withDrain(
310
+ {
311
+ turns: [first, duplicate, second, tail],
312
+ results: [FAILED, DONE],
313
+ budgetChars: 8,
314
+ dropAfter: 1,
315
+ saveCopy: async (_bufferKey, _reason, turns) => {
316
+ copied = turns;
317
+ return "/recovery/copy.json";
318
+ },
319
+ },
320
+ async (drain, _spy, window) => {
321
+ return await drain.run(window, SINGLE_RUN());
322
+ },
323
+ );
324
+ assert.equal(spy.calls.length, 2, "two chunks: the failing head, then the tail");
325
+ assert.deepEqual(
326
+ copied.map((seen) => seen.content),
327
+ ["aaaa", "aaaa", "bbbb"],
328
+ "the recovery copy holds the chunk's representative, its duplicate, and the next turn",
329
+ );
330
+ assert.deepEqual(
331
+ spy.calls[0]?.turns.map((seen) => [seen.content, seen.extractionDuplicateOf]),
332
+ [
333
+ ["aaaa", undefined],
334
+ ["aaaa", true],
335
+ ["bbbb", undefined],
336
+ ],
337
+ "the dropped chunk carries every identity; the duplicate is marked",
338
+ );
339
+ assert.deepEqual(
340
+ buffer.getTurns("s1").map((seen) => seen.content),
341
+ [],
342
+ "the drop removes every identity in the chunk and the tail drains: nothing left behind",
343
+ );
344
+ });
345
+
346
+ /** Ten-char contents so a 20-char budget packs exactly two representatives per chunk. */
347
+ const tenChars = (tag: string): string => tag.padEnd(10, "0");
348
+
349
+ test("a duplicate between two chunks is cleared with the chunk before it", async () => {
350
+ const a = makeTurn(tenChars("aaaa"));
351
+ const b = makeTurn(tenChars("bbbb"), { timestamp: "2026-11-16T12:00:01.000Z" });
352
+ const aAgain = makeTurn(tenChars("aaaa"), { timestamp: "2026-11-16T12:00:02.000Z" });
353
+ const c = makeTurn(tenChars("cccc"), { timestamp: "2026-11-16T12:00:03.000Z" });
354
+ const { spy, buffer } = await withDrain(
355
+ { turns: [a, b, aAgain, c], results: [DONE, DONE], budgetChars: 20 },
356
+ async (drain, _spy, window) => {
357
+ return await drain.run(window, SINGLE_RUN());
358
+ },
359
+ );
360
+ assert.equal(spy.calls.length, 2, "two chunks");
361
+ assert.deepEqual(
362
+ buffer.getTurns("s1"),
363
+ [],
364
+ "the gap duplicate rides with the preceding chunk: nothing left behind after success",
365
+ );
366
+ });
367
+
368
+ test("a duplicate after the last representative is cleared with the last chunk", async () => {
369
+ const a = makeTurn(tenChars("aaaa"));
370
+ const b = makeTurn(tenChars("bbbb"), { timestamp: "2026-11-16T12:00:01.000Z" });
371
+ const c = makeTurn(tenChars("cccc"), { timestamp: "2026-11-16T12:00:02.000Z" });
372
+ const aAgain = makeTurn(tenChars("aaaa"), { timestamp: "2026-11-16T12:00:03.000Z" });
373
+ const { spy, buffer } = await withDrain(
374
+ { turns: [a, b, c, aAgain], results: [DONE, DONE], budgetChars: 20 },
375
+ async (drain, _spy, window) => {
376
+ return await drain.run(window, SINGLE_RUN());
377
+ },
378
+ );
379
+ assert.equal(spy.calls.length, 2, "two chunks");
380
+ assert.deepEqual(
381
+ buffer.getTurns("s1"),
382
+ [],
383
+ "the trailing duplicate rides with the last chunk: nothing left behind after success",
384
+ );
385
+ });
386
+
387
+ /** Seeded PRNG so the property run is reproducible. */
388
+ function mulberry32(seed: number): () => number {
389
+ let state = seed;
390
+ return () => {
391
+ state |= 0;
392
+ state = (state + 0x6d2b79f5) | 0;
393
+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
394
+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
395
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
396
+ };
397
+ }
398
+
399
+ test("chunks partition every window: each turn cleared once, model never sees a duplicate", async () => {
400
+ // A window's first turn is always a representative by construction — there is no
401
+ // earlier occurrence to duplicate — so windows never start with a duplicate.
402
+ const random = mulberry32(3443);
403
+ for (let trial = 0; trial < 12; trial++) {
404
+ const size = 6 + Math.floor(random() * 10);
405
+ const window: BufferTurn[] = [];
406
+ let stamp = 0;
407
+ const nextTimestamp = (): string => {
408
+ const current = `2026-11-16T13:${String(Math.floor(stamp / 60) % 60).padStart(2, "0")}:${String(stamp % 60).padStart(2, "0")}.${String(stamp % 1000).padStart(3, "0")}Z`;
409
+ stamp += 1;
410
+ return current;
411
+ };
412
+ for (let index = 0; index < size; index++) {
413
+ if (index > 0 && random() < 0.3) {
414
+ const source = Math.floor(random() * index);
415
+ window.push(makeTurn(window[source]!.content, { timestamp: nextTimestamp() }));
416
+ } else {
417
+ window.push(makeTurn(`${trial}-${index}`.padEnd(10, "0"), { timestamp: nextTimestamp() }));
418
+ }
419
+ }
420
+ const identity = (entry: BufferTurn): string => `${entry.timestamp}|${entry.content}`;
421
+ const budget = 10 * (1 + Math.floor(random() * 3));
422
+ const { spy, buffer } = await withDrain(
423
+ { turns: window, results: Array.from({ length: window.length }, () => DONE), budgetChars: budget },
424
+ async (drain, _spy, drainWindow) => {
425
+ return await drain.run(drainWindow, SINGLE_RUN());
426
+ },
427
+ );
428
+ const chunked = spy.calls.flatMap((call) => call.turns);
429
+ assert.deepEqual(
430
+ chunked.map(identity),
431
+ window.map(identity),
432
+ `trial ${trial}: chunks partition the window — every turn exactly once, in order`,
433
+ );
434
+ const modelSeen = spy.calls.flatMap((call) => modelTurnsOf(call).map((seen) => `${seen.role}\u0000${seen.content}`));
435
+ assert.equal(modelSeen.length, new Set(modelSeen).size, `trial ${trial}: the model never sees a duplicate`);
436
+ assert.deepEqual(buffer.getTurns("s1"), [], `trial ${trial}: a fully successful drain clears the whole window`);
437
+ }
438
+ });
439
+
440
+ test("a failed chunk keeps its identities; its gap duplicate drains on the retry pass", async () => {
441
+ // Window [A, B | C, A-dup]: chunk 1 holds A and B; the gap duplicate sits before
442
+ // chunk 2's span, so it rides with chunk 2. Below the drop threshold a retained
443
+ // failure STOPS the drain, so on the failing pass chunk 2 (and the duplicate) are
444
+ // not attempted; on the retry pass both chunks succeed and the duplicate drains
445
+ // with chunk 2. If the failing chunk is eventually dropped instead, its recovery
446
+ // side-file copy holds its identities — the duplicate's text is identical to its
447
+ // representative's, so no content is lost either way (ACCEPTED TRADE-OFF, also
448
+ // documented in the PR).
449
+ const a = makeTurn(tenChars("aaaa"));
450
+ const b = makeTurn(tenChars("bbbb"), { timestamp: "2026-11-16T12:00:01.000Z" });
451
+ const c = makeTurn(tenChars("cccc"), { timestamp: "2026-11-16T12:00:02.000Z" });
452
+ const aAgain = makeTurn(tenChars("aaaa"), { timestamp: "2026-11-16T12:00:03.000Z" });
453
+ const { spy, buffer } = await withDrain(
454
+ { turns: [a, b, c, aAgain], results: [FAILED, DONE, DONE], budgetChars: 20 },
455
+ async (drain, runSpy, window, liveBuffer) => {
456
+ const failed = await drain.run(window, SINGLE_RUN());
457
+ assert.equal(failed.status, "skipped", "chunk 1 fails and retains");
458
+ assert.equal(runSpy.calls.length, 1, "a retained failure stops the drain before chunk 2");
459
+ assert.deepEqual(
460
+ liveBuffer.getTurns("s1").map((seen) => seen.timestamp),
461
+ [a.timestamp, b.timestamp, c.timestamp, aAgain.timestamp],
462
+ "nothing cleared: chunk 1's identities stay retained, the duplicate still rides with chunk 2",
463
+ );
464
+ return await drain.run(window, SINGLE_RUN());
465
+ },
466
+ );
467
+ assert.equal(spy.calls.length, 3, "retry: both chunks run and succeed");
468
+ assert.deepEqual(
469
+ spy.calls[2]?.turns.map((seen) => [seen.content, seen.extractionDuplicateOf]),
470
+ [
471
+ [tenChars("cccc"), undefined],
472
+ [tenChars("aaaa"), true],
473
+ ],
474
+ "on the retry the gap duplicate rides with chunk 2, marked — the model never re-reads A's text",
475
+ );
476
+ assert.deepEqual(buffer.getTurns("s1"), [], "the retry pass drains every identity, including the gap duplicate");
477
+ });
@@ -6,6 +6,7 @@ import { describeError } from "../buffer-turn-helpers.js";
6
6
  import { chunkExtractionWindow, classifyDrainResult, mergeDrainResults } from "../extraction-window-drain.js";
7
7
  import { log } from "../logger.js";
8
8
  import type { BufferTurn } from "../types.js";
9
+ import { type CollapsedDuplicates, collapseExactDuplicateTurns, markDuplicateTurns } from "./extraction-dedupe.js";
9
10
  import type { ExtractionPreemptHandle } from "./extraction-queue-coordinator.js";
10
11
  import type { ExtractionRunCoordinator, ExtractionRunResult } from "./extraction-run.js";
11
12
 
@@ -142,35 +143,94 @@ export class ExtractionDrain {
142
143
  preemptHandle?: ExtractionPreemptHandle
143
144
  ): Promise<ExtractionRunResult> {
144
145
  const budgetChars = this.deps.extractionWindowBudgetChars?.() ?? Number.POSITIVE_INFINITY;
145
- const plan = this.chunkPlan(turns, runOptions, budgetChars);
146
+ // Exact duplicates (same role AND content, one scope) collapse to their first
147
+ // occurrence before chunk planning (#3443): chunks pack unique turns and the model
148
+ // sees each text once. Every original stays a distinct identity the chunk must
149
+ // account for, so chunks carry the duplicates as marked copies — clearing and
150
+ // drops remove representative and duplicates together.
151
+ const collapsed = collapseExactDuplicateTurns(turns);
152
+ const window = collapsed.duplicateCount > 0 ? markDuplicateTurns(turns, collapsed) : turns;
153
+ const plan = this.chunkPlan(turns, runOptions, budgetChars, collapsed);
146
154
  // The tail of a window that already qualified goes through the chunk loop even when it now fits in one
147
155
  // chunk, so its failures still count toward the drop threshold.
148
- if (plan.singleRun) return await this.deps.runExtraction(turns, runOptions);
156
+ if (plan.singleRun) {
157
+ // Without duplicates this is today's single-run path: the run judges its own
158
+ // thresholds on the raw window.
159
+ if (collapsed.duplicateCount === 0) return await this.deps.runExtraction(turns, runOptions);
160
+ // With duplicates, eligibility belongs to the RAW window — duplicate inflation
161
+ // must not change whether a window qualifies (#3443). Below the threshold,
162
+ // today's skip path runs on the raw window (unmarked, so skip/capture/clear
163
+ // judge every identity exactly as before); above it, the representative subset
164
+ // is never re-judged — the same rule the chunk loop applies to chunks.
165
+ if (this.windowBelowThreshold(turns, runOptions)) return await this.deps.runExtraction(turns, runOptions);
166
+ return await this.deps.runExtraction(window, {
167
+ ...runOptions,
168
+ skipCharThreshold: true,
169
+ skipUserTurnThreshold: true,
170
+ });
171
+ }
149
172
  // Eligibility (minimum user turns and characters) belongs to the whole
150
173
  // window: a window that never qualified keeps the single-run path, which
151
174
  // judges it exactly as before.
152
175
  if (!plan.resumed && this.windowBelowThreshold(turns, runOptions)) {
153
176
  return await this.deps.runExtraction(turns, runOptions);
154
177
  }
155
- return await this.runChunked(plan.chunks, runOptions, preemptable, preemptHandle);
178
+ // A deduped window is never re-judged on its representative subset inside the
179
+ // run: eligibility above (or the caller's skip flags) already decided it.
180
+ const options =
181
+ collapsed.duplicateCount > 0
182
+ ? { ...runOptions, skipCharThreshold: true, skipUserTurnThreshold: true }
183
+ : runOptions;
184
+ return await this.runChunked(plan.chunks, options, preemptable, preemptHandle);
156
185
  }
157
186
 
158
- /** Chunking plan for one trigger-drain window. Accepted-capture groups */
187
+ /** Chunking plan for one trigger-drain window. Accepted-capture groups
188
+ * keep their pinned head; a window with duplicates is planned on its
189
+ * representatives and each chunk is then expanded back to its contiguous
190
+ * original span with the duplicates marked. */
159
191
  private chunkPlan(
160
192
  turns: readonly BufferTurn[],
161
193
  runOptions: DrainRunOptions,
162
- budgetChars: number
194
+ budgetChars: number,
195
+ collapsed?: CollapsedDuplicates
163
196
  ): ChunkPlan {
164
- const chunks = this.chunkable(runOptions, turns, budgetChars)
197
+ const deduped = collapsed !== undefined && collapsed.duplicateCount > 0;
198
+ const planning = deduped ? collapsed.representatives : turns;
199
+ const repChunks = this.chunkable(runOptions, turns, budgetChars)
165
200
  ? this.deps.measureRenderedTurns !== undefined
166
- ? this.chunkByRenderedSize(turns, budgetChars)
167
- : chunkExtractionWindow(turns, budgetChars)
201
+ ? this.chunkByRenderedSize(planning, budgetChars)
202
+ : chunkExtractionWindow(planning, budgetChars)
168
203
  : [];
169
204
  const resumed =
170
- chunks.length > 0 && this.qualified.get(runOptions.bufferKey) === chunkFingerprint(chunks[0].slice(0, 1));
205
+ repChunks.length > 0 && this.qualified.get(runOptions.bufferKey) === chunkFingerprint(repChunks[0].slice(0, 1));
206
+ const chunks = deduped ? this.expandedChunks(turns, collapsed, repChunks) : repChunks;
171
207
  return { singleRun: chunks.length <= 1 && !resumed, chunks, resumed };
172
208
  }
173
209
 
210
+ /** Each representative chunk expands to a PARTITION slice of the original window:
211
+ * chunk k spans [start_k, start_k+1) where start_0 = 0 and start_k+1 is chunk
212
+ * k+1's first representative's position; the last chunk runs to the window end.
213
+ * A gap or trailing duplicate therefore rides with the chunk BEFORE which it
214
+ * sits — whose representatives precede it (its own representative is in that
215
+ * chunk or an earlier one) — so every identity is cleared or dropped exactly
216
+ * once and nothing is left behind after a fully successful drain (#3443). */
217
+ private expandedChunks(
218
+ turns: readonly BufferTurn[],
219
+ collapsed: CollapsedDuplicates,
220
+ repChunks: readonly BufferTurn[][]
221
+ ): BufferTurn[][] {
222
+ const chunks: BufferTurn[][] = [];
223
+ let repIndex = 0;
224
+ for (let index = 0; index < repChunks.length; index += 1) {
225
+ const start = index === 0 ? 0 : collapsed.representativePositions[repIndex]!;
226
+ repIndex += repChunks[index]!.length;
227
+ const end =
228
+ index === repChunks.length - 1 ? turns.length : collapsed.representativePositions[repIndex]!;
229
+ chunks.push(markDuplicateTurns(turns, collapsed, start, end));
230
+ }
231
+ return chunks;
232
+ }
233
+
174
234
  /** Automatic chunking needs a clearable window, no fail-closed/forced
175
235
  * caller, and a real budget to chunk against. */
176
236
  private chunkable(runOptions: DrainRunOptions, turns: readonly BufferTurn[], budgetChars: number): boolean {
@@ -540,6 +540,8 @@ export class ExtractionRunCoordinator {
540
540
  }
541
541
 
542
542
  const normalizedTurns = turns
543
+ // #3443: marked duplicate copies ride along for clearing/drop identity only; the representative is already here.
544
+ .filter((t) => t.extractionDuplicateOf !== true)
543
545
  .filter((t) => (t.role === "user" || t.role === "assistant") && typeof t.content === "string")
544
546
  .map((t) => ({
545
547
  ...t,
@@ -1429,3 +1429,69 @@ for (const changed of ["inode", "size", "mtime"] as const) {
1429
1429
  assert.ok(contents.includes("b") && contents.includes("c"), `b is handed in again, not lost: ${contents.join(",")}`);
1430
1430
  });
1431
1431
  }
1432
+
1433
+ // ── #3442: sidecar oldest-turn timestamp + cheap TTL-cached totals ──────────
1434
+
1435
+ test("claim summaries record the oldest pending turn timestamp across active and retained turns", async () => {
1436
+ const s = setup();
1437
+ try {
1438
+ s.seedSession("sess-a", {
1439
+ turns: [turn("newer", "2026-11-10T00:00:00.000Z")],
1440
+ retainedTurns: [turn("older-retained", "2026-11-01T00:00:00.000Z")],
1441
+ lastExtractionAt: null,
1442
+ extractionCount: 0,
1443
+ });
1444
+ assert.equal(await s.claims.claimFromSessionFile("sess-a", makeLease()), "claimed");
1445
+ const countPath = path.join(s.stateDir, "buffer", "drain", `${bufferSessionFileName("sess-a")}.count`);
1446
+ const summary = JSON.parse(readFileSync(countPath, "utf8"));
1447
+ assert.equal(summary.oldestTurnAt, "2026-11-01T00:00:00.000Z");
1448
+ } finally {
1449
+ s.cleanup();
1450
+ }
1451
+ });
1452
+
1453
+ test("claimTotals reads sidecars only (never a claim body), TTL-cached, bounded", async () => {
1454
+ const stateDir = mkdtempSync(path.join(os.tmpdir(), "remnic-drain-totals-ttl-"));
1455
+ try {
1456
+ const dir = path.join(stateDir, "buffer", "drain");
1457
+ mkdirSync(dir, { recursive: true });
1458
+ // Throwing io: any claim-body/inbox read would fail the test loudly — the
1459
+ // health path must stay on the sidecars.
1460
+ const claims = new BufferDrainClaims(stateDir, {
1461
+ read: async () => {
1462
+ throw new Error("claimTotals must not read claim bodies");
1463
+ },
1464
+ write: async () => {
1465
+ throw new Error("claimTotals must not write");
1466
+ },
1467
+ append: async () => {
1468
+ throw new Error("claimTotals must not append");
1469
+ },
1470
+ });
1471
+ const writeClaimFiles = (key: string, pending: number, oldestTurnAt: string) => {
1472
+ const body = path.join(dir, bufferSessionFileName(key));
1473
+ writeFileSync(body, JSON.stringify({ key, entry: { turns: [], lastExtractionAt: null, extractionCount: 0 } }));
1474
+ const identity = statSync(body);
1475
+ writeFileSync(`${body}.count`, JSON.stringify({ key, size: identity.size, mtimeMs: identity.mtimeMs, pending, drained: 0, oldestTurnAt }));
1476
+ };
1477
+ writeClaimFiles("s1", 5, "2026-11-01T00:00:00.000Z");
1478
+
1479
+ const first = await claims.claimTotals({ ttlMs: 1_000, nowMs: 1_000 });
1480
+ assert.equal(first.claimedSessions, 1);
1481
+ assert.equal(first.claimedPendingTurns, 5);
1482
+
1483
+ writeClaimFiles("s2", 7, "2026-11-02T00:00:00.000Z");
1484
+ const cached = await claims.claimTotals({ ttlMs: 1_000, nowMs: 1_500 });
1485
+ assert.deepEqual(cached, first, "inside the TTL the cached snapshot is returned");
1486
+
1487
+ const refreshed = await claims.claimTotals({ ttlMs: 1_000, nowMs: 3_000 });
1488
+ assert.equal(refreshed.claimedSessions, 2);
1489
+ assert.equal(refreshed.claimedPendingTurns, 12);
1490
+
1491
+ const bounded = await claims.claimTotals({ ttlMs: 0, nowMs: 3_000, maxClaims: 1 });
1492
+ assert.equal(bounded.claimedSessions, 2);
1493
+ assert.equal(bounded.truncated, true);
1494
+ } finally {
1495
+ rmSync(stateDir, { recursive: true, force: true });
1496
+ }
1497
+ });