Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

35.4 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';

import type { PipelineContext } from '../../types';
import { cacheEconomicsForProvider, StaleToolResultTrimProcessor } from '../StaleToolResultTrim';

const previousTurnMessage = (createdAt: string) => ({
  content: 'previous turn done',
  createdAt,
  id: 'prev',
  role: 'assistant',
});

const createContext = (messages: any[]): PipelineContext => ({
  initialState: { messages: [] },
  isAborted: false,
  messages,
  metadata: {},
});

const toolMessage = (
  identifier: string,
  apiName: string,
  content: string,
  overrides?: Record<string, unknown>,
) => ({
  content,
  id: `tool-${apiName}-${Math.random()}`,
  plugin: { apiName, identifier },
  role: 'tool',
  tool_call_id: `call-${apiName}`,
  ...overrides,
});

const readFileResult = (path: string, content: string, loc?: [number, number]) =>
  toolMessage('lobe-local-system', 'readFile', content, {
    plugin: {
      apiName: 'readFile',
      // Canonical wire shape: arguments arrive as the serialized JSON string
      // from the model's tool call, not a parsed object.
      arguments: JSON.stringify({ loc, path }),
      identifier: 'lobe-local-system',
    },
    pluginState: { loc, path },
  });

const writeFileResult = (path: string) =>
  toolMessage('lobe-local-system', 'writeFile', `Successfully wrote to ${path}`, {
    plugin: {
      apiName: 'writeFile',
      arguments: JSON.stringify({ path }),
      identifier: 'lobe-local-system',
    },
    pluginState: { path, success: true },
  });

// Tail padding that keeps the trim window away from the messages under test.
const recencyPadding = (n: number) =>
  Array.from({ length: n }, (_, i) => ({
    content: `recent ${i}`,
    id: `pad-${i}`,
    role: 'assistant',
    tool_call_id: undefined,
  }));

const createProcessor = () =>
  new StaleToolResultTrimProcessor({ keepRecentMessages: 3, minTotalToolChars: 0 });

describe('StaleToolResultTrimProcessor', () => {
  it('trims a readFile result superseded by a later write to the same path', async () => {
    const messages = [
      readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
      writeFileResult('/a.ts'),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toBe(
      '[readFile result trimmed: /a.ts — superseded by a later write to this file. Call readFile again if you need the current content.]',
    );
    expect(result.messages[0].tool_call_id).toBe(messages[0].tool_call_id);
    expect(result.messages[1].content).toBe(messages[1].content);
    expect(result.metadata.staleToolResultTrim).toMatchObject({
      byRule: { readSupersededByWrite: 1 },
      cacheWarm: false,
      savedChars: 5000 - (result.messages[0].content as string).length,
      trimmedMessages: 1,
    });
  });

  it('trims a readFile result whose range was fully re-read later', async () => {
    const messages = [
      readFileResult('/a.ts', 'y'.repeat(3000), [0, 100]),
      readFileResult('/a.ts', 'z'.repeat(6000), [0, 200]),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toContain('the same range was read again later');
    expect(result.messages[1].content).toBe('z'.repeat(6000));
  });

  it('keeps complementary reads of the same file (partial overlap is not coverage)', async () => {
    const messages = [
      readFileResult('/a.ts', 'first chunk', [0, 200]),
      readFileResult('/a.ts', 'second chunk', [200, 400]),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toBe('first chunk');
    expect(result.messages[1].content).toBe('second chunk');
    expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
  });

  describe('chat images from readMessages', () => {
    const T0 = Date.parse('2026-09-20T08:00:00Z');
    const images = (n: number) =>
      Array.from({ length: n }, (_, i) => ({ mediaType: 'image/png', url: `https://app/f/${i}` }));
    const readWithImages = (n: number) =>
      toolMessage('lobe-message', 'readMessages', 'Fetched 3 messages', {
        pluginState: { images: images(n), messages: [] },
      });
    // Old read, filler pushing it out of the recency tail, then the turn boundary.
    const history = (imageCount: number, gapMs: number) => [
      readWithImages(imageCount),
      { content: 'filler 1', id: 'f1', role: 'assistant' },
      { content: 'filler 2', id: 'f2', role: 'assistant' },
      { content: 'filler 3', id: 'f3', role: 'assistant' },
      { content: 'done', createdAt: T0, id: 'prev', role: 'assistant' },
      { content: 'next', createdAt: T0 + gapMs, id: 'trigger', role: 'user' },
    ];

    it('drops the images of an old result but keeps its text', async () => {
      const result = await createProcessor().process(createContext(history(1, 600_000)));

      expect(result.messages[0].content).toBe(
        'Fetched 3 messages\n[1 image(s) from this readMessages result are no longer attached. Call readMessages again if you need to see them.]',
      );
      expect((result.messages[0] as any).pluginState.images).toBeUndefined();
      expect((result.messages[0] as any).pluginState.messages).toEqual([]);
      expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ staleMessageImages: 1 });
    });

    // Regression (Codex P2): images were worth 0 chars, so a history of image reads never
    // cleared the size gate however many images it held.
    it('counts images toward the minimum-size gate', async () => {
      const processor = new StaleToolResultTrimProcessor({
        imageCharEquivalent: 5000,
        keepRecentMessages: 3,
        minTotalToolChars: 20_000,
      });

      const below = await processor.process(createContext(history(3, 600_000)));
      expect((below.messages[0] as any).pluginState.images).toHaveLength(3);

      const above = await processor.process(createContext(history(4, 600_000)));
      expect((above.messages[0] as any).pluginState.images).toBeUndefined();
    });

    // Regression (Codex P2): the replacement only appends text, so without counting the dropped
    // images the saving was negative and the warm-cache break-even always skipped.
    it('counts dropped images as savings in the warm-cache break-even', async () => {
      const result = await createProcessor().process(createContext(history(4, 60_000)));

      expect(result.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: true,
        byRule: { staleMessageImages: 1 },
      });
      expect((result.messages[0] as any).pluginState.images).toBeUndefined();
    });

    it('keeps the images inside the recency window', async () => {
      const result = await createProcessor().process(createContext([readWithImages(1)]));

      expect((result.messages[0] as any).pluginState.images).toHaveLength(1);
    });
  });

  it('trims stale browser snapshots outside the recency window', async () => {
    const messages = [
      toolMessage('lobe-browser', 'snapshot', '- button "写作" [ref=e1]\n'.repeat(100)),
      toolMessage('lobe-browser', 'snapshot', '- button "大纲" [ref=e2]\n'.repeat(100)),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toContain('stale page state');
    expect(result.messages[1].content).toContain('stale page state');
    expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ staleBrowserPage: 2 });
  });

  // Codex P1: readPage text is source material for the final answer, not
  // interaction state — keep a head excerpt like the crawl rules instead of
  // dropping it wholesale.
  it('keeps a head excerpt of old readPage text instead of dropping it', async () => {
    const pageText = `Page: Example (https://example.com)\n${'article body '.repeat(500)}`;
    const messages = [toolMessage('lobe-browser', 'readPage', pageText), ...recencyPadding(3)];

    const result = await createProcessor().process(createContext(messages));

    const content = result.messages[0].content as string;
    // the lead (title, URL, start of the article) stays quotable
    expect(content.startsWith('Page: Example (https://example.com)')).toBe(true);
    expect(content).toContain('trimmed');
    expect(content).toContain('readPage again');
    expect(content.length).toBeLessThan(pageText.length);
    expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ stalePageText: 1 });
  });

  it('leaves short readPage results intact', async () => {
    const messages = [
      toolMessage('lobe-browser', 'readPage', 'short page text'),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toBe('short page text');
  });

  it('keeps the head and tail of old command output', async () => {
    const longOutput = `HEAD-${'a'.repeat(2000)}-TAIL`;
    const messages = [
      toolMessage('lobe-local-system', 'runCommand', longOutput),
      ...recencyPadding(3),
    ];

    const result = await new StaleToolResultTrimProcessor({
      commandKeepChars: 100,
      keepRecentMessages: 3,
      minTotalToolChars: 0,
    }).process(createContext(messages));

    const content = result.messages[0].content as string;
    expect(content).toContain('HEAD-');
    expect(content).toContain('-TAIL');
    expect(content).toContain('trimmed');
    expect(content.length).toBeLessThan(longOutput.length);
  });

  it('trims old web-browsing results to a head excerpt', async () => {
    const longPage = `<crawlResults>${'p'.repeat(5000)}</crawlResults>`;
    const messages = [
      toolMessage('lobe-web-browsing', 'crawlSinglePage', longPage),
      ...recencyPadding(3),
    ];

    const result = await new StaleToolResultTrimProcessor({
      crawlKeepChars: 200,
      keepRecentMessages: 3,
      minTotalToolChars: 0,
    }).process(createContext(messages));

    const content = result.messages[0].content as string;
    expect(content.startsWith('<crawlResults>')).toBe(true);
    expect(content).toContain('trimmed');
    expect(content.length).toBeLessThan(400);
  });

  it('never trims error results', async () => {
    const messages = [
      toolMessage('lobe-browser', 'snapshot', 'e'.repeat(5000), {
        pluginError: { message: 'Script failed to execute' },
      }),
      ...recencyPadding(3),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[0].content).toBe('e'.repeat(5000));
  });

  it('never touches the recency window', async () => {
    const messages = [
      ...recencyPadding(3),
      toolMessage('lobe-browser', 'snapshot', 'recent snapshot '.repeat(100)),
    ];

    const result = await createProcessor().process(createContext(messages));

    expect(result.messages[3].content).toBe('recent snapshot '.repeat(100));
  });

  it('skips small histories entirely', async () => {
    const processor = new StaleToolResultTrimProcessor({ minTotalToolChars: 1_000_000 });
    const messages = [
      readFileResult('/a.ts', 'short', [0, 10]),
      writeFileResult('/a.ts'),
      ...recencyPadding(3),
    ];

    const result = await processor.process(createContext(messages));

    expect(result.messages[0].content).toBe('short');
    expect(result.metadata.staleToolResultTrim).toBeUndefined();
  });

  it('is idempotent — trimming an already-trimmed history is byte-stable', async () => {
    const processor = createProcessor();
    const messages = [
      readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
      writeFileResult('/a.ts'),
      toolMessage('lobe-browser', 'snapshot', 'snap '.repeat(500)),
      ...recencyPadding(3),
    ];

    const first = await processor.process(createContext(messages));
    const second = await processor.process(createContext(first.messages));

    expect(second.messages).toEqual(first.messages);
    expect(second.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
  });

  it('does nothing when disabled', async () => {
    const processor = new StaleToolResultTrimProcessor({ enabled: false, minTotalToolChars: 0 });
    const messages = [readFileResult('/a.ts', 'x'.repeat(5000)), writeFileResult('/a.ts')];

    const result = await processor.process(createContext(messages));

    expect(result.messages[0].content).toBe('x'.repeat(5000));
  });

  // Every LLM step of a running operation re-runs the pipeline; the trim set
  // must stay frozen for the whole turn or the prefix flips mid-operation.
  it('never trims messages from the in-flight turn, and an in-flight write does not retroactively trim', async () => {
    const processor = new StaleToolResultTrimProcessor({
      keepRecentMessages: 1,
      minTotalToolChars: 0,
    });
    const messages = [
      readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
      writeFileResult('/a.ts'),
      { content: 'ç»§ç»­', id: 'user-1', role: 'user' },
      readFileResult('/b.ts', 'y'.repeat(5000), [0, 200]),
      writeFileResult('/b.ts'), // in-flight write — must NOT trim the read above mid-turn
      ...recencyPadding(3),
    ];

    const result = await processor.process(createContext(messages));

    // Closed history before the boundary: trimmed
    expect(result.messages[0].content).toContain('superseded by a later write');
    // In-flight: untouched even though /b.ts was likewise overwritten
    expect(result.messages[3].content).toBe('y'.repeat(5000));
    expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);
  });

  // Regression (Codex P1): the recency cutoff must be derived from the turn
  // boundary, not the growing message count — otherwise results that started
  // inside the protected tail cross the cutoff as the op appends messages.
  it('freezes the recency window at the turn boundary for the whole operation', async () => {
    const processor = new StaleToolResultTrimProcessor({
      keepRecentMessages: 3,
      minTotalToolChars: 0,
    });
    const staleSnapshot = toolMessage('lobe-browser', 'snapshot', 'snap '.repeat(500));
    const messages = [
      { content: 'older turn', id: 'm0', role: 'assistant' },
      staleSnapshot, // index 1: inside the 3-message protected tail at turn start
      { content: 'tail', id: 'm2', role: 'assistant' },
      { content: 'start working', id: 'user-1', role: 'user' },
      // 50 in-flight messages appended as the operation progresses
      ...recencyPadding(50),
    ];

    const result = await processor.process(createContext(messages));

    expect(result.messages[1].content).toBe(staleSnapshot.content);
    expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
  });

  it('parses serialized string arguments when pluginState is absent', async () => {
    const legacyRead = toolMessage('lobe-local-system', 'readFile', 'x'.repeat(5000), {
      plugin: {
        apiName: 'readFile',
        arguments: JSON.stringify({ path: '/legacy.ts' }),
        identifier: 'lobe-local-system',
      },
    });
    const legacyWrite = toolMessage(
      'lobe-local-system',
      'writeFile',
      'Successfully wrote to /legacy.ts',
      {
        plugin: {
          apiName: 'writeFile',
          arguments: JSON.stringify({ path: '/legacy.ts' }),
          identifier: 'lobe-local-system',
        },
      },
    );

    const result = await createProcessor().process(
      createContext([legacyRead, legacyWrite, ...recencyPadding(3)]),
    );

    expect(result.messages[0].content).toContain('superseded by a later write');
  });

  describe('cache-warmth gate', () => {
    const T0 = Date.parse('2026-09-20T08:00:00Z');
    const MIN = 60_000;

    // Filler between the write and the trigger keeps the write result outside
    // the recency tail (keepRecentMessages=3 in createProcessor), so the stale
    // read is a trim candidate; the last two entries fix the turn-boundary
    // timestamps the warmth gate reads.
    const turnMessages = (staleChars: number, gapMs: number, liveChars = 0) => [
      readFileResult('/a.ts', 'x'.repeat(staleChars), [0, 200]),
      writeFileResult('/a.ts'),
      ...(liveChars > 0
        ? [{ content: 'z'.repeat(liveChars), id: 'big-live-doc', role: 'assistant' }]
        : []),
      { content: 'filler 1', id: 'f1', role: 'assistant' },
      { content: 'filler 2', id: 'f2', role: 'assistant' },
      { content: 'filler 3', id: 'f3', role: 'assistant' },
      previousTurnMessage(new Date(T0).toISOString()),
      {
        content: 'next task',
        createdAt: new Date(T0 + gapMs).toISOString(),
        id: 'trigger',
        role: 'user',
      },
      ...recencyPadding(3),
    ];

    it('trims when the gap exceeds the cache TTL (cold cache — trim is free)', async () => {
      const result = await createProcessor().process(
        createContext(turnMessages(5000, 10 * MIN)), // 10 min gap > 5 min TTL
      );

      expect(result.messages[0].content).toContain('superseded by a later write');
      expect(result.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: false,
        gapMs: 10 * MIN,
        trimmedMessages: 1,
      });
    });

    it('skips the trim on a warm follow-up when savings are small relative to the payload', async () => {
      // Large live payload after the stale read + small saving: rewriting the
      // ~500k chars behind it at write price dwarfs 20 steps of 5k-char savings.
      const result = await createProcessor().process(
        createContext(turnMessages(5000, 1 * MIN, 500_000)),
      );

      expect(result.messages[0].content).toBe('x'.repeat(5000));
      expect(result.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: true,
        gapMs: 60_000,
        savedChars: 0,
        skippedReason: 'warm-cache',
        trimmedMessages: 0,
      });
      // the gate's economic inputs are recorded for observability
      expect(result.metadata.staleToolResultTrim?.potentialSavedChars).toBeGreaterThan(4000);
      expect(result.metadata.staleToolResultTrim?.gainEstimate).toBeGreaterThan(0);
      expect(result.metadata.staleToolResultTrim?.rewriteCostEstimate).toBeGreaterThan(0);
    });

    it('still trims on a warm follow-up when savings clear the warm thresholds', async () => {
      const result = await createProcessor().process(
        createContext(turnMessages(400_000, 1 * MIN)), // ~400k chars saved, >99% of payload
      );

      expect(result.messages[0].content).toContain('superseded by a later write');
      expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);
    });

    // Regression (Codex P1): UIChatMessage.createdAt is epoch-ms NUMBER on the
    // canonical path; Date.parse(number) yields NaN, which would silently
    // disable the warmth gate (always "cold").
    it('reads numeric epoch-ms timestamps for the warmth check', async () => {
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        writeFileResult('/a.ts'),
        { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
        { content: 'filler', id: 'f1', role: 'assistant' },
        { content: 'filler', id: 'f2', role: 'assistant' },
        { content: 'filler', id: 'f3', role: 'assistant' },
        { content: 'previous turn done', createdAt: T0, id: 'prev', role: 'assistant' },
        { content: 'next task', createdAt: T0 + MIN, id: 'trigger', role: 'user' },
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: true,
        gapMs: MIN,
        skippedReason: 'warm-cache',
      });
    });
  });

  describe('closed-history pinning', () => {
    // Regression (Codex P1): the warm break-even must price the rewrite from
    // the payload frozen at the turn boundary. Counting in-flight output
    // grows the cost estimate step by step and flips a passing trim back to a
    // skip mid-operation — restoring the original prefix.
    it('does not flip the warm-gate decision as in-flight output grows', async () => {
      const T0 = Date.parse('2026-09-20T08:00:00Z');
      const buildMessages = (inFlightChars: number) => [
        readFileResult('/a.ts', 'x'.repeat(200_000), [0, 200]), // big stale read → trim candidate
        writeFileResult('/a.ts'),
        { content: 'filler', id: 'f1', role: 'assistant' },
        { content: 'filler', id: 'f2', role: 'assistant' },
        { content: 'filler', id: 'f3', role: 'assistant' },
        previousTurnMessage(new Date(T0).toISOString()),
        {
          content: 'next task',
          createdAt: new Date(T0 + 60_000).toISOString(), // warm: 1 min gap
          id: 'trigger',
          role: 'user',
        },
        // in-flight output appended as the operation progresses
        toolMessage('lobe-local-system', 'runCommand', 'y'.repeat(inFlightChars)),
        ...recencyPadding(3),
      ];

      const processor = createProcessor();
      const atTurnStart = await processor.process(createContext(buildMessages(0)));
      const midOperation = await processor.process(createContext(buildMessages(2_000_000)));

      expect(atTurnStart.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);
      expect(midOperation.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);
      expect(midOperation.messages[0].content).toBe(atTurnStart.messages[0].content);
    });

    // Regression (Codex P1): the size gate must be measured on the closed
    // history only — otherwise in-flight tool output trips it mid-turn and
    // activates trims that were off at the boundary, flipping the prefix.
    it('does not let in-flight tool output trip the minimum-size gate mid-turn', async () => {
      const processor = new StaleToolResultTrimProcessor({
        keepRecentMessages: 3,
        minTotalToolChars: 10_000,
      });
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(3000), [0, 200]), // closed history: 3k < 10k gate
        writeFileResult('/a.ts'),
        { content: 'start', id: 'u1', role: 'user' },
        // in-flight tool output pushes total tool chars past the gate
        toolMessage('lobe-local-system', 'runCommand', 'y'.repeat(50_000)),
        ...recencyPadding(3),
      ];

      const result = await processor.process(createContext(messages));

      expect(result.messages[0].content).toBe('x'.repeat(3000));
      expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
    });
  });

  // Regression: a cold turn trimmed old results and the cache stored
  // the trimmed bytes; the next warm follow-up failed the break-even for its
  // new candidates and fell back to the untrimmed history, restoring the full
  // text and invalidating the cache from the first restored result.
  describe('sticky trims across turns', () => {
    const T0 = Date.parse('2026-09-20T08:00:00Z');
    const MIN = 60_000;
    const at = (ms: number) => new Date(ms).toISOString();
    const fillers = (prefix: string) =>
      Array.from({ length: 3 }, (_, i) => ({
        content: `${prefix} filler ${i}`,
        id: `${prefix}-f${i}`,
        role: 'assistant',
      }));

    it('keeps an earlier turn’s trims on a warm follow-up that skips new trims', async () => {
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        writeFileResult('/a.ts'),
        ...fillers('t1'),
        previousTurnMessage(at(T0)),
        // Turn 1 starts after a cold gap, so its trim of /a.ts is free.
        { content: 'turn 1', createdAt: at(T0 + 10 * MIN), id: 'u1', role: 'user' },
        ...fillers('t1-run'),
        readFileResult('/b.ts', 'y'.repeat(5000), [0, 200]),
        writeFileResult('/b.ts'),
        { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
        ...fillers('t2'),
        { content: 'turn 1 done', createdAt: at(T0 + 20 * MIN), id: 'done1', role: 'assistant' },
        // Turn 2 follows within the TTL; trimming /b.ts would not pay for the rewrite.
        { content: 'turn 2', createdAt: at(T0 + 21 * MIN), id: 'u2', role: 'user' },
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toContain('superseded by a later write');
      expect(result.messages.find((m) => m.content === 'y'.repeat(5000))).toBeDefined();
      expect(result.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: true,
        carriedMessages: 1,
        skippedReason: 'warm-cache',
        trimmedMessages: 1,
      });
    });

    it('keeps the placeholder an earlier turn chose when a later event matches another rule', async () => {
      const messages = [
        readFileResult('/c.ts', 'x'.repeat(5000), [0, 200]),
        readFileResult('/c.ts', 'x'.repeat(5000), [0, 200]),
        ...fillers('t1'),
        previousTurnMessage(at(T0)),
        { content: 'turn 1', createdAt: at(T0 + 10 * MIN), id: 'u1', role: 'user' },
        // Turn 1 writes the file: by turn 2 the first read also counts as superseded by a write.
        writeFileResult('/c.ts'),
        ...fillers('t2'),
        { content: 'turn 1 done', createdAt: at(T0 + 20 * MIN), id: 'done1', role: 'assistant' },
        { content: 'turn 2', createdAt: at(T0 + 30 * MIN), id: 'u2', role: 'user' },
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toBe(
        '[readFile result trimmed: /c.ts (lines 0-200) — the same range was read again later. Refer to the newer read, or call readFile again if needed.]',
      );
    });

    // Regression: the warm gate priced the whole payload, including context
    // injected into the trigger only for that request (an active-document
    // snapshot). The next turn's replay no longer saw the injection, so it
    // reached a different verdict than the turn itself had.
    it('reaches the same warm-gate verdict when the turn is replayed without its send-time injection', async () => {
      const history = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        writeFileResult('/a.ts'),
        ...fillers('t1'),
        previousTurnMessage(at(T0)),
      ];
      const turn1 = (content: string) => ({
        content,
        createdAt: at(T0 + MIN),
        id: 'u1',
        role: 'user',
      });

      const sentInTurn1 = await createProcessor().process(
        createContext([
          ...history,
          turn1(`turn 1\n\n<active_topic_document>${'d'.repeat(500_000)}</active_topic_document>`),
          ...recencyPadding(3),
        ]),
      );
      const replayedInTurn2 = await createProcessor().process(
        createContext([
          ...history,
          turn1('turn 1'),
          ...fillers('t1-run'),
          { content: 'turn 1 done', createdAt: at(T0 + 2 * MIN), id: 'done1', role: 'assistant' },
          { content: 'turn 2', createdAt: at(T0 + 3 * MIN), id: 'u2', role: 'user' },
          ...recencyPadding(3),
        ]),
      );

      expect(sentInTurn1.messages[0].content).toContain('superseded by a later write');
      expect(replayedInTurn2.messages[0].content).toBe(sentInTurn1.messages[0].content);
    });

    // Regression: the rewrite was priced on string content only, so a large
    // tool-call argument behind the candidate (a 500k-char writeFile) did not
    // count, and the gate accepted a rewrite that could never pay back.
    it('prices tool-call arguments behind the candidate in the warm gate', async () => {
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        {
          content: '',
          id: 'big-write-call',
          role: 'assistant',
          tools: [
            {
              apiName: 'writeFile',
              arguments: JSON.stringify({ content: 'w'.repeat(500_000), path: '/a.ts' }),
              id: 'call-w',
              identifier: 'lobe-local-system',
            },
          ],
        },
        writeFileResult('/a.ts'),
        ...fillers('t1'),
        previousTurnMessage(at(T0)),
        { content: 'turn 1', createdAt: at(T0 + MIN), id: 'u1', role: 'user' },
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toBe('x'.repeat(5000));
      expect(result.metadata.staleToolResultTrim?.skippedReason).toBe('warm-cache');
    });

    // Regression: a virtual tail user message (TodoInjector and friends) is
    // re-created at the end of every step; treating it as the turn trigger
    // moved the boundary mid-operation and trimmed the in-flight turn.
    it('ignores virtual tail user messages when locating the turn boundary', async () => {
      const messages = [
        { content: 'turn 1', id: 'u1', role: 'user' },
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        writeFileResult('/a.ts'),
        ...fillers('t1-run'),
        {
          content: '<todos>…</todos>',
          id: 'virtual-last-user-TodoInjector',
          meta: { injectType: 'TodoInjector', virtualLastUser: true },
          role: 'user',
        },
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[1].content).toBe('x'.repeat(5000));
    });
  });

  describe('invalidation index hygiene', () => {
    // Regression (Codex P2): a FAILED write must not supersede a good read.
    it('ignores failed writes when superseding reads', async () => {
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        toolMessage('lobe-local-system', 'writeFile', 'Error: disk full', {
          plugin: {
            apiName: 'writeFile',
            arguments: JSON.stringify({ path: '/a.ts' }),
            identifier: 'lobe-local-system',
          },
          pluginError: { message: 'disk full' },
          pluginState: { path: '/a.ts', success: false },
        }),
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toBe('x'.repeat(5000));
    });

    // Regression (Codex P2): an omitted loc means the service's [0, 200]
    // default window, not a full-file read.
    it('treats an omitted loc as the default [0, 200] window', async () => {
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(500), undefined),
        readFileResult('/a.ts', 'y'.repeat(500), undefined),
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toContain('the same range was read again later');
    });

    it('a default-window re-read does not cover an explicit later range', async () => {
      const messages = [
        readFileResult('/a.ts', 'middle chunk', [300, 400]),
        readFileResult('/a.ts', 'default window', undefined),
        ...recencyPadding(3),
      ];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toBe('middle chunk');
    });

    // Regression (Codex P2): an image read whose result is trimmed must also
    // drop pluginState.images, or MessageContentProcessor still sends the
    // stale image as image_url parts.
    it('clears image attachments when an image read result is trimmed', async () => {
      const imageRead = toolMessage('lobe-local-system', 'readFile', '[Image: design.png]', {
        plugin: {
          apiName: 'readFile',
          arguments: JSON.stringify({ path: '/design.png' }),
          identifier: 'lobe-local-system',
        },
        pluginState: {
          images: [
            { fileId: 'f1', mediaType: 'image/png', url: 'https://files.example.com/x.png' },
          ],
          path: '/design.png',
        },
      });
      const messages = [imageRead, writeFileResult('/design.png'), ...recencyPadding(3)];

      const result = await createProcessor().process(createContext(messages));

      expect(result.messages[0].content).toContain('superseded by a later write');
      expect((result.messages[0].pluginState as any).images).toBeUndefined();
    });

    // Regression (Codex P2): a result barely over the keep threshold would
    // grow once the trim notice is appended — never admit it.
    it('rejects replacements that would grow the payload', async () => {
      const messages = [
        toolMessage('lobe-web-browsing', 'crawlSinglePage', 'p'.repeat(101)),
        ...recencyPadding(3),
      ];

      const result = await new StaleToolResultTrimProcessor({
        crawlKeepChars: 100,
        keepRecentMessages: 3,
        minTotalToolChars: 0,
      }).process(createContext(messages));

      expect(result.messages[0].content).toBe('p'.repeat(101));
      expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
    });

    // Regression: after each accepting turn the replay pruned trimmed reads
    // from every path it had ever seen, so a long history of distinct files
    // cost O(turns²) per request.
    it('prunes trimmed reads only from the accepted rows’ paths', async () => {
      const turns = 60;
      const messages = Array.from({ length: turns }, (_, i) => [
        { content: `turn ${i}`, id: `user-${i}`, role: 'user' },
        readFileResult(`/f${i}.ts`, 'x'.repeat(5000)),
        writeFileResult(`/f${i}.ts`),
      ]).flat();
      messages.push(...recencyPadding(3), { content: 'last', id: 'user-last', role: 'user' });

      const filter = vi.spyOn(Array.prototype, 'filter');
      let result;
      let filterCalls: number;
      try {
        result = await createProcessor().process(createContext(messages));
      } finally {
        // mockRestore clears the recorded calls, so read the count first.
        filterCalls = filter.mock.calls.length;
        filter.mockRestore();
      }

      expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(turns);
      expect(filterCalls).toBeLessThanOrEqual(turns * 2);
    });
  });

  describe('cacheEconomicsForProvider', () => {
    it('returns provider-specific policies and falls back to Anthropic', () => {
      expect(cacheEconomicsForProvider('some-new-provider')).toEqual(
        cacheEconomicsForProvider('anthropic'),
      );
    });

    it('prices the warmth check with the active provider policy', async () => {
      // 10-minute gap: cold under Anthropic's 5-min TTL, still warm under
      // DeepSeek's hour-long disk cache.
      const T0 = Date.parse('2026-09-20T08:00:00Z');
      const messages = [
        readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
        writeFileResult('/a.ts'),
        { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
        { content: 'filler', id: 'f1', role: 'assistant' },
        { content: 'filler', id: 'f2', role: 'assistant' },
        { content: 'filler', id: 'f3', role: 'assistant' },
        previousTurnMessage(new Date(T0).toISOString()),
        {
          content: 'next task',
          createdAt: new Date(T0 + 600_000).toISOString(),
          id: 'trigger',
          role: 'user',
        },
        ...recencyPadding(3),
      ];

      const anthropic = await createProcessor().process(createContext(messages));
      expect(anthropic.metadata.staleToolResultTrim?.cacheWarm).toBe(false);
      expect(anthropic.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);

      const deepseek = await new StaleToolResultTrimProcessor({
        economics: cacheEconomicsForProvider('deepseek'),
        keepRecentMessages: 3,
        minTotalToolChars: 0,
      }).process(createContext(messages));
      expect(deepseek.metadata.staleToolResultTrim).toMatchObject({
        cacheWarm: true,
        skippedReason: 'warm-cache',
      });
    });
  });
});