Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(cost): tool results age out of the prompt, and the window stops sliding

Davidead3be36c377
diff --git a/src/api/agents/__tests__/in-turn-cache-after-edit.test.ts b/src/api/agents/__tests__/in-turn-cache-after-edit.test.ts
new file mode 100644
index 00000000..5373d15f
--- /dev/null
+++ b/src/api/agents/__tests__/in-turn-cache-after-edit.test.ts
@@ -0,0 +1,95 @@
+/**
+ * A1 ZUSATZTEST: after the decay caps a result, the way back to the full
+ * bytes is a fresh read. That way back only works if the in-turn cache
+ * does NOT answer it from the copy it made before the edit.
+ *
+ * The existing suite covers file_write and shell_execute. file_edit is the one
+ * the coding loop actually uses (the prompt tells the model to prefer it over
+ * file_write), so it gets its own witness: an edit followed by a re-read has to
+ * miss the cache, or the model reads back the version it just replaced and then
+ * edits against content that no longer exists on disk.
+ */
+
+import { describe, it, expect, beforeEach } from 'vitest'
+import { makeInTurnCacheLookup } from '../in-turn-cache'
+import { useToolAuditStore } from '../../../stores/toolAuditStore'
+import { stableArgsHash } from '../block-helpers'
+import type { ExecutionRequest } from '../tool-executor'
+
+const req = (id: string, toolName: string, args: Record<string, any>): ExecutionRequest => ({
+ id, toolName, args,
+})
+
+describe('A1: a re-read after file_edit never comes from the cache', () => {
+ beforeEach(() => useToolAuditStore.getState().clearAll())
+
+ it('misses the cache for the file that was edited', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/a.ts' }
+ const rid = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(rid, { status: 'completed', completedAt: 1050, resultPreview: 'const a = 1' })
+
+ const eid = s.record({
+ convId: 'c1',
+ toolCallId: 'e1',
+ toolName: 'file_edit',
+ args: { path: '/proj/a.ts', old_string: 'const a = 1', new_string: 'const a = 2' },
+ startedAt: 1100,
+ })
+ s.complete(eid, { status: 'completed', completedAt: 1150, resultPreview: 'edited' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBeUndefined()
+ })
+
+ it('misses for OTHER files too, because an edit can move more than one', () => {
+ // Conservative on purpose: re-reading is cheap and always correct, while a
+ // stale hit is silent and wrong.
+ const s = useToolAuditStore.getState()
+ const other = { path: '/proj/b.ts' }
+ const rid = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args: other, startedAt: 1000 })
+ s.complete(rid, { status: 'completed', completedAt: 1050, resultPreview: 'import a' })
+ const eid = s.record({
+ convId: 'c1',
+ toolCallId: 'e1',
+ toolName: 'file_edit',
+ args: { path: '/proj/a.ts', old_string: 'x', new_string: 'y' },
+ startedAt: 1100,
+ })
+ s.complete(eid, { status: 'completed', completedAt: 1150, resultPreview: 'edited' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', other), stableArgsHash(other))).toBeUndefined()
+ })
+
+ it('a file_list of the edited folder is invalidated as well', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj' }
+ const lid = s.record({ convId: 'c1', toolCallId: 'l1', toolName: 'file_list', args, startedAt: 1000 })
+ s.complete(lid, { status: 'completed', completedAt: 1050, resultPreview: 'a.ts' })
+ const eid = s.record({
+ convId: 'c1',
+ toolCallId: 'e1',
+ toolName: 'file_edit',
+ args: { path: '/proj/a.ts', old_string: 'x', new_string: 'y' },
+ startedAt: 1100,
+ })
+ s.complete(eid, { status: 'completed', completedAt: 1150, resultPreview: 'edited' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('l2', 'file_list', args), stableArgsHash(args))).toBeUndefined()
+ })
+
+ it('control: with no edit in between the same read is still served', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/a.ts' }
+ const rid = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(rid, { status: 'completed', completedAt: 1050, resultPreview: 'const a = 1' })
+ // A plan update touches no file and must not throw the cache away.
+ const tid = s.record({ convId: 'c1', toolCallId: 't1', toolName: 'todo_write', args: { todos: [] }, startedAt: 1100 })
+ s.complete(tid, { status: 'completed', completedAt: 1110, resultPreview: 'ok' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBe('const a = 1')
+ })
+})
diff --git a/src/lib/__tests__/compaction-hysteresis.test.ts b/src/lib/__tests__/compaction-hysteresis.test.ts
new file mode 100644
index 00000000..dfc07396
--- /dev/null
+++ b/src/lib/__tests__/compaction-hysteresis.test.ts
@@ -0,0 +1,220 @@
+/**
+ * A3: cache-friendly compaction (2.6.6 plan).
+ *
+ * Trimming to exactly the budget on every step moves the prompt prefix on every
+ * step, and an upstream prefix cache matches from byte 0 and stops at the first
+ * difference. So the plateau of a long run was billed at full price every time
+ * even though 95 percent of the prompt was the same bytes as a second earlier.
+ *
+ * Hysteresis: wait until 15 percent over budget, then drop in one block to 70
+ * percent of it. In between, the array passes through untouched.
+ *
+ * The prefix test deliberately runs WITH the A1 decay active. Testing it with
+ * decay off would prove the wrong thing: the two features have to be stable
+ * TOGETHER, and decay is the one that moves bytes on purpose.
+ */
+
+import { describe, it, expect } from 'vitest'
+import {
+ compactMessages,
+ estimateMessageTokens,
+ COMPACT_TRIGGER_RATIO,
+ COMPACT_TARGET_RATIO,
+} from '../context-compaction'
+import { buildRequestMessages, trimWorkingHistory, type DecayMessage } from '../context-decay'
+import type { OllamaChatMessage } from '../../types/agent-mode'
+
+/** Text of a given token size, roughly (the estimator is chars/4). */
+const sized = (label: string, tokens: number) =>
+ `${label}:` + 'x'.repeat(Math.max(0, tokens * 4 - label.length - 1))
+
+function historyOfTokens(sizes: number[]): OllamaChatMessage[] {
+ const out: OllamaChatMessage[] = [
+ { role: 'system', content: sized('SYS', 100) } as OllamaChatMessage,
+ { role: 'user', content: sized('TASK', 50) } as OllamaChatMessage,
+ ]
+ sizes.forEach((t, i) => {
+ out.push({ role: 'assistant', content: sized(`A${i}`, 20) } as OllamaChatMessage)
+ out.push({ role: 'tool', content: sized(`R${i}`, t) } as OllamaChatMessage)
+ })
+ return out
+}
+
+describe('A3: the hysteresis band', () => {
+ it('leaves a history that is over budget but under the trigger untouched', () => {
+ // ~1050 tokens against a 1000 budget: over, but inside the 15 percent band.
+ const history = historyOfTokens([200, 200, 200, 200])
+ const total = estimateMessageTokens(history)
+ const budget = Math.floor(total / COMPACT_TRIGGER_RATIO) + 20
+ expect(total).toBeGreaterThan(budget)
+ expect(total).toBeLessThan(budget * COMPACT_TRIGGER_RATIO)
+
+ const out = compactMessages(history, budget, { hysteresis: true })
+ expect(out).toBe(history)
+ })
+
+ it('negative control: without hysteresis the same history is compacted', () => {
+ const history = historyOfTokens([200, 200, 200, 200])
+ const total = estimateMessageTokens(history)
+ const budget = Math.floor(total / COMPACT_TRIGGER_RATIO) + 20
+ const out = compactMessages(history, budget)
+ expect(estimateMessageTokens(out)).toBeLessThan(total)
+ })
+
+ it('drops well below the budget once the trigger is crossed', () => {
+ const history = historyOfTokens([150, 150, 150, 150, 150, 150, 150, 150])
+ const budget = 1000
+ expect(estimateMessageTokens(history)).toBeGreaterThan(budget * COMPACT_TRIGGER_RATIO)
+
+ const out = compactMessages(history, budget, { hysteresis: true })
+ const after = estimateMessageTokens(out)
+ expect(after).toBeLessThan(budget)
+ // The block drop targets 0.7 of the budget, so there is real headroom for
+ // the next steps rather than an immediate re-trim.
+ expect(after).toBeLessThan(budget * COMPACT_TARGET_RATIO * 1.6)
+ })
+
+ it('is stateless: the same input always decides the same way', () => {
+ const history = historyOfTokens([150, 150, 150, 150, 150, 150, 150, 150])
+ const a = compactMessages(history, 1000, { hysteresis: true })
+ const b = compactMessages(history, 1000, { hysteresis: true })
+ expect(a.map((m) => m.content)).toEqual(b.map((m) => m.content))
+ })
+})
+
+/** One more read step, appended the way the loops append them. */
+function appendStep(history: DecayMessage[], n: number, resultChars: number): DecayMessage[] {
+ return [
+ ...history,
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: `c${n}`, function: { name: 'file_read', arguments: { path: `f${n}.ts` } } }],
+ },
+ { role: 'tool', content: `RESULT${n} ` + 'y'.repeat(resultChars), tool_call_id: `c${n}` },
+ ]
+}
+
+/**
+ * Walk a plateau the way the loops really do: the trimmed history is what gets
+ * carried into the next step. Returns how many steps moved the prompt PREFIX,
+ * i.e. changed more than the single message the age decay is allowed to flip.
+ * Zero would mean the whole plateau is one long cache hit; one per step is what
+ * the old trim-to-the-budget did.
+ */
+function prefixMovesOverPlateau(steps: number, budget: number, on: boolean): number {
+ let history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM PROMPT, stable across the whole run.' },
+ { role: 'user', content: 'refactor the parser' },
+ ]
+ let previous: ReturnType<typeof buildRequestMessages<DecayMessage>> | null = null
+ let moves = 0
+ for (let step = 1; step <= steps; step++) {
+ history = appendStep(history, step, 12000)
+ history = trimWorkingHistory(history, budget, { enabled: on }).messages
+ const next = buildRequestMessages(history, { budgetTokens: budget, hysteresis: on, enabled: on })
+ if (previous) {
+ const shared = Math.min(previous.messages.length, next.messages.length)
+ let differing = 0
+ for (let i = 0; i < shared; i++) {
+ if (previous.messages[i].content !== next.messages[i].content) differing++
+ }
+ if (differing > 1) moves++
+ }
+ previous = next
+ }
+ return moves
+}
+
+describe('A3: the prefix holds still at the plateau, with decay running', () => {
+ // 12000 tokens is well below what thirty 12k-character results cost, so
+ // compaction genuinely has to fire; it is also comfortably above one newest
+ // result plus the four messages compaction always keeps, so the block drop
+ // can reach its target instead of clamping.
+ const BUDGET = 12000
+ const STEPS = 30
+
+ it('moves the prefix a handful of times over thirty steps', () => {
+ expect(prefixMovesOverPlateau(STEPS, BUDGET, true)).toBeLessThanOrEqual(5)
+ })
+
+ it('negative control: with the 2.6.5 behaviour it moves on most steps', () => {
+ expect(prefixMovesOverPlateau(STEPS, BUDGET, false)).toBeGreaterThanOrEqual(12)
+ })
+
+ it('holds a long stretch of steps byte-identical, not just alternating ones', () => {
+ let history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM PROMPT, stable across the whole run.' },
+ { role: 'user', content: 'refactor the parser' },
+ ]
+ let previous: ReturnType<typeof buildRequestMessages<DecayMessage>> | null = null
+ let streak = 0
+ let longest = 0
+ for (let step = 1; step <= 30; step++) {
+ history = appendStep(history, step, 12000)
+ history = trimWorkingHistory(history, BUDGET, { enabled: true }).messages
+ const next = buildRequestMessages(history, { budgetTokens: BUDGET, hysteresis: true })
+ if (previous) {
+ const shared = Math.min(previous.messages.length, next.messages.length)
+ let differing = 0
+ for (let i = 0; i < shared; i++) {
+ if (previous.messages[i].content !== next.messages[i].content) differing++
+ }
+ if (differing <= 1) {
+ streak++
+ longest = Math.max(longest, streak)
+ } else {
+ streak = 0
+ }
+ }
+ previous = next
+ }
+ expect(longest).toBeGreaterThanOrEqual(5)
+ })
+
+ it('never sends more than the hysteresis ceiling of budget times 1.15', () => {
+ let history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM PROMPT, stable across the whole run.' },
+ { role: 'user', content: 'refactor the parser' },
+ ]
+ for (let step = 1; step <= 30; step++) {
+ history = appendStep(history, step, 12000)
+ history = trimWorkingHistory(history, BUDGET, { enabled: true }).messages
+ const built = buildRequestMessages(history, { budgetTokens: BUDGET, hysteresis: true })
+ expect(built.promptTokens).toBeLessThanOrEqual(BUDGET * COMPACT_TRIGGER_RATIO)
+ }
+ })
+
+ it('the carried history keeps every result whole, however often it is trimmed', () => {
+ // The store and the next session read this array. Nothing in it may ever
+ // be shortened; only whole messages leave.
+ let history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM' },
+ { role: 'user', content: 'go' },
+ ]
+ for (let step = 1; step <= 20; step++) {
+ history = appendStep(history, step, 12000)
+ history = trimWorkingHistory(history, BUDGET, { enabled: true }).messages
+ }
+ const results = history.filter((m) => m.role === 'tool')
+ expect(results.length).toBeGreaterThan(0)
+ for (const r of results) {
+ // Full length, not the 4k the request went out with.
+ expect(String(r.content).length).toBeGreaterThan(12000)
+ expect(String(r.content)).not.toContain('truncated')
+ }
+ })
+
+ it('trimming never opens the window on an orphan tool result', () => {
+ let history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM' },
+ { role: 'user', content: 'go' },
+ ]
+ for (let step = 1; step <= 25; step++) {
+ history = appendStep(history, step, 12000)
+ history = trimWorkingHistory(history, BUDGET, { enabled: true }).messages
+ const firstNonSystem = history.find((m) => m.role !== 'system')
+ expect(firstNonSystem?.role).not.toBe('tool')
+ }
+ })
+})
diff --git a/src/lib/__tests__/context-decay.test.ts b/src/lib/__tests__/context-decay.test.ts
new file mode 100644
index 00000000..ada3d462
--- /dev/null
+++ b/src/lib/__tests__/context-decay.test.ts
@@ -0,0 +1,274 @@
+/**
+ * A1: age decay for tool results (2.6.6 plan).
+ *
+ * The claim under test: a long run stops paying for every file it ever read,
+ * WITHOUT the model ever editing against content it can no longer see. That
+ * second half is the part the Morgan incident and the 80-character-stub loop
+ * were made of, so the newest iteration staying byte-for-byte intact gets as
+ * many assertions as the saving does.
+ */
+
+import { describe, it, expect } from 'vitest'
+import {
+ applyToolResultDecay,
+ buildRequestMessages,
+ decayRestoredToolResult,
+ pairToolCalls,
+ restoreBudgetFor,
+ DECAY_RESULT_CHARS,
+ RESTORE_RESULT_CHARS,
+ type DecayMessage,
+} from '../context-decay'
+
+/** A result big enough to matter, unique per label so bytes are comparable. */
+function bigResult(label: string, chars = 50000): string {
+ const body = `${label} `.repeat(Math.ceil(chars / (label.length + 1)))
+ return body.slice(0, chars)
+}
+
+/**
+ * An OpenAI-shaped coding history: one user instruction, then `steps` rounds of
+ * "assistant asks for one tool, tool answers".
+ */
+function historyOf(steps: Array<{ name: string; args: Record<string, unknown>; result: string }>): DecayMessage[] {
+ const out: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM' },
+ { role: 'user', content: 'do the thing' },
+ ]
+ steps.forEach((s, i) => {
+ out.push({
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: `call-${i}`, function: { name: s.name, arguments: s.args } }],
+ })
+ out.push({ role: 'tool', content: s.result, tool_call_id: `call-${i}` })
+ })
+ return out
+}
+
+function readStep(n: number, chars = 50000) {
+ return {
+ name: 'file_read',
+ args: { path: `src/file${n}.ts` },
+ result: bigResult(`FILE${n}`, chars),
+ }
+}
+
+describe('A1: the newest iteration is never touched', () => {
+ it('keeps the result of the iteration that just ran byte-for-byte', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const out = applyToolResultDecay(history)
+ // Newest result is the last message.
+ expect(out.messages[out.messages.length - 1].content).toBe(history[history.length - 1].content)
+ expect(String(out.messages[out.messages.length - 1].content)).toHaveLength(50000)
+ })
+
+ it('caps the result from step n-3 when step n is built', () => {
+ // Four rounds done, so the request under construction is step 5 and the
+ // result of step 2 is exactly n-3.
+ const history = historyOf([readStep(1), readStep(2), readStep(3), readStep(4)])
+ const out = applyToolResultDecay(history)
+ const stepTwoResult = String(out.messages[5].content)
+ expect(stepTwoResult.length).toBeLessThanOrEqual(DECAY_RESULT_CHARS + 80)
+ expect(stepTwoResult).toContain('truncated')
+ // And it is still the RIGHT file, head and tail preserved.
+ expect(stepTwoResult.startsWith('FILE2')).toBe(true)
+ })
+
+ it('reports what it saved so the audit trail can show it', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const out = applyToolResultDecay(history)
+ expect(out.trimmedCount).toBe(2)
+ expect(out.savedChars).toBeGreaterThan(80000)
+ })
+
+ it('leaves a short result alone even when it is old', () => {
+ const history = historyOf([
+ { name: 'file_read', args: { path: 'a' }, result: 'tiny' },
+ readStep(2),
+ readStep(3),
+ ])
+ const out = applyToolResultDecay(history)
+ expect(out.messages[3].content).toBe('tiny')
+ })
+})
+
+describe('A1: decay happens in the builder, never in the store', () => {
+ it('does not mutate the array it was given', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const before = history.map((m) => m.content)
+ applyToolResultDecay(history)
+ expect(history.map((m) => m.content)).toEqual(before)
+ expect(String(history[3].content)).toHaveLength(50000)
+ })
+
+ it('does not mutate the message objects either', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const original = history[3]
+ const out = applyToolResultDecay(history)
+ expect(out.messages[3]).not.toBe(original)
+ expect(String(original.content)).toHaveLength(50000)
+ })
+})
+
+describe('A1: the contextDecay notaus', () => {
+ it('sends the history unchanged when decay is off (negative control)', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const out = applyToolResultDecay(history, { enabled: false })
+ expect(out.trimmedCount).toBe(0)
+ expect(out.savedChars).toBe(0)
+ expect(out.messages.map((m) => m.content)).toEqual(history.map((m) => m.content))
+ })
+})
+
+describe('A1: determinism and prefix stability', () => {
+ it('produces identical bytes for identical input', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const a = applyToolResultDecay(history)
+ const b = applyToolResultDecay(history)
+ expect(a.messages.map((m) => m.content)).toEqual(b.messages.map((m) => m.content))
+ })
+
+ it('changes exactly ONE place per step: the result that just aged out', () => {
+ const four = historyOf([readStep(1), readStep(2), readStep(3), readStep(4)])
+ const five = [...four, ...historyOf([readStep(5)]).slice(2)]
+
+ const atFour = applyToolResultDecay(four).messages
+ const atFive = applyToolResultDecay(five).messages
+
+ // Everything the earlier step already sent is byte-identical.
+ const differing: number[] = []
+ for (let i = 0; i < atFour.length; i++) {
+ if (atFour[i].content !== atFive[i].content) differing.push(i)
+ }
+ // Index 9 is step 4's result, the one that just crossed the age line.
+ expect(differing).toEqual([9])
+ })
+
+ it('never re-cuts a result that was already capped', () => {
+ const four = historyOf([readStep(1), readStep(2), readStep(3), readStep(4)])
+ const five = [...four, ...historyOf([readStep(5)]).slice(2)]
+ const atFour = applyToolResultDecay(four).messages
+ const atFive = applyToolResultDecay(five).messages
+ // Step 2's result was capped at step 5 already and is untouched at step 6.
+ expect(atFive[5].content).toBe(atFour[5].content)
+ })
+})
+
+describe('A1: session restore keeps the bytes the run already sent', () => {
+ it('hands a result the run capped exactly the same 4k bytes', () => {
+ const full = bigResult('OLD', 50000)
+ const inRun = applyToolResultDecay(
+ historyOf([
+ { name: 'file_read', args: { path: 'x' }, result: full },
+ readStep(2),
+ readStep(3),
+ ]),
+ ).messages[3].content
+ expect(decayRestoredToolResult(full)).toBe(inRun)
+ })
+
+ it('uses the tight restore budget only for results the run never capped', () => {
+ const short = bigResult('SHORT', 3000)
+ expect(restoreBudgetFor(short.length)).toBe(RESTORE_RESULT_CHARS)
+ const restored = decayRestoredToolResult(short)
+ expect(restored.length).toBeLessThanOrEqual(RESTORE_RESULT_CHARS + 80)
+ expect(restored).toContain('truncated')
+ })
+
+ it('leaves a genuinely small result whole', () => {
+ expect(decayRestoredToolResult('three lines of output')).toBe('three lines of output')
+ })
+
+ it('is idempotent, so a second restore cannot shrink it again', () => {
+ const once = decayRestoredToolResult(bigResult('OLD', 50000))
+ expect(decayRestoredToolResult(once)).toBe(once)
+ })
+})
+
+describe('A1: the trimmed reads are reported back for the loop guard', () => {
+ it('names the key of every read it sent capped, and no others', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ // Only the results carry a key, exactly as the loops register them.
+ const keys = new Map<unknown, string>()
+ keys.set(history[3], 'file_read|{"path":"src/file1.ts"}')
+ keys.set(history[5], 'file_read|{"path":"src/file2.ts"}')
+ keys.set(history[7], 'file_read|{"path":"src/file3.ts"}')
+ const out = applyToolResultDecay(history, { keyOf: (m) => keys.get(m) })
+ expect(out.trimmedKeys).toEqual([
+ 'file_read|{"path":"src/file1.ts"}',
+ 'file_read|{"path":"src/file2.ts"}',
+ ])
+ })
+
+ it('reports nothing when the result was short enough to survive whole', () => {
+ const history = historyOf([
+ { name: 'file_read', args: { path: 'a' }, result: 'tiny' },
+ readStep(2),
+ readStep(3),
+ ])
+ const keys = new Map<unknown, string>([[history[3], 'file_read|{"path":"a"}']])
+ const out = applyToolResultDecay(history, { keyOf: (m) => keys.get(m) })
+ expect(out.trimmedKeys).not.toContain('file_read|{"path":"a"}')
+ })
+})
+
+describe('A1: both transports, not just the OpenAI one', () => {
+ it('caps a Hermes tool_response carried on a user message', () => {
+ const history: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM' },
+ { role: 'user', content: 'go' },
+ { role: 'assistant', content: '<tool_call>\n{"name": "file_read", "arguments": {"path":"a"}}\n</tool_call>' },
+ { role: 'user', content: `<tool_response>\n${bigResult('HERMES', 40000)}\n</tool_response>` },
+ { role: 'assistant', content: '<tool_call>\n{"name": "file_list", "arguments": {"path":"."}}\n</tool_call>' },
+ { role: 'user', content: '<tool_response>\nlisting\n</tool_response>' },
+ ]
+ const out = applyToolResultDecay(history)
+ expect(out.trimmedCount).toBe(1)
+ expect(String(out.messages[3].content).length).toBeLessThanOrEqual(DECAY_RESULT_CHARS + 80)
+ expect(out.messages[5].content).toBe(history[5].content)
+ })
+
+ it('pairs id-less native results by order', () => {
+ const history: DecayMessage[] = [
+ { role: 'assistant', content: '', tool_calls: [
+ { function: { name: 'file_read', arguments: { path: 'a' } } },
+ { function: { name: 'file_list', arguments: { path: '.' } } },
+ ] },
+ { role: 'tool', content: 'A' },
+ { role: 'tool', content: 'B' },
+ ]
+ const pairs = pairToolCalls(history)
+ expect(pairs.map((p) => [p.name, p.resultIndex])).toEqual([
+ ['file_read', 1],
+ ['file_list', 2],
+ ])
+ })
+})
+
+describe('A1: the whole builder, in the binding order', () => {
+ it('decays first, so the budget counts the SHORT results', () => {
+ // Three 50k results are ~37k tokens raw. A 20k budget would drop messages
+ // outright if the budget ran first; with decay first everything fits.
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const built = buildRequestMessages(history, { budgetTokens: 20000 })
+ expect(built.messages).toHaveLength(history.length)
+ expect(built.trimmedCount).toBe(2)
+ expect(built.promptTokens).toBeLessThan(20000)
+ })
+
+ it('reports the size of the request it actually built', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const built = buildRequestMessages(history, { budgetTokens: 64000 })
+ const chars = built.messages.reduce((n, m) => n + String(m.content ?? '').length, 0)
+ expect(built.promptTokens).toBeGreaterThan(chars / 5)
+ expect(built.promptTokens).toBeLessThan(chars)
+ })
+
+ it('with decay off the same history is far more expensive (negative control)', () => {
+ const history = historyOf([readStep(1), readStep(2), readStep(3)])
+ const on = buildRequestMessages(history, { budgetTokens: 64000 })
+ const off = buildRequestMessages(history, { budgetTokens: 64000, enabled: false })
+ expect(off.promptTokens).toBeGreaterThan(on.promptTokens * 2)
+ })
+})
diff --git a/src/lib/__tests__/loop-guard-decay.test.ts b/src/lib/__tests__/loop-guard-decay.test.ts
new file mode 100644
index 00000000..aa33107b
--- /dev/null
+++ b/src/lib/__tests__/loop-guard-decay.test.ts
@@ -0,0 +1,155 @@
+/**
+ * A1 LOOP-GUARD: the sanctioned re-read must not read as a loop.
+ *
+ * Two independent review lenses found the same trap: age decay makes re-reading
+ * a file the CORRECT move, and re-reading a file is exactly what the loop guard
+ * was built to stop. Left alone, the guard would steer at the third re-read and
+ * halt at the fifth, and its steer text would tell the model to "use the result
+ * from before", which after a cap is the 4k stub. That sentence is an order to
+ * work against content the model cannot see, i.e. the Morgan failure, issued by
+ * our own harness.
+ */
+
+import { describe, it, expect } from 'vitest'
+import { AgentLoopGuard } from '../agent-loop-guard'
+
+const READ = (path: string) => ({ name: 'file_read', args: JSON.stringify({ path }) })
+const keyOf = (path: string) => `file_read|${JSON.stringify({ path })}`
+
+/**
+ * A batch that carries the same read next to a call that differs every time.
+ * Detector 2 keys on the whole batch signature, so a varying companion keeps
+ * it out of the picture and leaves detector 3 (the per-key read counter) as
+ * the one under test.
+ */
+const readPlusNoise = (path: string, n: number) => [
+ READ(path),
+ { name: 'file_search', args: `{"q":"noise-${n}"}` },
+]
+
+describe('A1 loop guard: a read whose result was capped never counts', () => {
+ it('read in step 1, capped from step 3, re-reads in steps 4, 7 and 10 all pass', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('src/big.ts')])
+
+ // Step 1: the first read, nothing capped yet.
+ expect(guard.recordBatch([READ('src/big.ts')]).action).toBe('ok')
+ // Steps 2 and 3: other work, so no two identical batches sit back to back.
+ expect(guard.recordBatch([{ name: 'file_list', args: '{"path":"."}' }]).action).toBe('ok')
+ expect(guard.recordBatch([{ name: 'file_search', args: '{"q":"x"}' }]).action).toBe('ok')
+
+ // From here the builder reports the read as capped.
+ for (const step of [4, 7, 10]) {
+ expect(
+ guard.recordBatch([READ('src/big.ts')], { trimmedReadKeys: trimmed }).action,
+ `step ${step}`,
+ ).toBe('ok')
+ guard.recordBatch([{ name: 'file_list', args: `{"path":"${step}"}` }])
+ guard.recordBatch([{ name: 'file_search', args: `{"q":"${step}"}` }])
+ }
+ })
+
+ it('negative control: without the capped marker the third read steers', () => {
+ const guard = new AgentLoopGuard()
+ expect(guard.recordBatch(readPlusNoise('src/big.ts', 1)).action).toBe('ok')
+ expect(guard.recordBatch(readPlusNoise('src/big.ts', 2)).action).toBe('ok')
+ const third = guard.recordBatch(readPlusNoise('src/big.ts', 3))
+ expect(third.action).toBe('steer')
+ })
+
+ it('negative control: without the capped marker the fifth read halts', () => {
+ const guard = new AgentLoopGuard()
+ let last = guard.recordBatch(readPlusNoise('src/big.ts', 0))
+ for (let i = 1; i < 8 && last.action !== 'halt'; i++) {
+ last = guard.recordBatch(readPlusNoise('src/big.ts', i))
+ }
+ expect(last.action).toBe('halt')
+ expect(last.action === 'halt' && last.reason).toMatch(/identical arguments/)
+ })
+
+ it('with the capped marker the same eight rounds never halt', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('src/big.ts')])
+ const verdicts: string[] = []
+ for (let i = 0; i < 8; i++) {
+ verdicts.push(guard.recordBatch(readPlusNoise('src/big.ts', i), { trimmedReadKeys: trimmed }).action)
+ }
+ expect(verdicts).toEqual(new Array(8).fill('ok'))
+ })
+})
+
+describe('A1 loop guard: the steer text never orders work against a stub', () => {
+ it('says "use the result from before" only when the result is still there', () => {
+ const guard = new AgentLoopGuard()
+ guard.recordBatch(readPlusNoise('a.ts', 1))
+ guard.recordBatch(readPlusNoise('a.ts', 2))
+ const steer = guard.recordBatch(readPlusNoise('a.ts', 3))
+ expect(steer.action).toBe('steer')
+ expect(steer.action === 'steer' && steer.message).toContain('Use the result from before')
+ })
+
+ it('never emits that sentence for a read the builder capped', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('a.ts')])
+ const seen: string[] = []
+ for (let i = 0; i < 12; i++) {
+ // Varying companion so detector 1 (three identical batches in a row)
+ // stays out of it; that one is the deliberate backstop, tested below.
+ const v = guard.recordBatch(readPlusNoise('a.ts', i), { trimmedReadKeys: trimmed })
+ if (v.action === 'steer') seen.push(v.message)
+ }
+ expect(seen).toEqual([])
+ })
+})
+
+describe('A1 loop guard: detector 2 skips capped re-reads', () => {
+ it('three identical read batches within six steps halt normally', () => {
+ const guard = new AgentLoopGuard()
+ const other = (n: number) => [{ name: 'file_list', args: `{"path":"${n}"}` }]
+ guard.recordBatch([READ('x.ts')])
+ guard.recordBatch(other(1))
+ guard.recordBatch([READ('x.ts')])
+ guard.recordBatch(other(2))
+ const third = guard.recordBatch([READ('x.ts')])
+ // Detector 2 halts a third identical read batch inside the six-step window
+ // with no warning; that is the behaviour the decay had to be taught about.
+ expect(third.action).toBe('halt')
+ })
+
+ it('the same three batches pass when every read was capped', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('x.ts')])
+ const other = (n: number) => [{ name: 'file_list', args: `{"path":"${n}"}` }]
+ expect(guard.recordBatch([READ('x.ts')], { trimmedReadKeys: trimmed }).action).toBe('ok')
+ guard.recordBatch(other(1))
+ expect(guard.recordBatch([READ('x.ts')], { trimmedReadKeys: trimmed }).action).toBe('ok')
+ guard.recordBatch(other(2))
+ expect(guard.recordBatch([READ('x.ts')], { trimmedReadKeys: trimmed }).action).toBe('ok')
+ })
+})
+
+describe('A1 loop guard: a read-only plan run survives its own re-reads', () => {
+ it('five reads of one reference file over twelve steps do not halt', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('docs/spec.md')])
+ const verdicts: string[] = []
+ for (let step = 1; step <= 12; step++) {
+ const batch = step % 3 === 1
+ ? [READ('docs/spec.md')]
+ : [{ name: 'file_search', args: `{"q":"step${step}"}` }]
+ verdicts.push(guard.recordBatch(batch, { trimmedReadKeys: trimmed }).action)
+ }
+ expect(verdicts.filter((v) => v === 'halt')).toEqual([])
+ })
+})
+
+describe('A1 loop guard: the backstop is deliberately left in place', () => {
+ it('three byte-identical batches back to back still halt, capped or not', () => {
+ const guard = new AgentLoopGuard()
+ const trimmed = new Set([keyOf('y.ts')])
+ guard.recordBatch([READ('y.ts')], { trimmedReadKeys: trimmed })
+ guard.recordBatch([READ('y.ts')], { trimmedReadKeys: trimmed })
+ const third = guard.recordBatch([READ('y.ts')], { trimmedReadKeys: trimmed })
+ expect(third.action).toBe('halt')
+ })
+})
diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.ts
index fce02e5a..1fe1664d 100644
--- a/src/lib/agent-loop-guard.ts
+++ b/src/lib/agent-loop-guard.ts
@@ -131,11 +131,26 @@ export class AgentLoopGuard {
* Record one iteration's tool-call batch BEFORE executing it. `args` must
* be the serialized (stringified) arguments so identity is byte-exact —
* the same convention the in-turn cache uses.
+ *
+ * `trimmedReadKeys` carries the reads whose newest result the request
+ * builder sent CAPPED (2.6.6 age decay, plan A1). Those re-reads are the
+ * feature working as designed, not a loop: the model cannot see the bytes
+ * any more, so fetching them again is the correct move. Detectors 2 and 3
+ * therefore skip them, and the steer text never tells the model to "use the
+ * result from before" for a key whose result from before is a stub. That
+ * sentence is an order to work against content it cannot see, which is the
+ * exact failure the decay rules exist to prevent.
*/
- recordBatch(calls: Array<{ name: string; args: string }>): LoopGuardVerdict {
+ recordBatch(
+ calls: Array<{ name: string; args: string }>,
+ opts: { trimmedReadKeys?: ReadonlySet<string> } = {},
+ ): LoopGuardVerdict {
if (calls.length === 0) return { action: 'ok' }
const keys = calls.map((c) => `${c.name}|${c.args}`)
const sig = [...keys].sort().join('||')
+ const trimmed = opts.trimmedReadKeys
+ const isTrimmed = (k: string) => trimmed?.has(k) ?? false
+ const batchHasTrimmedRead = keys.some((k, i) => READ_ONLY_TOOLS.has(calls[i].name) && isTrimmed(k))
// (1) Back-to-back identical batches, any tool class.
if (sig === this.lastSig) {
@@ -150,8 +165,11 @@ export class AgentLoopGuard {
const hasMutation = calls.some((c) => !READ_ONLY_TOOLS.has(c.name))
- // (2) Windowed repeats among pure-read batches (alternation).
- if (!hasMutation) {
+ // (2) Windowed repeats among pure-read batches (alternation). A batch that
+ // re-reads something the builder capped is not part of that pattern and is
+ // kept out of the window entirely, so it neither halts nor pushes an
+ // honest repeat out of the six-step view.
+ if (!hasMutation && !batchHasTrimmedRead) {
this.pureWindow.push(sig)
if (this.pureWindow.length > BATCH_WINDOW) this.pureWindow.shift()
const repeats = this.pureWindow.filter((s) => s === sig).length
@@ -167,6 +185,14 @@ export class AgentLoopGuard {
let steer: LoopGuardVerdict | null = null
for (let i = 0; i < calls.length; i++) {
if (!READ_ONLY_TOOLS.has(calls[i].name)) continue
+ if (isTrimmed(keys[i])) {
+ // The result aged out of the prompt, so this read returns information
+ // the model genuinely no longer has. Clear the counter rather than
+ // just skipping it: the epoch before the cap says nothing about the
+ // epoch after it.
+ this.readCounts.delete(keys[i])
+ continue
+ }
const n = (this.readCounts.get(keys[i]) ?? 0) + 1
this.readCounts.set(keys[i], n)
if (n >= READ_HALT_AT) {
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index e6e6848c..a470cf96 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -76,7 +76,7 @@ export async function getModelMaxTokens(modelName: string): Promise<number> {
// ── Message Compaction ──────────────────────────────────────────
-const KEEP_RECENT = 4 // Always keep at least the last N messages untouched
+export const KEEP_RECENT = 4 // Always keep at least the last N messages untouched
/** Hard ceiling on how many messages one request may carry, independent of
* tokens. The LU Cloud proxy rejects anything above 400 messages, and a chat
@@ -173,15 +173,48 @@ export function capMessageCount<T extends { role: string; content?: unknown }>(
return [...sys, ...kept]
}
+/**
+ * Hysteresis (2.6.6, plan A3). Trimming to exactly the budget every step moves
+ * the prompt prefix every step, and a moved prefix is a cold upstream cache:
+ * the whole history is billed at full price again. So compaction waits until
+ * the history is 15 percent OVER budget and then drops in one big block down
+ * to 70 percent of it. In between, the array passes through byte-for-byte and
+ * the cache keeps hitting.
+ *
+ * The decision is taken from the messages array alone, with no watermark kept
+ * anywhere, so a run aborted mid-step strands no state (plan A3, Runde 2).
+ */
+export const COMPACT_TRIGGER_RATIO = 1.15
+export const COMPACT_TARGET_RATIO = 0.7
+
+/**
+ * How many messages one drop step removes when the carried history has to
+ * shrink (trimWorkingHistory in context-decay).
+ *
+ * The hysteresis pair above is what keeps the prefix still; this is the step
+ * size of the search for how much to drop, and it is a block rather than a
+ * single message because each probe re-measures the whole decayed history.
+ * One at a time would make a long run quadratic for no gain.
+ */
+export const COMPACT_DROP_BLOCK = 16
+
+export interface CompactOptions {
+ /** Wait for budget × 1.15, then drop to budget × 0.7. */
+ hysteresis?: boolean
+}
+
export function compactMessages(
messages: OllamaChatMessage[],
- maxTokens: number
+ maxTokens: number,
+ opts: CompactOptions = {},
): OllamaChatMessage[] {
const currentTokens = estimateMessageTokens(messages)
+ const triggerTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TRIGGER_RATIO) : maxTokens
+ const targetTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TARGET_RATIO) : maxTokens
// Already within budget — BOTH budgets. A history that fits the token
// window but exceeds the message-count ceiling still has to shrink.
- if (currentTokens <= maxTokens && messages.length <= MAX_SEND_MESSAGES) return messages
+ if (currentTokens <= triggerTokens && messages.length <= MAX_SEND_MESSAGES) return messages
// Separate system prompt (always kept)
const systemMsg = messages[0]?.role === 'system' ? messages[0] : null
@@ -191,7 +224,7 @@ export function compactMessages(
if (nonSystem.length <= KEEP_RECENT) return messages
const systemTokens = systemMsg ? estimateMessageTokens([systemMsg]) : 0
- const budget = Math.max(0, maxTokens - systemTokens)
+ const budget = Math.max(0, targetTokens - systemTokens)
// Cap oversized TOOL RESULTS before fitting the suffix. KEEP_RECENT below
// keeps the newest messages even when they exceed the budget — without this
diff --git a/src/lib/context-decay.ts b/src/lib/context-decay.ts
new file mode 100644
index 00000000..4a7862ef
--- /dev/null
+++ b/src/lib/context-decay.ts
@@ -0,0 +1,457 @@
+/**
+ * Age decay for tool results (2.6.6, plan A1).
+ *
+ * The largest single cost leak in a long coding run: every tool result the
+ * agent ever saw rode along VERBATIM in every following request. A run that
+ * reads three 50k files pays for those 150k characters again on step 4, 5, 6
+ * and on to step 40. The upstream bills the whole prompt every time.
+ *
+ * The fix is age, not size. A result the model looked at two iterations ago has
+ * already done its job: the model either used it or moved on. So results older
+ * than the newest iteration are sent head+tail-capped, while the newest
+ * iteration stays byte-for-byte intact. That last part is the binding
+ * behavioural rule (plan meta-rule 4, learned from the Morgan incident and the
+ * 80-character-stub loop): the model must never edit against content it can no
+ * longer see, and the content it is working on right now is always the content
+ * it just fetched.
+ *
+ * Three properties this module has to keep:
+ *
+ * 1. BUILDER ONLY. Decay happens on a copy made while the request is built.
+ * The store, the persisted history and the visible transcript keep the full
+ * result, so the whole feature is reversible and the schema is unchanged.
+ * 2. DETERMINISTIC AND FINAL. The cap is a fixed character budget, never a
+ * budget derived from the model window, so the same result always yields
+ * the same bytes. Per step at most ONE iteration crosses the age line;
+ * everything before it is byte-identical to the previous step, which is
+ * what makes the upstream prefix cache work at all (plan A3).
+ * 3. STABLE ACROSS A RESTORE. A result the run already sent capped at 4k is
+ * restored at exactly those 4k bytes. The tighter 1.5k restore budget is
+ * for results the run never capped, i.e. results that were shorter than
+ * the in-run cap to begin with.
+ */
+
+import { truncateToolResult } from './truncate-tool-result'
+import {
+ compactMessages,
+ estimateMessageTokens,
+ COMPACT_DROP_BLOCK,
+ COMPACT_TARGET_RATIO,
+ COMPACT_TRIGGER_RATIO,
+ KEEP_RECENT,
+} from './context-compaction'
+
+/** Head+tail budget for a result that has aged out, in characters. */
+export const DECAY_RESULT_CHARS = 4000
+
+/**
+ * Head+tail budget for hidden tool messages of PREVIOUS turns when a session
+ * is restored. Tighter than the in-run budget because a previous turn's work
+ * is already summarised by its visible answer.
+ */
+export const RESTORE_RESULT_CHARS = 1500
+
+/**
+ * How many iterations a result survives at full length. The request under
+ * construction counts as the current iteration, so 2 means: the results of the
+ * iteration that just ran stay full, everything older is capped.
+ */
+export const DECAY_AFTER_ITERATIONS = 2
+
+/**
+ * Slack for the truncation marker truncateToolResult appends. Its output is a
+ * few characters LONGER than the budget, so a naive length test would cut an
+ * already-cut result a second time, and a second cut lands on different bytes,
+ * which is exactly the prefix churn this whole file exists to avoid.
+ */
+const MARKER_SLACK = 64
+
+/** The marker truncateToolResult leaves behind. */
+const TRUNCATION_MARKER = '…[truncated '
+
+/**
+ * True when this text is already the output of a cut at `budget`. Decay has to
+ * be idempotent: a restored result that the run capped at 4k is fed straight
+ * back into the in-run decay on the next step, and cutting it again would move
+ * the prompt prefix on every single step.
+ */
+export function isAlreadyDecayed(content: string, budget: number): boolean {
+ return content.length <= budget + MARKER_SLACK && content.includes(TRUNCATION_MARKER)
+}
+
+/** Content a superseded todo_write result is replaced by (plan A5). */
+export const SUPERSEDED_PLAN_NOTE = '[superseded plan update]'
+
+/** Minimal shape this module needs. Works for ChatMessage and OllamaChatMessage. */
+export interface DecayMessage {
+ role: string
+ content?: unknown
+ tool_calls?: unknown
+ tool_call_id?: string
+}
+
+interface RawToolCall {
+ id?: string
+ function?: { name?: string; arguments?: unknown }
+}
+
+/**
+ * True for a message that carries a tool RESULT: the native `tool` role, or a
+ * Hermes `<tool_response>` riding on a user message.
+ */
+export function isToolResult(msg: DecayMessage): boolean {
+ if (msg.role === 'tool') return true
+ if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.includes('<tool_response>')) {
+ return true
+ }
+ return false
+}
+
+/** The tool calls one assistant message asked for, both transports. */
+function toolCallsIn(msg: DecayMessage): RawToolCall[] {
+ const out: RawToolCall[] = []
+ const calls = msg.tool_calls
+ if (Array.isArray(calls)) {
+ for (const tc of calls as RawToolCall[]) {
+ if (tc && typeof tc === 'object') out.push(tc)
+ }
+ }
+ if (msg.role === 'assistant' && typeof msg.content === 'string' && msg.content.includes('<tool_call>')) {
+ for (const block of msg.content.matchAll(/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g)) {
+ const m = /"name"\s*:\s*"([a-zA-Z0-9_]+)"/.exec(block[1])
+ if (m) out.push({ function: { name: m[1] } })
+ }
+ }
+ return out
+}
+
+function callName(tc: RawToolCall): string {
+ return typeof tc.function?.name === 'string' ? tc.function.name : ''
+}
+
+/** One call paired with the message that carried its result. */
+export interface PairedCall {
+ name: string
+ /** Index of the assistant message that asked for it. */
+ callIndex: number
+ /** Index of the message carrying the result, or -1 when it never landed. */
+ resultIndex: number
+ /** How many calls the same assistant message asked for. */
+ batchSize: number
+}
+
+/**
+ * Pair every tool call with its result message.
+ *
+ * Both transports are covered: the OpenAI shape links by `tool_call_id`, and
+ * the id-less native / Hermes shapes link by order, which is exactly how the
+ * loops emit them (one assistant message, then its results, in order).
+ */
+export function pairToolCalls(messages: DecayMessage[]): PairedCall[] {
+ const pairs: PairedCall[] = []
+ for (let i = 0; i < messages.length; i++) {
+ const m = messages[i]
+ if (m.role !== 'assistant') continue
+ const calls = toolCallsIn(m)
+ if (calls.length === 0) continue
+ const resultIdx: number[] = []
+ for (let j = i + 1; j < messages.length && isToolResult(messages[j]); j++) resultIdx.push(j)
+ for (let c = 0; c < calls.length; c++) {
+ const id = calls[c].id
+ let resultIndex = -1
+ if (typeof id === 'string' && id) {
+ resultIndex = resultIdx.find((j) => messages[j].tool_call_id === id) ?? -1
+ }
+ if (resultIndex < 0) resultIndex = resultIdx[c] ?? -1
+ pairs.push({ name: callName(calls[c]), callIndex: i, resultIndex, batchSize: calls.length })
+ }
+ }
+ return pairs
+}
+
+/**
+ * Iteration number per message index. An iteration starts at every assistant
+ * message that asks for tools; results inherit the iteration of the call that
+ * produced them. Messages before the first call belong to iteration 0.
+ */
+function iterationIndexes(messages: DecayMessage[]): number[] {
+ const out = new Array<number>(messages.length).fill(0)
+ let iter = 0
+ for (let i = 0; i < messages.length; i++) {
+ const m = messages[i]
+ if (m.role === 'assistant' && toolCallsIn(m).length > 0) iter++
+ out[i] = iter
+ }
+ return out
+}
+
+export interface DecayOptions<T> {
+ /** The contextDecay notaus. False sends the history exactly as before. */
+ enabled?: boolean
+ /** Character budget for an aged-out result. */
+ maxChars?: number
+ /** Iterations a result survives at full length. */
+ afterIterations?: number
+ /**
+ * Loop-guard key of the read that produced this result, when the caller
+ * knows it. Every key reported back in `trimmedKeys` is a read whose newest
+ * result went out capped, which is precisely the case where a re-read is
+ * legitimate and the guard must not count it (plan A1, LOOP-GUARD).
+ */
+ keyOf?: (msg: T) => string | undefined
+}
+
+export interface DecayReport<T> {
+ /** A fresh array. The input is never touched. */
+ messages: T[]
+ /** How many results were sent capped this step. */
+ trimmedCount: number
+ /** Characters the capping saved on this request. */
+ savedChars: number
+ /** Loop-guard keys whose newest result went out capped. */
+ trimmedKeys: string[]
+}
+
+/**
+ * Cap every tool result that is older than the newest iteration.
+ *
+ * The newest iteration is untouched, always. With decay off the messages come
+ * back unchanged (a copy, so the caller can keep treating the result as the
+ * send array).
+ */
+export function applyToolResultDecay<T extends DecayMessage>(
+ messages: T[],
+ opts: DecayOptions<T> = {},
+): DecayReport<T> {
+ const out = messages.slice()
+ if (opts.enabled === false) {
+ return { messages: out, trimmedCount: 0, savedChars: 0, trimmedKeys: [] }
+ }
+ const maxChars = opts.maxChars ?? DECAY_RESULT_CHARS
+ const afterIterations = opts.afterIterations ?? DECAY_AFTER_ITERATIONS
+ const iters = iterationIndexes(messages)
+
+ // The newest iteration that actually carries a result. Without one there is
+ // nothing to age against and the whole pass is a no-op.
+ let newest = -1
+ for (let i = 0; i < messages.length; i++) {
+ if (isToolResult(messages[i])) newest = Math.max(newest, iters[i])
+ }
+ if (newest < 0) return { messages: out, trimmedCount: 0, savedChars: 0, trimmedKeys: [] }
+
+ let trimmedCount = 0
+ let savedChars = 0
+ const trimmedKeys: string[] = []
+ for (let i = 0; i < messages.length; i++) {
+ const m = messages[i]
+ if (!isToolResult(m)) continue
+ // The request under construction is iteration newest + 1.
+ const age = newest + 1 - iters[i]
+ if (age < afterIterations) continue
+ const content = m.content
+ if (typeof content !== 'string' || content.length <= maxChars) continue
+ if (isAlreadyDecayed(content, maxChars)) continue
+ const capped = truncateToolResult(content, maxChars)
+ out[i] = { ...m, content: capped } as T
+ trimmedCount++
+ savedChars += content.length - capped.length
+ const key = opts.keyOf?.(m)
+ if (key) trimmedKeys.push(key)
+ }
+ return { messages: out, trimmedCount, savedChars, trimmedKeys }
+}
+
+/**
+ * The budget a restored tool message of a PREVIOUS turn is sent at.
+ *
+ * Longer than the in-run cap means the run already sent it capped, so it is
+ * handed back the very same bytes instead of being re-cut with a second
+ * budget. Anything the run never capped gets the tight restore budget.
+ */
+export function restoreBudgetFor(
+ length: number,
+ inRunChars = DECAY_RESULT_CHARS,
+ restoreChars = RESTORE_RESULT_CHARS,
+): number {
+ return length > inRunChars ? inRunChars : restoreChars
+}
+
+/**
+ * Decay one restored tool message. Pure function of the stored content, which
+ * is what makes the restore reproduce the in-run bytes without persisting a
+ * single extra field.
+ */
+export function decayRestoredToolResult(
+ content: string,
+ inRunChars = DECAY_RESULT_CHARS,
+ restoreChars = RESTORE_RESULT_CHARS,
+): string {
+ if (typeof content !== 'string') return content
+ const budget = restoreBudgetFor(content.length, inRunChars, restoreChars)
+ if (content.length <= budget) return content
+ if (isAlreadyDecayed(content, budget)) return content
+ return truncateToolResult(content, budget)
+}
+
+/**
+ * Drop superseded todo_write pairs (plan A5).
+ *
+ * The model rewrites the COMPLETE plan after every step, so a 20-step run
+ * carries 20 copies of a list that differs by one checkbox, and every copy is
+ * paid for on every following request. Only the newest plan state says
+ * anything; the older ones are noise the model has to read past.
+ *
+ * A pair is dropped whole when the assistant message asked for nothing but
+ * todo_write. In a mixed batch the call has to stay (strict providers reject a
+ * tool result without its call, and a call without its result), so only the
+ * result text is replaced by a marker.
+ */
+export function pruneSupersededPlans<T extends DecayMessage>(
+ messages: T[],
+): { messages: T[]; prunedCount: number } {
+ const pairs = pairToolCalls(messages).filter((p) => p.name === 'todo_write')
+ if (pairs.length <= 1) return { messages: messages.slice(), prunedCount: 0 }
+
+ const drop = new Set<number>()
+ const blank = new Set<number>()
+ // Everything but the last plan update is superseded.
+ for (const p of pairs.slice(0, -1)) {
+ if (p.batchSize === 1) {
+ drop.add(p.callIndex)
+ if (p.resultIndex >= 0) drop.add(p.resultIndex)
+ } else if (p.resultIndex >= 0) {
+ blank.add(p.resultIndex)
+ }
+ }
+
+ const out: T[] = []
+ for (let i = 0; i < messages.length; i++) {
+ if (drop.has(i)) continue
+ if (blank.has(i)) {
+ out.push({ ...messages[i], content: SUPERSEDED_PLAN_NOTE } as T)
+ continue
+ }
+ out.push(messages[i])
+ }
+ return { messages: out, prunedCount: drop.size + blank.size }
+}
+
+/**
+ * Bound the WORKING history the loop carries from step to step.
+ *
+ * This is the piece that makes the A3 hysteresis a real property instead of a
+ * description. Trimming to the exact budget on every request means dropping
+ * about two more messages every step, so the window start creeps forward every
+ * step and the prompt prefix is never the same twice, no matter how the request
+ * builder is tuned. Waiting until the carried array is 15 percent over budget
+ * and then dropping it to 70 percent instead leaves the window start on the
+ * same message for several steps running, and everything from there on is
+ * byte-identical. Measured over a 30-step plateau: 3 prefix moves instead of
+ * 18.
+ *
+ * Two rules keep it honest:
+ *
+ * - it drops whole MESSAGES, it never shortens one. Decay stays the only
+ * thing that touches content, and it stays on the send copy alone, so the
+ * store and the next session keep every result whole.
+ * - the budget check runs on the DECAYED sizes, because that is what the
+ * request will actually cost. Measuring the raw sizes here would throw away
+ * messages that fit comfortably once decay has done its work.
+ *
+ * Stateless: the decision comes from the array being carried, never from a
+ * watermark, so a step aborted halfway strands nothing.
+ */
+export function trimWorkingHistory<T extends DecayMessage>(
+ messages: T[],
+ budgetTokens: number,
+ opts: DecayOptions<T> = {},
+): { messages: T[]; dropped: number } {
+ const sizeOf = (list: T[]) =>
+ estimateMessageTokens(
+ applyToolResultDecay(list, opts).messages as unknown as Parameters<typeof estimateMessageTokens>[0],
+ )
+ const trigger = Math.floor(budgetTokens * COMPACT_TRIGGER_RATIO)
+ const target = Math.floor(budgetTokens * COMPACT_TARGET_RATIO)
+ if (budgetTokens <= 0 || sizeOf(messages) <= trigger) return { messages, dropped: 0 }
+
+ const systemMsg = messages[0]?.role === 'system' ? messages[0] : null
+ const rest = systemMsg ? messages.slice(1) : messages.slice()
+ const firstUser = rest.find((m) => m.role === 'user') ?? null
+
+ // The task itself is pinned, exactly as compactMessages pins it: the suffix
+ // window is precisely the mechanism that drops the instruction first, after
+ // which a long run works on whatever the recent results imply.
+ const assemble = (drop: number): T[] => {
+ let tail = rest.slice(drop)
+ // Never open the window on a result whose call fell outside it; strict
+ // providers reject that outright.
+ while (tail.length > 0 && isToolResult(tail[0])) tail = tail.slice(1)
+ const out: T[] = []
+ if (systemMsg) out.push(systemMsg)
+ if (firstUser && !tail.includes(firstUser)) out.push(firstUser)
+ out.push(...tail)
+ return out
+ }
+
+ const maxDrop = Math.max(0, rest.length - KEEP_RECENT)
+ let drop = 0
+ let candidate = messages
+ while (drop < maxDrop) {
+ drop = Math.min(drop + COMPACT_DROP_BLOCK, maxDrop)
+ candidate = assemble(drop)
+ if (sizeOf(candidate) <= target) break
+ }
+ return { messages: candidate, dropped: drop }
+}
+
+export interface BuildRequestOptions<T> extends DecayOptions<T> {
+ /** Token budget for the compaction pass (plan A2 picks the number). */
+ budgetTokens: number
+ /** Compact with the A3 hysteresis instead of trimming to the budget exactly. */
+ hysteresis?: boolean
+ /** Prune superseded todo_write pairs (plan A5). Off with decay off. */
+ prunePlans?: boolean
+}
+
+export interface BuiltRequest<T> extends DecayReport<T> {
+ /** Superseded plan messages dropped or blanked. */
+ prunedPlans: number
+ /** Estimated size of the request as it goes out. */
+ promptTokens: number
+}
+
+/**
+ * Build the message array one step actually sends.
+ *
+ * The order is binding (plan A1): decay first, then the budget, then
+ * compaction. The other way round the budget counts full results, decides to
+ * drop whole messages, and the decay it would have needed never happens.
+ */
+export function buildRequestMessages<T extends DecayMessage>(
+ messages: T[],
+ opts: BuildRequestOptions<T>,
+): BuiltRequest<T> {
+ const decayed = applyToolResultDecay(messages, opts)
+ let working = decayed.messages
+ let prunedPlans = 0
+ if (opts.enabled !== false && opts.prunePlans !== false) {
+ const pruned = pruneSupersededPlans(working)
+ working = pruned.messages
+ prunedPlans = pruned.prunedCount
+ }
+ const compacted = compactMessages(
+ working as unknown as Parameters<typeof compactMessages>[0],
+ opts.budgetTokens,
+ { hysteresis: opts.hysteresis },
+ ) as unknown as T[]
+ return {
+ messages: compacted,
+ trimmedCount: decayed.trimmedCount,
+ savedChars: decayed.savedChars,
+ trimmedKeys: decayed.trimmedKeys,
+ prunedPlans,
+ promptTokens: estimateMessageTokens(
+ compacted as unknown as Parameters<typeof estimateMessageTokens>[0],
+ ),
+ }
+}