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 stable across in-run edits (#22965)

YuTengjingc2ca24f4d731
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 008e3632b52..3cbad24d057 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -1,4 +1,5 @@
import { type AgentState } from '@lobechat/agent-runtime';
+import type { AgentDocumentIndexFacts } from '@lobechat/context-engine/agent-document';
import {
type AgentShareVisitorContext,
type CancelVirtualSubAgentParams,
@@ -43,6 +44,13 @@ export interface RuntimeExecutorContext {
* tools: [] for an intermediate graph node and continue to another node.
*/
allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
+ /**
+ * Receives the agent-document index facts a step froze (first sight, or a
+ * document that appeared mid-run). `executeStep` writes them into
+ * `binding.agentDocumentIndex` of the state it saves, so later steps render
+ * the same index rows and keep the prompt-cache prefix.
+ */
+ bindAgentDocumentIndex?: (facts: AgentDocumentIndexFacts) => void;
botContext?: unknown;
/**
* Callback to stop a running `lobe-agent.callSubAgent` child dispatched by
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
index 82999f9a61b..f8ff6d7711a 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
@@ -2,6 +2,7 @@ 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 { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';
import {
agentShareDocumentAccessScope,
@@ -249,7 +250,14 @@ export const createServerContextFactProviders = ({
undefined,
documentAccessScope,
).getAgentContextDocuments(agentId);
- return toAgentContextDocuments(docs);
+ // 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;
},
// 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 8912b53c799..08bebc699f8 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
@@ -259,6 +259,56 @@ 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', () => {
+ const reportRow = (contentCharCount: number, updatedAt: string) => ({
+ content: '',
+ contentCharCount,
+ documentId: 'doc-1',
+ filename: 'report.md',
+ id: 'agent-doc-1',
+ policyLoad: 'progressive',
+ 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({
+ ctx: { bindAgentDocumentIndex, serverDB: {}, userId: 'owner-1' } as never,
+ state: {} as never,
+ });
+
+ await providers.listAgentDocuments!('agent-1');
+
+ expect(bindAgentDocumentIndex).toHaveBeenCalledWith({
+ 'agent-doc-1': { contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' },
+ });
+ });
+
+ 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')]);
+ 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' },
+ },
+ },
+ } as never,
+ });
+
+ const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+
+ expect(doc).toMatchObject({ contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' });
+ expect(bindAgentDocumentIndex).not.toHaveBeenCalled();
+ });
+ });
+
describe('resolveSandboxPersistence', () => {
// Regression: this provider read the raw context id while every other fact
// here is scoped to the run's workspace. On the paths that do not carry it,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index f47b30d4ecb..ef193319539 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -1,4 +1,5 @@
import { type AgentRuntimeContext, getLlmCallCount } from '@lobechat/agent-runtime';
+import type { AgentDocumentIndexFacts } from '@lobechat/context-engine/agent-document';
import { context as otelContext, trace as otelTrace } from '@lobechat/observability-otel/api';
import {
buildInvokeAgentAttributes,
@@ -298,6 +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;
// Create Agent and Runtime instances
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
@@ -307,6 +311,9 @@ export async function executeStep(
const { runtime } = await deps.createAgentRuntime({
abortSignal: abortPoll.signal,
agentState,
+ bindAgentDocumentIndex: (facts) => {
+ agentDocumentIndex = facts;
+ },
operationId,
stepIndex,
tracingContextEngine: (input, output, metadata) => {
@@ -329,6 +336,12 @@ export async function executeStep(
runtime,
stepIndex,
});
+ if (agentDocumentIndex) {
+ stepResult.newState.binding = {
+ ...stepResult.newState.binding,
+ agentDocumentIndex,
+ };
+ }
const { content, shouldContinue, stepPresentationData, toolsCalling } =
await saveAndPublishStep(deps, {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
index 8bc9bc0b719..d24bc039f84 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
@@ -180,6 +180,7 @@ export async function createAgentRuntime(
{
abortSignal,
agentState,
+ bindAgentDocumentIndex,
operationId,
stepIndex,
tracingContextEngine,
@@ -193,6 +194,7 @@ export async function createAgentRuntime(
* Works, so loading should cover that window).
*/
agentState?: any;
+ bindAgentDocumentIndex?: RuntimeExecutorContext['bindAgentDocumentIndex'];
operationId: string;
stepIndex: number;
tracingContextEngine?: (input: unknown, output: unknown, metadata?: unknown) => void;
@@ -270,6 +272,7 @@ export async function createAgentRuntime(
// Create streaming executor context
const executorContext: RuntimeExecutorContext = {
abortSignal,
+ bindAgentDocumentIndex,
// The factory may be a Graph-aware dispatcher that still returns the
// default agent for ordinary conversations. Keep the early visible
// output end behavior tied to the actual agent, not factory presence.
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
new file mode 100644
index 00000000000..613203e3349
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentRuntimeService } from '../AgentRuntimeService';
+import { stubRunningDurableOperation } from '../AgentRuntimeService/__tests__/testUtils';
+import { hookDispatcher } from '../hooks';
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return { query: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+vi.mock('@/server/modules/AgentRuntime', () => ({
+ AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {
+ return {
+ createAgentOperation: vi.fn(),
+ getOperationMetadata: vi.fn(),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
+ isInterrupted: vi.fn().mockResolvedValue(false),
+ loadAgentState: vi.fn(),
+ refreshStepLock: vi.fn().mockResolvedValue(true),
+ releaseStepLock: vi.fn().mockResolvedValue(undefined),
+ saveAgentState: vi.fn(),
+ saveStepResult: vi.fn(),
+ tryClaimStep: vi.fn().mockResolvedValue(true),
+ };
+ }),
+ createStreamEventManager: vi.fn(function () {
+ return {
+ cleanupOperation: vi.fn(),
+ publishAgentRuntimeEnd: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ publishStreamEvent: vi.fn(),
+ };
+ }),
+}));
+vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({
+ createRuntimeExecutors: vi.fn(function () {
+ return {};
+ }),
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));
+vi.mock('@/server/services/queue', () => ({
+ QueueService: vi.fn().mockImplementation(function () {
+ return { getImpl: vi.fn(() => ({})), scheduleMessage: vi.fn() };
+ }),
+}));
+vi.mock('@/server/services/queue/impls', () => ({ LocalQueueServiceImpl: class {} }));
+vi.mock('@/server/services/toolExecution', () => ({
+ ToolExecutionService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+vi.mock('@/server/services/toolExecution/builtin', () => ({
+ BuiltinToolsExecutor: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({
+ dynamicInterventionAudits: [],
+}));
+
+beforeEach(() => {
+ stubRunningDurableOperation();
+});
+
+// The agent-document index rows a step froze 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 () => {
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+ const coordinator = (service as any).coordinator;
+ const completionLifecycle = (service as any).completionLifecycle;
+
+ const state: any = {
+ binding: { device: { id: 'device-1' } },
+ cost: { currency: 'USD', total: 0 },
+ host: { hooks: [] },
+ lastModified: new Date().toISOString(),
+ messages: [],
+ operationId: 'op-doc-index',
+ status: 'running',
+ stepCount: 0,
+ usage: {},
+ };
+ let savedState: any;
+ coordinator.loadAgentState = vi.fn().mockResolvedValue(state);
+ coordinator.saveStepResult = vi.fn().mockImplementation(async (_operationId, stepResult) => {
+ savedState = stepResult.newState;
+ });
+
+ const facts = {
+ 'agent-doc-1': { contentCharCount: 9400, updatedAt: '2026-05-01T00:00:00.000Z' },
+ };
+ vi.spyOn(service as any, 'createAgentRuntime').mockImplementation(
+ async ({ bindAgentDocumentIndex }: any) => ({
+ runtime: {
+ step: vi.fn().mockImplementation(async () => {
+ bindAgentDocumentIndex(facts);
+ return { events: [], newState: { ...state, status: 'done', stepCount: 1 } };
+ }),
+ },
+ }),
+ );
+ vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue(true);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+
+ await service.executeStep({
+ context: { phase: 'agent_step' } as any,
+ operationId: 'op-doc-index',
+ stepIndex: 0,
+ });
+
+ expect(savedState.binding).toEqual({
+ agentDocumentIndex: facts,
+ device: { id: 'device-1' },
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index d3dd4047a48..770d2a59354 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,6 +1,7 @@
import type {
ActivatedStepSkill,
ActivatedStepTool,
+ AgentDocumentIndexFacts,
AgentGroupConfig,
BotPlatformContext,
DiscordContext,
@@ -349,6 +350,13 @@ export interface AgentWorldSnapshot {
* prompt placeholders and tool cwd resolution.
*/
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.
+ */
+ agentDocumentIndex?: AgentDocumentIndexFacts;
/**
* 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
@@ -372,8 +380,8 @@ export interface AgentState {
activatedStepTools?: ActivatedStepTool[];
// --- Late-bound execution facts ---
/**
- * Execution facts bound at a step boundary (device routing). The only
- * business slot the host may write after creation.
+ * Execution facts bound at a step boundary (device routing, agent-document
+ * index facts). The only business slot the host may write after creation.
*/
binding?: AgentRunBinding;
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
index 3e719c5509a..d5f6b45378e 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
@@ -8,6 +8,8 @@ export {
AGENT_DOCUMENT_INJECTION_POSITIONS,
type AgentContextDocument,
type AgentDocumentFilterContext,
+ type AgentDocumentIndexFact,
+ type AgentDocumentIndexFacts,
type AgentDocumentInjectionPosition,
type AgentDocumentLoadFormat,
type AgentDocumentLoadRule,
@@ -15,6 +17,7 @@ export {
combineDocuments,
filterDocumentsByRules,
formatDocument,
+ freezeAgentDocumentIndexFacts,
getDocumentsForPositions,
sortByPriority,
withRunStartedAt,
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
index 7cc9671d635..a31a5a5b57f 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
@@ -95,6 +95,70 @@ 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
new file mode 100644
index 00000000000..52b38ee93bf
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexFacts.test.ts
@@ -0,0 +1,134 @@
+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/index.ts b/packages/context-engine/src/providers/index.ts
index 5bd5f5323e7..cc4053fb820 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -79,6 +79,8 @@ export type {
AgentContextDocument,
AgentDocumentBeforeSystemInjectorConfig,
AgentDocumentContextInjectorConfig,
+ AgentDocumentIndexFact,
+ AgentDocumentIndexFacts,
AgentDocumentInjectionPosition,
AgentDocumentLoadRule,
AgentDocumentLoadRules,