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.

⚑️ perf(agent-documents): keep the document index cached across turns (#22989)

YuTengjing553d091d297c
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index d13b1bfc1a4..be09e864dea 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -5,6 +5,7 @@ import {
selectExpertise,
} from '@lobechat/agent-runtime';
import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
+import { cacheEconomicsForProvider, getSlicedMessages } from '@lobechat/context-engine';
import { gatherContextFacts } from '@lobechat/mecha';
import type { ChatStreamPayload } from '@lobechat/model-runtime';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
@@ -146,12 +147,26 @@ export const buildServerCallLlmContext = async ({
topicId,
workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,
},
- createServerContextFactProviders({ ctx, state }),
+ createServerContextFactProviders({
+ ctx,
+ documentIndexTurn: {
+ cacheTtlMs: cacheEconomicsForProvider(provider).ttlMs,
+ messages: messagesForContext,
+ // The engine drops older messages when history is limited; a change note
+ // on a dropped message no longer reaches the model.
+ visibleMessages: getSlicedMessages(messagesForContext, {
+ enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,
+ historyCount,
+ }),
+ },
+ state,
+ }),
);
const contextEngineInput = {
additionalContexts: llmPayload.additionalContexts,
attachmentPreviewFileIds: llmPayload.attachmentPreviewFileIds,
+ agentDocumentChanges: facts.agentDocumentChanges,
agentDocuments: facts.agentDocuments,
// Identity lives on the agent row, not in the prompt text β€” inject it so
// the model introduces itself by the user-given name.
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 3cbad24d057..2ff93fb0114 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -1,5 +1,5 @@
import { type AgentState } from '@lobechat/agent-runtime';
-import type { AgentDocumentIndexFacts } from '@lobechat/context-engine/agent-document';
+import type { AgentDocumentIndexSnapshot } from '@lobechat/context-engine/agent-document';
import {
type AgentShareVisitorContext,
type CancelVirtualSubAgentParams,
@@ -45,12 +45,12 @@ export interface RuntimeExecutorContext {
*/
allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
/**
- * Receives the agent-document index facts a step froze (first sight, or a
- * document that appeared mid-run). `executeStep` writes them into
+ * Receives the agent-document index snapshot a step pinned (the run's first
+ * step, or a mid-run compression). `executeStep` writes it into
* `binding.agentDocumentIndex` of the state it saves, so later steps render
- * the same index rows and keep the prompt-cache prefix.
+ * the same index and change notes and keep the prompt-cache prefix.
*/
- bindAgentDocumentIndex?: (facts: AgentDocumentIndexFacts) => void;
+ bindAgentDocumentIndex?: (snapshot: AgentDocumentIndexSnapshot) => void;
botContext?: unknown;
/**
* Callback to stop a running `lobe-agent.callSubAgent` child dispatched by
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
index a9314b5adcc..683bd25f1fe 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
@@ -16,6 +16,7 @@ export const toContextSnapshot = ({
additionalVariables,
agentAccountContext,
agentBuilderContext,
+ agentDocumentChanges,
agentDocuments,
agentGroup,
agentIdentity,
@@ -58,6 +59,7 @@ export const toContextSnapshot = ({
workspaceContext,
}: ServerMessagesEngineParams): ContextSnapshot => ({
agent: {
+ documentChanges: agentDocumentChanges,
documents: agentDocuments,
enableHistoryCount,
enableStaleToolResultTrim,
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocumentIndex.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocumentIndex.ts
new file mode 100644
index 00000000000..98a226e6722
--- /dev/null
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocumentIndex.ts
@@ -0,0 +1,66 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import {
+ type AgentContextDocument,
+ type AgentDocumentIndexSnapshot,
+ resolveAgentDocumentIndex,
+ type ResolveAgentDocumentIndexInput,
+} from '@lobechat/context-engine/agent-document';
+
+import type { RuntimeExecutorContext } from '@/server/modules/AgentRuntime/context';
+import { redisService } from '@/server/services/redis';
+
+/** What the agent-document index decision needs to know about the step. */
+export interface AgentDocumentIndexTurn {
+ /** Prompt-cache TTL of the provider the step calls. */
+ cacheTtlMs: number;
+ /** The conversation the context engine runs on. */
+ messages: ResolveAgentDocumentIndexInput['messages'];
+ /** The messages left after history truncation, when the agent limits history. */
+ visibleMessages?: ResolveAgentDocumentIndexInput['messages'];
+}
+
+interface ResolveInput {
+ agentId: string;
+ ctx: RuntimeExecutorContext;
+ docs: AgentContextDocument[];
+ state: AgentState;
+ turn: AgentDocumentIndexTurn;
+}
+
+/**
+ * Resolve the snapshot this step renders the agent-document index from.
+ *
+ * The run pins the snapshot in `binding.agentDocumentIndex`; the conversation
+ * keeps it in Redis between runs so the next turn can continue it while the
+ * prompt cache is warm. Without a topic (or without Redis) every run takes a
+ * fresh snapshot, which still keeps the index fixed within the run.
+ */
+export const resolveServerAgentDocumentIndex = async ({
+ agentId,
+ ctx,
+ docs,
+ state,
+ turn,
+}: ResolveInput): Promise<AgentDocumentIndexSnapshot> => {
+ const pinned = state.binding?.agentDocumentIndex;
+ const topicId = state.origin?.topicId ?? ctx.topicId;
+ const scope = topicId ? { agentId, threadId: state.origin?.threadId, topicId } : undefined;
+
+ // Only a run's first step may continue the stored snapshot; later steps never read it.
+ const stored = !pinned && scope ? await redisService.agentDocumentIndex.get(scope) : undefined;
+ const resolved = resolveAgentDocumentIndex({
+ cacheTtlMs: turn.cacheTtlMs,
+ docs,
+ messages: turn.messages,
+ now: new Date(),
+ pinned,
+ stored,
+ visibleMessages: turn.visibleMessages,
+ });
+
+ if (resolved.pin) ctx.bindAgentDocumentIndex?.(resolved.snapshot);
+ if (resolved.store && scope) {
+ await redisService.agentDocumentIndex.set(scope, resolved.snapshot);
+ }
+ return resolved.snapshot;
+};
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
index f8ff6d7711a..d813c338e29 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
@@ -2,7 +2,12 @@ import { type AgentState, selectToolSourceMap } from '@lobechat/agent-runtime';
import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';
import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
-import { freezeAgentDocumentIndexFacts } from '@lobechat/context-engine/agent-document';
+import {
+ type AgentContextDocument,
+ agentDocumentChangesByMessage,
+ type AgentDocumentIndexSnapshot,
+ agentDocumentsFromSnapshot,
+} from '@lobechat/context-engine/agent-document';
import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';
import {
agentShareDocumentAccessScope,
@@ -36,8 +41,16 @@ import { OnboardingService } from '@/server/services/onboarding';
import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';
+import { type AgentDocumentIndexTurn, resolveServerAgentDocumentIndex } from './agentDocumentIndex';
+
export interface ServerContextFactSource {
ctx: RuntimeExecutorContext;
+ /**
+ * The step's conversation and provider cache TTL. With it the documents
+ * index renders from a snapshot kept across warm turns; without it, from
+ * the live documents.
+ */
+ documentIndexTurn?: AgentDocumentIndexTurn;
state: AgentState;
}
@@ -66,6 +79,7 @@ const getAppUrl = (): string | undefined => {
*/
export const createServerContextFactProviders = ({
ctx,
+ documentIndexTurn,
state,
}: ServerContextFactSource): ContextFactProviders => {
const { serverDB, userId } = ctx;
@@ -80,6 +94,46 @@ export const createServerContextFactProviders = ({
})
: ordinaryDocumentAccessScope;
+ // `listAgentDocuments` and `listAgentDocumentChanges` must render from the
+ // same snapshot, and resolving one may write it, so resolve once per agent.
+ const agentDocumentIndexes = new Map<
+ string,
+ Promise<{ docs: AgentContextDocument[]; snapshot?: AgentDocumentIndexSnapshot }>
+ >();
+ const loadAgentDocumentIndex = (agentId: string) => {
+ let pending = agentDocumentIndexes.get(agentId);
+ if (!pending) {
+ pending = (async () => {
+ const docs = toAgentContextDocuments(
+ await new AgentDocumentsService(
+ db,
+ userId,
+ workspaceId,
+ undefined,
+ documentAccessScope,
+ ).getAgentContextDocuments(agentId),
+ );
+ if (!documentIndexTurn) return { docs };
+ try {
+ const snapshot = await resolveServerAgentDocumentIndex({
+ agentId,
+ ctx,
+ docs,
+ state,
+ turn: documentIndexTurn,
+ });
+ return { docs, snapshot };
+ } catch (error) {
+ // A snapshot only saves cache; never lose the documents over it.
+ log('Agent-document index snapshot failed, rendering live documents: %O', error);
+ return { docs };
+ }
+ })();
+ agentDocumentIndexes.set(agentId, pending);
+ }
+ return pending;
+ };
+
return {
findAgentDocument: async (agentId, documentId) => {
const doc = await new AgentDocumentsService(
@@ -242,22 +296,17 @@ export const createServerContextFactProviders = ({
};
},
+ listAgentDocumentChanges: async (agentId) => {
+ const index = await loadAgentDocumentIndex(agentId);
+ return index.snapshot && agentDocumentChangesByMessage(index.snapshot);
+ },
+
listAgentDocuments: async (agentId) => {
- const docs = await new AgentDocumentsService(
- db,
- userId,
- workspaceId,
- undefined,
- documentAccessScope,
- ).getAgentContextDocuments(agentId);
- // Render index rows from what this run first saw, so editing a document
- // mid-run does not rewrite the prompt prefix behind the index.
- const { documents, facts } = freezeAgentDocumentIndexFacts(
- toAgentContextDocuments(docs),
- state.binding?.agentDocumentIndex,
- );
- if (facts) ctx.bindAgentDocumentIndex?.(facts);
- return documents;
+ const { docs, snapshot } = await loadAgentDocumentIndex(agentId);
+ // The index renders the snapshot, so documents created, edited or
+ // deleted since do not rewrite the prompt prefix behind it; the change
+ // notes (`listAgentDocumentChanges`) tell the model about them.
+ return snapshot ? agentDocumentsFromSnapshot(docs, snapshot) : docs;
},
// Connected = ACTIVE Composio connections across BOTH the legacy plugin
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
index 08bebc699f8..2a057e95021 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
@@ -1,5 +1,5 @@
import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createServerContextFactProviders } from './index';
@@ -62,6 +62,13 @@ vi.mock('@/server/services/agentDocuments', () => ({
getDocumentByFilename = vi.fn();
},
}));
+const { redisIndexGet, redisIndexSet } = vi.hoisted(() => ({
+ redisIndexGet: vi.fn(),
+ redisIndexSet: vi.fn(),
+}));
+vi.mock('@/server/services/redis', () => ({
+ redisService: { agentDocumentIndex: { get: redisIndexGet, set: redisIndexSet } },
+}));
vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test' } }));
vi.mock('@/server/services/market', () => ({
MarketService: class {
@@ -259,9 +266,10 @@ describe('createServerContextFactProviders', () => {
);
});
- // A document the run edits must keep the index row it first had,
- // or the cached conversation behind the index is written to the cache again.
- describe('listAgentDocuments index facts', () => {
+ // Documents changed in an earlier turn must not re-render the index at the
+ // front of the prompt while the cache is warm, or the whole cached
+ // conversation behind it is written to the cache again.
+ describe('agent-document index snapshot', () => {
const reportRow = (contentCharCount: number, updatedAt: string) => ({
content: '',
contentCharCount,
@@ -272,41 +280,107 @@ describe('createServerContextFactProviders', () => {
title: 'Report',
updatedAt: new Date(updatedAt),
});
-
- it('freezes the rows on first sight and hands them to the host', async () => {
- getAgentContextDocuments.mockResolvedValue([reportRow(9400, '2026-05-01T00:00:00.000Z')]);
- const bindAgentDocumentIndex = vi.fn();
- const providers = createServerContextFactProviders({
+ const turn = {
+ cacheTtlMs: 5 * 60 * 1000,
+ messages: [
+ { createdAt: '2026-11-14T10:00:00.000Z', id: 'u1', role: 'user' },
+ { createdAt: '2026-11-14T10:00:30.000Z', id: 'a1', role: 'assistant' },
+ { createdAt: '2026-11-14T10:02:00.000Z', id: 'u2', role: 'user' },
+ ],
+ };
+ const stored = {
+ notes: [],
+ rows: [
+ {
+ contentCharCount: 9400,
+ filename: 'report.md',
+ id: 'agent-doc-1',
+ title: 'Report',
+ updatedAt: '2026-05-01T00:00:00.000Z',
+ },
+ ],
+ takenAt: '2026-11-14T10:00:00.000Z',
+ };
+ const providersFor = (state: Record<string, unknown>, bindAgentDocumentIndex = vi.fn()) =>
+ createServerContextFactProviders({
ctx: { bindAgentDocumentIndex, serverDB: {}, userId: 'owner-1' } as never,
- state: {} as never,
+ documentIndexTurn: turn,
+ state: state as never,
});
- await providers.listAgentDocuments!('agent-1');
-
- expect(bindAgentDocumentIndex).toHaveBeenCalledWith({
- 'agent-doc-1': { contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' },
- });
+ beforeEach(() => {
+ getAgentContextDocuments.mockReset();
+ redisIndexGet.mockReset();
+ redisIndexSet.mockReset();
});
- it('renders an edited document from the facts bound earlier in the run', async () => {
- getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-13T00:10:50.000Z')]);
+ it('continues the stored snapshot on a warm turn and notes the edit on the new user message', async () => {
+ getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ redisIndexGet.mockResolvedValue(stored);
const bindAgentDocumentIndex = vi.fn();
- const providers = createServerContextFactProviders({
- ctx: { bindAgentDocumentIndex, serverDB: {}, userId: 'owner-1' } as never,
- state: {
- binding: {
- agentDocumentIndex: {
- 'agent-doc-1': { contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' },
- },
+ const providers = providersFor({ origin: { topicId: 'topic-1' } }, bindAgentDocumentIndex);
+
+ const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+ const changes = await providers.listAgentDocumentChanges!('agent-1');
+
+ expect(doc).toMatchObject({ contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' });
+ expect(changes).toEqual({
+ u2: [
+ {
+ contentCharCount: 14_100,
+ id: 'agent-doc-1',
+ kind: 'edited',
+ title: 'Report',
+ updatedAt: '2026-11-14T10:00:20.000Z',
},
- } as never,
+ ],
});
+ expect(getAgentContextDocuments).toHaveBeenCalledTimes(1);
+ expect(redisIndexGet).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ threadId: undefined,
+ topicId: 'topic-1',
+ });
+ expect(redisIndexSet).toHaveBeenCalledTimes(1);
+ expect(bindAgentDocumentIndex).toHaveBeenCalledWith(redisIndexSet.mock.calls[0][1]);
+ });
+
+ it('renders later steps from the pinned snapshot without reading the stored one', async () => {
+ getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ const bindAgentDocumentIndex = vi.fn();
+ const providers = providersFor(
+ { binding: { agentDocumentIndex: stored }, origin: { topicId: 'topic-1' } },
+ bindAgentDocumentIndex,
+ );
const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
- expect(doc).toMatchObject({ contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' });
+ expect(doc).toMatchObject({ contentCharCount: 9400 });
+ expect(redisIndexGet).not.toHaveBeenCalled();
+ expect(redisIndexSet).not.toHaveBeenCalled();
expect(bindAgentDocumentIndex).not.toHaveBeenCalled();
});
+
+ it('renders the live documents when the snapshot cannot be resolved', async () => {
+ getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ redisIndexGet.mockRejectedValue(new Error('redis down'));
+ const providers = providersFor({ origin: { topicId: 'topic-1' } });
+
+ const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+
+ expect(doc).toMatchObject({ contentCharCount: 14_100 });
+ expect(await providers.listAgentDocumentChanges!('agent-1')).toBeUndefined();
+ });
+
+ it('renders the live documents for a host that passes no turn', async () => {
+ getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ const providers = createServerContextFactProviders(source());
+
+ const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+
+ expect(doc).toMatchObject({ contentCharCount: 14_100 });
+ expect(redisIndexGet).not.toHaveBeenCalled();
+ });
});
describe('resolveSandboxPersistence', () => {
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
index 6b307883427..dff9004663b 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
@@ -2,6 +2,7 @@
import type {
AgentBuilderContext,
AgentContextDocument,
+ AgentDocumentChangesByMessage,
AgentGroupConfig,
AgentManagementContext,
BotPlatformContext,
@@ -94,6 +95,8 @@ export interface ServerMessagesEngineParams {
attachmentPreviewFileIds?: string[];
/** Agent documents to inject into context based on load rules and positions */
agentDocuments?: AgentContextDocument[];
+ /** Agent-document change notes keyed by the user message each belongs to */
+ agentDocumentChanges?: AgentDocumentChangesByMessage;
/** Immutable expertise captured when the operation started. */
expertise?: ExpertiseContextSnapshot;
/** Whether to inject the operation expertise snapshot. */
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
index bf321a87aa0..af347e02ae9 100644
--- a/apps/server/src/modules/Redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -253,6 +253,12 @@ export const RedisKeys = {
* Lobechat core scope - for application-level caching
*/
lobechat: {
+ /**
+ * The agent-document index snapshot one conversation renders from, and its change notes.
+ * Full key: lobechat:agent_document_index:v1:{topicId}:{threadId|main}:{agentId}
+ */
+ agentDocumentIndex: (topicId: string, threadId: string | undefined, agentId: string): string =>
+ `agent_document_index:v1:${topicId}:${threadId ?? 'main'}:${agentId}`,
/**
* Digest of the body the last projection of a page's collaboration room wrote.
* Full key: lobechat:page_projection:v1:{documentId}
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index ef193319539..70cc9bd3dbf 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -1,5 +1,5 @@
import { type AgentRuntimeContext, getLlmCallCount } from '@lobechat/agent-runtime';
-import type { AgentDocumentIndexFacts } from '@lobechat/context-engine/agent-document';
+import type { AgentDocumentIndexSnapshot } from '@lobechat/context-engine/agent-document';
import { context as otelContext, trace as otelTrace } from '@lobechat/observability-otel/api';
import {
buildInvokeAgentAttributes,
@@ -299,9 +299,9 @@ export async function executeStep(
// hitting Upstash Redis 10MB limit. Bypassing events keeps the heavy
// payload in trace only, reducing per-step Redis state by ~500x.
let contextEnginePayload: { input: unknown; metadata?: unknown; output: unknown } | undefined;
- // Agent-document index facts the step froze, written into the state it
- // saves so the next step renders the same index rows.
- let agentDocumentIndex: AgentDocumentIndexFacts | undefined;
+ // Agent-document index snapshot the step pinned, written into the state
+ // it saves so the next step renders the same index and change notes.
+ let agentDocumentIndex: AgentDocumentIndexSnapshot | undefined;
// Create Agent and Runtime instances
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
@@ -311,8 +311,8 @@ export async function executeStep(
const { runtime } = await deps.createAgentRuntime({
abortSignal: abortPoll.signal,
agentState,
- bindAgentDocumentIndex: (facts) => {
- agentDocumentIndex = facts;
+ bindAgentDocumentIndex: (snapshot) => {
+ agentDocumentIndex = snapshot;
},
operationId,
stepIndex,
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
index 613203e3349..76ac448b26a 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
@@ -65,11 +65,11 @@ beforeEach(() => {
stubRunningDurableOperation();
});
-// The agent-document index rows a step froze must reach the state the
+// The agent-document index snapshot a step pinned must reach the state the
// step saves, or the next step renders the edited document live and rewrites
// the prompt-cache prefix behind the index.
-describe('AgentRuntimeService.executeStep - agent-document index facts', () => {
- it('writes the facts the step bound into binding.agentDocumentIndex', async () => {
+describe('AgentRuntimeService.executeStep - agent-document index snapshot', () => {
+ it('writes the snapshot the step bound into binding.agentDocumentIndex', async () => {
const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
const coordinator = (service as any).coordinator;
const completionLifecycle = (service as any).completionLifecycle;
@@ -91,14 +91,16 @@ describe('AgentRuntimeService.executeStep - agent-document index facts', () => {
savedState = stepResult.newState;
});
- const facts = {
- 'agent-doc-1': { contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' },
+ const snapshot = {
+ notes: [],
+ rows: [{ contentCharCount: 9400, filename: 'report.md', id: 'agent-doc-1' }],
+ takenAt: '2026-05-01T00:00:00.000Z',
};
vi.spyOn(service as any, 'createAgentRuntime').mockImplementation(
async ({ bindAgentDocumentIndex }: any) => ({
runtime: {
step: vi.fn().mockImplementation(async () => {
- bindAgentDocumentIndex(facts);
+ bindAgentDocumentIndex(snapshot);
return { events: [], newState: { ...state, status: 'done', stepCount: 1 } };
}),
},
@@ -115,7 +117,7 @@ describe('AgentRuntimeService.executeStep - agent-document index facts', () => {
});
expect(savedState.binding).toEqual({
- agentDocumentIndex: facts,
+ agentDocumentIndex: snapshot,
device: { id: 'device-1' },
});
});
diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.md
index 9ae78d22de5..5df984195c8 100644
--- a/apps/server/src/services/redis/README.md
+++ b/apps/server/src/services/redis/README.md
@@ -11,6 +11,9 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.
a day. Atomic append (bounded), drain and restore; the runtime drains it into the next turn.
Writes return `undefined` without Redis, and the caller tells the client to send directly.
- `linear`: single-use OAuth state for "Connect Linear" (ten minutes, deleted on first read).
+- `agentDocumentIndex`: the agent-document index snapshot and change notes one conversation
+ (topic/thread/agent) renders from, for a day. `undefined` without Redis; the runtime then
+ takes a fresh snapshot every run.
- `pageCollab`: a digest of the body each page's last room projection wrote, for a day, so the
next projection can tell that something wrote the body outside the room. `null` without Redis.
- `agentSignal`: spend bounds for background self-iteration β€” classifier calls per user per UTC
diff --git a/apps/server/src/services/redis/agentDocumentIndex.ts b/apps/server/src/services/redis/agentDocumentIndex.ts
new file mode 100644
index 00000000000..c3a5d085059
--- /dev/null
+++ b/apps/server/src/services/redis/agentDocumentIndex.ts
@@ -0,0 +1,46 @@
+import { getJSONFromRedis, RedisKeys } from '@/server/modules/Redis';
+
+import { getRedisServiceClient } from './client';
+
+const getClient = () => getRedisServiceClient('lobechat');
+
+/**
+ * The snapshot only saves cache while the provider cache is warm (minutes).
+ * A day leaves room for longer provider TTLs; a lost key only costs one
+ * index refresh on a turn that would usually be cold anyway.
+ */
+const SNAPSHOT_TTL_SECONDS = 24 * 60 * 60;
+
+export interface AgentDocumentIndexScope {
+ agentId: string;
+ threadId?: string;
+ topicId: string;
+}
+
+const keyOf = ({ agentId, threadId, topicId }: AgentDocumentIndexScope) =>
+ RedisKeys.lobechat.agentDocumentIndex(topicId, threadId, agentId);
+
+export const agentDocumentIndex = {
+ /**
+ * The snapshot the conversation's last run rendered its agent-document index
+ * from. `undefined` without Redis, after expiry, or on a read failure: the
+ * caller then takes a fresh snapshot.
+ */
+ async get(scope: AgentDocumentIndexScope): Promise<unknown> {
+ const redis = await getClient();
+ if (!redis) return undefined;
+ try {
+ return (await getJSONFromRedis<unknown>(redis, keyOf(scope))) ?? undefined;
+ } catch {
+ return undefined;
+ }
+ },
+
+ async set(scope: AgentDocumentIndexScope, snapshot: unknown): Promise<void> {
+ const redis = await getClient();
+ if (!redis) return;
+ await redis
+ .set(keyOf(scope), JSON.stringify(snapshot), { ex: SNAPSHOT_TTL_SECONDS })
+ .catch(() => undefined);
+ },
+};
diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.ts
index fee90317152..a7e6c5add44 100644
--- a/apps/server/src/services/redis/index.ts
+++ b/apps/server/src/services/redis/index.ts
@@ -1,3 +1,4 @@
+import { agentDocumentIndex } from './agentDocumentIndex';
import { agentIdentity } from './agentIdentity';
import { agentRunSlots } from './agentRunSlots';
import { agentSignal } from './agentSignal';
@@ -13,6 +14,7 @@ import { workspaceRescan } from './workspaceRescan';
/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */
export const redisService = {
+ agentDocumentIndex,
agentIdentity,
agentRunSlots,
agentSignal,
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 770d2a59354..da6e0dd9988 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,7 +1,7 @@
import type {
ActivatedStepSkill,
ActivatedStepTool,
- AgentDocumentIndexFacts,
+ AgentDocumentIndexSnapshot,
AgentGroupConfig,
BotPlatformContext,
DiscordContext,
@@ -351,12 +351,12 @@ export interface AgentWorldSnapshot {
*/
export interface AgentRunBinding {
/**
- * SIZE / UPDATED of each progressive agent-document index row, as this run
- * first saw it. Steps render the index from here so a document the run edits
- * does not rewrite the prompt prefix behind the index (see
- * `freezeAgentDocumentIndexFacts`). Grows when a new document shows up.
+ * The agent-document index snapshot (rows + change notes) this run renders
+ * from, pinned on its first step so later steps send the same index and
+ * notes (see `resolveAgentDocumentIndex`). Replaced only when the history is
+ * compressed mid-run.
*/
- agentDocumentIndex?: AgentDocumentIndexFacts;
+ agentDocumentIndex?: AgentDocumentIndexSnapshot;
/**
* Device routed for this run. `id` stays absent until a device is bound;
* `systemInfo` may already carry a working directory for runs whose cwd was
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index b23a6cce3b0..b92f4bdd66c 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -36,6 +36,7 @@ import {
AgentAccountContextInjector,
AgentBuilderContextInjector,
AgentDocumentBeforeSystemInjector,
+ AgentDocumentChangesInjector,
AgentDocumentContextInjector,
AgentDocumentMessageInjector,
AgentDocumentSystemAppendInjector,
@@ -199,6 +200,7 @@ export class MessagesEngine {
additionalContexts,
agentGroup,
agentDocuments,
+ agentDocumentChanges,
planTodo,
userMemory,
initialContext,
@@ -455,6 +457,14 @@ export class MessagesEngine {
// Agent documents β†’ after-first-user, context-end
new AgentDocumentMessageInjector(agentDocConfig),
+ // Agent-document change notes β†’ the user message each belongs to (the
+ // index renders a snapshot; these say what changed since). Not gated on
+ // `hasAgentDocuments`: a snapshot taken before the first document has no
+ // rows, and the notes are then the only place new documents appear.
+ new AgentDocumentChangesInjector({
+ changes: agentDocumentChanges,
+ enabled: isAgentMode && !!agentDocumentChanges,
+ }),
// Active topic document β†’ last user message, for continuing document work outside page scope
new ActiveTopicDocumentContextInjector({
activeTopicDocument: initialContext?.activeTopicDocument,
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 28190e7c9c1..e83b7620de9 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -14,7 +14,10 @@ import type { OpenAIChatMessage, UIChatMessage } from '@/types/index';
import type { AgentInfo } from '../../processors/GroupRoleTransform';
import type { AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
-import type { AgentContextDocument } from '../../providers/AgentDocumentInjector';
+import type {
+ AgentContextDocument,
+ AgentDocumentChangesByMessage,
+} from '../../providers/AgentDocumentInjector';
import type { AgentManagementContext } from '../../providers/AgentManagementContextInjector';
import type { BotPlatformContext } from '../../providers/BotPlatformContextInjector';
import type { DiscordContext } from '../../providers/DiscordContextProvider';
@@ -298,6 +301,12 @@ export interface MessagesEngineParams {
knowledge?: KnowledgeConfig;
/** Agent document configuration for context injection */
agentDocuments?: AgentContextDocument[];
+ /**
+ * Agent-document change notes keyed by the user message each belongs to.
+ * The host passes them when `agentDocuments` renders the index from a
+ * snapshot (see `resolveAgentDocumentIndex`).
+ */
+ agentDocumentChanges?: AgentDocumentChangesByMessage;
// ========== Skills ==========
/** Skills configuration */
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index 27610419f1e..6d882ae435a 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -44,6 +44,7 @@ export { planAttachmentPreviews } from './tokenAccounting/attachmentBudget';
export type { PlaceholderValue, PlaceholderValueMap } from './processors';
export {
buildPlaceholderGenerators,
+ cacheEconomicsForProvider,
formatPlaceholderValues,
getSlicedMessages,
GroupMessageFlattenProcessor,
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/ChangesInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/ChangesInjector.ts
new file mode 100644
index 00000000000..4a383626ee3
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/ChangesInjector.ts
@@ -0,0 +1,45 @@
+import debug from 'debug';
+
+import { BaseEveryUserContentProvider } from '../../base/BaseEveryUserContentProvider';
+import type { Message, ProcessorOptions } from '../../types';
+import type { AgentDocumentChangesByMessage } from './indexSnapshot';
+import { formatAgentDocumentChanges } from './indexSnapshot';
+
+const log = debug('context-engine:provider:AgentDocumentChangesInjector');
+
+export interface AgentDocumentChangesInjectorConfig {
+ /** Change notes keyed by the user message each was attached to. */
+ changes?: AgentDocumentChangesByMessage;
+ enabled?: boolean;
+}
+
+/**
+ * Attaches each agent-document change note to the user message it belongs to.
+ *
+ * The `<agent_documents_index>` block renders a snapshot that stays fixed while
+ * the prompt cache is warm (see `resolveAgentDocumentIndex`); these notes tell
+ * the model what changed since. Every note stays on its own message and renders
+ * the same on every later request, so earlier turns keep their cached bytes.
+ */
+export class AgentDocumentChangesInjector extends BaseEveryUserContentProvider {
+ readonly name = 'AgentDocumentChangesInjector';
+
+ constructor(
+ private config: AgentDocumentChangesInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected buildContentForMessage(
+ message: Message,
+ ): { content: string; contextType: string } | null {
+ if (this.config.enabled === false || !message.id) return null;
+
+ const changes = this.config.changes?.[message.id];
+ if (!changes || changes.length === 0) return null;
+
+ log('Attaching %d agent-document changes to message %s', changes.length, message.id);
+ return { content: formatAgentDocumentChanges(changes), contextType: 'agent_documents_changes' };
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
index d5f6b45378e..ee61ef63c38 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
@@ -1,5 +1,7 @@
export type { AgentDocumentBeforeSystemInjectorConfig } from './BeforeSystemInjector';
export { AgentDocumentBeforeSystemInjector } from './BeforeSystemInjector';
+export type { AgentDocumentChangesInjectorConfig } from './ChangesInjector';
+export { AgentDocumentChangesInjector } from './ChangesInjector';
export type { AgentDocumentContextInjectorConfig } from './ContextInjector';
export { AgentDocumentContextInjector } from './ContextInjector';
export type { AgentDocumentMessageInjectorConfig } from './MessageInjector';
@@ -7,19 +9,31 @@ export { AgentDocumentMessageInjector } from './MessageInjector';
export {
AGENT_DOCUMENT_INJECTION_POSITIONS,
type AgentContextDocument,
+ type AgentDocumentChange,
+ type AgentDocumentChangeKind,
+ type AgentDocumentChangesByMessage,
+ agentDocumentChangesByMessage,
type AgentDocumentFilterContext,
- type AgentDocumentIndexFact,
- type AgentDocumentIndexFacts,
+ type AgentDocumentIndexNote,
+ type AgentDocumentIndexRow,
+ type AgentDocumentIndexSnapshot,
type AgentDocumentInjectionPosition,
type AgentDocumentLoadFormat,
type AgentDocumentLoadRule,
type AgentDocumentLoadRules,
+ agentDocumentsFromSnapshot,
combineDocuments,
+ diffAgentDocumentIndex,
filterDocumentsByRules,
+ formatAgentDocumentChanges,
formatDocument,
- freezeAgentDocumentIndexFacts,
getDocumentsForPositions,
+ noteAgentDocumentChanges,
+ resolveAgentDocumentIndex,
+ type ResolveAgentDocumentIndexInput,
+ type ResolvedAgentDocumentIndex,
sortByPriority,
+ takeAgentDocumentIndexSnapshot,
withRunStartedAt,
} from './shared';
export type { AgentDocumentSystemAppendInjectorConfig } from './SystemAppendInjector';
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts b/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts
new file mode 100644
index 00000000000..56a18c58f2c
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts
@@ -0,0 +1,477 @@
+import type { AgentContextDocument } from './shared';
+
+/**
+ * Keeping the `<agent_documents_index>` block byte-stable across turns.
+ *
+ * The index sits at the very front of the prompt, so any change to it rewrites
+ * the provider prompt cache for the whole conversation behind it. Documents do
+ * change between turns (the agent creates, edits and deletes them), so instead
+ * of rendering the live list, the index renders a snapshot taken once, and
+ * what changed since is told to the model as a note on the user message that
+ * started the turn:
+ *
+ * index (front) ← snapshot rows only, never rewritten while the cache is warm
+ * user msg #2 ← <agent_documents_changes> created "Plan"
+ * user msg #3 ← <agent_documents_changes> created "Plan", edited "Notes"
+ *
+ * A note is computed once when its turn starts and is replayed verbatim on
+ * later turns, so the tail stays stable too. The snapshot is refreshed (and
+ * the notes dropped) only where the cache is cold anyway: the first turn, a
+ * gap longer than the cache TTL, or a history compression.
+ */
+
+/** One progressive-index row as the snapshot saw it: everything needed to render it again. */
+export interface AgentDocumentIndexRow {
+ contentCharCount: number;
+ filename: string;
+ folderTitle?: string;
+ id: string;
+ loadPosition?: AgentContextDocument['loadPosition'];
+ loadRules?: AgentContextDocument['loadRules'];
+ parentId?: string | null;
+ parentKind?: AgentContextDocument['parentKind'];
+ sourceType?: AgentContextDocument['sourceType'];
+ title?: string;
+ /** ISO timestamp; absent when the document had none. */
+ updatedAt?: string;
+}
+
+export type AgentDocumentChangeKind = 'created' | 'deleted' | 'edited';
+
+/** How one document differs from its snapshot row, as of the turn the note belongs to. */
+export interface AgentDocumentChange {
+ /** Current size; absent for a deleted document. */
+ contentCharCount?: number;
+ folderTitle?: string;
+ id: string;
+ kind: AgentDocumentChangeKind;
+ title: string;
+ /** Current ISO timestamp; absent for a deleted document. */
+ updatedAt?: string;
+}
+
+/** The changes noted on one user message. */
+export interface AgentDocumentIndexNote {
+ changes: AgentDocumentChange[];
+ messageId: string;
+}
+
+export interface AgentDocumentIndexSnapshot {
+ /**
+ * Id of the newest compressed-history message when the snapshot was taken.
+ * A compression rewrites the prompt anyway, so a different id refreshes it.
+ */
+ compressionId?: string;
+ /** Change notes in turn order. Each is replayed on its user message. */
+ notes: AgentDocumentIndexNote[];
+ rows: AgentDocumentIndexRow[];
+ /** ISO timestamp of when the rows were taken. */
+ takenAt: string;
+}
+
+/** Changes keyed by the id of the user message they are attached to. */
+export type AgentDocumentChangesByMessage = Record<string, AgentDocumentChange[]>;
+
+const isProgressive = (doc: AgentContextDocument) =>
+ (doc.policyLoad ?? 'progressive') === 'progressive';
+
+/** The index hides web-crawled documents behind a hint, so their changes are not noted either. */
+const isListed = (doc: { sourceType?: AgentContextDocument['sourceType'] }) =>
+ doc.sourceType !== 'web';
+
+const toIsoTimestamp = (at: Date | string | undefined): string | undefined => {
+ if (!at) return undefined;
+ const date = typeof at === 'string' ? new Date(at) : at;
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+};
+
+const sizeOf = (doc: AgentContextDocument) => doc.contentCharCount ?? doc.content?.length ?? 0;
+
+const titleOf = (doc: { filename?: string; title?: string }) =>
+ doc.title || doc.filename || '(untitled)';
+
+const toRow = (doc: AgentContextDocument & { id: string }): AgentDocumentIndexRow => {
+ const updatedAt = toIsoTimestamp(doc.updatedAt);
+ return {
+ contentCharCount: sizeOf(doc),
+ filename: doc.filename,
+ id: doc.id,
+ ...(doc.folderTitle && { folderTitle: doc.folderTitle }),
+ ...(doc.loadPosition && { loadPosition: doc.loadPosition }),
+ ...(doc.loadRules && { loadRules: doc.loadRules }),
+ ...(doc.parentId && { parentId: doc.parentId }),
+ ...(doc.parentKind && { parentKind: doc.parentKind }),
+ ...(doc.sourceType && { sourceType: doc.sourceType }),
+ ...(doc.title && { title: doc.title }),
+ ...(updatedAt && { updatedAt }),
+ };
+};
+
+const indexedDocs = (docs: AgentContextDocument[]) =>
+ docs.filter(
+ (doc): doc is AgentContextDocument & { id: string } => !!doc.id && isProgressive(doc),
+ );
+
+export function takeAgentDocumentIndexSnapshot(
+ docs: AgentContextDocument[],
+ { compressionId, takenAt }: { compressionId?: string; takenAt: Date },
+): AgentDocumentIndexSnapshot {
+ return {
+ ...(compressionId && { compressionId }),
+ notes: [],
+ rows: indexedDocs(docs).map(toRow),
+ takenAt: takenAt.toISOString(),
+ };
+}
+
+/**
+ * Every listed document that differs from its snapshot row: created since,
+ * edited since (size, date, title or folder changed), or deleted since. Cumulative β€”
+ * a note always states the full difference, so a reader that only sees the
+ * newest note (older ones truncated away) still has the whole picture.
+ */
+export function diffAgentDocumentIndex(
+ rows: AgentDocumentIndexRow[],
+ docs: AgentContextDocument[],
+): AgentDocumentChange[] {
+ const live = new Map(indexedDocs(docs).map((doc) => [doc.id, doc]));
+ const changes: AgentDocumentChange[] = [];
+
+ for (const row of rows) {
+ if (!isListed(row)) continue;
+ const doc = live.get(row.id);
+ if (!doc) {
+ changes.push({
+ id: row.id,
+ kind: 'deleted',
+ title: titleOf(row),
+ ...(row.folderTitle && { folderTitle: row.folderTitle }),
+ });
+ continue;
+ }
+ const current = toRow(doc);
+ if (
+ current.contentCharCount !== row.contentCharCount ||
+ current.updatedAt !== row.updatedAt ||
+ titleOf(current) !== titleOf(row) ||
+ // A move changes neither the timestamp nor the size, but a folded folder
+ // in the index would keep pointing at the old parent.
+ (current.parentId ?? null) !== (row.parentId ?? null) ||
+ current.folderTitle !== row.folderTitle
+ ) {
+ changes.push(toChange(current, 'edited'));
+ }
+ }
+
+ const known = new Set(rows.map((row) => row.id));
+ for (const doc of live.values()) {
+ if (!known.has(doc.id) && isListed(doc)) changes.push(toChange(toRow(doc), 'created'));
+ }
+
+ return changes;
+}
+
+const toChange = (
+ row: AgentDocumentIndexRow,
+ kind: AgentDocumentChangeKind,
+): AgentDocumentChange => ({
+ contentCharCount: row.contentCharCount,
+ id: row.id,
+ kind,
+ title: titleOf(row),
+ ...(row.folderTitle && { folderTitle: row.folderTitle }),
+ ...(row.updatedAt && { updatedAt: row.updatedAt }),
+});
+
+/**
+ * Documents an earlier note reported as created that no longer exist. The
+ * snapshot rows never had them, so the row diff alone would leave the model
+ * with the old "created" note and no word that they are gone.
+ */
+const deletedSinceNoted = (
+ snapshot: AgentDocumentIndexSnapshot,
+ docs: AgentContextDocument[],
+): AgentDocumentChange[] => {
+ const live = new Set(indexedDocs(docs).map((doc) => doc.id));
+ const inRows = new Set(snapshot.rows.map((row) => row.id));
+ const deleted = new Map<string, AgentDocumentChange>();
+ for (const note of snapshot.notes) {
+ for (const change of note.changes) {
+ if (change.kind !== 'created' || live.has(change.id) || inRows.has(change.id)) continue;
+ deleted.set(change.id, {
+ id: change.id,
+ kind: 'deleted',
+ title: change.title,
+ ...(change.folderTitle && { folderTitle: change.folderTitle }),
+ });
+ }
+ }
+ return [...deleted.values()];
+};
+
+/**
+ * Documents an earlier note reported as edited that now match their snapshot
+ * row again (renamed back, say). The row diff no longer lists them, so without
+ * this the earlier note β€” which overrides the index β€” would stay the last word.
+ */
+const revertedSinceNoted = (
+ snapshot: AgentDocumentIndexSnapshot,
+ docs: AgentContextDocument[],
+ diffed: AgentDocumentChange[],
+): AgentDocumentChange[] => {
+ const live = new Map(indexedDocs(docs).map((doc) => [doc.id, doc]));
+ const inDiff = new Set(diffed.map((change) => change.id));
+ const reverted = new Map<string, AgentDocumentChange>();
+ for (const note of snapshot.notes) {
+ for (const change of note.changes) {
+ const doc = live.get(change.id);
+ if (change.kind !== 'edited' || !doc || inDiff.has(change.id)) continue;
+ reverted.set(change.id, toChange(toRow(doc), 'edited'));
+ }
+ }
+ return [...reverted.values()];
+};
+
+const sameChanges = (a: AgentDocumentChange[], b: AgentDocumentChange[]) =>
+ JSON.stringify(a) === JSON.stringify(b);
+
+/**
+ * Note on `messageId` how the documents differ from the snapshot, once.
+ *
+ * - A message that already has a note keeps it (a retried step or a
+ * regenerated reply replays the same note).
+ * - No note is added when nothing changed, or when the difference equals the
+ * newest note still in the conversation β€” that note already says it.
+ *
+ * @returns the same snapshot object when nothing was added.
+ */
+export function noteAgentDocumentChanges(
+ snapshot: AgentDocumentIndexSnapshot,
+ docs: AgentContextDocument[],
+ { messageId, presentMessageIds }: { messageId: string; presentMessageIds: Set<string> },
+): AgentDocumentIndexSnapshot {
+ if (snapshot.notes.some((note) => note.messageId === messageId)) return snapshot;
+
+ const diffed = [
+ ...diffAgentDocumentIndex(snapshot.rows, docs),
+ ...deletedSinceNoted(snapshot, docs),
+ ];
+ const changes = [...diffed, ...revertedSinceNoted(snapshot, docs, diffed)];
+ if (changes.length === 0) return snapshot;
+
+ const newestPresent = snapshot.notes.findLast((note) => presentMessageIds.has(note.messageId));
+ if (newestPresent && sameChanges(newestPresent.changes, changes)) return snapshot;
+
+ return { ...snapshot, notes: [...snapshot.notes, { changes, messageId }] };
+}
+
+/**
+ * The documents the index renders from: snapshot rows in place of the live
+ * progressive documents β€” a deleted document keeps its row, a newer one has
+ * none β€” and every other live document (`always` content) unchanged.
+ */
+export function agentDocumentsFromSnapshot(
+ docs: AgentContextDocument[],
+ snapshot: AgentDocumentIndexSnapshot,
+): AgentContextDocument[] {
+ const others = docs.filter((doc) => !doc.id || !isProgressive(doc));
+ // `createdAt` is left out on purpose: no snapshot row is "new since the last
+ // user message", so the index never carries that marker and never drops it.
+ const rows = snapshot.rows.map((row): AgentContextDocument => ({
+ ...row,
+ policyLoad: 'progressive',
+ }));
+ return [...others, ...rows];
+}
+
+export const agentDocumentChangesByMessage = (
+ snapshot: AgentDocumentIndexSnapshot,
+): AgentDocumentChangesByMessage | undefined =>
+ snapshot.notes.length > 0
+ ? Object.fromEntries(snapshot.notes.map((note) => [note.messageId, note.changes]))
+ : undefined;
+
+const isSnapshot = (value: unknown): value is AgentDocumentIndexSnapshot =>
+ !!value &&
+ typeof value === 'object' &&
+ Array.isArray((value as AgentDocumentIndexSnapshot).rows) &&
+ Array.isArray((value as AgentDocumentIndexSnapshot).notes) &&
+ typeof (value as AgentDocumentIndexSnapshot).takenAt === 'string';
+
+interface TurnMessage {
+ createdAt?: Date | number | string;
+ id?: string;
+ role: string;
+}
+
+const toEpochMs = (value: TurnMessage['createdAt']): number | undefined => {
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ if (value instanceof Date) return value.getTime();
+ if (typeof value === 'string') {
+ const time = Date.parse(value);
+ return Number.isFinite(time) ? time : undefined;
+ }
+ return undefined;
+};
+
+export interface ResolveAgentDocumentIndexInput {
+ /**
+ * How long the provider keeps a prompt cache. A turn whose user message came
+ * later than this after the previous message starts cold, so the snapshot is
+ * refreshed for free. Same test as `StaleToolResultTrimProcessor`.
+ */
+ cacheTtlMs: number;
+ /** Live documents of the agent. */
+ docs: AgentContextDocument[];
+ /** The conversation the step runs on. */
+ messages: TurnMessage[];
+ now: Date;
+ /** The snapshot this run already pinned (absent on the run's first step). */
+ pinned?: unknown;
+ /** The snapshot kept for the conversation between runs. */
+ stored?: unknown;
+ /**
+ * The messages the model will actually see, after history truncation. A note
+ * only counts as already shown while its message is among them. Defaults to
+ * `messages`.
+ */
+ visibleMessages?: TurnMessage[];
+}
+
+export interface ResolvedAgentDocumentIndex {
+ /** The run has not pinned this snapshot yet: pin it for its next steps. */
+ pin: boolean;
+ /** What the index and the change notes render from. */
+ snapshot: AgentDocumentIndexSnapshot;
+ /** The snapshot differs from the stored one: keep it for the next run. */
+ store: boolean;
+}
+
+/**
+ * Pick the snapshot a step renders from.
+ *
+ * - Later steps of a run reuse the one the run pinned, so nothing moves mid-run;
+ * documents the run itself creates or edits are seen through tool results.
+ * - A run's first step continues the stored snapshot while the cache can
+ * still be warm, noting this turn's difference on its user message.
+ * - Otherwise (no stored snapshot, a cold gap, or a new compression β€” also
+ * mid-run) a fresh snapshot is taken and the old notes go with the old one.
+ */
+export function resolveAgentDocumentIndex({
+ cacheTtlMs,
+ docs,
+ messages,
+ now,
+ pinned,
+ stored,
+ visibleMessages = messages,
+}: ResolveAgentDocumentIndexInput): ResolvedAgentDocumentIndex {
+ const compressionId = messages.findLast((m) => m.role === 'compressedGroup')?.id;
+
+ if (isSnapshot(pinned) && pinned.compressionId === compressionId) {
+ return { pin: false, snapshot: pinned, store: false };
+ }
+
+ const lastUserIndex = messages.findLastIndex((m) => m.role === 'user');
+ const lastUser = messages[lastUserIndex];
+ const triggeredAt = toEpochMs(lastUser?.createdAt);
+ const previousAt = toEpochMs(messages[lastUserIndex - 1]?.createdAt);
+ const warm =
+ triggeredAt !== undefined && previousAt !== undefined && triggeredAt - previousAt <= cacheTtlMs;
+
+ if (
+ !pinned &&
+ warm &&
+ lastUser?.id &&
+ isSnapshot(stored) &&
+ stored.compressionId === compressionId
+ ) {
+ const presentMessageIds = new Set(visibleMessages.flatMap((m) => (m.id ? [m.id] : [])));
+ const snapshot = noteAgentDocumentChanges(stored, docs, {
+ messageId: lastUser.id,
+ presentMessageIds,
+ });
+ return { pin: true, snapshot, store: snapshot !== stored };
+ }
+
+ return {
+ pin: true,
+ snapshot: takeAgentDocumentIndexSnapshot(docs, { compressionId, takenAt: now }),
+ store: true,
+ };
+}
+
+const formatChangeSize = (length: number | undefined): string => {
+ if (length === undefined) return 'β€”';
+ if (length === 0) return 'empty';
+ if (length < 1000) return String(length);
+ if (length < 10_000) return `${(length / 1000).toFixed(1)}k`;
+ if (length < 1_000_000) return `${Math.round(length / 1000)}k`;
+ return `${(length / 1_000_000).toFixed(1)}M`;
+};
+
+const CHANGE_LABEL: Record<AgentDocumentChangeKind, string> = {
+ created: 'created',
+ deleted: 'deleted',
+ edited: 'edited',
+};
+
+/**
+ * Render a note as a fixed-width table, in the same columns as the index:
+ *
+ * CHANGE TITLE ID SIZE UPDATED
+ * created Launch plan 9c1f… 2.3k 2026-11-14
+ * deleted Old draft 4be2… β€” β€”
+ */
+export function formatAgentDocumentChanges(changes: AgentDocumentChange[]): string {
+ const rows = changes.map((change) => ({
+ change: CHANGE_LABEL[change.kind],
+ id: change.id,
+ size: change.kind === 'deleted' ? 'β€”' : formatChangeSize(change.contentCharCount),
+ title: change.folderTitle ? `${change.title} (in ${change.folderTitle})` : change.title,
+ updated: change.kind === 'deleted' ? 'β€”' : (change.updatedAt?.slice(0, 10) ?? 'β€”'),
+ }));
+
+ const width = (header: string, values: string[]) =>
+ Math.max(header.length, ...values.map((value) => value.length));
+ const changeWidth = width(
+ 'CHANGE',
+ rows.map((r) => r.change),
+ );
+ const titleWidth = width(
+ 'TITLE',
+ rows.map((r) => r.title),
+ );
+ const idWidth = width(
+ 'ID',
+ rows.map((r) => r.id),
+ );
+ const sizeWidth = width(
+ 'SIZE',
+ rows.map((r) => r.size),
+ );
+
+ const line = (cells: [string, string, string, string, string]) =>
+ [
+ cells[0].padEnd(changeWidth),
+ cells[1].padEnd(titleWidth),
+ cells[2].padEnd(idWidth),
+ cells[3].padEnd(sizeWidth),
+ cells[4],
+ ].join(' ');
+
+ const hasDeleted = changes.some((change) => change.kind === 'deleted');
+ const hasEdited = changes.some((change) => change.kind === 'edited');
+ return [
+ 'Agent documents changed since <agent_documents_index> was listed. The index is not refreshed; for these documents this table is current' +
+ (hasDeleted ? ', and deleted ones no longer exist β€” do not read them.' : '.') +
+ // gpt-5.4-mini kept answering from a stale earlier read of an edited document
+ // until it was told so explicitly (agent-document-index-ab eval).
+ (hasEdited
+ ? ' Content read earlier from an edited document is outdated; read it again before using it.'
+ : ''),
+ '',
+ line(['CHANGE', 'TITLE', 'ID', 'SIZE', 'UPDATED']),
+ ...rows.map((r) => line([r.change, r.title, r.id, r.size, r.updated])),
+ ].join('\n');
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
index a31a5a5b57f..c0e280606be 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
@@ -9,6 +9,8 @@ import { matchesLoadRules } from '../../policies/agentDocumentLoadPolicy';
export type { AgentDocumentLoadRule, AgentDocumentLoadRules };
export type { AgentDocumentPolicyLoad };
+export * from './indexSnapshot';
+
export const AGENT_DOCUMENT_INJECTION_POSITIONS = [
'after-first-user',
'before-first-user',
@@ -95,70 +97,6 @@ export function withRunStartedAt<T extends AgentDocumentFilterContext>(
: { ...context, runStartedAt: lastUserMessage.createdAt };
}
-/** The values one progressive-index row shows for a document. */
-export interface AgentDocumentIndexFact {
- contentCharCount: number;
- /** ISO timestamp; absent when the document had none. */
- updatedAt?: string;
-}
-
-/** Progressive-index facts keyed by document id, as one run first saw them. */
-export type AgentDocumentIndexFacts = Record<string, AgentDocumentIndexFact>;
-
-const isProgressive = (doc: AgentContextDocument) =>
- (doc.policyLoad ?? 'progressive') === 'progressive';
-
-const toIsoTimestamp = (at: Date | string | undefined): string | undefined => {
- if (!at) return undefined;
- const date = typeof at === 'string' ? new Date(at) : at;
- return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
-};
-
-/**
- * Pin the SIZE / UPDATED values (and the recency order derived from them) of
- * progressive-index rows to what the run first saw.
- *
- * The `<agent_documents_index>` block sits at the very front of the prompt and
- * is rebuilt every step. When the agent edits one of its own documents
- * mid-run, the row's size and date change, so every cached token behind the
- * block is written again β€” on a long conversation one `modifyNodes` re-writes
- * the whole cached history. The index is only a directory β€”
- * the edit itself is visible to the model through the tool result β€” so the row
- * may lag behind until the next run.
- *
- * Only these display facts are pinned. The document list stays live (new and
- * deleted documents still show), and `always` documents keep their current
- * content. A document first seen mid-run is frozen from that step on.
- *
- * @returns the documents to render, and `facts` (the input plus every newly
- * seen document) when it grew β€” the host persists it for the next step.
- */
-export function freezeAgentDocumentIndexFacts(
- docs: AgentContextDocument[],
- frozen: AgentDocumentIndexFacts | undefined,
-): { documents: AgentContextDocument[]; facts?: AgentDocumentIndexFacts } {
- let added: AgentDocumentIndexFacts | undefined;
-
- const documents = docs.map((doc) => {
- if (!doc.id || !isProgressive(doc)) return doc;
-
- const fact = frozen?.[doc.id];
- if (fact) {
- return { ...doc, contentCharCount: fact.contentCharCount, updatedAt: fact.updatedAt };
- }
-
- added ??= {};
- const updatedAt = toIsoTimestamp(doc.updatedAt);
- added[doc.id] = {
- contentCharCount: doc.contentCharCount ?? doc.content?.length ?? 0,
- ...(updatedAt && { updatedAt }),
- };
- return doc;
- });
-
- return { documents, ...(added && { facts: { ...frozen, ...added } }) };
-}
-
/**
* Filter documents by load rules (always, by-keywords, by-regexp, by-time-range)
*/
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentIndexFacts.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexFacts.test.ts
deleted file mode 100644
index 52b38ee93bf..00000000000
--- a/packages/context-engine/src/providers/__tests__/AgentDocumentIndexFacts.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { PipelineContext } from '../../types';
-import type { AgentContextDocument, AgentDocumentIndexFacts } from '../AgentDocumentInjector';
-import {
- AgentDocumentContextInjector,
- freezeAgentDocumentIndexFacts,
-} from '../AgentDocumentInjector';
-
-const REPORT_ID = '2af6eb88-8bdb-468f-887f-620baa394efa';
-const OLDER_ID = '32e12975-7db2-4818-8415-9b5c3d383f05';
-
-const progressiveDoc = (doc: Partial<AgentContextDocument> & { id: string }) =>
- ({
- filename: `${doc.id}.md`,
- loadPosition: 'before-first-user',
- loadRules: { rule: 'always' },
- policyLoad: 'progressive',
- sourceType: 'agent',
- ...doc,
- }) as AgentContextDocument;
-
-/** The documents as the run's first step saw them. */
-const beforeEdit = (): AgentContextDocument[] => [
- progressiveDoc({
- contentCharCount: 13_200,
- id: OLDER_ID,
- title: 'Weekly notes',
- updatedAt: new Date('2026-05-28T00:00:00.000Z'),
- }),
- progressiveDoc({
- contentCharCount: 9_400,
- id: REPORT_ID,
- title: 'Draft report',
- updatedAt: new Date('2026-05-01T00:00:00.000Z'),
- }),
-];
-
-/** The same documents after the agent's `modifyNodes` grew and touched the report. */
-const afterEdit = (): AgentContextDocument[] => [
- beforeEdit()[0],
- progressiveDoc({
- contentCharCount: 14_100,
- id: REPORT_ID,
- title: 'Draft report',
- updatedAt: new Date('2026-11-13T00:10:50.000Z'),
- }),
-];
-
-const renderIndex = async (documents: AgentContextDocument[]) => {
- const context: PipelineContext = {
- initialState: { messages: [], model: 'claude-sonnet-5-5', provider: 'lobehub' },
- isAborted: false,
- messages: [
- {
- content: 'Fix the table',
- createdAt: '2026-11-13T00:10:20.000Z',
- id: 'user-1',
- role: 'user',
- },
- ],
- metadata: { maxTokens: 4096, model: 'claude-sonnet-5-5' },
- };
- const result = await new AgentDocumentContextInjector({ documents }).process(context);
- return result.messages[0].content as string;
-};
-
-describe('freezeAgentDocumentIndexFacts', () => {
- // Regression: the index sits at the front of the prompt. A document the run
- // edited changed its SIZE / UPDATED (and moved to the top by recency), so the
- // whole cached conversation behind it was written to the cache again.
- it('keeps the index byte-identical after the run edits a document', async () => {
- const first = freezeAgentDocumentIndexFacts(beforeEdit(), undefined);
- const firstIndex = await renderIndex(first.documents);
- // Rendered live, the edit changes the row (14k, 2026-11-13, first row).
- expect(await renderIndex(afterEdit())).not.toBe(firstIndex);
-
- const next = freezeAgentDocumentIndexFacts(afterEdit(), first.facts);
-
- expect(await renderIndex(next.documents)).toBe(firstIndex);
- expect(firstIndex).toContain('9.4k');
- expect(next.facts).toBeUndefined();
- });
-
- it('records every progressive document on first sight', () => {
- const { documents, facts } = freezeAgentDocumentIndexFacts(beforeEdit(), undefined);
-
- expect(documents).toEqual(beforeEdit());
- expect(facts).toEqual({
- [OLDER_ID]: { contentCharCount: 13_200, updatedAt: '2026-05-28T00:00:00.000Z' },
- [REPORT_ID]: { contentCharCount: 9_400, updatedAt: '2026-05-01T00:00:00.000Z' },
- });
- });
-
- it('adds a document first seen mid-run and keeps the frozen rows', () => {
- const frozen: AgentDocumentIndexFacts = {
- [REPORT_ID]: { contentCharCount: 9_400, updatedAt: '2026-05-01T00:00:00.000Z' },
- };
- const created = progressiveDoc({
- content: 'new notes',
- id: 'new-doc',
- title: 'Notes',
- updatedAt: '2026-11-13T00:11:00.000Z',
- });
-
- const { documents, facts } = freezeAgentDocumentIndexFacts([afterEdit()[1], created], frozen);
-
- expect(documents[0]).toMatchObject({
- contentCharCount: 9_400,
- updatedAt: '2026-05-01T00:00:00.000Z',
- });
- expect(documents[1]).toBe(created);
- expect(facts).toEqual({
- ...frozen,
- 'new-doc': { contentCharCount: 9, updatedAt: '2026-11-13T00:11:00.000Z' },
- });
- });
-
- it('leaves always-loaded documents live so their content stays current', () => {
- const inline = progressiveDoc({
- content: 'edited rules',
- id: 'rules',
- policyLoad: 'always',
- updatedAt: '2026-11-13T00:11:00.000Z',
- });
-
- const { documents, facts } = freezeAgentDocumentIndexFacts([inline], {
- rules: { contentCharCount: 3, updatedAt: '2026-01-01T00:00:00.000Z' },
- });
-
- expect(documents[0]).toBe(inline);
- expect(facts).toBeUndefined();
- });
-});
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts
new file mode 100644
index 00000000000..1107f195622
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts
@@ -0,0 +1,371 @@
+import { describe, expect, it } from 'vitest';
+
+import { MessagesEngine } from '../../engine/messages/MessagesEngine';
+import { getSlicedMessages } from '../../processors/HistoryTruncate';
+import type { UIChatMessage } from '../../types';
+import type { AgentContextDocument, AgentDocumentIndexSnapshot } from '../AgentDocumentInjector';
+import {
+ agentDocumentChangesByMessage,
+ agentDocumentsFromSnapshot,
+ diffAgentDocumentIndex,
+ formatAgentDocumentChanges,
+ noteAgentDocumentChanges,
+ resolveAgentDocumentIndex,
+ takeAgentDocumentIndexSnapshot,
+} from '../AgentDocumentInjector';
+
+const REPORT_ID = '2af6eb88-8bdb-468f-887f-620baa394efa';
+const NOTES_ID = '32e12975-7db2-4818-8415-9b5c3d383f05';
+const PLAN_ID = '9c1f0d4e-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
+const TTL = 5 * 60 * 1000;
+
+const progressiveDoc = (doc: Partial<AgentContextDocument> & { id: string }) =>
+ ({
+ filename: `${doc.id}.md`,
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ policyLoad: 'progressive',
+ sourceType: 'agent',
+ ...doc,
+ }) as AgentContextDocument;
+
+const report = (size = 9_400, updatedAt = '2026-05-01T00:00:00.000Z') =>
+ progressiveDoc({ contentCharCount: size, id: REPORT_ID, title: 'Draft report', updatedAt });
+const notes = () =>
+ progressiveDoc({
+ contentCharCount: 13_200,
+ id: NOTES_ID,
+ title: 'Weekly notes',
+ updatedAt: '2026-05-28T00:00:00.000Z',
+ });
+const plan = () =>
+ progressiveDoc({
+ contentCharCount: 2_300,
+ createdAt: '2026-11-14T10:01:30.000Z',
+ id: PLAN_ID,
+ title: 'Launch plan',
+ updatedAt: '2026-11-14T10:01:30.000Z',
+ });
+
+const at = (minute: number, second = 0) =>
+ `2026-11-14T10:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}.000Z`;
+
+const user = (id: string, createdAt: string, content = id): UIChatMessage =>
+ ({ content, createdAt, id, role: 'user', updatedAt: createdAt }) as UIChatMessage;
+const assistant = (id: string, createdAt: string): UIChatMessage =>
+ ({
+ content: `reply ${id}`,
+ createdAt,
+ id,
+ role: 'assistant',
+ updatedAt: createdAt,
+ }) as UIChatMessage;
+
+/** What the server host does per step: resolve the snapshot, then run the engine on it. */
+const runTurn = async (
+ docs: AgentContextDocument[],
+ messages: UIChatMessage[],
+ stored?: AgentDocumentIndexSnapshot,
+ history: { enableHistoryCount?: boolean; historyCount?: number } = {},
+) => {
+ const { snapshot } = resolveAgentDocumentIndex({
+ cacheTtlMs: TTL,
+ docs,
+ messages,
+ now: new Date(messages.at(-1)!.createdAt as unknown as string),
+ stored,
+ visibleMessages: getSlicedMessages(messages, history),
+ });
+ const result = await new MessagesEngine({
+ agentDocumentChanges: agentDocumentChangesByMessage(snapshot),
+ agentDocuments: agentDocumentsFromSnapshot(docs, snapshot),
+ enableSystemDate: false,
+ ...history,
+ messages,
+ model: 'claude-sonnet-5-5',
+ provider: 'anthropic',
+ }).process();
+ return { payload: result.messages, snapshot };
+};
+
+const turn1 = [user('u1', at(0))];
+const turn2 = [...turn1, assistant('a1', at(0, 30)), user('u2', at(2))];
+const turn3 = [...turn2, assistant('a2', at(2, 30)), user('u3', at(4))];
+
+describe('agent-document index snapshot', () => {
+ // Regression: the index sits at the front of the prompt. A document created,
+ // edited or deleted in an earlier turn re-rendered it, so the whole cached
+ // conversation behind it was written to the cache again on the next turn.
+ it('keeps every earlier message byte-identical while documents change between warm turns', async () => {
+ const first = await runTurn([report(), notes()], turn1);
+ // Turn 1 created a plan and edited the report.
+ const second = await runTurn(
+ [report(14_100, at(0, 20)), notes(), plan()],
+ turn2,
+ first.snapshot,
+ );
+ // Turn 2 deleted the weekly notes.
+ const third = await runTurn([report(14_100, at(0, 20)), plan()], turn3, second.snapshot);
+
+ // Rendered from the live documents, turn 2 rewrites the index at the front.
+ const live = await new MessagesEngine({
+ agentDocuments: [report(14_100, at(0, 20)), notes(), plan()],
+ enableSystemDate: false,
+ messages: turn2,
+ model: 'claude-sonnet-5-5',
+ provider: 'anthropic',
+ }).process();
+ expect(live.messages[0]).not.toEqual(first.payload[0]);
+
+ expect(second.payload.slice(0, first.payload.length)).toEqual(first.payload);
+ expect(third.payload.slice(0, second.payload.length)).toEqual(second.payload);
+
+ const index = JSON.stringify(first.payload[0].content);
+ expect(index).toContain('9.4k');
+ expect(index).not.toContain('Launch plan');
+
+ const lastContent = (payload: typeof first.payload) => payload.at(-1)!.content as string;
+ expect(lastContent(second.payload)).toContain('<agent_documents_changes>');
+ expect(lastContent(second.payload)).toMatch(/created\s+Launch plan/);
+ expect(lastContent(second.payload)).toMatch(/edited\s+Draft report\s+\S+\s+14k/);
+ expect(lastContent(second.payload)).toContain('read it again before using it');
+ expect(lastContent(third.payload)).toMatch(/deleted\s+Weekly notes/);
+ expect(lastContent(third.payload)).toContain('do not read them');
+ });
+
+ // Regression: a topic that started with no documents has an empty snapshot,
+ // and the notes were switched off with the (empty) index, hiding new documents.
+ it('shows documents created after an empty snapshot', async () => {
+ const first = await runTurn([], turn1);
+ const second = await runTurn([plan()], turn2, first.snapshot);
+
+ expect(second.payload.at(-1)!.content as string).toMatch(/created\s+Launch plan/);
+ });
+
+ // Regression: with history limited, the message carrying the earlier note is
+ // cut before the engine runs, so suppressing an identical note left the model
+ // with neither the snapshot row nor a note for the new document.
+ it('notes the difference again when history truncation drops the earlier note', async () => {
+ const history = { enableHistoryCount: true, historyCount: 1 };
+ const first = await runTurn([], turn1, undefined, history);
+ const second = await runTurn([plan()], turn2, first.snapshot, history);
+ const third = await runTurn([plan()], turn3, second.snapshot, history);
+
+ expect(JSON.stringify(third.payload)).not.toContain('"u2"');
+ expect(third.payload.at(-1)!.content as string).toMatch(/created\s+Launch plan/);
+ });
+
+ it('refreshes the index and drops the notes once the cache has gone cold', async () => {
+ const first = await runTurn([report(), notes()], turn1);
+ const second = await runTurn([report(), notes(), plan()], turn2, first.snapshot);
+ const coldTurn = [...turn2, assistant('a2', at(2, 30)), user('u3', at(30))];
+
+ const third = await runTurn([report(), notes(), plan()], coldTurn, second.snapshot);
+
+ expect(third.snapshot.notes).toEqual([]);
+ expect(JSON.stringify(third.payload[0].content)).toContain('Launch plan');
+ expect(JSON.stringify(third.payload)).not.toContain('agent_documents_changes');
+ });
+
+ it('refreshes the index after the history is compressed', () => {
+ const stored = takeAgentDocumentIndexSnapshot([report()], { takenAt: new Date(at(0)) });
+ const compressed = [
+ { createdAt: at(1), id: 'compressed-1', role: 'compressedGroup' },
+ user('u2', at(2)),
+ ];
+
+ const { snapshot } = resolveAgentDocumentIndex({
+ cacheTtlMs: TTL,
+ docs: [report(), plan()],
+ messages: compressed,
+ now: new Date(at(2)),
+ stored,
+ });
+
+ expect(snapshot.compressionId).toBe('compressed-1');
+ expect(snapshot.rows.map((row) => row.id)).toEqual([REPORT_ID, PLAN_ID]);
+ });
+
+ it('reuses the pinned snapshot on later steps of the run, whatever the documents do', () => {
+ const pinned = takeAgentDocumentIndexSnapshot([report()], { takenAt: new Date(at(0)) });
+
+ const resolved = resolveAgentDocumentIndex({
+ cacheTtlMs: TTL,
+ docs: [report(14_100, at(0, 20)), plan()],
+ messages: [...turn1, assistant('a1', at(0, 30))],
+ now: new Date(at(0, 40)),
+ pinned,
+ });
+
+ expect(resolved).toEqual({ pin: false, snapshot: pinned, store: false });
+ });
+
+ it('takes a fresh snapshot over a pinned value of the earlier per-run format', () => {
+ const { pin, snapshot } = resolveAgentDocumentIndex({
+ cacheTtlMs: TTL,
+ docs: [report()],
+ messages: turn1,
+ now: new Date(at(0)),
+ pinned: { [REPORT_ID]: { contentCharCount: 9_400 } },
+ });
+
+ expect(pin).toBe(true);
+ expect(snapshot.rows).toHaveLength(1);
+ });
+
+ it('renders deleted documents from their snapshot row and hides newer ones', () => {
+ const snapshot = takeAgentDocumentIndexSnapshot([report(), notes()], {
+ takenAt: new Date(at(0)),
+ });
+ const inline = progressiveDoc({ content: 'rules', id: 'rules', policyLoad: 'always' });
+
+ const docs = agentDocumentsFromSnapshot([inline, report(14_100, at(0, 20)), plan()], snapshot);
+
+ expect(docs[0]).toBe(inline);
+ expect(docs.slice(1).map((doc) => [doc.id, doc.contentCharCount])).toEqual([
+ [REPORT_ID, 9_400],
+ [NOTES_ID, 13_200],
+ ]);
+ expect(docs.some((doc) => doc.createdAt)).toBe(false);
+ });
+});
+
+describe('noteAgentDocumentChanges', () => {
+ const snapshot = () => takeAgentDocumentIndexSnapshot([report()], { takenAt: new Date(at(0)) });
+ const present = (...ids: string[]) => new Set(ids);
+
+ it('keeps the note a message already has', () => {
+ const noted = noteAgentDocumentChanges(snapshot(), [report(), plan()], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ const again = noteAgentDocumentChanges(noted, [report(14_100, at(3))], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ expect(again).toBe(noted);
+ });
+
+ it('adds nothing when nothing changed or the newest present note already says it', () => {
+ const base = snapshot();
+ expect(
+ noteAgentDocumentChanges(base, [report()], { messageId: 'u2', presentMessageIds: present() }),
+ ).toBe(base);
+
+ const noted = noteAgentDocumentChanges(base, [report(), plan()], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+ expect(
+ noteAgentDocumentChanges(noted, [report(), plan()], {
+ messageId: 'u3',
+ presentMessageIds: present('u2', 'u3'),
+ }),
+ ).toBe(noted);
+ });
+
+ // Regression: the snapshot rows never had a document created after it, so
+ // deleting that document produced no note and the earlier "created" stood.
+ it('reports a deletion of a document an earlier note reported as created', () => {
+ const noted = noteAgentDocumentChanges(snapshot(), [report(), plan()], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ const next = noteAgentDocumentChanges(noted, [report()], {
+ messageId: 'u3',
+ presentMessageIds: present('u2', 'u3'),
+ });
+
+ expect(next.notes.at(-1)).toEqual({
+ changes: [{ id: PLAN_ID, kind: 'deleted', title: 'Launch plan' }],
+ messageId: 'u3',
+ });
+ });
+
+ // Regression: a move keeps the timestamp and size, so a folded folder in the
+ // index kept pointing the model at the old parent with no note.
+ it('reports a document moved to another folder', () => {
+ const inFolder = (parentId: string, folderTitle: string) =>
+ progressiveDoc({ ...report(), folderTitle, parentId });
+ const base = takeAgentDocumentIndexSnapshot([inFolder('f1', 'Drafts')], {
+ takenAt: new Date(at(0)),
+ });
+
+ const next = noteAgentDocumentChanges(base, [inFolder('f2', 'Final')], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ expect(next.notes.at(-1)!.changes).toMatchObject([
+ { folderTitle: 'Final', id: REPORT_ID, kind: 'edited' },
+ ]);
+ });
+
+ // Regression: renaming back to the snapshot title left an empty diff, so the
+ // earlier note β€” which overrides the index β€” kept the intermediate title.
+ it('corrects an earlier edit note once the document matches its snapshot again', () => {
+ const renamed = progressiveDoc({ ...report(), title: 'Interim report' });
+ const noted = noteAgentDocumentChanges(snapshot(), [renamed], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ const next = noteAgentDocumentChanges(noted, [report()], {
+ messageId: 'u3',
+ presentMessageIds: present('u2', 'u3'),
+ });
+
+ expect(next.notes.at(-1)).toEqual({
+ changes: [expect.objectContaining({ id: REPORT_ID, kind: 'edited', title: 'Draft report' })],
+ messageId: 'u3',
+ });
+ });
+
+ it('repeats the difference when the message carrying it is gone', () => {
+ const noted = noteAgentDocumentChanges(snapshot(), [report(), plan()], {
+ messageId: 'u2',
+ presentMessageIds: present('u2'),
+ });
+
+ const next = noteAgentDocumentChanges(noted, [report(), plan()], {
+ messageId: 'u3',
+ presentMessageIds: present('u3'),
+ });
+
+ expect(next.notes.map((note) => note.messageId)).toEqual(['u2', 'u3']);
+ });
+});
+
+describe('diffAgentDocumentIndex', () => {
+ it('ignores web-crawled documents, which the index does not list', () => {
+ const web = progressiveDoc({ contentCharCount: 10, id: 'web-1', sourceType: 'web' });
+ const { rows } = takeAgentDocumentIndexSnapshot([report()], { takenAt: new Date(at(0)) });
+
+ expect(diffAgentDocumentIndex(rows, [report(), web])).toEqual([]);
+ });
+
+ it('formats changes in the index columns', () => {
+ expect(
+ formatAgentDocumentChanges([
+ {
+ contentCharCount: 2_300,
+ folderTitle: 'Plans',
+ id: PLAN_ID,
+ kind: 'created',
+ title: 'Launch plan',
+ updatedAt: '2026-11-14T10:01:30.000Z',
+ },
+ { id: NOTES_ID, kind: 'deleted', title: 'Weekly notes' },
+ ]),
+ ).toMatchInlineSnapshot(`
+ "Agent documents changed since <agent_documents_index> was listed. The index is not refreshed; for these documents this table is current, and deleted ones no longer exist β€” do not read them.
+
+ CHANGE TITLE ID SIZE UPDATED
+ created Launch plan (in Plans) 9c1f0d4e-5a6b-4c7d-8e9f-0a1b2c3d4e5f 2.3k 2026-11-14
+ deleted Weekly notes 32e12975-7db2-4818-8415-9b5c3d383f05 β€” β€”"
+ `);
+ });
+});
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index cc4053fb820..abf9b43a237 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -8,6 +8,7 @@ export { AgentBuilderContextInjector } from './AgentBuilderContextInjector';
export {
AGENT_DOCUMENT_INJECTION_POSITIONS,
AgentDocumentBeforeSystemInjector,
+ AgentDocumentChangesInjector,
AgentDocumentContextInjector,
AgentDocumentMessageInjector,
AgentDocumentSystemAppendInjector,
@@ -78,9 +79,10 @@ export type {
export type {
AgentContextDocument,
AgentDocumentBeforeSystemInjectorConfig,
+ AgentDocumentChange,
+ AgentDocumentChangesByMessage,
AgentDocumentContextInjectorConfig,
- AgentDocumentIndexFact,
- AgentDocumentIndexFacts,
+ AgentDocumentIndexSnapshot,
AgentDocumentInjectionPosition,
AgentDocumentLoadRule,
AgentDocumentLoadRules,
diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
index ee939b14a22..f4de6a472aa 100644
--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
@@ -75,6 +75,7 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEn
stepContext: run.stepContext,
// --- agent definition ---
+ agentDocumentChanges: agent.documentChanges,
agentDocuments: agent.documents,
agentIdentity: agent.identity,
enableHistoryCount: agent.enableHistoryCount,
diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
index 5e910495373..c92f33d4144 100644
--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
@@ -500,6 +500,10 @@ export const gatherContextFacts = async (
attempt('agentDocuments', () =>
docsAgentId ? providers.listAgentDocuments?.(docsAgentId) : undefined,
),
+ () =>
+ attempt('agentDocumentChanges', () =>
+ docsAgentId ? providers.listAgentDocumentChanges?.(docsAgentId) : undefined,
+ ),
() =>
attempt('agentAccountContext', async () => {
const context = await providers.listAgentAccountContext?.(request.agentId);
@@ -542,6 +546,7 @@ export const gatherContextFacts = async (
const [
agentDocuments,
+ agentDocumentChanges,
agentAccountContext,
agentBuilderContext,
agentManagementContext,
@@ -560,6 +565,7 @@ export const gatherContextFacts = async (
] = await tupleSettled(tasks);
return {
+ agentDocumentChanges,
agentDocuments: agentDocuments?.length ? agentDocuments : undefined,
step: {
agentAccountContext,
diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.ts
index be6c1f4a5b3..220e4070bae 100644
--- a/packages/mecha/src/contextEngineering/facts/types.ts
+++ b/packages/mecha/src/contextEngineering/facts/types.ts
@@ -1,6 +1,7 @@
import type { CredSummary } from '@lobechat/builtin-tool-creds';
import type {
AgentContextDocument,
+ AgentDocumentChangesByMessage,
AgentManagementContext,
AvailablePluginInfo,
AvailableProviderInfo,
@@ -158,6 +159,13 @@ export interface ContextFactProviders {
* on a host with no identity store.
*/
listAgentAccountContext?: (agentId?: string) => Promise<AgentAccountContext | undefined>;
+ /**
+ * Change notes for an index rendered from a snapshot, keyed by user message.
+ * Only a host whose `listAgentDocuments` returns snapshot rows provides it.
+ */
+ listAgentDocumentChanges?: (
+ agentId: string,
+ ) => Promise<AgentDocumentChangesByMessage | undefined>;
/** Context documents attached to an agent. */
listAgentDocuments?: (agentId: string) => Promise<AgentContextDocument[] | undefined>;
/** Connector identifiers (Composio services, LobeHub skill providers) connected for the agent. */
@@ -196,6 +204,7 @@ export interface ContextFactProviders {
}
export interface GatheredContextFacts {
+ agentDocumentChanges?: AgentDocumentChangesByMessage;
agentDocuments?: AgentContextDocument[];
step: ContextStepSnapshot & { agentManagementContext?: AgentManagementContext };
variables: ContextVariables;
diff --git a/packages/mecha/src/contextEngineering/types.ts b/packages/mecha/src/contextEngineering/types.ts
index 5fadd5b5e75..026330e7063 100644
--- a/packages/mecha/src/contextEngineering/types.ts
+++ b/packages/mecha/src/contextEngineering/types.ts
@@ -1,6 +1,7 @@
import type {
AgentBuilderContext,
AgentContextDocument,
+ AgentDocumentChangesByMessage,
AgentGroupConfig,
AgentManagementContext,
BotPlatformContext,
@@ -42,6 +43,8 @@ export type ContextVariables = Record<string, string | (() => string)>;
* host (`resolveAgentConfig`) and frozen.
*/
export interface ContextAgentSnapshot {
+ /** Change notes for the documents index, keyed by the user message each belongs to. */
+ documentChanges?: AgentDocumentChangesByMessage;
/** Agent documents the agent may consult. */
documents?: AgentContextDocument[];
enableHistoryCount?: boolean;