@tangle-network/agent-eval 0.119.0 → 0.119.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/analyst/index.d.ts +30 -39
  3. package/dist/analyst/index.js +9 -5
  4. package/dist/analyst/index.js.map +1 -1
  5. package/dist/benchmarks/index.js +5 -5
  6. package/dist/campaign/index.d.ts +28 -29
  7. package/dist/campaign/index.js +5 -5
  8. package/dist/{chunk-LMJ2TGWJ.js → chunk-JM2SKQMS.js} +2 -2
  9. package/dist/{chunk-RLCJQ6VZ.js → chunk-PSXJ32SR.js} +157 -3
  10. package/dist/chunk-PSXJ32SR.js.map +1 -0
  11. package/dist/{chunk-6QIM2EAP.js → chunk-PXD6ZFNY.js} +99 -1
  12. package/dist/chunk-PXD6ZFNY.js.map +1 -0
  13. package/dist/{chunk-GERDAIAL.js → chunk-QWMPPZ3X.js} +3 -3
  14. package/dist/{chunk-7A4LIMMY.js → chunk-S5TT5R3L.js} +229 -97
  15. package/dist/chunk-S5TT5R3L.js.map +1 -0
  16. package/dist/{chunk-ZYHJNKI3.js → chunk-ULOKLHIQ.js} +42 -5
  17. package/dist/chunk-ULOKLHIQ.js.map +1 -0
  18. package/dist/{chunk-FIUFRXP3.js → chunk-WW2A73HW.js} +49 -91
  19. package/dist/chunk-WW2A73HW.js.map +1 -0
  20. package/dist/{chunk-F6YUH3L4.js → chunk-XMBOU5W7.js} +12 -165
  21. package/dist/chunk-XMBOU5W7.js.map +1 -0
  22. package/dist/contract/index.d.ts +25 -16
  23. package/dist/contract/index.js +281 -5
  24. package/dist/contract/index.js.map +1 -1
  25. package/dist/index.d.ts +71 -68
  26. package/dist/index.js +31 -32
  27. package/dist/index.js.map +1 -1
  28. package/dist/openapi.json +1 -1
  29. package/dist/traces.d.ts +39 -25
  30. package/dist/traces.js +3 -5
  31. package/docs/trace-analysis.md +6 -2
  32. package/package.json +2 -2
  33. package/dist/chunk-6QIM2EAP.js.map +0 -1
  34. package/dist/chunk-7A4LIMMY.js.map +0 -1
  35. package/dist/chunk-F6YUH3L4.js.map +0 -1
  36. package/dist/chunk-FIUFRXP3.js.map +0 -1
  37. package/dist/chunk-RLCJQ6VZ.js.map +0 -1
  38. package/dist/chunk-ZYHJNKI3.js.map +0 -1
  39. /package/dist/{chunk-LMJ2TGWJ.js.map → chunk-JM2SKQMS.js.map} +0 -0
  40. /package/dist/{chunk-GERDAIAL.js.map → chunk-QWMPPZ3X.js.map} +0 -0
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OtlpFileTraceStore,
3
- TraceFileMissingError,
4
- buildTraceAnalystTools
5
- } from "./chunk-6QIM2EAP.js";
3
+ buildTraceAnalystTools,
4
+ runTraceAnalysisLoop
5
+ } from "./chunk-PXD6ZFNY.js";
6
6
 
7
7
  // src/trace-analyst/prompts.ts
8
8
  var TRACE_ANALYST_ACTOR_DESCRIPTION = `You answer questions about an OTLP-shaped JSONL trace dataset using the trace tools provided in the \`traces\` namespace.
@@ -32,51 +32,33 @@ DISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol \u2014 follow exactly:
32
32
 
33
33
  9. If a ~4KB-truncated payload from viewTrace / searchTrace matters for your answer, first try viewSpans on that span id (~16KB cap). If a 16KB-truncated payload from viewSpans still matters, narrow further with searchSpan against a more specific regex rather than asking for the full payload again.
34
34
 
35
- 10. If maxDepth > 0 and the question splits into independent semantic branches, delegate well-defined subtasks to subagents using \`await llmQuery(...)\`. Pass narrow context and a focused query. Examples:
35
+ 10. If the question splits into independent reasoning branches, use bounded \`llmQuery(...)\` calls over evidence you already loaded. Subqueries cannot inspect the trace store, so pass the exact trace excerpts they need. Example:
36
36
 
37
37
  const reviews = await llmQuery([
38
- { query: 'Drill into trace abc123 \u2014 what tool calls preceded the failure?', context: { trace_id: 'abc123' } },
39
- { query: 'Drill into trace def456 \u2014 same failure mode?', context: { trace_id: 'def456' } },
38
+ { query: 'Classify the failure mechanism in this excerpt.', context: traceAbcExcerpt },
39
+ { query: 'Classify the failure mechanism in this excerpt.', context: traceDefExcerpt },
40
40
  ]);
41
41
 
42
42
  OBSERVABILITY rules:
43
- - Each non-final actor turn must emit at least one \`console.log(...)\` for evidence. Up to 3 logs per turn is fine when correlating multiple data sources (e.g. one log for findings list, one for source-file content, one for derived analysis).
44
- - Do NOT combine \`console.log\` with \`final(...)\` or \`askClarification(...)\` in the same turn \u2014 finish gathering data first, then call final on its own turn.
43
+ - Each discovery turn must emit at least one concise \`console.log(...)\` showing what evidence was learned.
44
+ - Finish gathering evidence before submitting the analysis.
45
45
  - Reuse runtime variables across turns; don't recompute.
46
- - When done, call \`await final(answer)\` with the fully-formed report. The responder rewrites the answer into output fields; if you only pass a vague summary string the responder has nothing concrete to format.
47
-
48
- CRITICAL \u2014 \`final()\` payload contract for evidence-grounded analysis tasks:
49
- - Pass a STRUCTURED object as the second arg with the actual data the responder needs to format the answer. Do NOT pass abstract instructions; pass evidence.
50
- - Example for per-item verdict tasks:
51
- \`\`\`js
52
- await final("Format the per-item verdict report from the evidence below.", {
53
- findings: [
54
- { id: 'sub-1-finding-1', claim: '...', verdict: 'TRUE-POSITIVE', evidence: 'lines 42-45 of contracts/X.sol show ...' },
55
- ...all items
56
- ],
57
- systemic_summary: '3 sentences I wrote based on the evidence above'
58
- });
59
- \`\`\`
60
- - Calling \`final("answer", {})\` with no evidence is a failure mode \u2014 the responder will hallucinate or echo back the field names. Always include the gathered data.
61
- - Premature final after a single viewSpans call is INSUFFICIENT for per-finding analysis tasks. Read the requested attributes (e.g. \`spans[i].attributes['redteam.finding.title']\`), and for each one perform the requested cross-reference (e.g. read the source SPAN's \`attributes['source.content']\`).
62
46
 
63
47
  OUTPUT contract \u2014 your final answer must include:
64
48
  - A clear prose conclusion answering the user's question.
65
49
  - Trace ids and span ids cited as evidence for each claim.
66
50
  - Failure modes named in the user's domain language, with frequency and concrete examples.
51
+ - A concise findings array containing only claims supported by inspected evidence.
67
52
 
68
53
  Do NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.`;
69
- var TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v5-2026-05-06";
70
- var TRACE_ANALYST_SUBAGENT_DESCRIPTION = `You are a trace-analyst subagent. Your parent has delegated a focused trace-inspection question. Use the same DISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol but stay tightly scoped: do exactly what was asked, return a concise compact answer, do NOT spawn further subagents unless the parent's question is genuinely multi-branch.
71
-
72
- Cite trace ids and span ids for every claim. Do NOT invent ids.`;
54
+ var TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v6-2026-07-14";
73
55
 
74
56
  // src/trace-analyst/analyst.ts
75
- import { AxJSRuntime, agent } from "@ax-llm/ax";
76
57
  async function analyzeTraces(input, options) {
77
58
  if (!input.question || typeof input.question !== "string") {
78
59
  throw new TypeError("analyzeTraces: input.question must be a non-empty string");
79
60
  }
61
+ rejectRemovedOptions(options);
80
62
  const store = typeof options.source === "string" ? new OtlpFileTraceStore({ path: options.source }) : options.source;
81
63
  if (store instanceof OtlpFileTraceStore) {
82
64
  await store.ensureIndexed();
@@ -93,6 +75,7 @@ async function analyzeTraces(input, options) {
93
75
  }
94
76
  const actorTurnCallback = async (turn) => {
95
77
  const snap = {
78
+ stage: turn.stage,
96
79
  turn: turn.turn,
97
80
  isError: turn.isError,
98
81
  code: turn.code,
@@ -109,81 +92,57 @@ async function analyzeTraces(input, options) {
109
92
  }
110
93
  if (options.onTurn) await options.onTurn(snap);
111
94
  };
112
- const maxDepth = options.maxDepth ?? 1;
95
+ const maxSubqueries = options.maxSubqueries ?? 4;
113
96
  const maxTurns = options.maxTurns ?? 12;
114
- const maxParallelSubagents = options.maxParallelSubagents ?? 2;
97
+ const maxParallelSubqueries = options.maxParallelSubqueries ?? 2;
115
98
  const maxRuntimeChars = options.maxRuntimeChars ?? 6e3;
116
- const functions = tools;
117
- const analyst = agent(
118
- // `reasoning!` is an internal (Ax `!`) scratchpad field: generated first to
119
- // force reason-before-conclude, stripped from the returned output — so the
120
- // consumed shape stays { answer, findings }. Brings the trace-analyst to the
121
- // same prose-first CoT ordering the kind-factory gets from its `report` field.
122
- "question:string -> reasoning!:string, answer:string, findings:string[]",
123
- {
124
- agentIdentity: {
125
- name: "TraceAnalyst",
126
- description: "Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes."
127
- },
128
- contextFields: ["question"],
129
- runtime: new AxJSRuntime({
130
- permissions: [],
131
- blockDynamicImport: true,
132
- allowedModules: [],
133
- freezeIntrinsics: true,
134
- blockShadowRealm: true,
135
- // RLM stdout mode relies on runtime bindings persisting across turns.
136
- preventGlobalThisExtensions: false
137
- }),
138
- mode: maxDepth > 0 ? "advanced" : "simple",
139
- recursionOptions: maxDepth > 0 ? { maxDepth } : void 0,
99
+ let completed;
100
+ try {
101
+ completed = await runTraceAnalysisLoop({
102
+ id: "TraceAnalyst",
103
+ description: "Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes.",
104
+ prompt: `${options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION}
105
+
106
+ The report must answer the user's question, and findings must be an array of concise evidence-backed strings.`,
107
+ question: input.question,
108
+ ai: options.ai,
109
+ ...options.model ? { model: options.model } : {},
110
+ tools,
111
+ findingType: "string",
112
+ maxSubqueries,
113
+ maxParallelSubqueries,
140
114
  maxTurns,
141
115
  maxRuntimeChars,
142
- maxBatchedLlmQueryConcurrency: maxParallelSubagents,
143
- promptLevel: "detailed",
144
- // Trace analysis depends on exact prior tool results and runtime variables.
145
- contextPolicy: { preset: "full", budget: "balanced" },
146
- functions,
147
- actorOptions: {
148
- description: options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION,
149
- ...options.model ? { model: options.model } : {},
150
- // Keep actor messages tool-call/content shaped across reasoning models.
151
- showThoughts: false,
152
- thinkingTokenBudget: "none"
153
- },
154
- responderOptions: {
155
- ...options.model ? { model: options.model } : {},
156
- description: options.subagentDescription ?? TRACE_ANALYST_SUBAGENT_DESCRIPTION,
157
- showThoughts: false
158
- },
159
- actorTurnCallback,
160
- bubbleErrors: [TraceFileMissingError]
161
- }
162
- );
163
- let result;
164
- try {
165
- result = await analyst.forward(options.ai, { question: input.question });
116
+ ...options.signal ? { signal: options.signal } : {},
117
+ onTurn: actorTurnCallback
118
+ });
166
119
  } finally {
167
120
  if (progressFs) {
168
121
  await new Promise((resolve) => progressFs.end(() => resolve()));
169
122
  }
170
123
  }
171
124
  return {
172
- answer: typeof result.answer === "string" ? result.answer : String(result.answer ?? ""),
173
- findings: Array.isArray(result.findings) ? result.findings.filter((s) => typeof s === "string") : [],
125
+ answer: completed.report,
126
+ findings: completed.findings,
174
127
  turns,
175
128
  turnCount: turns.length,
176
- usage: normalizeRoleArrays(analyst.getUsage()),
177
- chatLog: normalizeRoleArrays(analyst.getChatLog()),
129
+ usage: { actor: normalizeRecordArray(completed.usage), responder: [] },
130
+ chatLog: { actor: normalizeRecordArray(completed.chatLog), responder: [] },
178
131
  actorPromptVersion: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION
179
132
  };
180
133
  }
181
- function normalizeRoleArrays(value) {
182
- const record = value && typeof value === "object" ? value : {};
183
- return {
184
- actor: normalizeRecordArray(record.actor),
185
- responder: normalizeRecordArray(record.responder)
186
- };
134
+ function rejectRemovedOptions(options) {
135
+ const supplied = options;
136
+ const migrations = [
137
+ ["maxDepth", "maxSubqueries"],
138
+ ["maxParallelSubagents", "maxParallelSubqueries"],
139
+ ["subagentDescription", "actorDescription"]
140
+ ];
141
+ for (const [removed, replacement] of migrations) {
142
+ if (removed in supplied) {
143
+ throw new TypeError(`analyzeTraces: '${removed}' is unsupported; use '${replacement}'`);
144
+ }
145
+ }
187
146
  }
188
147
  function normalizeRecordArray(value) {
189
148
  if (!Array.isArray(value)) return [];
@@ -195,7 +154,6 @@ function normalizeRecordArray(value) {
195
154
  export {
196
155
  TRACE_ANALYST_ACTOR_DESCRIPTION,
197
156
  TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,
198
- TRACE_ANALYST_SUBAGENT_DESCRIPTION,
199
157
  analyzeTraces
200
158
  };
201
- //# sourceMappingURL=chunk-FIUFRXP3.js.map
159
+ //# sourceMappingURL=chunk-WW2A73HW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts"],"sourcesContent":["/** Ax RLM prompt for bounded trace discovery and evidence-backed analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `You answer questions about an OTLP-shaped JSONL trace dataset using the trace tools provided in the \\`traces\\` namespace.\n\nDISCOVERY → NARROW → DEEP-READ protocol — follow exactly:\n\n1. ALWAYS call \\`traces.getDatasetOverview({})\\` FIRST without a regex_pattern. The result tells you total_traces, raw_jsonl_bytes, services, agents, models, and sample_trace_ids (real ids — never fabricate one).\n\n2. Use raw_jsonl_bytes to gauge how expensive raw scans will be. \\`filters.regex_pattern\\` is the one scan-heavy filter on getDatasetOverview / queryTraces / countTraces — narrow with indexed fields (has_errors, model_names, service_names, agent_names, time bounds) BEFORE adding a regex on a large dataset.\n\n3. To list more traces than the sample, call \\`traces.queryTraces({ filters?, limit, offset? })\\`. Each summary carries raw_jsonl_bytes — use it to choose between viewTrace and searchTrace BEFORE calling either.\n\n4. Per-trace inspection:\n - SMALL trace (raw_jsonl_bytes well under 150_000): call \\`traces.viewTrace({ trace_id })\\`. Returns all spans. Per-attribute payloads are head-capped at ~4KB; large \\`input.value\\` / \\`output.value\\` / \\`llm.input_messages\\` will show a \\`[trace-analyst truncated: N bytes]\\` marker.\n - LARGE trace (raw_jsonl_bytes near or above 150_000, or you saw an \\`oversized\\` response): use \\`traces.searchTrace({ trace_id, regex_pattern })\\` to get bounded SpanMatchRecords (span metadata + matched text + surrounding context). Then call \\`traces.viewSpans({ trace_id, span_ids: [...] })\\` for surgical reads (~16KB cap, 4× higher than discovery), or \\`traces.searchSpan({ trace_id, span_id, regex_pattern })\\` for one large span. Stays bounded regardless of trace size.\n - Useful regex patterns: \\`STATUS_CODE_ERROR\\` (failures), tool names like \\`grep\\` or \\`view_trace\\`, error strings like \\`MaxTurnsExceeded\\`, model names, attribute keys.\n\n5. ONLY call viewTrace / viewSpans / searchTrace / searchSpan with trace/span ids you have already seen in sample_trace_ids, a queryTraces page, or a previous search result. Never invent ids.\n\n5a. **Result-shape contract** — searchTrace and searchSpan return \\`{ trace_id, hits, total_matches, has_more }\\`. Iterate \\`result.hits\\` (NOT result.matches). Each hit has \\`{ span_id, span_name, span_kind, attribute_path, matched_text, context_before, context_after, match_offset }\\`. viewTrace returns \\`{ trace_id, spans }\\` (or \\`oversized\\`). viewSpans returns \\`{ trace_id, spans, missing_span_ids, truncated_attribute_count }\\`. Never assume a field name — log the result shape first if unsure.\n\n6. If viewTrace returns an \\`oversized\\` summary instead of \\`spans\\`, DO NOT retry the same call. Read the summary's top_span_names, span_count, span_response_bytes_max, error_span_count to plan a follow-up: switch to searchTrace (or searchSpan for one large span), then viewSpans on a smaller, surgical span_ids set.\n\n7. If searchTrace or searchSpan returns has_more=true, REFINE the regex to be more specific rather than blindly raising max_matches.\n\n8. If a tool errors (invalid regex, range error), STOP and reconsider — don't retry with a guessed id or argument. Use the discovery tools above to recover.\n\n9. If a ~4KB-truncated payload from viewTrace / searchTrace matters for your answer, first try viewSpans on that span id (~16KB cap). If a 16KB-truncated payload from viewSpans still matters, narrow further with searchSpan against a more specific regex rather than asking for the full payload again.\n\n10. If the question splits into independent reasoning branches, use bounded \\`llmQuery(...)\\` calls over evidence you already loaded. Subqueries cannot inspect the trace store, so pass the exact trace excerpts they need. Example:\n\n const reviews = await llmQuery([\n { query: 'Classify the failure mechanism in this excerpt.', context: traceAbcExcerpt },\n { query: 'Classify the failure mechanism in this excerpt.', context: traceDefExcerpt },\n ]);\n\nOBSERVABILITY rules:\n- Each discovery turn must emit at least one concise \\`console.log(...)\\` showing what evidence was learned.\n- Finish gathering evidence before submitting the analysis.\n- Reuse runtime variables across turns; don't recompute.\n\nOUTPUT contract — your final answer must include:\n- A clear prose conclusion answering the user's question.\n- Trace ids and span ids cited as evidence for each claim.\n- Failure modes named in the user's domain language, with frequency and concrete examples.\n- A concise findings array containing only claims supported by inspected evidence.\n\nDo NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-actor-v6-2026-07-14'\n","import type { AxAgentActorTurnCallbackArgs, AxAIService, AxFunction } from '@ax-llm/ax'\nimport { runTraceAnalysisLoop, type TraceAnalysisLoopResult } from './loop'\nimport { TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION } from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore } from './store-otlp'\nimport { buildTraceAnalystTools } from './tools'\n\nexport interface AnalyzeTracesInput {\n /** The user-facing question. Domain framing belongs here, not in the\n * actor description. */\n question: string\n}\n\nexport interface AnalyzeTracesResult {\n /** The actor's submitted prose answer. */\n answer: string\n /** Bulleted findings from the actor's structured completion. */\n findings: string[]\n /** Per-turn snapshots captured via `actorTurnCallback`. */\n turns: AnalyzeTracesTurnSnapshot[]\n /** Total turns the actor took. */\n turnCount: number\n /** Token usage by role. */\n usage: TraceAnalystUsage\n /** Full system + assistant + tool message log by role. */\n chatLog: TraceAnalystChatLog\n /** Prompt version that produced this run. */\n actorPromptVersion: string\n}\n\nexport interface TraceAnalystUsage {\n actor: TraceAnalystUsageEntry[]\n responder: TraceAnalystUsageEntry[]\n}\n\nexport interface TraceAnalystUsageEntry {\n [key: string]: unknown\n}\n\nexport interface TraceAnalystChatLog {\n actor: TraceAnalystChatMessage[]\n responder: TraceAnalystChatMessage[]\n}\n\nexport interface TraceAnalystChatMessage {\n [key: string]: unknown\n}\n\nexport interface AnalyzeTracesTurnSnapshot {\n stage: AxAgentActorTurnCallbackArgs['stage']\n turn: number\n isError: boolean\n /** The JS code the actor produced for this turn. */\n code: string\n /** The formatted action-log entry the actor sees on the next turn. */\n output: string\n /** Provider thought (when `executorOptions.showThoughts` is true and the\n * provider returns it). */\n thought?: string\n}\n\nexport interface AnalyzeTracesOptions {\n /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */\n source: string | TraceAnalysisStore\n /** Caller-provided AxAIService. */\n ai: AxAIService\n /** Model id forwarded to the actor. */\n model?: string\n /** Maximum model subqueries. 0 disables model fan-out. Default 4. */\n maxSubqueries?: number\n /** Maximum actor turns. Default 12. */\n maxTurns?: number\n /** Maximum parallel model subqueries. Default 2. */\n maxParallelSubqueries?: number\n /** Cancels in-flight model and tool work. */\n signal?: AbortSignal\n /** Override the actor description. */\n actorDescription?: string\n /** Per-turn observability hook. */\n onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void>\n /** Override max runtime characters per turn. Default 6000. */\n maxRuntimeChars?: number\n /** When set, every turn's snapshot is appended to this JSONL file\n * immediately. If the analyst crashes mid-loop (provider 503,\n * network error, validator reject) the partial reasoning is still\n * on disk for diagnosis and recovery. */\n progressLogPath?: string\n}\n\n/**\n * Run the trace analyst.\n *\n * Throws:\n * - `TraceFileMissingError` if `source` is a path and doesn't exist.\n * - `AxAgentClarificationError` if the analyst asks for clarification.\n * - Provider errors (auth, rate limits) propagate from the AI service.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (!input.question || typeof input.question !== 'string') {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n rejectRemovedOptions(options)\n\n const store: TraceAnalysisStore =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n\n // Pre-warm file stores so missing inputs fail before the RLM starts.\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed()\n }\n\n const tools: AxFunction[] = buildTraceAnalystTools({ store })\n const turns: AnalyzeTracesTurnSnapshot[] = []\n\n // Persist each turn as JSONL so interrupted analyst runs keep useful evidence.\n let progressFs: import('node:fs').WriteStream | undefined\n if (options.progressLogPath) {\n const { createWriteStream } = await import('node:fs')\n const { mkdir } = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await mkdir(dirname(options.progressLogPath), { recursive: true })\n progressFs = createWriteStream(options.progressLogPath, { flags: 'a' })\n }\n\n const actorTurnCallback = async (turn: AxAgentActorTurnCallbackArgs): Promise<void> => {\n const snap: AnalyzeTracesTurnSnapshot = {\n stage: turn.stage,\n turn: turn.turn,\n isError: turn.isError,\n code: turn.code,\n output: turn.output,\n thought: turn.thought,\n }\n turns.push(snap)\n if (progressFs) {\n try {\n progressFs.write(`${JSON.stringify({ ...snap, ts: Date.now() })}\\n`)\n } catch {\n // Progress logging must never fail the analyst.\n }\n }\n if (options.onTurn) await options.onTurn(snap)\n }\n\n const maxSubqueries = options.maxSubqueries ?? 4\n const maxTurns = options.maxTurns ?? 12\n const maxParallelSubqueries = options.maxParallelSubqueries ?? 2\n const maxRuntimeChars = options.maxRuntimeChars ?? 6000\n let completed: TraceAnalysisLoopResult<string>\n try {\n completed = await runTraceAnalysisLoop({\n id: 'TraceAnalyst',\n description:\n 'Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes.',\n prompt: `${options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION}\n\nThe report must answer the user's question, and findings must be an array of concise evidence-backed strings.`,\n question: input.question,\n ai: options.ai,\n ...(options.model ? { model: options.model } : {}),\n tools,\n findingType: 'string',\n maxSubqueries,\n maxParallelSubqueries,\n maxTurns,\n maxRuntimeChars,\n ...(options.signal ? { signal: options.signal } : {}),\n onTurn: actorTurnCallback,\n })\n } finally {\n if (progressFs) {\n await new Promise<void>((resolve) => progressFs!.end(() => resolve()))\n }\n }\n\n return {\n answer: completed.report,\n findings: completed.findings,\n turns,\n turnCount: turns.length,\n usage: { actor: normalizeRecordArray(completed.usage), responder: [] },\n chatLog: { actor: normalizeRecordArray(completed.chatLog), responder: [] },\n actorPromptVersion: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n }\n}\n\nfunction rejectRemovedOptions(options: AnalyzeTracesOptions): void {\n const supplied = options as unknown as Record<string, unknown>\n const migrations = [\n ['maxDepth', 'maxSubqueries'],\n ['maxParallelSubagents', 'maxParallelSubqueries'],\n ['subagentDescription', 'actorDescription'],\n ] as const\n for (const [removed, replacement] of migrations) {\n if (removed in supplied) {\n throw new TypeError(`analyzeTraces: '${removed}' is unsupported; use '${replacement}'`)\n }\n }\n}\n\nfunction normalizeRecordArray(value: unknown): Record<string, unknown>[] {\n if (!Array.isArray(value)) return []\n return value.map((item) =>\n item && typeof item === 'object' ? { ...(item as Record<string, unknown>) } : { value: item },\n )\n}\n"],"mappings":";;;;;;;AAEO,IAAM,kCAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CxC,IAAM,0CAA0C;;;ACgDvD,eAAsB,cACpB,OACA,SAC8B;AAC9B,MAAI,CAAC,MAAM,YAAY,OAAO,MAAM,aAAa,UAAU;AACzD,UAAM,IAAI,UAAU,0DAA0D;AAAA,EAChF;AACA,uBAAqB,OAAO;AAE5B,QAAM,QACJ,OAAO,QAAQ,WAAW,WACtB,IAAI,mBAAmB,EAAE,MAAM,QAAQ,OAAO,CAAC,IAC/C,QAAQ;AAGd,MAAI,iBAAiB,oBAAoB;AACvC,UAAM,MAAM,cAAc;AAAA,EAC5B;AAEA,QAAM,QAAsB,uBAAuB,EAAE,MAAM,CAAC;AAC5D,QAAM,QAAqC,CAA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loud,
7
8
  defaultProductionGate,
8
9
  gepaProposer,
@@ -15,7 +16,7 @@ import {
15
16
  runImprovementLoop,
16
17
  surfaceContentHash,
17
18
  surfaceHash
18
- } from "./chunk-RLCJQ6VZ.js";
19
+ } from "./chunk-PSXJ32SR.js";
19
20
  import {
20
21
  SearchLedgerConflictError,
21
22
  SearchLedgerError,
@@ -42,13 +43,14 @@ import {
42
43
  admitPolicyEdit,
43
44
  applyPolicyEditToSurface,
44
45
  assertNoJudgeVerdict,
46
+ createAnalystAi,
45
47
  createTraceAnalystKind,
46
48
  isPolicyEdit,
47
49
  makePolicyEdit,
48
50
  makePolicyEditCandidateRecord,
49
51
  policyEditsFromFindings,
50
52
  validatePolicyEditCandidateRecord
51
- } from "./chunk-7A4LIMMY.js";
53
+ } from "./chunk-S5TT5R3L.js";
52
54
  import {
53
55
  callLlm,
54
56
  callLlmJson,
@@ -58,11 +60,8 @@ import {
58
60
  } from "./chunk-NJC7U437.js";
59
61
  import {
60
62
  eProcess,
61
- mcnemar,
62
63
  mulberry32,
63
- pairedBootstrap,
64
- pairedRiskDifference,
65
- wilcoxonSignedRank
64
+ pairedBootstrap
66
65
  } from "./chunk-PJQFMIOX.js";
67
66
  import {
68
67
  CostAccountingIncompleteError,
@@ -70,10 +69,10 @@ import {
70
69
  } from "./chunk-JHOJHHU7.js";
71
70
  import {
72
71
  analyzeTraces
73
- } from "./chunk-FIUFRXP3.js";
72
+ } from "./chunk-WW2A73HW.js";
74
73
  import {
75
74
  OtlpFileTraceStore
76
- } from "./chunk-6QIM2EAP.js";
75
+ } from "./chunk-PXD6ZFNY.js";
77
76
  import {
78
77
  modelHasSnapshot,
79
78
  validateRunRecord
@@ -569,155 +568,6 @@ function failureModeRecallJudge(opts = {}) {
569
568
  };
570
569
  }
571
570
 
572
- // src/paired-arms.ts
573
- function pairArms(rows, opts) {
574
- const { baselineArm, treatmentArm } = opts;
575
- if (baselineArm === treatmentArm) {
576
- throw new ValidationError(
577
- `pairArms: baselineArm and treatmentArm are both '${baselineArm}' \u2014 an arm cannot be compared to itself`
578
- );
579
- }
580
- const byArm = /* @__PURE__ */ new Map();
581
- const armsSeen = /* @__PURE__ */ new Set();
582
- for (const row of rows) {
583
- armsSeen.add(row.arm);
584
- if (row.arm !== baselineArm && row.arm !== treatmentArm) continue;
585
- const byKey = byArm.get(row.arm) ?? /* @__PURE__ */ new Map();
586
- const group = byKey.get(row.pairKey) ?? [];
587
- group.push(row);
588
- byKey.set(row.pairKey, group);
589
- byArm.set(row.arm, byKey);
590
- }
591
- for (const arm of [baselineArm, treatmentArm]) {
592
- if (!byArm.has(arm)) {
593
- const seen = [...armsSeen].sort().join(", ") || "<none>";
594
- throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`);
595
- }
596
- }
597
- const baselineByKey = byArm.get(baselineArm);
598
- const treatmentByKey = byArm.get(treatmentArm);
599
- const allKeys = [.../* @__PURE__ */ new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort();
600
- const pairs = [];
601
- const unpairedBaseline = [];
602
- const unpairedTreatment = [];
603
- for (const pairKey of allKeys) {
604
- const b = baselineByKey.get(pairKey) ?? [];
605
- const t = treatmentByKey.get(pairKey) ?? [];
606
- if (b.length <= 1 && t.length <= 1) {
607
- if (b.length === 1 && t.length === 1) {
608
- pairs.push({ pairKey, repIndex: 0, baseline: b[0], treatment: t[0] });
609
- } else {
610
- unpairedBaseline.push(...b);
611
- unpairedTreatment.push(...t);
612
- }
613
- continue;
614
- }
615
- const bByRep = indexByRepKey(b, pairKey, baselineArm);
616
- const tByRep = indexByRepKey(t, pairKey, treatmentArm);
617
- const repKeys = [.../* @__PURE__ */ new Set([...bByRep.keys(), ...tByRep.keys()])].sort();
618
- let repIndex = 0;
619
- for (const repKey of repKeys) {
620
- const baseline = bByRep.get(repKey);
621
- const treatment = tByRep.get(repKey);
622
- if (baseline !== void 0 && treatment !== void 0) {
623
- pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment });
624
- } else if (baseline !== void 0) {
625
- unpairedBaseline.push(baseline);
626
- } else if (treatment !== void 0) {
627
- unpairedTreatment.push(treatment);
628
- }
629
- }
630
- }
631
- return { pairs, unpairedBaseline, unpairedTreatment };
632
- }
633
- function indexByRepKey(group, pairKey, arm) {
634
- const byRep = /* @__PURE__ */ new Map();
635
- for (const row of group) {
636
- if (row.repKey === void 0) {
637
- throw new ValidationError(
638
- `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' is missing repKey \u2014 multi-rep items require an explicit repKey on every row so reps pair by identity (pairing reps by outcome or by index would bias the paired statistics)`
639
- );
640
- }
641
- if (byRep.has(row.repKey)) {
642
- throw new ValidationError(
643
- `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' \u2014 (pairKey, repKey) must uniquely identify a rep within an arm`
644
- );
645
- }
646
- byRep.set(row.repKey, row);
647
- }
648
- return byRep;
649
- }
650
- function comparePairedArms(rows, opts) {
651
- const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(rows, opts);
652
- let correctness = null;
653
- const baselinePass = [];
654
- const treatmentPass = [];
655
- for (const pair of pairs) {
656
- if (pair.baseline.pass === void 0 || pair.treatment.pass === void 0) continue;
657
- baselinePass.push(pair.baseline.pass ? 1 : 0);
658
- treatmentPass.push(pair.treatment.pass ? 1 : 0);
659
- }
660
- if (baselinePass.length > 0) {
661
- const mc = mcnemar(baselinePass, treatmentPass);
662
- correctness = {
663
- b10: mc.b,
664
- b01: mc.c,
665
- mcnemar: mc,
666
- riskDifference: pairedRiskDifference(baselinePass, treatmentPass)
667
- };
668
- }
669
- const metricNames = opts.metricNames ?? [
670
- ...new Set(
671
- pairs.flatMap((p) => [
672
- ...Object.keys(p.baseline.metrics ?? {}),
673
- ...Object.keys(p.treatment.metrics ?? {})
674
- ])
675
- )
676
- ].sort();
677
- const metricDeltas = metricNames.map((name) => {
678
- const before = [];
679
- const after = [];
680
- let nMissing = 0;
681
- for (const pair of pairs) {
682
- const b = metricValue(pair.baseline, name);
683
- const t = metricValue(pair.treatment, name);
684
- if (b === void 0 || t === void 0) {
685
- nMissing++;
686
- continue;
687
- }
688
- before.push(b);
689
- after.push(t);
690
- }
691
- const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap);
692
- return {
693
- name,
694
- n: before.length,
695
- nMissing,
696
- medianDelta: bootstrapCi === null ? Number.NaN : bootstrapCi.median,
697
- meanDelta: bootstrapCi === null ? Number.NaN : bootstrapCi.mean,
698
- bootstrapCi,
699
- wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after)
700
- };
701
- });
702
- return {
703
- nPairs: pairs.length,
704
- nUnpairedBaseline: unpairedBaseline.length,
705
- nUnpairedTreatment: unpairedTreatment.length,
706
- correctness,
707
- metricDeltas
708
- };
709
- }
710
- function metricValue(row, name) {
711
- const v = row.metrics?.[name];
712
- if (v === void 0) return void 0;
713
- if (!Number.isFinite(v)) {
714
- throw new ValidationError(
715
- `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`
716
- );
717
- }
718
- return v;
719
- }
720
-
721
571
  // src/campaign/cross-surface-context.ts
722
572
  function validateCrossSurfaceInput(input) {
723
573
  assertNonEmptyUnique(input.taskOrder, "taskOrder");
@@ -6294,7 +6144,6 @@ ${block}
6294
6144
  }
6295
6145
 
6296
6146
  // src/campaign/proposers/trace-analyst.ts
6297
- import { ai } from "@ax-llm/ax";
6298
6147
  function renderFindings(findings) {
6299
6148
  return findings.map((f, i) => {
6300
6149
  const action = f.recommended_action ? `
@@ -6308,11 +6157,11 @@ function traceAnalystProposer(opts) {
6308
6157
  if (!opts.model) throw new Error("traceAnalystProposer: model is required");
6309
6158
  const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS;
6310
6159
  const produceFindings = opts.analyze ?? (async (path, c) => {
6311
- const aiService = ai({
6312
- name: opts.provider ?? "openai",
6160
+ const aiService = createAnalystAi({
6161
+ provider: opts.provider ?? "openai",
6313
6162
  apiKey: opts.apiKey,
6314
- apiURL: opts.baseUrl,
6315
- config: { model: opts.model }
6163
+ baseUrl: opts.baseUrl,
6164
+ model: opts.model
6316
6165
  });
6317
6166
  const registry = new AnalystRegistry();
6318
6167
  for (const spec of kinds) {
@@ -8026,8 +7875,6 @@ function resolveWorktreePath(surface, worktreeDir) {
8026
7875
  }
8027
7876
 
8028
7877
  export {
8029
- pairArms,
8030
- comparePairedArms,
8031
7878
  completionVerdict,
8032
7879
  verifyCompletion,
8033
7880
  parseCorrectnessResponse,
@@ -8109,4 +7956,4 @@ export {
8109
7956
  verifyCodeSurface,
8110
7957
  resolveWorktreePath
8111
7958
  };
8112
- //# sourceMappingURL=chunk-F6YUH3L4.js.map
7959
+ //# sourceMappingURL=chunk-XMBOU5W7.js.map