π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-tracing): pool context engine snapshots so long-run traces stop growing quadratically (#22522)
Mocha1c3e6a51a0af
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.tsindex 6085f0532fc..2146ce60324 100644--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts@@ -1,3 +1,5 @@+import { createHash } from 'node:crypto';+import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';import type { ChatMessageErrorAttribution, ChatMessageErrorSeverity } from '@lobechat/types';import debug from 'debug';@@ -8,6 +10,25 @@ const log = debug('lobe-server:operation-trace-recorder');type SignalEvent = { [key: string]: unknown; type: string };+/** Pool candidates of one step: ref β JSON text of the value it names. */+type CePoolCandidates = Map<string, string>;++/** One captured step's CE payload before it is pooled against the partial. */+interface CapturedCe {+ candidates: CePoolCandidates;+ /** Refs of the output messages, in order, when the output is a list. */+ outputRefs?: string[];+}++/** What the partial already pools, so a step stores only what is new. */+interface CePoolState {+ /** The last pooled output list: its node ancestry (root first) and message refs. */+ lastOutput?: { chain: Array<{ length: number; ref: string }>; refs: string[] };+ refs: Set<string>;+}++const ceRef = (json: string) => createHash('sha256').update(json).digest('base64url').slice(0, 22);+export interface AppendStepParams {afterStepSignalEvents: SignalEvent[];/**@@ -98,7 +119,12 @@ export class OperationTraceRecorder {* Measured in production (Tempo, 75 steps): ~570ms GET + ~960ms PUT per step,* on the critical path between two steps of an inlined run.*/- private cached: { operationId: string; partial: Partial<ExecutionSnapshot> } | null = null;+ private cached: {+ /** The partial's CE pool index, built on first use. */+ cePool?: CePoolState;+ operationId: string;+ partial: Partial<ExecutionSnapshot>;+ } | null = null;/** In-flight upload, if any. Never rejects β `drainSaves` logs and continues. */private pendingSave: Promise<void> | undefined;@@ -124,8 +150,8 @@ export class OperationTraceRecorder {this.initPartialHeader(partial, params.agentState);if (!partial.steps) partial.steps = [];- const newStep = this.buildStepSnapshot(params);- this.deduplicateCeSnapshot(newStep, partial.steps);+ const { ce, step: newStep } = this.buildStepSnapshot(params);+ this.poolCeSnapshot(newStep, ce, partial.steps, this.cePoolState(partial));partial.steps.push(newStep);// Upload in the background: the next step only needs the in-memory copy,@@ -312,53 +338,167 @@ export class OperationTraceRecorder {}}+ /** Index what the partial's steps already pooled β recorded values are never repeated. */+ private cePoolState(partial: Partial<ExecutionSnapshot>): CePoolState {+ if (this.cached?.partial === partial && this.cached.cePool) return this.cached.cePool;++ const pool = new Map<string, unknown>();+ for (const step of partial.steps ?? []) {+ for (const [ref, value] of Object.entries(step.contextEngine?.pool ?? {})) {+ pool.set(ref, value);+ }+ }+ const state: CePoolState = { refs: new Set(pool.keys()) };++ // Extend the list of the last recorded step. Any earlier list would also be+ // correct; the most recent one shares the longest prefix.+ const lastRef = partial.steps?.findLast((step) => step.contextEngine?.outputRef)?.contextEngine+ ?.outputRef;+ const nodes: Array<{ base?: string; ref: string; refs: string[] }> = [];+ for (let ref = lastRef; ref !== undefined && nodes.length <= pool.size;) {+ const node = pool.get(ref) as { base?: string; refs: string[] } | undefined;+ if (!node) break;+ nodes.unshift({ ...node, ref });+ ref = node.base;+ }+ if (lastRef !== undefined && nodes[0] && nodes[0].base === undefined) {+ const refs: string[] = [];+ const chain = nodes.map((node) => {+ refs.push(...node.refs);+ return { length: refs.length, ref: node.ref };+ });+ state.lastOutput = { chain, refs };+ }++ if (this.cached?.partial === partial) this.cached.cePool = state;+ return state;+ }+/**- * Strip `contextEngine` input/output/metadata fields that are identical to the- * most-recently stored values in previous steps. The viewer reconstructs the- * full snapshot by walking back through the step list (same pattern as- * messagesBaseline + messagesDelta).+ * Store only what the partial does not hold yet. The output list becomes a+ * node extending the longest prefix it shares with the last recorded list,+ * every value lands in this step's pool unless an earlier step pooled it, and+ * `metadata` is dropped when it equals the last stored one. A long run+ * re-sends nearly the same messages on every LLM call, so storing whole+ * payloads per step grows the trace β and the per-step read and rewrite of+ * the partial β with steps Γ context size. `resolveContextEngineSteps`+ * reverses this.*/- private deduplicateCeSnapshot(step: StepSnapshot, prevSteps: StepSnapshot[]): void {- if (!step.contextEngine) return;-- let lastInputJson: string | undefined;- let lastMetadataJson: string | undefined;- let lastOutputJson: string | undefined;-- for (let i = prevSteps.length - 1; i >= 0; i--) {- const prev = prevSteps[i];- if (!prev.contextEngine) continue;- if (lastInputJson === undefined && prev.contextEngine.input !== undefined) {- lastInputJson = JSON.stringify(prev.contextEngine.input);- }- if (lastMetadataJson === undefined && prev.contextEngine.metadata !== undefined) {- lastMetadataJson = JSON.stringify(prev.contextEngine.metadata);+ private poolCeSnapshot(+ step: StepSnapshot,+ captured: CapturedCe,+ prevSteps: StepSnapshot[],+ state: CePoolState,+ ): void {+ const ce = step.contextEngine;+ if (!ce) return;++ const { candidates, outputRefs } = captured;+ if (outputRefs) {+ const last = state.lastOutput;+ let shared = 0;+ while (+ last &&+ shared < last.refs.length &&+ shared < outputRefs.length &&+ last.refs[shared] === outputRefs[shared]+ ) {+ shared++;}- if (lastOutputJson === undefined && prev.contextEngine.output !== undefined) {- lastOutputJson = JSON.stringify(prev.contextEngine.output);+ const ancestorIndex = last ? last.chain.findLastIndex((node) => node.length <= shared) : -1;+ const ancestor = ancestorIndex >= 0 ? last!.chain[ancestorIndex] : undefined;++ if (ancestor && ancestor.length === outputRefs.length) {+ ce.outputRef = ancestor.ref;+ } else {+ const node = {+ ...(ancestor && { base: ancestor.ref }),+ refs: outputRefs.slice(ancestor?.length ?? 0),+ };+ const json = JSON.stringify(node);+ ce.outputRef = ceRef(json);+ candidates.set(ce.outputRef, json);}- if (- lastInputJson !== undefined &&- lastMetadataJson !== undefined &&- lastOutputJson !== undefined- )- break;+ state.lastOutput = {+ chain: [+ ...(last?.chain.slice(0, ancestorIndex + 1) ?? []),+ ...(ancestor?.ref === ce.outputRef+ ? []+ : [{ length: outputRefs.length, ref: ce.outputRef }]),+ ],+ refs: outputRefs,+ };}- const storeInput =- lastInputJson === undefined || JSON.stringify(step.contextEngine.input) !== lastInputJson;- const storeMetadata =- step.contextEngine.metadata !== undefined &&- (lastMetadataJson === undefined ||- JSON.stringify(step.contextEngine.metadata) !== lastMetadataJson);- const storeOutput =- lastOutputJson === undefined || JSON.stringify(step.contextEngine.output) !== lastOutputJson;-- step.contextEngine = {- ...(storeInput ? { input: step.contextEngine.input } : {}),- ...(storeMetadata ? { metadata: step.contextEngine.metadata } : {}),- ...(storeOutput ? { output: step.contextEngine.output } : {}),+ const pool: Record<string, unknown> = {};+ for (const [ref, json] of candidates) {+ if (state.refs.has(ref)) continue;+ pool[ref] = JSON.parse(json);+ state.refs.add(ref);+ }+ if (Object.keys(pool).length > 0) ce.pool = pool;++ if (ce.metadata === undefined) return;+ const lastMetadata = prevSteps.findLast((prev) => prev.contextEngine?.metadata !== undefined)+ ?.contextEngine?.metadata;+ if (+ lastMetadata !== undefined &&+ JSON.stringify(ce.metadata) === JSON.stringify(lastMetadata)+ ) {+ delete ce.metadata;+ }+ }++ /**+ * Capture the CE payload as JSON now: the next step can mutate the source+ * objects while a trace read is pending, and Dates convert once here instead+ * of on every serialization of the partial. Object inputs become refs and+ * array outputs message refs (values go to the pool candidates); other+ * shapes stay whole.+ */+ private captureCeSnapshot(ceInput: AppendStepParams['contextEngine']): {+ ce: CapturedCe;+ contextEngine: StepSnapshot['contextEngine'];+ } {+ const ce: CapturedCe = { candidates: new Map() };+ if (!ceInput) return { ce, contextEngine: undefined };++ const toRef = (value: unknown): string | undefined => {+ const json = JSON.stringify(value);+ if (json === undefined) return undefined;+ const ref = ceRef(json);+ ce.candidates.set(ref, json);+ return ref;};+ const copy = (value: unknown) => {+ const json = JSON.stringify(value);+ return json === undefined ? undefined : JSON.parse(json);+ };++ const contextEngine: NonNullable<StepSnapshot['contextEngine']> = {};+ const { input, metadata, output } = ceInput;++ if (input && typeof input === 'object' && !Array.isArray(input)) {+ const inputRefs: Record<string, string> = {};+ for (const [key, value] of Object.entries(input)) {+ const ref = toRef(value);+ if (ref !== undefined) inputRefs[key] = ref;+ }+ contextEngine.inputRefs = inputRefs;+ } else if (input !== undefined) {+ contextEngine.input = copy(input);+ }++ if (Array.isArray(output)) {+ // JSON turns a hole or `undefined` element into `null`; keep that meaning.+ ce.outputRefs = output.map((value) => toRef(value) ?? toRef(null)!);+ } else if (output !== undefined) {+ contextEngine.output = copy(output);+ }++ if (metadata !== undefined) contextEngine.metadata = copy(metadata);++ return { ce, contextEngine };}private initPartialHeader(partial: any, agentState: any): void {@@ -369,7 +509,7 @@ export class OperationTraceRecorder {agentState?.world?.agent?.provider ?? agentState?.modelRuntimeConfig?.provider;}- private buildStepSnapshot(params: AppendStepParams): StepSnapshot {+ private buildStepSnapshot(params: AppendStepParams): { ce: CapturedCe; step: StepSnapshot } {const {agentState,afterStepSignalEvents,@@ -394,11 +534,8 @@ export class OperationTraceRecorder {// CE data is structural state, not a streaming event β delivered via the// typed `contextEngine` field on AppendStepParams (sourced from- // RuntimeExecutorContext.tracingContextEngine). Uses the same delta- // pattern as messagesBaseline/messagesDelta.- const contextEngine: StepSnapshot['contextEngine'] = ceInput- ? { input: ceInput.input, metadata: ceInput.metadata, output: ceInput.output }- : undefined;+ // RuntimeExecutorContext.tracingContextEngine).+ const { ce, contextEngine } = this.captureCeSnapshot(ceInput);// Strip heavy/redundant data from events before persisting to snapshot.const rawEvents = (stepResult.events as any[]) ?? [];@@ -455,7 +592,7 @@ export class OperationTraceRecorder {? afterActivated.slice(prevActivated.length): undefined;- return {+ const step: StepSnapshot = {activatedStepToolsDelta,contextEngine,completedAt: Date.now(),@@ -484,5 +621,6 @@ export class OperationTraceRecorder {totalCost: presentation.stepCost ?? 0,totalTokens: presentation.stepTotalTokens ?? 0,};+ return { ce, step };}}diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.tsindex 1f252d2742b..ceb8049ba73 100644--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { resolveContextEngineSteps } from '@lobechat/agent-tracing';import { beforeEach, describe, expect, it, vi } from 'vitest';import { OperationTraceRecorder } from '../OperationTraceRecorder';@@ -436,222 +437,203 @@ describe('OperationTraceRecorder', () => {});});- describe('contextEngine dedup (via appendStep)', () => {- let store: ReturnType<typeof buildStore>;- let recorder: OperationTraceRecorder;+ describe('contextEngine recording', () => {+ type Ce = { input?: unknown; metadata?: unknown; output?: unknown };- beforeEach(() => {- store = buildStore();- recorder = new OperationTraceRecorder(store as any);- });-- const buildCe = (overrides: { input?: unknown; output?: unknown } = {}) => ({- input: { messages: ['hello'] },- output: { tokens: 42 },- ...overrides,- });-- const appendStepWithCe = (- ce: { input?: unknown; output?: unknown },- prevStepsInStore: any[],+ /**+ * Queue-mode shape: every step runs in a fresh invocation that loads the+ * partial the previous one saved.+ */+ const recordAcrossInvocations = async (+ ces: Array<Ce | undefined>,+ initialSteps: any[] = [],) => {- store.loadPartial.mockResolvedValue({ startedAt: 1, steps: prevStepsInStore });- return recorder.appendStep('op-ce', {- afterStepSignalEvents: [],- agentState: { messages: [] },- beforeStepSignalEvents: [],- contextEngine: ce,- currentContext: { phase: 'user_input' },- externalRetryCount: 0,- presentation: buildPresentation(),- startedAt: 1000,- stepIndex: prevStepsInStore.length,- stepResult: {- events: [],- newState: { activatedStepTools: [], messages: [] },- },- });+ let stored: any = { startedAt: 1, steps: initialSteps };+ for (const [offset, ce] of ces.entries()) {+ const store = buildStore();+ store.loadPartial.mockResolvedValue(structuredClone(stored));+ const recorder = new OperationTraceRecorder(store as any);+ await recorder.appendStep('op-ce', {+ afterStepSignalEvents: [],+ agentState: { messages: [] },+ beforeStepSignalEvents: [],+ contextEngine: ce,+ currentContext: { phase: ce ? 'user_input' : 'tool_result' },+ externalRetryCount: 0,+ presentation: buildPresentation({ stepType: ce ? 'call_llm' : 'call_tool' }),+ startedAt: 1000,+ stepIndex: initialSteps.length + offset,+ stepResult: { events: [], newState: { activatedStepTools: [], messages: [] } },+ });+ await recorder.flushPartial();+ // Round-trip through JSON like the real store does.+ // eslint-disable-next-line unicorn/prefer-structured-clone -- the store serializes JSON+ stored = JSON.parse(JSON.stringify(store.savePartial.mock.calls.at(-1)![1]));+ }+ return stored as { steps: any[] };};- const getSavedStep = (newStepIndex: number) => {- const saved = store.savePartial.mock.calls[0][1];- return saved.steps.find((s: any) => s.stepIndex === newStepIndex);+ const resolveAll = (steps: any[]) => {+ const resolved = resolveContextEngineSteps(steps);+ return steps.map((step) => resolved.get(step));};+ const message = (i: number) => ({ content: `message ${i} ${'x'.repeat(200)}`, role: 'user' });+ const growingRun = (steps: number) =>+ Array.from({ length: steps }, (_, i) => ({+ input: {+ agentDocuments: [{ content: `shared doc ${'d'.repeat(2000)}` }],+ planTodo: { done: i },+ },+ output: Array.from({ length: i + 1 }, (_, j) => message(j)),+ }));+it('routes CE input/output into contextEngine, never into events', async () => {- await appendStepWithCe(buildCe(), []);+ const { steps } = await recordAcrossInvocations([{ input: { a: 1 }, output: [] }]);- const step = getSavedStep(0);- // CE data lives in contextEngine, not events- expect(step.contextEngine).toBeDefined();- expect(step.events.some((e: any) => e.type === 'context_engine_result')).toBe(false);+ expect(steps[0].contextEngine).toBeDefined();+ expect(steps[0].events.some((e: any) => e.type === 'context_engine_result')).toBe(false);});- it('keeps both input and output on the first step (no previous CE to compare against)', async () => {- await appendStepWithCe(buildCe(), []);-- const step = getSavedStep(0);- expect(step.contextEngine.input).toEqual({ messages: ['hello'] });- expect(step.contextEngine.output).toEqual({ tokens: 42 });- });+ it('resolves every step back to exactly what the context engine produced', async () => {+ const ces: Array<Ce | undefined> = [+ {+ input: { systemRole: 'be brief', toolCount: 3 },+ metadata: { trim: 0 },+ output: [message(0)],+ },+ undefined, // a tool step runs no CE+ {+ input: { systemRole: 'be brief', toolCount: 3 },+ metadata: { trim: 0 },+ output: [message(0), message(1)],+ },+ // Middle message rewritten (stale tool result trim), metadata changed.+ {+ input: { systemRole: 'be brief', toolCount: 4 },+ metadata: { trim: 1 },+ output: [message(0), { content: '[trimmed]', role: 'tool' }, message(2), message(2)],+ },+ // Compression collapses the history; an input key disappears.+ {+ input: { systemRole: 'be brief' },+ metadata: { trim: 1 },+ output: [{ content: 'summary', role: 'system' }],+ },+ ];- it('strips both input and output when both are identical to the previous step', async () => {- const prevStep = {- contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },- stepIndex: 0,- stepType: 'call_llm',- };- await appendStepWithCe(buildCe(), [prevStep]);+ const { steps } = await recordAcrossInvocations(ces);- const step = getSavedStep(1);- expect(step.contextEngine.input).toBeUndefined();- expect(step.contextEngine.output).toBeUndefined();+ expect(resolveAll(steps)).toEqual(+ ces.map((ce) =>+ ce ? { input: ce.input, metadata: ce.metadata, output: ce.output } : undefined,+ ),+ );});- it('strips only input when input matches previous but output differs', async () => {- const prevStep = {- contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },- stepIndex: 0,- stepType: 'call_llm',- };- await appendStepWithCe(buildCe({ input: { messages: ['hello'] }, output: { tokens: 99 } }), [- prevStep,- ]);+ it('stores each distinct value once however many steps re-send it', async () => {+ const { steps } = await recordAcrossInvocations(growingRun(40));+ const serialized = JSON.stringify(steps);- const step = getSavedStep(1);- expect(step.contextEngine.input).toBeUndefined();- expect(step.contextEngine.output).toEqual({ tokens: 99 });+ expect(serialized.split('message 0 ').length - 1).toBe(1);+ expect(serialized.split('message 39 ').length - 1).toBe(1);+ expect(serialized.split('shared doc').length - 1).toBe(1);+ expect(resolveAll(steps).at(-1)?.output).toHaveLength(40);});- it('strips only output when output matches previous but input differs', async () => {- const prevStep = {- contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },- stepIndex: 0,- stepType: 'call_llm',- };- await appendStepWithCe(buildCe({ input: { messages: ['world'] }, output: { tokens: 42 } }), [- prevStep,- ]);+ it('grows linearly with the conversation, not with steps Γ context', async () => {+ const size = async (n: number) =>+ JSON.stringify((await recordAcrossInvocations(growingRun(n))).steps).length;- const step = getSavedStep(1);- expect(step.contextEngine.input).toEqual({ messages: ['world'] });- expect(step.contextEngine.output).toBeUndefined();- });+ const [small, large] = [await size(50), await size(100)];- it('keeps both when both input and output differ from previous', async () => {- const prevStep = {- contextEngine: { input: { messages: ['old'] }, output: { tokens: 10 } },- stepIndex: 0,- stepType: 'call_llm',- };- await appendStepWithCe(buildCe({ input: { messages: ['new'] }, output: { tokens: 20 } }), [- prevStep,- ]);-- const step = getSavedStep(1);- expect(step.contextEngine.input).toEqual({ messages: ['new'] });- expect(step.contextEngine.output).toEqual({ tokens: 20 });+ // Quadratic storage would quadruple; linear doubles (plus per-step refs).+ expect(large / small).toBeLessThan(2.6);});- it('walks back past intermediate steps without CE to find last stored values', async () => {- const prevSteps = [+ it('continues a partial recorded in the changed-fields format', async () => {+ const legacy = [{- contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },+ contextEngine: { input: { toolCount: 3 }, metadata: { trim: 0 }, output: [message(0)] },stepIndex: 0,stepType: 'call_llm',},- // step 1 has no contextEngine β dedup must skip it and walk back to step 0- { stepIndex: 1, stepType: 'call_tool' },+ { contextEngine: {}, stepIndex: 1, stepType: 'call_llm' },];- await appendStepWithCe(buildCe(), prevSteps);+ const next = {+ input: { toolCount: 3 },+ metadata: { trim: 0 },+ output: [message(0), message(1)],+ };- const step = getSavedStep(2);- expect(step.contextEngine.input).toBeUndefined();- expect(step.contextEngine.output).toBeUndefined();- });+ const { steps } = await recordAcrossInvocations([next], legacy);- it('stores CE pipeline metadata and dedupes it independently', async () => {- const withMeta = {- input: { messages: ['hello'] },- metadata: { staleToolResultTrim: { savedChars: 100, trimmedMessages: 2 } },- output: { tokens: 42 },- };- // NB: the recorder caches the partial in memory between appendStep calls,- // so each call appends to the same running partial β read the last step.- const lastStep = () => {- const saved = store.savePartial.mock.calls.at(-1)![1];- return saved.steps.at(-1);- };+ expect(resolveAll(steps)).toEqual([+ { input: { toolCount: 3 }, metadata: { trim: 0 }, output: [message(0)] },+ { input: { toolCount: 3 }, metadata: { trim: 0 }, output: [message(0)] },+ next,+ ]);+ });- await appendStepWithCe(withMeta, []);- expect(lastStep().contextEngine.metadata).toEqual({- staleToolResultTrim: { savedChars: 100, trimmedMessages: 2 },- });+ it('re-pools a value whose introducing step never reached the store', async () => {+ const first = await recordAcrossInvocations([{ input: { a: 1 }, output: [message(0)] }]);+ // The step that pooled message 0 was lost (crash before upload): the+ // next invocation starts from a partial that lacks it.+ const lostPredecessor = first.steps.map((step) => ({ ...step, stepIndex: 99 })).slice(0, 0);- // identical metadata on the next step is stripped like input/output- await appendStepWithCe(withMeta, []);- expect(lastStep().contextEngine.metadata).toBeUndefined();+ const { steps } = await recordAcrossInvocations(+ [{ input: { a: 1 }, output: [message(0), message(1)] }],+ lostPredecessor,+ );- // changed metadata is kept while identical input/output are stripped- const changedMeta = {- ...withMeta,- metadata: { staleToolResultTrim: { savedChars: 250, trimmedMessages: 5 } },- };- await appendStepWithCe(changedMeta, []);- const step = lastStep();- expect(step.contextEngine.input).toBeUndefined();- expect(step.contextEngine.output).toBeUndefined();- expect(step.contextEngine.metadata).toEqual({- staleToolResultTrim: { savedChars: 250, trimmedMessages: 5 },- });+ expect(resolveAll(steps)[0]?.output).toEqual([message(0), message(1)]);});- it('resolves input and output independently from different previous steps', async () => {- // step 0 stored only input (output was stripped vs its own predecessor)- // step 1 stored only output (input was stripped vs step 0)- // New step 2 has the same input as step 0 and same output as step 1 β both deduped- const prevSteps = [- { contextEngine: { input: { messages: ['hello'] } }, stepIndex: 0, stepType: 'call_llm' },- { contextEngine: { output: { tokens: 42 } }, stepIndex: 1, stepType: 'call_llm' },- ];- await appendStepWithCe(- buildCe({ input: { messages: ['hello'] }, output: { tokens: 42 } }),- prevSteps,- );+ it('stores metadata only when it changes', async () => {+ const { steps } = await recordAcrossInvocations([+ { input: {}, metadata: { trim: 1 }, output: [] },+ { input: {}, metadata: { trim: 1 }, output: [] },+ { input: {}, metadata: { trim: 2 }, output: [] },+ ]);- const step = getSavedStep(2);- expect(step.contextEngine.input).toBeUndefined();- expect(step.contextEngine.output).toBeUndefined();+ expect(steps.map((step) => step.contextEngine.metadata)).toEqual([+ { trim: 1 },+ undefined,+ { trim: 2 },+ ]);});- it('sets contextEngine to undefined when no CE was recorded for the step', async () => {- const prevStep = {- contextEngine: { input: { messages: ['hello'] }, output: { tokens: 42 } },- stepIndex: 0,- stepType: 'call_llm',- };- store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [prevStep] });+ it('records the values as of the append, not later mutations of the source objects', async () => {+ const store = buildStore();+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [] });+ const recorder = new OperationTraceRecorder(store as any);+ const output = [{ content: 'before', role: 'user', at: new Date(0) }];await recorder.appendStep('op-ce', {afterStepSignalEvents: [],agentState: { messages: [] },beforeStepSignalEvents: [],- currentContext: { phase: 'tool_result' },+ contextEngine: { input: { toolCount: 1 }, output },+ currentContext: { phase: 'user_input' },externalRetryCount: 0,- presentation: buildPresentation({ stepType: 'call_tool' }),+ presentation: buildPresentation(),startedAt: 1000,- stepIndex: 1,- stepResult: {- events: [{ type: 'tool_result', id: 'tc-1' }],- newState: { activatedStepTools: [], messages: [] },- },+ stepIndex: 0,+ stepResult: { events: [], newState: { activatedStepTools: [], messages: [] } },});+ output[0].content = 'after';+ await recorder.flushPartial();- const saved = store.savePartial.mock.calls[0][1];- const newStep = saved.steps.find((s: any) => s.stepIndex === 1);- expect(newStep.contextEngine).toBeUndefined();- expect(newStep.events.some((e: any) => e.type === 'context_engine_result')).toBe(false);- expect(newStep.events.some((e: any) => e.type === 'tool_result')).toBe(true);+ const { steps } = store.savePartial.mock.calls.at(-1)![1];+ expect(resolveAll(steps)[0]?.output).toEqual([+ { at: '1970-01-01T00:00:00.000Z', content: 'before', role: 'user' },+ ]);+ });++ it('sets contextEngine to undefined when no CE was recorded for the step', async () => {+ const { steps } = await recordAcrossInvocations([{ input: { a: 1 }, output: [] }, undefined]);++ expect(steps[1].contextEngine).toBeUndefined();});});diff --git a/packages/agent-tracing/src/analysis/contextLint.test.ts b/packages/agent-tracing/src/analysis/contextLint.test.tsindex 744f40d303b..9323740bcce 100644--- a/packages/agent-tracing/src/analysis/contextLint.test.ts+++ b/packages/agent-tracing/src/analysis/contextLint.test.ts@@ -32,6 +32,24 @@ describe('resolvePayloads', () => {expect(payloads[1].messages).toEqual(payloads[0].messages);});+ it('resolves pooled output lists, including a run that spans the old format', () => {+ const hi = { content: 'hi', role: 'user' };+ const ok = { content: 'ok', role: 'assistant' };+ const snap = base([+ { contextEngine: { output: [hi] }, stepIndex: 0, stepType: 'call_llm' },+ {+ contextEngine: { outputRef: 'n1', pool: { hi, n1: { refs: ['hi', 'ok'] }, ok } },+ stepIndex: 1,+ stepType: 'call_llm',+ },+ ]);++ expect(resolvePayloads(snap).payloads.map((payload) => payload.messages)).toEqual([+ [hi],+ [hi, ok],+ ]);+ });+it('falls back to legacy messages when CE fields are absent', () => {const snap = base([{ messages: [{ content: 'hi', role: 'user' }], stepIndex: 0, stepType: 'call_llm' },diff --git a/packages/agent-tracing/src/analysis/contextLint.ts b/packages/agent-tracing/src/analysis/contextLint.tsindex 5c8d1351591..c0fd22d0ac4 100644--- a/packages/agent-tracing/src/analysis/contextLint.ts+++ b/packages/agent-tracing/src/analysis/contextLint.ts@@ -1,6 +1,7 @@import { encode } from 'gpt-tokenizer';import type { ExecutionSnapshot, StepSnapshot } from '../types';+import { resolveContextEngineSteps } from '../utils/contextEngine';import { analyzeToolResult } from './toolFeedback';/**@@ -121,18 +122,18 @@ export function contentText(m: PayloadMessage): string {}/**- * Resolve the messages array the model saw at each `call_llm` step.- * `contextEngine.output` uses a changed-fields delta: reuse the last seen value when a- * step's CE entry omits it.+ * Resolve the messages array the model saw at each `call_llm` step from the resolved+ * `contextEngine.output`, carrying the last one forward past steps that did not run the CE.*/export function resolvePayloads(snapshot: ExecutionSnapshot): {payloadSource: ContextLintFeatures['payloadSource'];payloads: Array<{ messages: PayloadMessage[]; stepIndex: number }>;} {+ const resolvedCe = resolveContextEngineSteps(snapshot.steps);let current: PayloadMessage[] | undefined;const payloads: Array<{ messages: PayloadMessage[]; stepIndex: number }> = [];for (const step of snapshot.steps) {- const out = step.contextEngine?.output;+ const out = resolvedCe.get(step)?.output;if (Array.isArray(out)) current = out as PayloadMessage[];if (step.stepType === 'call_llm' && current)payloads.push({ messages: current, stepIndex: step.stepIndex });diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.tsindex 98adb833f1a..4864eaae6d3 100644--- a/packages/agent-tracing/src/index.ts+++ b/packages/agent-tracing/src/index.ts@@ -32,6 +32,7 @@ export {} from './store/remote-store';export type { ISnapshotStore, PartialSaveOptions, PartialSaveResult } from './store/types';export type { ExecutionSnapshot, SnapshotSummary, StepSnapshot } from './types';+export { resolveContextEngineSteps, type ResolvedContextEngine } from './utils/contextEngine';export {expandSnapshot,isIncrementalFormat,diff --git a/packages/agent-tracing/src/inspect/inspectSnapshot.test.ts b/packages/agent-tracing/src/inspect/inspectSnapshot.test.tsindex 8c7bc7e5679..0b913297266 100644--- a/packages/agent-tracing/src/inspect/inspectSnapshot.test.ts+++ b/packages/agent-tracing/src/inspect/inspectSnapshot.test.ts@@ -46,6 +46,25 @@ describe('inspectSnapshot', () => {expect(JSON.parse(inspectSnapshot(snap, { json: true, step: '1' })).stepIndex).toBe(1);});+ it('renders a targeted step with its resolved context engine snapshot', () => {+ const hi = { content: 'hi', role: 'user' };+ const snap = snapshot([+ {+ contextEngine: {+ inputRefs: { toolCount: 't' },+ outputRef: 'n',+ pool: { hi, n: { refs: ['hi'] }, t: 2 },+ },+ },+ { contextEngine: {} },+ ]);++ expect(JSON.parse(inspectSnapshot(snap, { json: true, step: '1' })).contextEngine).toEqual({+ input: { toolCount: 2 },+ output: [hi],+ });+ });+it('defaults the step-scoped views to step 0', () => {const snap = snapshot([withSystemRole('first'), withSystemRole('second')]);expect(JSON.parse(inspectSnapshot(snap, { json: true, systemRole: true }))).toBe('first');diff --git a/packages/agent-tracing/src/inspect/inspectSnapshot.ts b/packages/agent-tracing/src/inspect/inspectSnapshot.tsindex 34cf7d64c30..a413d2f6de0 100644--- a/packages/agent-tracing/src/inspect/inspectSnapshot.ts+++ b/packages/agent-tracing/src/inspect/inspectSnapshot.ts@@ -150,7 +150,12 @@ export function inspectSnapshot(snapshot: ExecutionSnapshot, opts: InspectOption}if (opts.json) {- return stepIndex === undefined ? json(snapshot) : json(findStep(snapshot, stepIndex));+ if (stepIndex === undefined) return json(snapshot);+ // A step is read on its own, so give it the resolved CE rather than the+ // stored refs / omitted fields that only make sense against other steps.+ const step = findStep(snapshot, stepIndex);+ if (step.contextEngine === undefined) return json(step);+ return json({ ...step, contextEngine: resolveCeSnapshot(step, snapshot.steps) });}if (stepIndex === undefined) return renderSnapshot(snapshot);diff --git a/packages/agent-tracing/src/types.ts b/packages/agent-tracing/src/types.tsindex a9a4025337c..cef1f9aa0d8 100644--- a/packages/agent-tracing/src/types.ts+++ b/packages/agent-tracing/src/types.ts@@ -46,20 +46,29 @@ export interface StepSnapshot {};/*** Context Engine result snapshot for this step. Only present on steps where the CE ran- * (typically `call_llm`). Uses a delta format: only `input`/`output`/`metadata` fields- * that changed from the previous step are stored β resolve the full snapshot by walking- * backward through steps (same pattern as `messagesBaseline`/`messagesDelta`).+ * (typically `call_llm`). `undefined` means the CE did not run (e.g., `call_tool` steps).+ * Resolve it with `resolveContextEngineSteps` / `resolveCeSnapshot`, never by reading the+ * fields directly.*- * - `undefined` β CE did not run for this step (e.g., `call_tool` steps)- * - `{}` β CE ran but `input`/`output`/`metadata` are unchanged from before- * - `{ input }` β input changed; `output`/`metadata` unchanged- * - `{ metadata }` β pipeline decision metadata changed (trim stats, cache gates, β¦)- * - `{ input, output}` β both changed (full snapshot, typical of the first CE event)+ * Current recordings pool values: `inputRefs` maps each top-level input key to a ref, and+ * `outputRef` names an output list node `{ base?: ref, refs: ref[] }` β the messages of+ * the `base` node followed by `refs`. Every ref resolves through the `pool` of whichever+ * step of the snapshot first recorded it, so resolution does not depend on step order.+ * A long run re-sends nearly the same messages on every call; storing each message once+ * and each step's list as an extension of an earlier one keeps the trace linear in the+ * conversation instead of in steps Γ context size.+ *+ * Older recordings store full `input`/`output` values and omit a field that is unchanged+ * from the closest earlier step that stored it (`{}` = nothing changed). `metadata`+ * always uses this changed-fields form.*/contextEngine?: {input?: unknown;+ inputRefs?: Record<string, string>;metadata?: unknown;output?: unknown;+ outputRef?: string;+ pool?: Record<string, unknown>;};/*** Provider-native subscription credits consumed by this step (e.g. Qoder),diff --git a/packages/agent-tracing/src/utils/contextEngine.ts b/packages/agent-tracing/src/utils/contextEngine.tsnew file mode 100644index 00000000000..79058621bf3--- /dev/null+++ b/packages/agent-tracing/src/utils/contextEngine.ts@@ -0,0 +1,111 @@+import type { StepSnapshot } from '../types';++export interface ResolvedContextEngine {+ input?: unknown;+ metadata?: unknown;+ output?: unknown;+}++const resolvedBySteps = new WeakMap<+ readonly StepSnapshot[],+ { length: number; resolved: Map<StepSnapshot, ResolvedContextEngine> }+>();++/**+ * Resolve the full Context Engine snapshot of every step that ran the CE.+ *+ * Two storage formats coexist, possibly within one snapshot (a run that spans+ * a deploy):+ * - pooled: `inputRefs` / `outputRef` point into the `pool` entries that any+ * step of the snapshot introduced. `outputRef` names a list node+ * `{ base?, refs }`: the list of `base` followed by `refs`. Resolution does not+ * depend on step order.+ * - changed-fields: `input` / `output` / `metadata` hold full values, and an+ * omitted field means "same as the closest earlier step that stored it".+ *+ * `metadata` always uses the changed-fields form. Results are memoized per+ * steps array, so per-step callers (viewers) stay linear.+ */+export function resolveContextEngineSteps(+ steps: readonly StepSnapshot[],+): Map<StepSnapshot, ResolvedContextEngine> {+ const cached = resolvedBySteps.get(steps);+ if (cached && cached.length === steps.length) return cached.resolved;++ const pool = new Map<string, unknown>();+ for (const step of steps) {+ const entries = step.contextEngine?.pool;+ if (!entries) continue;+ for (const [ref, value] of Object.entries(entries)) pool.set(ref, value);+ }++ const lookup = (ref: string, stepIndex: number) => {+ if (!pool.has(ref)) {+ throw new Error(+ `Context engine pool entry ${ref} referenced by step ${stepIndex} is missing`,+ );+ }+ return pool.get(ref);+ };++ const lists = new Map<string, string[]>();+ const resolveList = (ref: string, stepIndex: number): string[] => {+ // Walk down to a resolved ancestor, then build the lists back up iteratively.+ const pending: Array<{ node: { base?: string; refs: string[] }; ref: string }> = [];+ let cursor: string | undefined = ref;+ let list: string[] = [];+ while (cursor !== undefined) {+ const known = lists.get(cursor);+ if (known) {+ list = known;+ break;+ }+ const node = lookup(cursor, stepIndex) as { base?: string; refs: string[] };+ pending.push({ node, ref: cursor });+ if (pending.length > pool.size) {+ throw new Error(`Context engine output list ${ref} of step ${stepIndex} is cyclic`);+ }+ cursor = node.base;+ }+ for (const { node, ref: nodeRef } of pending.reverse()) {+ list = [...list, ...node.refs];+ lists.set(nodeRef, list);+ }+ return list;+ };++ const resolved = new Map<StepSnapshot, ResolvedContextEngine>();+ let lastInput: unknown;+ let lastMetadata: unknown;+ let lastOutput: unknown;++ // Stable sort: equal step indexes keep their recorded order.+ const ordered = [...steps].sort((a, b) => a.stepIndex - b.stepIndex);+ for (const step of ordered) {+ const ce = step.contextEngine;+ if (!ce) continue;++ if (ce.inputRefs) {+ lastInput = Object.fromEntries(+ Object.entries(ce.inputRefs).map(([key, ref]) => [key, lookup(ref, step.stepIndex)]),+ );+ } else if (ce.input !== undefined) {+ lastInput = ce.input;+ }++ if (ce.outputRef !== undefined) {+ lastOutput = resolveList(ce.outputRef, step.stepIndex).map((ref) =>+ lookup(ref, step.stepIndex),+ );+ } else if (ce.output !== undefined) {+ lastOutput = ce.output;+ }++ if (ce.metadata !== undefined) lastMetadata = ce.metadata;++ resolved.set(step, { input: lastInput, metadata: lastMetadata, output: lastOutput });+ }++ resolvedBySteps.set(steps, { length: steps.length, resolved });+ return resolved;+}diff --git a/packages/agent-tracing/src/viewer/index.ts b/packages/agent-tracing/src/viewer/index.tsindex d5500333d36..5ed62178f96 100644--- a/packages/agent-tracing/src/viewer/index.ts+++ b/packages/agent-tracing/src/viewer/index.ts@@ -1,56 +1,27 @@import { encode } from 'gpt-tokenizer';import type { ExecutionSnapshot, SnapshotSummary, StepSnapshot } from '../types';+import { resolveContextEngineSteps } from '../utils/contextEngine';import { reconstructMessages } from '../utils/reconstruct';export { analyzeAgentSignal, renderAgentSignal } from './agentSignal';/**- * Resolve the Context Engine snapshot for a step, reconstructing missing `input`/`output`- * fields by walking back through previous steps (delta format).- * Returns undefined if CE did not run for this step.+ * Resolve the Context Engine snapshot for a step: pooled refs are looked up and fields+ * omitted by the changed-fields format are taken from earlier steps. Pass `allSteps` for+ * anything but a self-contained step. Returns undefined if CE did not run for this step.*- * Supports both the new `contextEngine` field format and the legacy `context_engine_result`- * event format for backward compatibility with older snapshots.+ * Supports both the `contextEngine` field and the legacy `context_engine_result` event+ * format of older snapshots.*/export function resolveCeSnapshot(step: StepSnapshot,allSteps?: StepSnapshot[],): Record<string, unknown> | undefined {- // New format: contextEngine typed fieldif (step.contextEngine !== undefined) {- let resolvedInput = step.contextEngine.input;- let resolvedMetadata = step.contextEngine.metadata;- let resolvedOutput = step.contextEngine.output;-- if (- allSteps &&- (resolvedInput === undefined ||- resolvedMetadata === undefined ||- resolvedOutput === undefined)- ) {- for (let i = step.stepIndex - 1; i >= 0; i--) {- const prevStep = allSteps.find((s) => s.stepIndex === i);- if (!prevStep?.contextEngine) continue;- if (resolvedInput === undefined && prevStep.contextEngine.input !== undefined) {- resolvedInput = prevStep.contextEngine.input;- }- if (resolvedMetadata === undefined && prevStep.contextEngine.metadata !== undefined) {- resolvedMetadata = prevStep.contextEngine.metadata;- }- if (resolvedOutput === undefined && prevStep.contextEngine.output !== undefined) {- resolvedOutput = prevStep.contextEngine.output;- }- if (- resolvedInput !== undefined &&- resolvedMetadata !== undefined &&- resolvedOutput !== undefined- )- break;- }- }-- return { input: resolvedInput, metadata: resolvedMetadata, output: resolvedOutput };+ const steps = allSteps?.includes(step) ? allSteps : [...(allSteps ?? []), step];+ const { input, metadata, output } = resolveContextEngineSteps(steps).get(step) ?? {};+ return { input, metadata, output };}// Legacy format: context_engine_result stored in events arraydiff --git a/packages/agent-tracing/src/viewer/resolveCeSnapshot.test.ts b/packages/agent-tracing/src/viewer/resolveCeSnapshot.test.tsindex 600b68b1d7d..f92a2ec6f04 100644--- a/packages/agent-tracing/src/viewer/resolveCeSnapshot.test.ts+++ b/packages/agent-tracing/src/viewer/resolveCeSnapshot.test.ts@@ -77,3 +77,46 @@ describe('resolveCeSnapshot', () => {});});});++describe('resolveCeSnapshot β pooled refs', () => {+ const m1 = { content: 'one', role: 'user' };+ const m2 = { content: 'two', role: 'assistant' };++ it('resolves refs whatever order the steps are stored in', () => {+ const steps = [+ ceStep(2, { inputRefs: { toolCount: 'r3' }, outputRef: 'n2' }),+ ceStep(0, {+ inputRefs: { toolCount: 'r3' },+ outputRef: 'n1',+ pool: { m1, n1: { refs: ['m1'] }, r3: 3 },+ }),+ ceStep(1, { outputRef: 'n1', pool: { m2, n2: { base: 'n1', refs: ['m2'] } } }),+ ];++ expect(resolveCeSnapshot(steps[0], steps)).toEqual({+ input: { toolCount: 3 },+ metadata: undefined,+ output: [m1, m2],+ });+ // Step 1 pooled n2 but only references n1; its input carries over from step 0.+ expect(resolveCeSnapshot(steps[2], steps)?.output).toEqual([m1]);+ expect(resolveCeSnapshot(steps[2], steps)?.input).toEqual({ toolCount: 3 });+ });++ it('fails loudly when a referenced pool entry is missing', () => {+ const steps = [ceStep(0, { outputRef: 'gone' })];++ expect(() => resolveCeSnapshot(steps[0], steps)).toThrow(/gone .*step 0 is missing/);+ });++ it('fails instead of looping on a cyclic output list', () => {+ const steps = [+ ceStep(0, {+ outputRef: 'a',+ pool: { a: { base: 'b', refs: [] }, b: { base: 'a', refs: [] } },+ }),+ ];++ expect(() => resolveCeSnapshot(steps[0], steps)).toThrow(/cyclic/);+ });+});