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.

✨ feat(agent-tracing): ctx-lint context quality linter + golden payload tests (#17113)

Arvin Xu1577b7989040
diff --git a/packages/agent-tracing/package.json b/packages/agent-tracing/package.json
index 94c26be7730..bd0c568c3f3 100644
--- a/packages/agent-tracing/package.json
+++ b/packages/agent-tracing/package.json
@@ -12,8 +12,14 @@
"agent-tracing": "./src/cli/index.ts",
"at": "./src/cli/index.ts"
},
+ "scripts": {
+ "test": "vitest run"
+ },
"dependencies": {
"commander": "^13.1.0",
"gpt-tokenizer": "^3.4.0"
+ },
+ "devDependencies": {
+ "vitest": "^3.2.4"
}
}
diff --git a/packages/agent-tracing/src/analysis/contextLint.test.ts b/packages/agent-tracing/src/analysis/contextLint.test.ts
new file mode 100644
index 00000000000..744f40d303b
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/contextLint.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExecutionSnapshot } from '../types';
+import { lintSnapshot, resolvePayloads } from './contextLint';
+
+const base = (steps: any[]): ExecutionSnapshot =>
+ ({
+ operationId: 'op_test',
+ startedAt: 0,
+ steps,
+ totalCost: 0,
+ totalSteps: steps.length,
+ totalTokens: 0,
+ traceId: 't',
+ }) as ExecutionSnapshot;
+
+describe('resolvePayloads', () => {
+ it('walks the contextEngine.output delta chain', () => {
+ const snap = base([
+ {
+ contextEngine: { output: [{ content: 'hi', role: 'user' }] },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ { stepIndex: 1, stepType: 'call_tool' },
+ // CE ran but output unchanged — must reuse step 0's payload
+ { contextEngine: {}, stepIndex: 2, stepType: 'call_llm' },
+ ]);
+ const { payloadSource, payloads } = resolvePayloads(snap);
+ expect(payloadSource).toBe('ce');
+ expect(payloads).toHaveLength(2);
+ expect(payloads[1].messages).toEqual(payloads[0].messages);
+ });
+
+ it('falls back to legacy messages when CE fields are absent', () => {
+ const snap = base([
+ { messages: [{ content: 'hi', role: 'user' }], stepIndex: 0, stepType: 'call_llm' },
+ ]);
+ expect(resolvePayloads(snap).payloadSource).toBe('legacy');
+ });
+});
+
+describe('lintSnapshot rules', () => {
+ it('clean payload produces no findings and score 100', () => {
+ const snap = base([
+ {
+ contextEngine: {
+ output: [
+ { content: 'You are helpful.', role: 'system' },
+ { content: 'hello', role: 'user' },
+ ],
+ },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]);
+ const { features, findings } = lintSnapshot(snap);
+ expect(findings).toHaveLength(0);
+ expect(features.lintScore).toBe(100);
+ expect(features.payloadMessages).toBe(2);
+ });
+
+ it('flags oversized tool results without truncation markers', () => {
+ const big = 'line of output that pads the result body considerably\n'.repeat(1500);
+ const snap = base([
+ {
+ stepIndex: 0,
+ stepType: 'call_tool',
+ toolsResult: [{ apiName: 'crawl', identifier: 'web', isSuccess: true, output: big }],
+ },
+ ]);
+ const rules = lintSnapshot(snap).findings.map((f) => f.rule);
+ expect(rules).toContain('oversized-tool-result');
+ // uniform repeats must also trip the degenerate-repetition rule
+ expect(rules).toContain('degenerate-repetition');
+ });
+
+ it('does not flag oversized results that declare truncation', () => {
+ const big = 'x'.repeat(40_000) + '\n[truncated: 900 more lines]';
+ const snap = base([
+ {
+ stepIndex: 0,
+ stepType: 'call_tool',
+ toolsResult: [{ apiName: 'read', identifier: 'fs', isSuccess: true, output: big }],
+ },
+ ]);
+ const rules = lintSnapshot(snap).findings.map((f) => f.rule);
+ expect(rules).not.toContain('oversized-tool-result');
+ });
+
+ it('flags oversized error results', () => {
+ const stack = 'Error: ECONNRESET\n at fetch (node:internal)\n'.repeat(80);
+ const snap = base([
+ {
+ stepIndex: 0,
+ stepType: 'call_tool',
+ toolsResult: [{ apiName: 'crawl', identifier: 'web', isSuccess: false, output: stack }],
+ },
+ ]);
+ const f = lintSnapshot(snap).findings.find((x) => x.rule === 'error-result-oversized');
+ expect(f).toBeDefined();
+ expect(f!.tool).toBe('web/crawl');
+ });
+
+ it('flags orphan tool results in the final payload', () => {
+ const snap = base([
+ {
+ contextEngine: {
+ output: [
+ { content: 'q', role: 'user' },
+ { content: 'result with no matching call', role: 'tool', tool_call_id: 'call_missing' },
+ ],
+ },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]);
+ const { features, findings } = lintSnapshot(snap);
+ expect(features.orphanToolResults).toBe(1);
+ expect(findings.some((f) => f.rule === 'orphan-tool-result')).toBe(true);
+ });
+
+ it('flags duplicated context blocks across messages', () => {
+ const doc = 'A very long shared document body. '.repeat(120);
+ const snap = base([
+ {
+ contextEngine: {
+ output: [
+ { content: doc, role: 'user' },
+ { content: `I read it: ${doc}`, role: 'assistant' },
+ ],
+ },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]);
+ const { features, findings } = lintSnapshot(snap);
+ expect(features.dupShare).toBeGreaterThan(0.3);
+ expect(findings.some((f) => f.rule === 'duplicate-context-block')).toBe(true);
+ });
+
+ it('flags tool-def bloat from offered vs called', () => {
+ const tools = Array.from({ length: 60 }, (_, i) => ({ function: { name: `t${i}` } }));
+ const snap = base([
+ {
+ context: { payload: { tools }, phase: 'user_input' },
+ stepIndex: 0,
+ stepType: 'call_llm',
+ toolsCalling: [{ apiName: 'a', identifier: 'x' }],
+ },
+ ]);
+ const { features, findings } = lintSnapshot(snap);
+ expect(features.toolsOffered).toBe(60);
+ expect(features.toolsCalled).toBe(1);
+ expect(findings.some((f) => f.rule === 'tool-def-bloat')).toBe(true);
+ });
+});
diff --git a/packages/agent-tracing/src/analysis/contextLint.ts b/packages/agent-tracing/src/analysis/contextLint.ts
new file mode 100644
index 00000000000..19d95f05fe7
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/contextLint.ts
@@ -0,0 +1,428 @@
+import { encode } from 'gpt-tokenizer';
+
+import type { ExecutionSnapshot, StepSnapshot } from '../types';
+import { analyzeToolResult } from './toolFeedback';
+
+/**
+ * Context Lint — deterministic (no-LLM) rules over the *assembled LLM payload* of an
+ * operation, the way ESLint works over source files. Each finding names a rule, the
+ * offending step/message, and the tokens it wastes, so violations can be ranked by
+ * token-weighted cost and traced back to the harness component that owns the fix
+ * (tool formatter / tool gating / system-prompt template / history compression).
+ *
+ * The payload source is `steps[].contextEngine.output` — the exact messages array the
+ * Context Engine handed to the model. Snapshots that predate the CE field fall back to
+ * the legacy `messages` chain, with `payloadSource: 'legacy'` marking lower fidelity.
+ */
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export type LintSeverity = 'error' | 'warn';
+
+export interface LintFinding {
+ detail: string;
+ messageIndex?: number;
+ rule: string;
+ severity: LintSeverity;
+ stepIndex: number;
+ tool?: string;
+ /** Tokens implicated by this finding — the waste weight used for ranking. */
+ wasteTokens: number;
+}
+
+/** Flat per-op feature vector — the candidate rollup shape for `agent_operations`. */
+export interface ContextLintFeatures {
+ assistantTokens: number;
+ /** Share of final-payload chars covered by shingles that occur in ≥2 messages. */
+ dupShare: number;
+ errorResultCount: number;
+ errorResultTokens: number;
+ /** Tokens of the largest payload actually sent to the model (last call_llm step). */
+ finalPayloadTokens: number;
+ findingsErrorCount: number;
+ findingsWarnCount: number;
+ lintScore: number;
+ llmSteps: number;
+ operationId: string;
+ orphanToolCalls: number;
+ orphanToolResults: number;
+ payloadMessages: number;
+ payloadSource: 'ce' | 'legacy' | 'none';
+ selfRedundancyMax: number;
+ structuralNoiseMax: number;
+ systemShare: number;
+ systemTokens: number;
+ toolMsgShare: number;
+ toolMsgTokens: number;
+ toolResultCount: number;
+ toolResultMaxTokens: number;
+ toolsCalled: number;
+ toolsOffered: number;
+ toolUtilization: number;
+ totalSteps: number;
+ userTokens: number;
+ /** Sum of finding wasteTokens, deduped per message. */
+ wasteTokens: number;
+}
+
+export interface ContextLintResult {
+ features: ContextLintFeatures;
+ findings: LintFinding[];
+}
+
+// ---------------------------------------------------------------------------
+// Thresholds (calibrated on the 2026-07 651-op stratified corpus)
+// ---------------------------------------------------------------------------
+
+const OVERSIZED_WARN_TOKENS = 4000;
+const OVERSIZED_ERROR_TOKENS = 12_000;
+const ERROR_RESULT_WARN_TOKENS = 500;
+const ERROR_RESULT_ERROR_TOKENS = 2000;
+const REPETITION_MIN_TOKENS = 1000;
+const REPETITION_RATIO = 0.3;
+const NOISE_MIN_TOKENS = 1000;
+const NOISE_RATIO = 0.25;
+const SYSTEM_WARN_TOKENS = 24_000;
+const SYSTEM_ERROR_TOKENS = 40_000;
+const TOOL_BLOAT_MIN_OFFERED = 40;
+const TOOL_BLOAT_MAX_UTILIZATION = 0.15;
+const DUP_WARN_SHARE = 0.05;
+const DUP_ERROR_SHARE = 0.15;
+const TRUNCATION_MARKER_RE =
+ /truncat|已截断|省略|omitted|clipped|\.\.\.\s*\(\d+\s*more|<more|remaining\s+\d+/i;
+
+// ---------------------------------------------------------------------------
+// Payload reconstruction
+// ---------------------------------------------------------------------------
+
+interface PayloadMessage {
+ content?: unknown;
+ name?: string;
+ reasoning?: string;
+ role: string;
+ tool_call_id?: string;
+ tool_calls?: Array<{ function?: { arguments?: string; name?: string }; id?: string }>;
+}
+
+function contentText(m: PayloadMessage): string {
+ if (typeof m.content === 'string') return m.content;
+ if (Array.isArray(m.content)) {
+ return m.content
+ .map((p) =>
+ typeof p === 'string' ? p : typeof (p as any)?.text === 'string' ? (p as any).text : '',
+ )
+ .join('\n');
+ }
+ return '';
+}
+
+/**
+ * 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.
+ */
+export function resolvePayloads(snapshot: ExecutionSnapshot): {
+ payloadSource: ContextLintFeatures['payloadSource'];
+ payloads: Array<{ messages: PayloadMessage[]; stepIndex: number }>;
+} {
+ let current: PayloadMessage[] | undefined;
+ const payloads: Array<{ messages: PayloadMessage[]; stepIndex: number }> = [];
+ for (const step of snapshot.steps) {
+ const out = step.contextEngine?.output;
+ if (Array.isArray(out)) current = out as PayloadMessage[];
+ if (step.stepType === 'call_llm' && current)
+ payloads.push({ messages: current, stepIndex: step.stepIndex });
+ }
+ if (payloads.length > 0) return { payloadSource: 'ce', payloads };
+
+ // Legacy fallback: full messages arrays recorded before the CE field existed.
+ let legacy: PayloadMessage[] | undefined;
+ const legacyPayloads: Array<{ messages: PayloadMessage[]; stepIndex: number }> = [];
+ for (const step of snapshot.steps) {
+ const msgs = (step as StepSnapshot).messages;
+ if (Array.isArray(msgs) && msgs.length > 0) legacy = msgs as PayloadMessage[];
+ if (step.stepType === 'call_llm' && legacy)
+ legacyPayloads.push({ messages: legacy, stepIndex: step.stepIndex });
+ }
+ return legacyPayloads.length > 0
+ ? { payloadSource: 'legacy', payloads: legacyPayloads }
+ : { payloadSource: 'none', payloads: [] };
+}
+
+// ---------------------------------------------------------------------------
+// Rule helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Char share of content whose word-level shingles also occur in another message.
+ * Word shingles (vs fixed char windows) keep detection alignment-free: a block quoted
+ * behind a prefix or reflowed across lines still matches its original.
+ */
+const DUP_WORDS = 16;
+// owner index at stride 1 so a copy at ANY word offset (or periodic content) still matches
+const DUP_OWNER_STRIDE = 1;
+function crossMessageDupShare(texts: string[]): number {
+ const owner = new Map<string, number>();
+ const words = texts.map((t) => t.split(/\s+/).filter(Boolean));
+ let totalChars = 0;
+ for (const [mi, ws] of words.entries()) {
+ totalChars += texts[mi].length;
+ for (let i = 0; i + DUP_WORDS <= ws.length; i += DUP_OWNER_STRIDE) {
+ const sh = ws.slice(i, i + DUP_WORDS).join(' ');
+ if (!owner.has(sh)) owner.set(sh, mi);
+ }
+ }
+ if (totalChars === 0) return 0;
+ let dup = 0;
+ for (const [mi, ws] of words.entries()) {
+ for (let i = 0; i + DUP_WORDS <= ws.length; i += DUP_WORDS) {
+ const sh = ws.slice(i, i + DUP_WORDS).join(' ');
+ const seen = owner.get(sh);
+ if (seen !== undefined && seen !== mi) dup += sh.length;
+ }
+ }
+ return Math.min(1, dup / totalChars);
+}
+
+function distinctToolNames(snapshot: ExecutionSnapshot): Set<string> {
+ const called = new Set<string>();
+ for (const step of snapshot.steps) {
+ for (const c of step.toolsCalling ?? []) {
+ if (c?.apiName) called.add(`${c.identifier ?? '?'}/${c.apiName}`);
+ }
+ }
+ return called;
+}
+
+function toolsOfferedCount(snapshot: ExecutionSnapshot): number {
+ for (const step of snapshot.steps) {
+ const payload = (step.context?.payload ?? {}) as { tools?: unknown[] };
+ if (Array.isArray(payload.tools)) return payload.tools.length;
+ const baseline = step.toolsetBaseline as { tools?: unknown[] } | undefined;
+ if (Array.isArray(baseline?.tools)) return baseline.tools.length;
+ }
+ return 0;
+}
+
+// ---------------------------------------------------------------------------
+// Lint
+// ---------------------------------------------------------------------------
+
+export function lintSnapshot(snapshot: ExecutionSnapshot): ContextLintResult {
+ const findings: LintFinding[] = [];
+ const { payloadSource, payloads } = resolvePayloads(snapshot);
+ const final = payloads.at(-1);
+ const finalMessages = final?.messages ?? [];
+ const finalStep = final?.stepIndex ?? 0;
+
+ // --- final payload composition ---
+ const perMessageTokens = finalMessages.map((m) => {
+ const text = contentText(m) + (m.tool_calls ? JSON.stringify(m.tool_calls) : '');
+ return text ? encode(text).length : 0;
+ });
+ const finalPayloadTokens = perMessageTokens.reduce((s, t) => s + t, 0);
+ const roleTokens = (role: string) =>
+ finalMessages.reduce((s, m, i) => (m.role === role ? s + perMessageTokens[i] : s), 0);
+ const systemTokens = roleTokens('system');
+ const toolMsgTokens = roleTokens('tool');
+ const assistantTokens = roleTokens('assistant');
+ const userTokens = roleTokens('user');
+
+ const wastedByMessage = new Map<number, number>();
+ const noteWaste = (messageIndex: number | undefined, tokens: number) => {
+ if (messageIndex === undefined) return;
+ wastedByMessage.set(messageIndex, Math.max(wastedByMessage.get(messageIndex) ?? 0, tokens));
+ };
+
+ // --- rule: system-prompt-bloat ---
+ if (systemTokens >= SYSTEM_WARN_TOKENS) {
+ const sysIdx = finalMessages.findIndex((m) => m.role === 'system');
+ findings.push({
+ detail: `system prompt is ${systemTokens} tokens (${Math.round((systemTokens / Math.max(1, finalPayloadTokens)) * 100)}% of payload)`,
+ messageIndex: sysIdx,
+ rule: 'system-prompt-bloat',
+ severity: systemTokens >= SYSTEM_ERROR_TOKENS ? 'error' : 'warn',
+ stepIndex: finalStep,
+ wasteTokens: systemTokens - SYSTEM_WARN_TOKENS,
+ });
+ noteWaste(sysIdx, systemTokens - SYSTEM_WARN_TOKENS);
+ }
+
+ // --- per tool-result rules (scored on raw toolsResult, attributed to payload when present) ---
+ let toolResultCount = 0;
+ let toolResultMaxTokens = 0;
+ let errorResultCount = 0;
+ let errorResultTokens = 0;
+ let selfRedundancyMax = 0;
+ let structuralNoiseMax = 0;
+ for (const step of snapshot.steps) {
+ for (const r of step.toolsResult ?? []) {
+ if (typeof r?.output !== 'string') continue;
+ toolResultCount += 1;
+ const m = analyzeToolResult(r.output, r.isSuccess);
+ const tool = `${r.identifier ?? '?'}/${r.apiName ?? '?'}`;
+ toolResultMaxTokens = Math.max(toolResultMaxTokens, m.tokens);
+ selfRedundancyMax = Math.max(selfRedundancyMax, m.selfRedundancy);
+ structuralNoiseMax = Math.max(structuralNoiseMax, m.structuralNoiseRatio);
+ if (m.isError) {
+ errorResultCount += 1;
+ errorResultTokens += m.tokens;
+ }
+
+ if (m.tokens >= OVERSIZED_WARN_TOKENS && !TRUNCATION_MARKER_RE.test(r.output)) {
+ findings.push({
+ detail: `${m.tokens} tokens with no truncation marker`,
+ rule: 'oversized-tool-result',
+ severity: m.tokens >= OVERSIZED_ERROR_TOKENS ? 'error' : 'warn',
+ stepIndex: step.stepIndex,
+ tool,
+ wasteTokens: m.tokens - OVERSIZED_WARN_TOKENS,
+ });
+ }
+ if (m.isError && m.tokens >= ERROR_RESULT_WARN_TOKENS) {
+ findings.push({
+ detail: `error result is ${m.tokens} tokens — failures should be one line`,
+ rule: 'error-result-oversized',
+ severity: m.tokens >= ERROR_RESULT_ERROR_TOKENS ? 'error' : 'warn',
+ stepIndex: step.stepIndex,
+ tool,
+ wasteTokens: m.tokens - ERROR_RESULT_WARN_TOKENS,
+ });
+ }
+ if (m.selfRedundancy >= REPETITION_RATIO && m.tokens >= REPETITION_MIN_TOKENS) {
+ findings.push({
+ detail: `${Math.round(m.selfRedundancy * 100)}% of the content is exact repeats`,
+ rule: 'degenerate-repetition',
+ severity: 'error',
+ stepIndex: step.stepIndex,
+ tool,
+ wasteTokens: Math.round(m.tokens * m.selfRedundancy),
+ });
+ }
+ if (m.structuralNoiseRatio >= NOISE_RATIO && m.tokens >= NOISE_MIN_TOKENS) {
+ findings.push({
+ detail: `${Math.round(m.structuralNoiseRatio * 100)}% markup-attribute noise (id/class/data-*)`,
+ rule: 'structural-noise',
+ severity: 'warn',
+ stepIndex: step.stepIndex,
+ tool,
+ wasteTokens: Math.round(m.tokens * m.structuralNoiseRatio),
+ });
+ }
+ }
+ }
+
+ // --- rule: duplicate-context-block ---
+ const dupShare = crossMessageDupShare(finalMessages.map((m) => contentText(m)));
+ if (dupShare >= DUP_WARN_SHARE && finalPayloadTokens > 0) {
+ findings.push({
+ detail: `${Math.round(dupShare * 100)}% of payload chars appear in more than one message`,
+ rule: 'duplicate-context-block',
+ severity: dupShare >= DUP_ERROR_SHARE ? 'error' : 'warn',
+ stepIndex: finalStep,
+ wasteTokens: Math.round(finalPayloadTokens * dupShare),
+ });
+ }
+
+ // --- rule: orphan tool linkage (structure) ---
+ let orphanToolCalls = 0;
+ let orphanToolResults = 0;
+ if (finalMessages.length > 0) {
+ const callIds = new Set<string>();
+ for (const m of finalMessages) {
+ for (const c of m.tool_calls ?? []) if (c?.id) callIds.add(c.id);
+ }
+ const resultIds = new Set<string>();
+ for (const [i, m] of finalMessages.entries()) {
+ if (m.role !== 'tool') continue;
+ if (m.tool_call_id) resultIds.add(m.tool_call_id);
+ if (!m.tool_call_id || !callIds.has(m.tool_call_id)) {
+ orphanToolResults += 1;
+ findings.push({
+ detail: `tool message [${i}] has no matching assistant tool_call (${m.tool_call_id ?? 'missing id'})`,
+ messageIndex: i,
+ rule: 'orphan-tool-result',
+ severity: 'error',
+ stepIndex: finalStep,
+ wasteTokens: perMessageTokens[i] ?? 0,
+ });
+ noteWaste(i, perMessageTokens[i] ?? 0);
+ }
+ }
+ for (const id of callIds) if (!resultIds.has(id)) orphanToolCalls += 1;
+ if (orphanToolCalls > 0) {
+ findings.push({
+ detail: `${orphanToolCalls} assistant tool_call(s) have no tool result message`,
+ rule: 'orphan-tool-call',
+ severity: 'error',
+ stepIndex: finalStep,
+ wasteTokens: 0,
+ });
+ }
+ }
+
+ // --- rule: tool-def-bloat ---
+ const toolsOffered = toolsOfferedCount(snapshot);
+ const toolsCalled = distinctToolNames(snapshot).size;
+ const toolUtilization = toolsOffered > 0 ? toolsCalled / toolsOffered : 1;
+ if (toolsOffered >= TOOL_BLOAT_MIN_OFFERED && toolUtilization < TOOL_BLOAT_MAX_UTILIZATION) {
+ findings.push({
+ detail: `${toolsOffered} tools offered, ${toolsCalled} called (${Math.round(toolUtilization * 100)}% utilization)`,
+ rule: 'tool-def-bloat',
+ severity: 'warn',
+ stepIndex: 0,
+ wasteTokens: 0, // definitions live outside the messages payload; tracked as a count feature
+ });
+ }
+
+ // --- score: share of the final payload not implicated by any finding ---
+ const messageWaste = [...wastedByMessage.values()].reduce((s, t) => s + t, 0);
+ const resultWaste = findings
+ .filter((f) => f.messageIndex === undefined)
+ .reduce((s, f) => s + f.wasteTokens, 0);
+ const wasteTokens = messageWaste + resultWaste;
+ const lintScore =
+ finalPayloadTokens > 0
+ ? Math.max(0, Math.round(100 * (1 - wasteTokens / finalPayloadTokens)))
+ : findings.length > 0
+ ? 0
+ : 100;
+
+ return {
+ features: {
+ assistantTokens,
+ dupShare: Number(dupShare.toFixed(4)),
+ errorResultCount,
+ errorResultTokens,
+ findingsErrorCount: findings.filter((f) => f.severity === 'error').length,
+ findingsWarnCount: findings.filter((f) => f.severity === 'warn').length,
+ finalPayloadTokens,
+ lintScore,
+ llmSteps: snapshot.steps.filter((s) => s.stepType === 'call_llm').length,
+ operationId: snapshot.operationId,
+ orphanToolCalls,
+ orphanToolResults,
+ payloadMessages: finalMessages.length,
+ payloadSource,
+ selfRedundancyMax: Number(selfRedundancyMax.toFixed(4)),
+ structuralNoiseMax: Number(structuralNoiseMax.toFixed(4)),
+ systemShare:
+ finalPayloadTokens > 0 ? Number((systemTokens / finalPayloadTokens).toFixed(4)) : 0,
+ systemTokens,
+ toolMsgShare:
+ finalPayloadTokens > 0 ? Number((toolMsgTokens / finalPayloadTokens).toFixed(4)) : 0,
+ toolMsgTokens,
+ toolResultCount,
+ toolResultMaxTokens,
+ toolUtilization: Number(toolUtilization.toFixed(4)),
+ toolsCalled,
+ toolsOffered,
+ totalSteps: snapshot.steps.length,
+ userTokens,
+ wasteTokens,
+ },
+ findings,
+ };
+}
diff --git a/packages/agent-tracing/src/analysis/toolFeedback.test.ts b/packages/agent-tracing/src/analysis/toolFeedback.test.ts
new file mode 100644
index 00000000000..10e8d583250
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/toolFeedback.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyToolError } from './toolFeedback';
+
+describe('classifyToolError', () => {
+ it('trusts an explicit isSuccess flag over content', () => {
+ expect(classifyToolError('everything fine', false)).toBe(true);
+ // successful read of a file that talks about errors is NOT a failure
+ expect(classifyToolError('Error handling guide: ...'.repeat(500), true)).toBe(false);
+ });
+
+ it('mixed crawlResults with successful pages is not a failure', () => {
+ const mixed =
+ '<crawlResults>\n <error errorType="Error" errorMessage="500" />\n <page url="https://a.com">content</page>\n</crawlResults>';
+ expect(classifyToolError(mixed, undefined)).toBe(false);
+ });
+
+ it('crawlResults with only error entries is a failure', () => {
+ const allErr =
+ '<crawlResults>\n <error errorType="Error" errorMessage="Browserless 500" />\n <error errorType="Error" errorMessage="Browserless 500" />\n</crawlResults>';
+ expect(classifyToolError(allErr, undefined)).toBe(true);
+ });
+
+ it('falls back to the head regex only for short unflagged outputs', () => {
+ expect(classifyToolError('Error: ENOENT no such file', undefined)).toBe(true);
+ // long content mentioning "error" is usually mixed content, not a failure
+ const longDoc = `# Handling error states\n${'body text '.repeat(600)}`;
+ expect(classifyToolError(longDoc, undefined)).toBe(false);
+ });
+});
diff --git a/packages/agent-tracing/src/analysis/toolFeedback.ts b/packages/agent-tracing/src/analysis/toolFeedback.ts
index 1824685e220..c9d9be7a3f3 100644
--- a/packages/agent-tracing/src/analysis/toolFeedback.ts
+++ b/packages/agent-tracing/src/analysis/toolFeedback.ts
@@ -16,7 +16,7 @@ export interface ToolResultMetrics {
chars: number;
format: 'json' | 'xml' | 'markdown' | 'text';
identifier: string;
- /** `isSuccess === false`, or an error/stack signal in the head of the content. */
+ /** Failure per `classifyToolError`: explicit flag > structured containers > short-output regex. */
isError: boolean;
/** 0..1 — fraction of fixed-size shingles that are exact repeats (degenerate dumps). */
selfRedundancy: number;
@@ -36,6 +36,28 @@ export interface ToolResultMetrics {
const SHINGLE = 80;
const ERROR_HEAD = 2000;
const ERROR_RE = /\b(?:error|failed|failure|exception|enoent|econn|traceback|status\s+5\d\d)\b/i;
+// Content that merely *mentions* errors (mixed crawl results, code files, logs quoted in a
+// successful read) must not be classified as a failure — validated 2026-07: a sample of 10
+// "large error" results picked by the old head-regex were ALL isSuccess=true partial
+// successes. The regex is now only a fallback for short outputs with no explicit flag.
+const ERROR_RE_MAX_CHARS = 2000;
+
+/**
+ * Classify a tool result as a failure.
+ * Trust order: explicit `isSuccess` flag > structured error containers > head regex
+ * (short outputs only — long content that mentions "error" is usually mixed content).
+ */
+export function classifyToolError(content: string, isSuccess: boolean | undefined): boolean {
+ if (isSuccess === false) return true;
+ if (isSuccess === true) return false;
+ // structured container: <crawlResults> with only <error> entries and no successful pages
+ if (/^\s*<crawlResults[\s>]/.test(content)) {
+ const errors = (content.match(/<error[\s>]/g) ?? []).length;
+ const pages = (content.match(/<page[\s>]/g) ?? []).length;
+ return errors > 0 && pages === 0;
+ }
+ return content.length <= ERROR_RE_MAX_CHARS && ERROR_RE.test(content.slice(0, ERROR_HEAD));
+}
/** Tool outputs are frequently JSON-wrapped as `{"content":"..."}` — score the payload, not the envelope. */
function unwrapContent(output: string): string {
@@ -95,7 +117,7 @@ export function analyzeToolResult(
return {
chars: content.length,
format,
- isError: isSuccess === false || ERROR_RE.test(content.slice(0, ERROR_HEAD)),
+ isError: classifyToolError(content, isSuccess),
selfRedundancy: selfRedundancy(content),
structuralNoiseRatio: structuralNoiseRatio(content, format),
tokens: content ? encode(content).length : 0,
diff --git a/packages/agent-tracing/src/cli/ctx-lint.ts b/packages/agent-tracing/src/cli/ctx-lint.ts
new file mode 100644
index 00000000000..a673db85d3d
--- /dev/null
+++ b/packages/agent-tracing/src/cli/ctx-lint.ts
@@ -0,0 +1,133 @@
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Command } from 'commander';
+
+import { type ContextLintResult, type LintFinding, lintSnapshot } from '../analysis/contextLint';
+import { FileSnapshotStore } from '../store/file-store';
+import { isOperationId, RemoteSnapshotStore } from '../store/remote-store';
+import type { ExecutionSnapshot } from '../types';
+
+const dim = (s: string) => `\x1B[2m${s}\x1B[22m`;
+const bold = (s: string) => `\x1B[1m${s}\x1B[22m`;
+const red = (s: string) => `\x1B[31m${s}\x1B[39m`;
+const yellow = (s: string) => `\x1B[33m${s}\x1B[39m`;
+const green = (s: string) => `\x1B[32m${s}\x1B[39m`;
+const cyan = (s: string) => `\x1B[36m${s}\x1B[39m`;
+
+function fmtTokens(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return String(Math.round(n));
+}
+
+function sevIcon(f: LintFinding): string {
+ return f.severity === 'error' ? red('✖') : yellow('⚠');
+}
+
+function renderResult(result: ContextLintResult): string {
+ const { features: ft, findings } = result;
+ const lines: string[] = [];
+ const scoreColor = ft.lintScore >= 90 ? green : ft.lintScore >= 70 ? yellow : red;
+ lines.push(
+ `${bold('ctx-lint')} ${cyan(ft.operationId)} score ${scoreColor(String(ft.lintScore))} ` +
+ dim(
+ `payload ${fmtTokens(ft.finalPayloadTokens)} tok / ${ft.payloadMessages} msgs / source=${ft.payloadSource}`,
+ ),
+ );
+ lines.push(
+ dim(
+ ` system ${fmtTokens(ft.systemTokens)} (${Math.round(ft.systemShare * 100)}%) ` +
+ `tool-results ${fmtTokens(ft.toolMsgTokens)} (${Math.round(ft.toolMsgShare * 100)}%) ` +
+ `tools ${ft.toolsCalled}/${ft.toolsOffered} used dup ${Math.round(ft.dupShare * 100)}%`,
+ ),
+ );
+ if (findings.length === 0) {
+ lines.push(green(' ✓ no findings'));
+ return lines.join('\n');
+ }
+ const sorted = [...findings].sort((a, b) => b.wasteTokens - a.wasteTokens);
+ for (const f of sorted) {
+ const loc = `step ${f.stepIndex}${f.messageIndex === undefined ? '' : ` msg[${f.messageIndex}]`}`;
+ const tool = f.tool ? ` ${cyan(f.tool)}` : '';
+ const waste = f.wasteTokens > 0 ? dim(` −${fmtTokens(f.wasteTokens)} tok`) : '';
+ lines.push(
+ ` ${sevIcon(f)} ${bold(f.rule.padEnd(26))} ${dim(loc)}${tool} ${f.detail}${waste}`,
+ );
+ }
+ return lines.join('\n');
+}
+
+async function loadFromDir(dir: string, limit?: number): Promise<ExecutionSnapshot[]> {
+ const files = (await readdir(dir)).filter((f) => f.endsWith('.json'));
+ const selected = limit ? files.slice(0, limit) : files;
+ const out: ExecutionSnapshot[] = [];
+ for (const f of selected) {
+ try {
+ const snap = JSON.parse(await readFile(path.join(dir, f), 'utf8'));
+ if (snap?.operationId && Array.isArray(snap.steps)) out.push(snap);
+ } catch {
+ // skip non-snapshot json
+ }
+ }
+ return out;
+}
+
+export function registerCtxLintCommand(program: Command) {
+ program
+ .command('ctx-lint')
+ .alias('cl')
+ .description('Lint the assembled LLM context of one operation or a snapshot corpus')
+ .argument('[target]', 'operation id, snapshot json path, or directory of snapshots')
+ .option('-l, --limit <n>', 'max snapshots when target is a directory')
+ .option('-j, --json', 'JSON output (per-op features + findings)')
+ .option('--features-only', 'JSONL feature vectors only (for downstream analysis)')
+ .action(
+ async (
+ target: string | undefined,
+ opts: { featuresOnly?: boolean; json?: boolean; limit?: string },
+ ) => {
+ let snapshots: ExecutionSnapshot[];
+
+ if (target && isOperationId(target)) {
+ const store = new FileSnapshotStore();
+ let snap = await store.get(target);
+ if (!snap) snap = await new RemoteSnapshotStore().getCached(target);
+ if (!snap) {
+ console.error(
+ red(
+ `Snapshot not found for ${target} (fetch it first via \`agent-tracing inspect\`)`,
+ ),
+ );
+ process.exit(1);
+ }
+ snapshots = [snap];
+ } else if (target) {
+ const stat = await import('node:fs/promises').then((fs) => fs.stat(target));
+ snapshots = stat.isDirectory()
+ ? await loadFromDir(target, opts.limit ? Number.parseInt(opts.limit, 10) : undefined)
+ : [JSON.parse(await readFile(target, 'utf8'))];
+ } else {
+ const store = new FileSnapshotStore();
+ const latest = await store.getLatest();
+ if (!latest) {
+ console.error(red('No local snapshot found.'));
+ process.exit(1);
+ }
+ snapshots = [latest];
+ }
+
+ const results = snapshots.map((s) => lintSnapshot(s));
+
+ if (opts.featuresOnly) {
+ for (const r of results) console.log(JSON.stringify(r.features));
+ return;
+ }
+ if (opts.json) {
+ console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
+ return;
+ }
+ for (const r of results) console.log(renderResult(r) + '\n');
+ },
+ );
+}
diff --git a/packages/agent-tracing/src/cli/index.ts b/packages/agent-tracing/src/cli/index.ts
index abdd5c0dcae..a9d0f684ccf 100755
--- a/packages/agent-tracing/src/cli/index.ts
+++ b/packages/agent-tracing/src/cli/index.ts
@@ -2,6 +2,7 @@
import { Command } from 'commander';
+import { registerCtxLintCommand } from './ctx-lint';
import { registerInspectCommand } from './inspect';
import { registerListCommand } from './list';
import { registerPartialCommand } from './partial';
@@ -15,5 +16,6 @@ registerInspectCommand(program);
registerListCommand(program);
registerPartialCommand(program);
registerToolQualityCommand(program);
+registerCtxLintCommand(program);
program.parse();
diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.ts
index 58e42a75a2a..0a8ed9d6d81 100644
--- a/packages/agent-tracing/src/index.ts
+++ b/packages/agent-tracing/src/index.ts
@@ -1,3 +1,10 @@
+export {
+ type ContextLintFeatures,
+ type ContextLintResult,
+ type LintFinding,
+ lintSnapshot,
+ resolvePayloads,
+} from './analysis/contextLint';
export { appendStepToPartial, finalizeSnapshot } from './recorder';
export { FileSnapshotStore } from './store/file-store';
export { isOperationId, parseOperationId } from './store/remote-store';
diff --git a/packages/agent-tracing/vitest.config.mts b/packages/agent-tracing/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/agent-tracing/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.golden.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.golden.test.ts
new file mode 100644
index 00000000000..4c7e99afb33
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.golden.test.ts
@@ -0,0 +1,187 @@
+import { estimateTokenCount } from 'tokenx';
+import { describe, expect, it } from 'vitest';
+
+import type { UIChatMessage } from '@/types/index';
+
+import { MessagesEngine } from '../MessagesEngine';
+import type { MessagesEngineParams } from '../types';
+
+/**
+ * Golden regression tests for the assembled LLM payload.
+ *
+ * Unlike the behavior tests in MessagesEngine.test.ts, these pin the *entire* output
+ * payload for fixed scenarios via snapshots, plus hard budget/structure invariants.
+ * A processor change that grows the system prompt, drops a tool linkage, or reorders
+ * messages shows up here as a reviewable snapshot diff instead of a production
+ * token-bill surprise.
+ *
+ * Budgets are intentionally generous ceilings, not targets — bump them consciously in
+ * the same PR that grows the payload, with the cost called out in review.
+ */
+
+const at = 1_700_000_000_000; // fixed timestamps keep snapshots stable
+
+// object (not Partial<UIChatMessage>) so fixtures can carry OpenAI-shape fields like
+// tool_calls that UIChatMessage doesn't declare — same as the inline casts in MessagesEngine.test.ts
+const msg = (partial: object): UIChatMessage =>
+ ({ createdAt: at, updatedAt: at, ...partial }) as UIChatMessage;
+
+const payloadTokens = (messages: Array<{ content?: unknown; tool_calls?: unknown }>) =>
+ messages.reduce(
+ (sum, m) =>
+ sum +
+ estimateTokenCount(
+ (typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '')) +
+ (m.tool_calls ? JSON.stringify(m.tool_calls) : ''),
+ ),
+ 0,
+ );
+
+/** Structure invariants every assembled payload must satisfy. */
+const expectWellFormed = (messages: any[]) => {
+ // single leading system message (when present)
+ const systemIndexes = messages.flatMap((m, i) => (m.role === 'system' ? [i] : []));
+ expect(systemIndexes.length).toBeLessThanOrEqual(1);
+ if (systemIndexes.length === 1) expect(systemIndexes[0]).toBe(0);
+
+ // every tool message links to a preceding assistant tool_call (no orphans)
+ const seenCallIds = new Set<string>();
+ for (const m of messages) {
+ if (m.role === 'assistant') {
+ for (const c of m.tool_calls ?? []) seenCallIds.add(c.id);
+ }
+ if (m.role === 'tool') {
+ expect(m.tool_call_id, 'tool message must carry tool_call_id').toBeTruthy();
+ expect(seenCallIds.has(m.tool_call_id), `orphan tool result ${m.tool_call_id}`).toBe(true);
+ }
+ }
+
+ // no empty non-assistant messages (dead weight the model cannot use)
+ for (const m of messages) {
+ if (m.role === 'user' || m.role === 'tool') {
+ expect(String(m.content ?? '').length, `${m.role} message must not be empty`).toBeGreaterThan(
+ 0,
+ );
+ }
+ }
+};
+
+describe('MessagesEngine golden payloads', () => {
+ it('plain chat: system role + short history', async () => {
+ const params: MessagesEngineParams = {
+ enableSystemDate: false,
+ messages: [
+ msg({ content: '推荐一个 mac 上的 redis 客户端', id: 'u1', role: 'user' }),
+ msg({ content: '可以试试 Medis。', id: 'a1', role: 'assistant' }),
+ msg({ content: '开源的吗?', id: 'u2', role: 'user' }),
+ ],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: 'You are LobeHub assistant. Answer concisely in the user language.',
+ };
+
+ const { messages } = await new MessagesEngine(params).process();
+
+ expectWellFormed(messages);
+ expect(messages).toMatchSnapshot();
+ expect(payloadTokens(messages)).toBeLessThan(200);
+ });
+
+ it('tool round-trip: assistant tool_calls + tool result survive assembly intact', async () => {
+ const params: MessagesEngineParams = {
+ enableSystemDate: false,
+ messages: [
+ msg({ content: '查一下项目里有多少 TODO', id: 'u1', role: 'user' }),
+ msg({
+ content: '',
+ id: 'a1',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{"pattern":"TODO","path":"src"}',
+ name: 'lobe-local-system____grepContent',
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ }),
+ msg({
+ content:
+ 'Found 3 matches:\nsrc/a.ts:12: // TODO refactor\nsrc/b.ts:3: // TODO test\nsrc/c.ts:8: // TODO doc',
+ id: 't1',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ }),
+ msg({ content: '帮我列成表格', id: 'u2', role: 'user' }),
+ ],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: 'You are LobeHub assistant.',
+ };
+
+ const { messages } = await new MessagesEngine(params).process();
+
+ expectWellFormed(messages);
+ // the tool linkage must survive assembly — losing it silently breaks the next turn
+ expect(messages.some((m: any) => m.role === 'tool' && m.tool_call_id === 'call_1')).toBe(true);
+ expect(messages.some((m: any) => m.tool_calls?.some((c: any) => c.id === 'call_1'))).toBe(true);
+ expect(messages).toMatchSnapshot();
+ });
+
+ it('system prompt assembly stays inside its token budget', async () => {
+ const params: MessagesEngineParams = {
+ enableSystemDate: false,
+ knowledge: {
+ fileContents: [
+ { content: 'Redis is an in-memory data store.', fileId: 'f1', filename: 'redis.md' },
+ ],
+ knowledgeBases: [{ id: 'kb1', name: 'Docs' }],
+ },
+ messages: [msg({ content: 'redis 怎么做持久化?', id: 'u1', role: 'user' })],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: 'You are LobeHub assistant.',
+ };
+
+ const { messages } = await new MessagesEngine(params).process();
+ const system = messages.find((m: any) => m.role === 'system');
+
+ expectWellFormed(messages);
+ expect(system).toBeDefined();
+ // Fixture system prompt (role + knowledge scaffold) must stay small. The production
+ // median system prompt is already ~13k tokens / 32% of the payload — this guard is
+ // about catching *unreviewed template growth* at the source.
+ expect(estimateTokenCount(String(system!.content))).toBeLessThan(600);
+ expect(messages).toMatchSnapshot();
+ });
+
+ it('history truncation: historyCount actually bounds the payload', async () => {
+ const history: UIChatMessage[] = [];
+ for (let i = 0; i < 20; i++) {
+ history.push(
+ msg({ content: `question ${i}`, id: `u${i}`, role: 'user' }),
+ msg({ content: `answer ${i}`, id: `a${i}`, role: 'assistant' }),
+ );
+ }
+ history.push(msg({ content: 'final question', id: 'u-final', role: 'user' }));
+
+ const params: MessagesEngineParams = {
+ enableHistoryCount: true,
+ enableSystemDate: false,
+ historyCount: 4,
+ messages: history,
+ model: 'gpt-4',
+ provider: 'openai',
+ };
+
+ const { messages } = await new MessagesEngine(params).process();
+
+ expectWellFormed(messages);
+ const nonSystem = messages.filter((m: any) => m.role !== 'system');
+ expect(nonSystem.length).toBeLessThanOrEqual(5);
+ expect(nonSystem.at(-1)?.content).toBe('final question');
+ expect(messages).toMatchSnapshot();
+ });
+});
diff --git a/packages/context-engine/src/engine/messages/__tests__/__snapshots__/MessagesEngine.golden.test.ts.snap b/packages/context-engine/src/engine/messages/__tests__/__snapshots__/MessagesEngine.golden.test.ts.snap
new file mode 100644
index 00000000000..a5a20ab752f
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/__tests__/__snapshots__/MessagesEngine.golden.test.ts.snap
@@ -0,0 +1,109 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`MessagesEngine golden payloads > history truncation: historyCount actually bounds the payload 1`] = `
+[
+ {
+ "content": "answer 18",
+ "role": "assistant",
+ },
+ {
+ "content": "question 19",
+ "role": "user",
+ },
+ {
+ "content": "answer 19",
+ "role": "assistant",
+ },
+ {
+ "content": "final question",
+ "role": "user",
+ },
+]
+`;
+
+exports[`MessagesEngine golden payloads > plain chat: system role + short history 1`] = `
+[
+ {
+ "content": "You are LobeHub assistant. Answer concisely in the user language.",
+ "role": "system",
+ },
+ {
+ "content": "推荐一个 mac 上的 redis 客户端",
+ "role": "user",
+ },
+ {
+ "content": "可以试试 Medis。",
+ "role": "assistant",
+ },
+ {
+ "content": "开源的吗?",
+ "role": "user",
+ },
+]
+`;
+
+exports[`MessagesEngine golden payloads > system prompt assembly stays inside its token budget 1`] = `
+[
+ {
+ "content": "You are LobeHub assistant.",
+ "role": "system",
+ },
+ {
+ "content": "<agent_knowledge>
+<instruction>The following files and knowledge bases are available. For files, refer to their content directly. For knowledge bases, use the searchKnowledgeBase tool to find relevant information.</instruction>
+<files totalCount="1">
+<file id="f1" name="redis.md">
+Redis is an in-memory data store.
+</file>
+</files>
+<knowledge_bases totalCount="1">
+<knowledge_base id="kb1" name="Docs" />
+</knowledge_bases>
+</agent_knowledge>",
+ "role": "user",
+ },
+ {
+ "content": "redis 怎么做持久化?",
+ "role": "user",
+ },
+]
+`;
+
+exports[`MessagesEngine golden payloads > tool round-trip: assistant tool_calls + tool result survive assembly intact 1`] = `
+[
+ {
+ "content": "You are LobeHub assistant.",
+ "role": "system",
+ },
+ {
+ "content": "查一下项目里有多少 TODO",
+ "role": "user",
+ },
+ {
+ "content": "",
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "function": {
+ "arguments": "{"pattern":"TODO","path":"src"}",
+ "name": "lobe-local-system____grepContent",
+ },
+ "id": "call_1",
+ "type": "function",
+ },
+ ],
+ },
+ {
+ "content": "Found 3 matches:
+src/a.ts:12: // TODO refactor
+src/b.ts:3: // TODO test
+src/c.ts:8: // TODO doc",
+ "role": "tool",
+ "tool_call_id": "call_1",
+ },
+ {
+ "content": "帮我列成表格",
+ "role": "user",
+ },
+]
+`;