diff --git a/src/auto-reply/reply/memory-flush.ts b/src/auto-reply/reply/memory-flush.ts index 95f6dbaa053..967f1007a0a 100644 --- a/src/auto-reply/reply/memory-flush.ts +++ b/src/auto-reply/reply/memory-flush.ts @@ -197,9 +197,12 @@ export function shouldRunMemoryFlush(params: { return false; } const contextWindow = Math.max(1, Math.floor(params.contextWindowTokens)); - const reserveTokens = Math.max(0, Math.floor(params.reserveTokensFloor)); const softThreshold = Math.max(0, Math.floor(params.softThresholdTokens)); - const threshold = Math.max(0, contextWindow - reserveTokens - softThreshold); + const reserveTokens = Math.min( + Math.max(0, Math.floor(params.reserveTokensFloor)), + Math.max(0, contextWindow - softThreshold - 1), + ); + const threshold = contextWindow - reserveTokens - softThreshold; if (threshold <= 0) { return false; } diff --git a/src/auto-reply/reply/reply-state.test.ts b/src/auto-reply/reply/reply-state.test.ts index f83d313e2d3..4db8c4c39d3 100644 --- a/src/auto-reply/reply/reply-state.test.ts +++ b/src/auto-reply/reply/reply-state.test.ts @@ -357,6 +357,17 @@ describe("shouldRunMemoryFlush", () => { }), ).toBe(false); }); + + it("triggers when reserveTokensFloor equals contextWindowTokens", () => { + expect( + shouldRunMemoryFlush({ + entry: { totalTokens: 199_000, compactionCount: 0 }, + contextWindowTokens: 200_000, + reserveTokensFloor: 200_000, + softThresholdTokens: 4_000, + }), + ).toBe(true); + }); }); describe("hasAlreadyFlushedForCurrentCompaction", () => { @@ -483,4 +494,4 @@ describe("incrementCompactionCount", () => { // totalTokens unchanged expect(stored[sessionKey].totalTokens).toBe(180_000); }); -}); +}); \ No newline at end of file