@tangle-network/agent-eval 0.210.0 → 0.211.2
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.
- package/CHANGELOG.md +12 -0
- package/dist/analyst/index.d.ts +1 -1
- package/dist/analyst/index.js +7 -7
- package/dist/{benchmark-command-S8tCtkxh.js → benchmark-command-DO0aBGne.js} +10 -10
- package/dist/{benchmark-command-S8tCtkxh.js.map → benchmark-command-DO0aBGne.js.map} +1 -1
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.js +4 -4
- package/dist/{campaign-wvvJA1ps.js → campaign-CrMj5nYM.js} +7 -7
- package/dist/{campaign-wvvJA1ps.js.map → campaign-CrMj5nYM.js.map} +1 -1
- package/dist/{chat-client-CydfmLdO.js → chat-client-Bnx8NZe4.js} +2 -2
- package/dist/{chat-client-CydfmLdO.js.map → chat-client-Bnx8NZe4.js.map} +1 -1
- package/dist/{chat-json-call-BJJdJ2uj.js → chat-json-call-CZI1NoGZ.js} +2 -2
- package/dist/{chat-json-call-BJJdJ2uj.js.map → chat-json-call-CZI1NoGZ.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/contract/index.js +8 -8
- package/dist/{cost-ledger-_IbkejCF.js → cost-ledger-DFOeLeJi.js} +2 -2
- package/dist/{cost-ledger-_IbkejCF.js.map → cost-ledger-DFOeLeJi.js.map} +1 -1
- package/dist/{default-registry-DF4Yp7HQ.js → default-registry-BhYGMVbV.js} +3 -3
- package/dist/{default-registry-DF4Yp7HQ.js.map → default-registry-BhYGMVbV.js.map} +1 -1
- package/dist/{define-agent-eval-CoXXDCMu.js → define-agent-eval-BmF0c78X.js} +3 -3
- package/dist/{define-agent-eval-CoXXDCMu.js.map → define-agent-eval-BmF0c78X.js.map} +1 -1
- package/dist/{dspy-rlm-engine-BpaKVKJA.js → dspy-rlm-engine-D7BIsKyZ.js} +4 -4
- package/dist/{dspy-rlm-engine-BpaKVKJA.js.map → dspy-rlm-engine-D7BIsKyZ.js.map} +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/{external-optimizer-process-D2Txd-7D.js → external-optimizer-process-CB3RGyr7.js} +2 -2
- package/dist/{external-optimizer-process-D2Txd-7D.js.map → external-optimizer-process-CB3RGyr7.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-C0EsxEbI.js → external-optimizer-subprocess-DitxECD3.js} +3 -3
- package/dist/{external-optimizer-subprocess-C0EsxEbI.js.map → external-optimizer-subprocess-DitxECD3.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -15
- package/dist/{judge-gate-D2hCppem.d.ts → judge-gate-B1_O0QIs.d.ts} +21 -6
- package/dist/{judge-gate-D2hCppem.d.ts.map → judge-gate-B1_O0QIs.d.ts.map} +1 -1
- package/dist/{judge-gate-C59znGmR.js → judge-gate-B1qYnkpi.js} +34 -14
- package/dist/judge-gate-B1qYnkpi.js.map +1 -0
- package/dist/{kind-factory-ivTx6koH.js → kind-factory-CMlOx08-.js} +2 -2
- package/dist/{kind-factory-ivTx6koH.js.map → kind-factory-CMlOx08-.js.map} +1 -1
- package/dist/{llm-client-v968tWw8.js → llm-client-C_o62yG1.js} +2 -2
- package/dist/{llm-client-v968tWw8.js.map → llm-client-C_o62yG1.js.map} +1 -1
- package/dist/{llm-judge-Tr7MBUnf.js → llm-judge-BtMxSe1e.js} +4 -4
- package/dist/{llm-judge-Tr7MBUnf.js.map → llm-judge-BtMxSe1e.js.map} +1 -1
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/meta-eval/index.js +1 -1
- package/dist/{metrics-DOMpkoeb.js → metrics-BKaPBtIG.js} +5 -1
- package/dist/metrics-BKaPBtIG.js.map +1 -0
- package/dist/multishot/index.js +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{produced-state-CKybuR9F.js → produced-state-CYhim2We.js} +4 -4
- package/dist/{produced-state-CKybuR9F.js.map → produced-state-CYhim2We.js.map} +1 -1
- package/dist/{semantic-concept-judge-BQxZyXdN.js → semantic-concept-judge-B4zwq9Uy.js} +6 -6
- package/dist/{semantic-concept-judge-BQxZyXdN.js.map → semantic-concept-judge-B4zwq9Uy.js.map} +1 -1
- package/dist/{server-BZOt7eNC.js → server-BRpadnVt.js} +3 -3
- package/dist/{server-BZOt7eNC.js.map → server-BRpadnVt.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DujPOiwD.js → skillopt-optimization-method-Ds4Ck2Dn.js} +5 -5
- package/dist/{skillopt-optimization-method-DujPOiwD.js.map → skillopt-optimization-method-Ds4Ck2Dn.js.map} +1 -1
- package/dist/{store-otlp-__ebQ6Hn.js → store-otlp-0AiS29kg.js} +2 -2
- package/dist/{store-otlp-__ebQ6Hn.js.map → store-otlp-0AiS29kg.js.map} +1 -1
- package/dist/{store-tool-spans-TbRBuIM7.js → store-tool-spans-BAcBBSM8.js} +3 -3
- package/dist/{store-tool-spans-TbRBuIM7.js.map → store-tool-spans-BAcBBSM8.js.map} +1 -1
- package/dist/traces.js +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/concepts.md +2 -1
- package/package.json +1 -1
- package/dist/judge-gate-C59znGmR.js.map +0 -1
- package/dist/metrics-DOMpkoeb.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store-tool-spans-TbRBuIM7.js","names":[],"sources":["../src/trace/capture-fetch.ts","../src/trace/otlp-encoding.ts","../src/trace/wire-ids.ts","../src/trace/otel.ts","../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/store-tool-spans.ts"],"sourcesContent":["/**\n * Wrap a provider `fetch` and record request, response, and error events.\n *\n * The returned value is a plain `typeof fetch`. Capture is best-effort by\n * default; set `failClosed` when telemetry loss must stop the provider call.\n */\n\nimport {\n type ExtractedUsage,\n extractUsage,\n extractUsageFromSse,\n type SseUsageMode,\n} from './extract-usage'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderDirection,\n type RawProviderEvent,\n type RawProviderSink,\n} from './raw-provider-sink'\n\nexport interface CaptureFetchContext {\n /** Logical run id stamped on every captured event. Required — without it\n * the raw events can't be paired with their parent `Run`. */\n runId: string\n /** Optional logical span id (enables span-level sink filtering). */\n spanId?: string\n /** Resolved base URL (normalised, no trailing slash). Used for the event's\n * `baseUrl` and for endpoint-path extraction. */\n baseUrl: string\n /** Model id the caller intends to invoke. Stamped on every event. */\n model: string\n /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */\n provider?: string\n}\n\nexport interface CaptureFetchOptions {\n /** Override the capture-time redactor. Default `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n /** Cap on captured response-body bytes; beyond it the body is truncated and\n * `body_truncated` is added to `redactedFields`. Default 2 MiB. */\n responseBodyByteCap?: number\n /** When true, a sink-write failure propagates to the caller. Default false\n * — capture is best-effort so a sink failure never kills the LLM call. */\n failClosed?: boolean\n /**\n * Invoked with the token usage parsed off each successful response (JSON or\n * SSE), keyed by the captured context. Lets a caller fold usage → cost without\n * re-cloning the response themselves. Not called when the response carries no\n * usage. Best-effort: a throw here is swallowed (it never kills the LLM call)\n * unless `failClosed` is set.\n */\n onUsage?: (usage: ExtractedUsage, ctx: CaptureFetchContext) => void\n /** How repeated SSE usage events should be reconciled. Default `cumulative`. */\n sseUsageMode?: SseUsageMode\n}\n\nconst DEFAULT_BODY_CAP = 2 * 1024 * 1024\n\nfunction headersToRecord(headers: Headers | undefined): Record<string, string> | undefined {\n if (!headers) return undefined\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value\n })\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\n/** Best-effort request-body read across the `fetch` input forms. */\nasync function readRequestBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n): Promise<unknown> {\n if (typeof init?.body === 'string') return parseMaybeJson(init.body)\n if (init?.body != null) return undefined // streams / FormData / Blob — not captured\n if (input instanceof Request) {\n try {\n return parseMaybeJson(await input.clone().text())\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nfunction endpointFromUrl(url: string, baseUrl: string): string {\n const normalisedBase = baseUrl.replace(/\\/+$/, '')\n if (url.startsWith(normalisedBase)) return url.slice(normalisedBase.length) || '/'\n try {\n return new URL(url).pathname\n } catch {\n return url\n }\n}\n\nexport function captureFetchToRawSink(\n fetch: typeof globalThis.fetch,\n sink: RawProviderSink,\n ctx: CaptureFetchContext,\n opts: CaptureFetchOptions = {},\n): typeof globalThis.fetch {\n const provider = ctx.provider ?? providerFromBaseUrl(ctx.baseUrl)\n const redactor = opts.redactor ?? defaultProviderRedactor\n const bodyCap = opts.responseBodyByteCap ?? DEFAULT_BODY_CAP\n let warned = false\n\n const baseEvent = (direction: RawProviderDirection, endpoint: string): RawProviderEvent => ({\n eventId: crypto.randomUUID(),\n runId: ctx.runId,\n spanId: ctx.spanId,\n provider,\n model: ctx.model,\n endpoint,\n baseUrl: ctx.baseUrl,\n attemptIndex: 0, // retries are re-invocations one layer up; documented in 0.x\n direction,\n timestamp: Date.now(),\n redactedFields: [],\n })\n\n const record = async (event: RawProviderEvent): Promise<void> => {\n try {\n await sink.record(redactor(event))\n } catch (err) {\n if (opts.failClosed) throw err\n if (!warned) {\n warned = true\n console.warn(\n `captureFetchToRawSink: sink.record failed (capture is best-effort) — ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n }\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\n const endpoint = endpointFromUrl(url, ctx.baseUrl)\n\n const reqHeaders = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n )\n await record({\n ...baseEvent('request', endpoint),\n requestHeaders: { ...headersToRecord(reqHeaders), 'x-http-method': method },\n requestBody: await readRequestBody(input, init),\n })\n\n const start = Date.now()\n let response: Response\n try {\n response = await fetch(input, init)\n } catch (err) {\n await record({\n ...baseEvent('error', endpoint),\n durationMs: Date.now() - start,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n throw err\n }\n\n // Read the body off a clone so the caller still consumes the original.\n let responseBody: unknown\n let rawText: string | undefined\n const redactedFields: string[] = []\n try {\n rawText = await response.clone().text()\n if (rawText.length > bodyCap) {\n responseBody = rawText.slice(0, bodyCap)\n redactedFields.push('body_truncated')\n } else {\n responseBody = parseMaybeJson(rawText)\n }\n } catch {\n responseBody = undefined\n }\n\n if (opts.onUsage && rawText !== undefined) {\n // Reuse the body already read for capture; no extra clone. JSON first,\n // then SSE accumulation. A throw in the consumer's callback is swallowed\n // (best-effort) unless failClosed is set — the LLM call must not die here.\n try {\n const parsedForUsage = parseMaybeJson(rawText)\n const usage =\n extractUsage(parsedForUsage) ??\n (typeof parsedForUsage === 'string'\n ? extractUsageFromSse(rawText, { mode: opts.sseUsageMode })\n : null)\n if (usage) opts.onUsage(usage, ctx)\n } catch (err) {\n if (opts.failClosed) throw err\n }\n }\n\n await record({\n ...baseEvent('response', endpoint),\n durationMs: Date.now() - start,\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n responseBody,\n redactedFields,\n })\n\n return response\n }\n}\n","/**\n * The ONE encoding from this package's span values to OTLP wire values.\n *\n * Both exporters emit the same `OtlpSpan` shape, so an attribute typed as a\n * double by one and a string by the other would make the same run read\n * differently depending on which exporter produced it.\n */\n\n/** One OTLP `KeyValue`: the value is tagged with the protocol's type slot. */\nexport interface OtlpAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\n/** OTLP `KeyValue[]` for a flat attribute record. */\nexport function toOtlpAttributes(\n record: Record<string, string | number | boolean>,\n): OtlpAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\n/** OTLP nanosecond timestamp, as the decimal string the protocol requires. */\nexport function msToUnixNano(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n","/**\n * The ONE mapping from agent-eval's human-readable ids (run ids, span labels)\n * to W3C/OTLP wire ids. Every exporter in this package MUST route through\n * these two functions — two exporters with private paddings once produced\n * DIFFERENT trace ids for the same run, and one emitted invalid hex embedding\n * the raw run id in the wire id (tangle-network/agent-runtime#694).\n *\n * Semantics:\n * - an id that is ALREADY a valid W3C id passes through unchanged, so a\n * trace id received from an inbound `traceparent` survives the round-trip\n * and cross-process correlation is preserved;\n * - anything else is derived with the contract's `deriveHexId`, the only\n * legal derivation — deterministic, so every process that derives from the\n * same human id mints the SAME wire id.\n */\n\nimport { deriveHexId, isW3CSpanId, isW3CTraceId } from '@tangle-network/agent-trace-contract'\n\n/** 32-hex W3C trace id for any id string. */\nexport function traceIdForWire(id: string): string {\n return isW3CTraceId(id) ? id : deriveHexId(id, 16)\n}\n\n/** 16-hex W3C span id for any id string. */\nexport function spanIdForWire(id: string): string {\n return isW3CSpanId(id) ? id : deriveHexId(id, 8)\n}\n","/**\n * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so\n * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.\n *\n * Wire format only. We do NOT depend on the @opentelemetry SDK — that\n * would drag in polyfills incompatible with Workers/Edge. Consumers\n * push the JSON to their collector of choice via HTTP.\n *\n * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).\n */\n\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport { msToUnixNano, toOtlpAttributes } from './otlp-encoding'\nimport type { Run, Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\nimport { spanIdForWire, traceIdForWire } from './wire-ids'\n\nexport const OTEL_AGENT_EVAL_SCOPE = { name: '@tangle-network/agent-eval', version: '0.3.0' }\n\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n }>\n events?: Array<{ timeUnixNano: string; name: string; attributes?: OtlpSpan['attributes'] }>\n status?: { code: number; message?: string }\n}\n\nexport interface OtlpResourceSpans {\n resource: { attributes: OtlpSpan['attributes'] }\n scopeSpans: Array<{ scope: typeof OTEL_AGENT_EVAL_SCOPE; spans: OtlpSpan[] }>\n}\n\nexport interface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\n/** Export a single run's spans + events in OTLP/JSON. */\nexport async function exportRunAsOtlp(\n store: TraceStore,\n runId: string,\n resourceAttrs: Record<string, string | number | boolean> = {},\n): Promise<OtlpExport> {\n const run = await store.getRun(runId)\n if (!run) throw new Error(`run ${runId} not found`)\n const spans = await store.spans({ runId })\n const events = await store.events({ runId })\n const eventsBySpan = new Map<string, TraceEvent[]>()\n for (const e of events) {\n if (!e.spanId) continue\n const arr = eventsBySpan.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpan.set(e.spanId, arr)\n }\n const traceId = runToTraceId(run)\n const otlpSpans: OtlpSpan[] = spans.map((s) =>\n spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []),\n )\n return {\n resourceSpans: [\n {\n resource: {\n attributes: toOtlpAttributes({\n 'service.name': 'agent-eval',\n 'run.id': run.runId,\n 'run.scenario_id': run.scenarioId,\n 'run.variant_id': run.variantId ?? '',\n 'run.dataset_version': run.datasetVersion ?? '',\n 'run.code_sha': run.codeSha ?? '',\n 'run.model_fingerprint': run.modelFingerprint ?? '',\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: otlpSpans }],\n },\n ],\n }\n}\n\nfunction spanToOtlp(span: Span, traceId: string, events: TraceEvent[]): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n return {\n traceId,\n spanId: spanIdForWire(span.spanId),\n parentSpanId: span.parentSpanId ? spanIdForWire(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToUnixNano(span.startedAt),\n endTimeUnixNano: msToUnixNano(endedAt),\n attributes: toOtlpAttributes(flattenSpanAttributes(span)),\n events: events.map((e) => ({\n timeUnixNano: msToUnixNano(e.timestamp),\n name: e.kind,\n attributes: toOtlpAttributes(flattenPayload(e.payload)),\n })),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction flattenSpanAttributes(span: Span): Record<string, string | number | boolean> {\n const base: Record<string, string | number | boolean> = {}\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') base[k] = v\n }\n }\n base[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(base, span)\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(base, span)\n } else if (span.kind === 'retrieval') {\n base['retrieval.query'] = span.query\n base['retrieval.hits'] = span.hits.length\n } else if (span.kind === 'judge') {\n base['judge.id'] = span.judgeId\n base['judge.dimension'] = span.dimension\n base['judge.score'] = span.score\n base['judge.target_span_id'] = span.targetSpanId\n } else if (span.kind === 'sandbox') {\n if (span.image) base['sandbox.image'] = span.image\n if (span.exitCode !== undefined) base['sandbox.exit_code'] = span.exitCode\n if (span.testsPassed !== undefined) base['sandbox.tests_passed'] = span.testsPassed\n if (span.testsTotal !== undefined) base['sandbox.tests_total'] = span.testsTotal\n }\n return base\n}\n\nfunction flattenPayload(\n payload: Record<string, unknown>,\n): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const [k, v] of Object.entries(payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') out[k] = v\n else out[k] = JSON.stringify(v)\n }\n return out\n}\n\nfunction runToTraceId(run: Run): string {\n return traceIdForWire(run.runId)\n}\n","/** General policy for recursive, evidence-backed trace analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `Answer the question by inspecting the OTLP trace dataset with the available tools.\n\n1. Call getDatasetOverview first. Use its real trace ids and dataset size to plan the investigation.\n2. Narrow with queryTraces and countTraces before scanning large payloads.\n3. For a small trace, use viewTrace. For a large trace, use searchTrace and then viewSpans or searchSpan.\n4. Never invent a trace id, span id, tool result, error, frequency, or final outcome.\n5. When a search reports has_more, refine the query before drawing a conclusion.\n6. Use llm_query only over evidence already loaded. A recursive query cannot inspect traces itself.\n7. Cite exact evidence URIs returned by the tools. Include a short exact excerpt when it supports the claim.\n8. Return no finding when the available evidence cannot support one.\n\nThe prose answer must directly answer the question and state important uncertainty.\nThe findings array contains only actionable or decision-relevant claims supported by inspected evidence.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-research-v1-2026-07-30'\n","import { randomUUID } from 'node:crypto'\nimport type {\n TraceAnalysisEngine,\n TraceAnalysisEngineResult,\n TraceAnalystLimits,\n} from '../analyst/engine'\nimport { runTraceAnalyst } from '../analyst/kind-factory'\nimport type { TraceToolGroupName } from '../analyst/tool-groups'\nimport type { AnalystFinding, AnalystUsageReceipt } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION } from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore } from './store-otlp'\n\nexport interface AnalyzeTracesInput {\n question: string\n id?: string\n description?: string\n area?: string\n}\n\nexport type AnalyzeTracesResult = TraceAnalysisEngineResult\n\nexport interface AnalyzeTracesOptions {\n /** OTLP JSONL path or a caller-owned store. */\n source: string | TraceAnalysisStore\n /** Recursive research engine. */\n engine: TraceAnalysisEngine\n /** Override the general trace-research policy. */\n instructions?: string\n /** Smallest tool set that can answer the question. Default: all. */\n toolGroup?: TraceToolGroupName\n limits?: Partial<TraceAnalystLimits>\n runId?: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n costPhase?: string\n priorFindings?: readonly AnalystFinding[]\n upstreamFindings?: readonly AnalystFinding[]\n recordUsage?: (receipt: AnalystUsageReceipt) => void\n tags?: Record<string, string>\n log?: (message: string, fields?: Record<string, unknown>) => void\n signal?: AbortSignal\n}\n\n/**\n * Answer one question by recursively inspecting a trace store.\n *\n * The returned answer, cited findings, engine steps, call counts, and runtime\n * identity are one audit record. A direct one-shot model call is not used.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (typeof input.question !== 'string' || !input.question.trim()) {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n const id = input.id?.trim() || 'trace-analysis'\n const store =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed(options.signal ? { signal: options.signal } : undefined)\n }\n\n return runTraceAnalyst({\n definition: {\n id,\n description:\n input.description?.trim() ||\n 'Answers a caller-defined question by recursively inspecting trace evidence.',\n area: input.area?.trim() || 'trace-analysis',\n version: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n question: input.question,\n instructions: options.instructions ?? TRACE_ANALYST_ACTOR_DESCRIPTION,\n toolGroup: options.toolGroup ?? 'all',\n limits: options.limits,\n },\n engine: options.engine,\n store,\n context: {\n runId: options.runId ?? id,\n correlationId: randomUUID(),\n budgetUsd: options.budgetUsd,\n costLedger: options.costLedger,\n costPhase: options.costPhase ?? 'trace-analysis',\n priorFindings: options.priorFindings,\n upstreamFindings: options.upstreamFindings,\n recordUsage: options.recordUsage,\n tags: options.tags,\n log: options.log,\n signal: options.signal,\n },\n })\n}\n","import type { SearchArtifactRef } from '../campaign/search-ledger-types'\nimport { LEDGER_HASH_PATTERN } from '../ledger-core/canonical'\n\nexport interface TraceInsightTask {\n id: string\n name: string\n prompt?: string\n difficulty?: string\n tags?: string[]\n outcome?: string\n score?: number\n gaps?: string[]\n}\n\nexport interface TraceInsightSuite {\n name: string\n collectionId?: string\n tasks: TraceInsightTask[]\n}\n\nexport interface TraceInsightFinding {\n kind: string\n severity?: string\n taskIds: string[]\n evidence?: string\n proposedFixClass?: string\n /** Narrative evidence remains a note; customer attribution uses byte-backed evidence only. */\n attribution?: TraceInsightAttribution\n}\n\n/** A byte-backed observation. Locators are not identities; every link carries a digest. */\nexport interface TraceInsightEvidence {\n subject: {\n verticalId: string\n taskId: string\n cellId: string | null\n attemptId: string | null\n company: string | null\n tool: string | null\n toolRevision: string | null\n }\n artifacts: Record<\n 'seed' | 'task' | 'cell' | 'request' | 'response' | 'document' | 'controls' | 'binding',\n SearchArtifactRef | null\n >\n spans: Array<{ traceId: string; spanId: string; artifact: SearchArtifactRef }>\n}\n\nexport type TraceInsightAttribution = TraceInsightEvidence &\n (\n | { outcome: 'unknown'; evidenceClass: 'unknown'; reasons: string[] }\n | {\n outcome: 'tool-failure'\n evidenceClass: 'validated-request-response'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'authoritative-execution'\n documentation: 'stale' | 'contradictory'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'paired-corrected-document'\n proof: SearchArtifactRef\n plan: SearchArtifactRef\n comparisonId: string\n correctedEvidence: SearchArtifactRef\n }\n )\n\nfunction evidenceRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction evidenceText(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\n/** Structural validation only. The producer must verify bytes and execute the evidence rule. */\nexport function isTraceInsightArtifact(value: unknown): value is SearchArtifactRef {\n if (\n !evidenceRecord(value) ||\n !evidenceText(value.role) ||\n !evidenceText(value.uri) ||\n typeof value.sha256 !== 'string' ||\n !LEDGER_HASH_PATTERN.test(value.sha256) ||\n !Number.isSafeInteger(value.byteLength) ||\n (value.byteLength as number) < 0\n )\n return false\n // Customer reports must not turn a locator into an executable link.\n try {\n const url = new URL(value.uri)\n return ['https:', 'file:'].includes(url.protocol) && !url.username && !url.password\n } catch {\n return /^artifacts\\/[a-f0-9]{64}$/.test(value.uri)\n }\n}\n\nexport function isTraceInsightEvidence(value: unknown): value is TraceInsightEvidence {\n if (\n !evidenceRecord(value) ||\n !evidenceRecord(value.subject) ||\n !evidenceRecord(value.artifacts) ||\n !Array.isArray(value.spans)\n )\n return false\n const subject = value.subject\n if (!evidenceText(subject.verticalId) || !evidenceText(subject.taskId)) return false\n for (const field of ['cellId', 'attemptId', 'company', 'tool', 'toolRevision']) {\n if (subject[field] !== null && !evidenceText(subject[field])) return false\n }\n for (const role of [\n 'seed',\n 'task',\n 'cell',\n 'request',\n 'response',\n 'document',\n 'controls',\n 'binding',\n ]) {\n const artifact = value.artifacts[role]\n if (artifact !== null && (!isTraceInsightArtifact(artifact) || artifact.role !== role))\n return false\n }\n return value.spans.every(\n (span) =>\n evidenceRecord(span) &&\n typeof span.traceId === 'string' &&\n /^[a-f0-9]{32}$/.test(span.traceId) &&\n !/^0+$/.test(span.traceId) &&\n typeof span.spanId === 'string' &&\n /^[a-f0-9]{16}$/.test(span.spanId) &&\n !/^0+$/.test(span.spanId) &&\n isTraceInsightArtifact(span.artifact) &&\n span.artifact.role === 'span',\n )\n}\n\nexport function isTraceInsightAttribution(value: unknown): value is TraceInsightAttribution {\n if (!isTraceInsightEvidence(value)) return false\n const attribution = value as TraceInsightEvidence & Record<string, unknown>\n if (attribution.outcome === 'unknown') {\n return (\n attribution.evidenceClass === 'unknown' &&\n Array.isArray(attribution.reasons) &&\n attribution.reasons.length > 0 &&\n attribution.reasons.every(evidenceText)\n )\n }\n if (\n Object.values(value.subject).some((entry) => entry === null) ||\n Object.values(value.artifacts).some((artifact) => artifact === null) ||\n value.spans.length === 0 ||\n !isTraceInsightArtifact(attribution.proof)\n )\n return false\n if (attribution.outcome === 'tool-failure') {\n return (\n attribution.evidenceClass === 'validated-request-response' &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n if (attribution.outcome !== 'documentation-failure') return false\n if (attribution.evidenceClass === 'authoritative-execution') {\n return (\n (attribution.documentation === 'stale' || attribution.documentation === 'contradictory') &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n return (\n attribution.evidenceClass === 'paired-corrected-document' &&\n attribution.proof.role === 'publication' &&\n isTraceInsightArtifact(attribution.plan) &&\n attribution.plan.role === 'plan' &&\n isTraceInsightArtifact(attribution.correctedEvidence) &&\n attribution.correctedEvidence.role === 'binding' &&\n evidenceText(attribution.comparisonId)\n )\n}\n\nexport interface TraceInsightQuestion {\n id: string\n question: string\n why: string\n}\n\nexport interface TraceInsightPanelRole {\n id: string\n name: string\n responsibility: string\n}\n\nexport interface TraceInsightPromptInput {\n suite: TraceInsightSuite\n findings?: TraceInsightFinding[]\n agent?: Record<string, unknown>\n totals?: Record<string, unknown>\n maxRepresentativeTraces?: number\n}\n\nexport interface TraceInsightContext {\n suite: TraceInsightSuite\n scope: string\n keywords: string[]\n questions: TraceInsightQuestion[]\n panel: TraceInsightPanelRole[]\n findings: TraceInsightFinding[]\n agent: Record<string, unknown> | null\n totals: Record<string, unknown> | null\n}\n\nexport interface TraceInsightQualityGate {\n id: string\n label: string\n passed: boolean\n severity: 'critical' | 'high' | 'medium' | 'low'\n detail: string\n}\n\nexport interface TraceInsightReadiness {\n score: number\n grade: 'external-ready' | 'internal-review' | 'raw-analysis'\n gates: TraceInsightQualityGate[]\n}\n\nconst DOMAIN_STOP_WORDS = new Set([\n 'and',\n 'advanced',\n 'app',\n 'build',\n 'create',\n 'easy',\n 'expert',\n 'extreme',\n 'for',\n 'from',\n 'hard',\n 'implementation',\n 'integrate',\n 'medium',\n 'project',\n 'task',\n 'the',\n 'this',\n 'with',\n 'workflow',\n])\n\nexport function tokenizeDomainWords(value: string): string[] {\n return [...value.matchAll(/[A-Za-z][A-Za-z0-9.+#-]{2,}/g)]\n .map((match) => match[0].toLowerCase())\n .filter((word) => !DOMAIN_STOP_WORDS.has(word))\n}\n\nexport function inferDomainKeywords(suite: TraceInsightSuite): string[] {\n const suiteWords = new Set(tokenizeDomainWords(`${suite.name} ${suite.collectionId ?? ''}`))\n const source = [\n suite.name,\n suite.collectionId ?? '',\n ...suite.tasks.flatMap((task) => [\n task.id,\n task.name,\n task.prompt ?? '',\n task.difficulty ?? '',\n ...(task.tags ?? []),\n ...(task.gaps ?? []),\n ]),\n ].join(' ')\n const counts = new Map<string, number>()\n for (const word of tokenizeDomainWords(source)) counts.set(word, (counts.get(word) ?? 0) + 1)\n return [...counts.entries()]\n .filter(([word, count]) => count >= 2 || suiteWords.has(word))\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([word]) => word)\n .slice(0, 18)\n}\n\nexport function domainEvidencePattern(keywords: string[]): RegExp {\n const escaped = keywords\n .filter((keyword) => keyword.length >= 3)\n .map((keyword) => keyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n return escaped.length > 0\n ? new RegExp(`(?<![A-Za-z0-9])(?:${escaped.join('|')})(?![A-Za-z0-9])`, 'i')\n : /(?<![A-Za-z0-9])(?:sdk|api|css|dns|xml|provider|client|service|integration|webhook|transaction|auth|oauth|graphql|rest)(?![A-Za-z0-9])/i\n}\n\nexport function describeTraceInsightScope(suite: TraceInsightSuite): string {\n const taskLabel =\n suite.tasks.length === 1\n ? '1 implementation task'\n : `${suite.tasks.length} implementation tasks`\n const tags = new Map<string, number>()\n for (const task of suite.tasks) {\n for (const tag of task.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)\n }\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 8)\n .map(([tag]) => tag)\n if (topTags.length > 0) return `${taskLabel} across ${topTags.join(', ')}.`\n const difficulties = [\n ...new Set(\n suite.tasks.map((task) => task.difficulty).filter((value): value is string => Boolean(value)),\n ),\n ].join(', ')\n return `${taskLabel} across ${difficulties || 'the selected benchmark scope'}.`\n}\n\nexport function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[] {\n const hasFailures = input.suite.tasks.some((task) => task.outcome && task.outcome !== 'satisfied')\n const hasMultipleShots = input.suite.tasks.some((task) =>\n (task.gaps ?? []).some((gap) => /shot|review|retry|continue/i.test(gap)),\n )\n const questions: TraceInsightQuestion[] = [\n {\n id: 'execution-path',\n question: 'What did the worker actually do before the first meaningful implementation edit?',\n why: 'Separates grounded execution from polished but shallow output.',\n },\n {\n id: 'research-grounding',\n question:\n 'Did the worker inspect docs, source, examples, or package references before committing to an implementation path?',\n why: 'Identifies whether failures came from weak retrieval, weak examples, or premature coding.',\n },\n {\n id: 'domain-proof',\n question:\n 'Which tasks produced executable domain proof versus UI copy, placeholders, or inferred behavior?',\n why: 'Keeps product-quality claims tied to concrete evidence.',\n },\n {\n id: 'root-cause',\n question:\n 'For each major failure cluster, is the likely root cause prompt/scaffold, docs/examples, SDK/API ergonomics, evaluator, runtime, or model behavior?',\n why: 'Turns trace observations into actionable ownership.',\n },\n {\n id: 'evidence-quality',\n question:\n 'Which external-facing claims are directly supported by trace ids, span ids, verifier findings, reviewer notes, or generated code?',\n why: 'Prevents unsupported customer-report conclusions.',\n },\n ]\n if (hasMultipleShots) {\n questions.push({\n id: 'reviewer-lift',\n question: 'Where did reviewer feedback improve score, stall, or regress across shots?',\n why: 'Shows whether the driver loop is learning or merely repeating work.',\n })\n }\n if (hasFailures) {\n questions.push({\n id: 'optimization-targets',\n question:\n 'Which prompt, evaluator, scaffold, or workflow changes should feed the next GEPA/autoresearch optimization run?',\n why: 'Connects benchmark evidence to the optimization loop.',\n })\n }\n return questions\n}\n\nexport function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext {\n return {\n suite: input.suite,\n scope: describeTraceInsightScope(input.suite),\n keywords: inferDomainKeywords(input.suite),\n questions: planTraceInsightQuestions(input),\n panel: defaultTraceInsightPanel(),\n findings: input.findings ?? [],\n agent: input.agent ?? null,\n totals: input.totals ?? null,\n }\n}\n\nexport function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness {\n const failedTasks = context.suite.tasks.filter(\n (task) => task.outcome && task.outcome !== 'satisfied',\n )\n const findingTaskIds = new Set(context.findings.flatMap((finding) => finding.taskIds))\n const failedTasksWithFindings = failedTasks.filter((task) => findingTaskIds.has(task.id))\n const tasksWithGaps = context.suite.tasks.filter((task) => (task.gaps ?? []).length > 0)\n const gates: TraceInsightQualityGate[] = [\n {\n id: 'domain-context',\n label: 'Domain context inferred',\n passed: context.keywords.length > 0,\n severity: 'high',\n detail:\n context.keywords.length > 0\n ? `${context.keywords.length} domain terms inferred: ${context.keywords.slice(0, 8).join(', ')}`\n : 'No domain terms were inferred from suite, tasks, prompts, tags, or gaps.',\n },\n {\n id: 'panel-coverage',\n label: 'Analyst panel planned',\n passed: context.panel.length >= 4 && context.questions.length >= 5,\n severity: 'high',\n detail: `${context.panel.length} panel roles and ${context.questions.length} investigation questions planned.`,\n },\n {\n id: 'failure-coverage',\n label: 'Failures mapped to findings',\n passed:\n failedTasks.length === 0 || failedTasksWithFindings.length / failedTasks.length >= 0.5,\n severity: 'critical',\n detail:\n failedTasks.length === 0\n ? 'No failed tasks in suite.'\n : `${failedTasksWithFindings.length}/${failedTasks.length} failed tasks appear in finding clusters.`,\n },\n {\n id: 'gap-evidence',\n label: 'Task gaps captured',\n passed: failedTasks.length === 0 || tasksWithGaps.length / failedTasks.length >= 0.5,\n severity: 'medium',\n detail: `${tasksWithGaps.length} tasks include explicit evaluator or analyst gaps.`,\n },\n {\n id: 'attribution-evidence',\n label: 'Evidence-classed customer findings',\n passed:\n failedTasks.every((task) =>\n context.findings.some(\n (finding) =>\n finding.taskIds.includes(task.id) && finding.attribution?.subject.taskId === task.id,\n ),\n ) &&\n context.findings.every(\n (finding) =>\n isTraceInsightAttribution(finding.attribution) &&\n finding.taskIds.length === 1 &&\n finding.taskIds[0] === finding.attribution.subject.taskId,\n ),\n severity: 'critical',\n detail:\n 'Every finding needs an explicit evidence class and byte-backed links, or an explicit unknown; prose is not attribution evidence.',\n },\n ]\n const penalty = gates.reduce((sum, gate) => {\n if (gate.passed) return sum\n if (gate.severity === 'critical') return sum + 35\n if (gate.severity === 'high') return sum + 20\n if (gate.severity === 'medium') return sum + 10\n return sum + 5\n }, 0)\n const score = Math.max(0, Math.min(1, 1 - penalty / 100))\n return {\n score,\n grade: score >= 0.9 ? 'external-ready' : score >= 0.7 ? 'internal-review' : 'raw-analysis',\n gates,\n }\n}\n\nexport function defaultTraceInsightPanel(): TraceInsightPanelRole[] {\n return [\n {\n id: 'trace-forensics',\n name: 'Trace Forensics',\n responsibility:\n 'Reconstruct what the worker did in order, including research, edits, reviewer interventions, verifier feedback, and stop reason.',\n },\n {\n id: 'root-cause',\n name: 'Root Cause',\n responsibility:\n 'Map failures to prompt/scaffold, docs/examples, SDK/API/product ergonomics, evaluator, runtime, or model behavior.',\n },\n {\n id: 'optimization',\n name: 'Optimization',\n responsibility:\n 'Identify prompt, reviewer, evaluator, scaffold, and GEPA/autoresearch changes that should be tested next.',\n },\n {\n id: 'external-evidence',\n name: 'External Evidence',\n responsibility:\n 'Separate customer-safe claims from internal harness findings and reject conclusions without task, trace, span, code, reviewer, or verifier evidence.',\n },\n ]\n}\n\nexport function buildTraceInsightPrompt(input: TraceInsightPromptInput): string {\n const context = buildTraceInsightContext(input)\n const maxRepresentativeTraces = input.maxRepresentativeTraces ?? 6\n return `Analyze this benchmark run and produce evidence-backed trace intelligence.\n\nAudience:\n- internal AI/product leadership\n- possible customer-facing report for ${input.suite.name}\n\nInvestigation plan:\n${context.questions.map((item, index) => `${index + 1}. ${item.question} (${item.why})`).join('\\n')}\n\nAnalyst panel:\n${context.panel.map((role) => `- ${role.name}: ${role.responsibility}`).join('\\n')}\n\nIf the task branches are independent, use subagents for the panel roles above and aggregate their findings. Do not run a panel role unless its answer will change the final report.\n\nRequired output:\n1. Executive verdict: what this run proves and does not prove.\n2. The investigation questions you answered and the evidence used.\n3. Failure taxonomy: agent prompting, evaluator/harness, docs/examples, SDK/API/product integration, infra.\n4. Evidence-backed examples with trace ids/task ids and concrete verifier findings.\n5. Highest-ROI fixes for the benchmark harness, prompt/GEPA optimization, and customer-facing product/docs surface.\n6. What is safe for an external report versus what must stay internal.\n7. One rerun plan that would validate lift after optimization.\n\nBudget:\n- Inspect the dataset overview, the failure summary, and at most ${maxRepresentativeTraces} representative traces.\n- Prefer traces named in the failure summary over broad exploration.\n- Do not do exhaustive trace sweeps.\n- Return the final report as soon as the taxonomy and examples are supported.\n\nRun summary:\n${JSON.stringify(\n {\n suite: input.suite.name,\n scope: context.scope,\n inferredKeywords: context.keywords,\n agent: context.agent,\n totals: context.totals,\n findings: context.findings.map((finding) => ({\n kind: finding.kind,\n severity: finding.severity,\n taskCount: finding.taskIds.length,\n proposedFixClass: finding.proposedFixClass,\n attribution: finding.attribution,\n })),\n failures: input.suite.tasks\n .filter((task) => task.outcome && task.outcome !== 'satisfied')\n .map((task) => ({\n task: task.id,\n difficulty: task.difficulty,\n outcome: task.outcome,\n score: task.score,\n gaps: task.gaps ?? [],\n })),\n },\n null,\n 2,\n)}\n\nUse the trace tools. Do not invent facts. Cite task ids. Separate customer-facing claims from internal harness/model findings.\nCustomer attribution must preserve the supplied evidence class and artifact links. A narrative, regex label, observational rate, or document age is not causal evidence. Without validated request/response execution or a supported registered corrected-document comparison, report unknown; do not guess a failing company or tool.`\n}\n","/** Canonical flattened OTLP span shape shared by trace producers and readers. */\n\nimport type { SpanStatus } from './schema'\n\nexport type OtlpStatusCode = 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET'\n\nexport interface OtlpFlatLine {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: string\n start_time: string\n end_time: string\n status: {\n code: OtlpStatusCode\n message?: string\n }\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n events?: Array<{ name: string; timeUnixNano?: string; attributes?: Record<string, unknown> }>\n}\n\nexport interface CreateOtlpFlatLineInput {\n traceId: string\n spanId: string\n parentSpanId: string | null\n name: string\n kind: string\n startTime: string\n endTime: string\n statusCode: OtlpStatusCode\n statusMessage?: string\n resource: OtlpFlatLine['resource']\n attributes: Record<string, unknown>\n events?: OtlpFlatLine['events']\n}\n\nexport function createOtlpFlatLine(input: CreateOtlpFlatLineInput): OtlpFlatLine {\n return {\n trace_id: input.traceId,\n span_id: input.spanId,\n parent_span_id: input.parentSpanId,\n name: input.name,\n kind: input.kind,\n start_time: input.startTime,\n end_time: input.endTime,\n status: {\n code: input.statusCode,\n ...(input.statusMessage !== undefined ? { message: input.statusMessage } : {}),\n },\n resource: input.resource,\n attributes: input.attributes,\n ...(input.events && input.events.length > 0 ? { events: input.events } : {}),\n }\n}\n\n/** Map the canonical trace status while letting each caller choose its legacy default. */\nexport function spanStatusToOtlp(\n status: SpanStatus | undefined,\n error: string | undefined,\n defaultCode: OtlpStatusCode,\n): OtlpStatusCode {\n if (status === 'error' || error) return 'STATUS_CODE_ERROR'\n if (status === 'ok') return 'STATUS_CODE_OK'\n return defaultCode\n}\n\n/** Convert epoch milliseconds, returning `undefined` for invalid or out-of-range values. */\nexport function epochMillisToIso(value: number): string | undefined {\n if (!Number.isFinite(value)) return undefined\n try {\n return new Date(value).toISOString()\n } catch {\n return undefined\n }\n}\n","import { CaptureIntegrityError } from '../errors'\nimport { applyToolSpanOtlpAttributes, OPENINFERENCE_SPAN_KIND } from '../trace/otlp-attributes'\nimport { createOtlpFlatLine, epochMillisToIso, spanStatusToOtlp } from '../trace/otlp-flat'\nimport type { ToolSpan } from '../trace/schema'\nimport type { TraceAnalysisStore } from './store'\nimport { createOtlpBufferTraceStore, type ToolSpansToTraceAnalysisStoreOptions } from './store-otlp'\n\n/** Missing tool spans cannot distinguish a tool-free run from broken capture. */\nexport class ToolTraceMissingError extends CaptureIntegrityError {\n constructor() {\n super('toolSpansToTraceAnalysisStore: no tool spans supplied; trace evidence is missing')\n }\n}\n\n/**\n * Snapshot canonical tool spans into the read interface used by trace analysts.\n * One run becomes one trace while arguments, results, errors, and timing remain searchable.\n */\nexport function toolSpansToTraceAnalysisStore(\n spans: readonly ToolSpan[] | null | undefined,\n options: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!spans || spans.length === 0) throw new ToolTraceMissingError()\n\n const seen = new Set<string>()\n const lines = spans.map((span, index) => {\n assertToolSpanIdentity(span, index)\n const identity = `${span.runId}\\u0000${span.spanId}`\n if (seen.has(identity)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: duplicate span '${span.spanId}' in run '${span.runId}'`,\n )\n }\n seen.add(identity)\n\n const attributes = { ...(span.attributes ?? {}) }\n applyToolSpanOtlpAttributes(attributes, span)\n attributes[OPENINFERENCE_SPAN_KIND] = 'TOOL'\n\n const endedAt = span.endedAt ?? span.startedAt + (span.latencyMs ?? 0)\n const line = createOtlpFlatLine({\n traceId: span.runId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: toolSpanTimeIso(span.startedAt, span.spanId, 'startedAt'),\n endTime: toolSpanTimeIso(endedAt, span.spanId, 'endedAt'),\n statusCode: spanStatusToOtlp(span.status, span.error, 'STATUS_CODE_UNSET'),\n statusMessage: span.error,\n resource: { attributes: {} },\n attributes,\n })\n try {\n return JSON.stringify(line)\n } catch (cause) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' in run '${span.runId}' is not JSON-serializable`,\n { cause },\n )\n }\n })\n\n return createOtlpBufferTraceStore(Buffer.from(`${lines.join('\\n')}\\n`, 'utf8'), options)\n}\n\nfunction assertToolSpanIdentity(span: ToolSpan, index: number): void {\n if (span.kind !== 'tool') {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} has kind '${String(span.kind)}', not 'tool'`,\n )\n }\n if (!span.runId || !span.spanId || !span.name || !span.toolName) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} is missing runId, spanId, name, or toolName`,\n )\n }\n if (!Number.isFinite(span.startedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid startedAt`,\n )\n }\n if (span.endedAt !== undefined && !Number.isFinite(span.endedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid endedAt`,\n )\n }\n if (span.endedAt !== undefined && span.endedAt < span.startedAt) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' ends before it starts`,\n )\n }\n if (span.latencyMs !== undefined && (!Number.isFinite(span.latencyMs) || span.latencyMs < 0)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid latencyMs`,\n )\n }\n}\n\nfunction toolSpanTimeIso(value: number, spanId: string, field: string): string {\n const iso = epochMillisToIso(value)\n if (iso) return iso\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${spanId}' has invalid ${field}`,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0DA,MAAM,mBAAmB;AAEzB,SAAS,gBAAgB,SAAkE;CACzF,IAA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O,gBAAgB,OACjE;AACF"}
|
|
1
|
+
{"version":3,"file":"store-tool-spans-BAcBBSM8.js","names":[],"sources":["../src/trace/capture-fetch.ts","../src/trace/otlp-encoding.ts","../src/trace/wire-ids.ts","../src/trace/otel.ts","../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/store-tool-spans.ts"],"sourcesContent":["/**\n * Wrap a provider `fetch` and record request, response, and error events.\n *\n * The returned value is a plain `typeof fetch`. Capture is best-effort by\n * default; set `failClosed` when telemetry loss must stop the provider call.\n */\n\nimport {\n type ExtractedUsage,\n extractUsage,\n extractUsageFromSse,\n type SseUsageMode,\n} from './extract-usage'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderDirection,\n type RawProviderEvent,\n type RawProviderSink,\n} from './raw-provider-sink'\n\nexport interface CaptureFetchContext {\n /** Logical run id stamped on every captured event. Required — without it\n * the raw events can't be paired with their parent `Run`. */\n runId: string\n /** Optional logical span id (enables span-level sink filtering). */\n spanId?: string\n /** Resolved base URL (normalised, no trailing slash). Used for the event's\n * `baseUrl` and for endpoint-path extraction. */\n baseUrl: string\n /** Model id the caller intends to invoke. Stamped on every event. */\n model: string\n /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */\n provider?: string\n}\n\nexport interface CaptureFetchOptions {\n /** Override the capture-time redactor. Default `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n /** Cap on captured response-body bytes; beyond it the body is truncated and\n * `body_truncated` is added to `redactedFields`. Default 2 MiB. */\n responseBodyByteCap?: number\n /** When true, a sink-write failure propagates to the caller. Default false\n * — capture is best-effort so a sink failure never kills the LLM call. */\n failClosed?: boolean\n /**\n * Invoked with the token usage parsed off each successful response (JSON or\n * SSE), keyed by the captured context. Lets a caller fold usage → cost without\n * re-cloning the response themselves. Not called when the response carries no\n * usage. Best-effort: a throw here is swallowed (it never kills the LLM call)\n * unless `failClosed` is set.\n */\n onUsage?: (usage: ExtractedUsage, ctx: CaptureFetchContext) => void\n /** How repeated SSE usage events should be reconciled. Default `cumulative`. */\n sseUsageMode?: SseUsageMode\n}\n\nconst DEFAULT_BODY_CAP = 2 * 1024 * 1024\n\nfunction headersToRecord(headers: Headers | undefined): Record<string, string> | undefined {\n if (!headers) return undefined\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value\n })\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\n/** Best-effort request-body read across the `fetch` input forms. */\nasync function readRequestBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n): Promise<unknown> {\n if (typeof init?.body === 'string') return parseMaybeJson(init.body)\n if (init?.body != null) return undefined // streams / FormData / Blob — not captured\n if (input instanceof Request) {\n try {\n return parseMaybeJson(await input.clone().text())\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nfunction endpointFromUrl(url: string, baseUrl: string): string {\n const normalisedBase = baseUrl.replace(/\\/+$/, '')\n if (url.startsWith(normalisedBase)) return url.slice(normalisedBase.length) || '/'\n try {\n return new URL(url).pathname\n } catch {\n return url\n }\n}\n\nexport function captureFetchToRawSink(\n fetch: typeof globalThis.fetch,\n sink: RawProviderSink,\n ctx: CaptureFetchContext,\n opts: CaptureFetchOptions = {},\n): typeof globalThis.fetch {\n const provider = ctx.provider ?? providerFromBaseUrl(ctx.baseUrl)\n const redactor = opts.redactor ?? defaultProviderRedactor\n const bodyCap = opts.responseBodyByteCap ?? DEFAULT_BODY_CAP\n let warned = false\n\n const baseEvent = (direction: RawProviderDirection, endpoint: string): RawProviderEvent => ({\n eventId: crypto.randomUUID(),\n runId: ctx.runId,\n spanId: ctx.spanId,\n provider,\n model: ctx.model,\n endpoint,\n baseUrl: ctx.baseUrl,\n attemptIndex: 0, // retries are re-invocations one layer up; documented in 0.x\n direction,\n timestamp: Date.now(),\n redactedFields: [],\n })\n\n const record = async (event: RawProviderEvent): Promise<void> => {\n try {\n await sink.record(redactor(event))\n } catch (err) {\n if (opts.failClosed) throw err\n if (!warned) {\n warned = true\n console.warn(\n `captureFetchToRawSink: sink.record failed (capture is best-effort) — ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n }\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\n const endpoint = endpointFromUrl(url, ctx.baseUrl)\n\n const reqHeaders = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n )\n await record({\n ...baseEvent('request', endpoint),\n requestHeaders: { ...headersToRecord(reqHeaders), 'x-http-method': method },\n requestBody: await readRequestBody(input, init),\n })\n\n const start = Date.now()\n let response: Response\n try {\n response = await fetch(input, init)\n } catch (err) {\n await record({\n ...baseEvent('error', endpoint),\n durationMs: Date.now() - start,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n throw err\n }\n\n // Read the body off a clone so the caller still consumes the original.\n let responseBody: unknown\n let rawText: string | undefined\n const redactedFields: string[] = []\n try {\n rawText = await response.clone().text()\n if (rawText.length > bodyCap) {\n responseBody = rawText.slice(0, bodyCap)\n redactedFields.push('body_truncated')\n } else {\n responseBody = parseMaybeJson(rawText)\n }\n } catch {\n responseBody = undefined\n }\n\n if (opts.onUsage && rawText !== undefined) {\n // Reuse the body already read for capture; no extra clone. JSON first,\n // then SSE accumulation. A throw in the consumer's callback is swallowed\n // (best-effort) unless failClosed is set — the LLM call must not die here.\n try {\n const parsedForUsage = parseMaybeJson(rawText)\n const usage =\n extractUsage(parsedForUsage) ??\n (typeof parsedForUsage === 'string'\n ? extractUsageFromSse(rawText, { mode: opts.sseUsageMode })\n : null)\n if (usage) opts.onUsage(usage, ctx)\n } catch (err) {\n if (opts.failClosed) throw err\n }\n }\n\n await record({\n ...baseEvent('response', endpoint),\n durationMs: Date.now() - start,\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n responseBody,\n redactedFields,\n })\n\n return response\n }\n}\n","/**\n * The ONE encoding from this package's span values to OTLP wire values.\n *\n * Both exporters emit the same `OtlpSpan` shape, so an attribute typed as a\n * double by one and a string by the other would make the same run read\n * differently depending on which exporter produced it.\n */\n\n/** One OTLP `KeyValue`: the value is tagged with the protocol's type slot. */\nexport interface OtlpAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\n/** OTLP `KeyValue[]` for a flat attribute record. */\nexport function toOtlpAttributes(\n record: Record<string, string | number | boolean>,\n): OtlpAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\n/** OTLP nanosecond timestamp, as the decimal string the protocol requires. */\nexport function msToUnixNano(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n","/**\n * The ONE mapping from agent-eval's human-readable ids (run ids, span labels)\n * to W3C/OTLP wire ids. Every exporter in this package MUST route through\n * these two functions — two exporters with private paddings once produced\n * DIFFERENT trace ids for the same run, and one emitted invalid hex embedding\n * the raw run id in the wire id (tangle-network/agent-runtime#694).\n *\n * Semantics:\n * - an id that is ALREADY a valid W3C id passes through unchanged, so a\n * trace id received from an inbound `traceparent` survives the round-trip\n * and cross-process correlation is preserved;\n * - anything else is derived with the contract's `deriveHexId`, the only\n * legal derivation — deterministic, so every process that derives from the\n * same human id mints the SAME wire id.\n */\n\nimport { deriveHexId, isW3CSpanId, isW3CTraceId } from '@tangle-network/agent-trace-contract'\n\n/** 32-hex W3C trace id for any id string. */\nexport function traceIdForWire(id: string): string {\n return isW3CTraceId(id) ? id : deriveHexId(id, 16)\n}\n\n/** 16-hex W3C span id for any id string. */\nexport function spanIdForWire(id: string): string {\n return isW3CSpanId(id) ? id : deriveHexId(id, 8)\n}\n","/**\n * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so\n * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.\n *\n * Wire format only. We do NOT depend on the @opentelemetry SDK — that\n * would drag in polyfills incompatible with Workers/Edge. Consumers\n * push the JSON to their collector of choice via HTTP.\n *\n * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).\n */\n\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport { msToUnixNano, toOtlpAttributes } from './otlp-encoding'\nimport type { Run, Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\nimport { spanIdForWire, traceIdForWire } from './wire-ids'\n\nexport const OTEL_AGENT_EVAL_SCOPE = { name: '@tangle-network/agent-eval', version: '0.3.0' }\n\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n }>\n events?: Array<{ timeUnixNano: string; name: string; attributes?: OtlpSpan['attributes'] }>\n status?: { code: number; message?: string }\n}\n\nexport interface OtlpResourceSpans {\n resource: { attributes: OtlpSpan['attributes'] }\n scopeSpans: Array<{ scope: typeof OTEL_AGENT_EVAL_SCOPE; spans: OtlpSpan[] }>\n}\n\nexport interface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\n/** Export a single run's spans + events in OTLP/JSON. */\nexport async function exportRunAsOtlp(\n store: TraceStore,\n runId: string,\n resourceAttrs: Record<string, string | number | boolean> = {},\n): Promise<OtlpExport> {\n const run = await store.getRun(runId)\n if (!run) throw new Error(`run ${runId} not found`)\n const spans = await store.spans({ runId })\n const events = await store.events({ runId })\n const eventsBySpan = new Map<string, TraceEvent[]>()\n for (const e of events) {\n if (!e.spanId) continue\n const arr = eventsBySpan.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpan.set(e.spanId, arr)\n }\n const traceId = runToTraceId(run)\n const otlpSpans: OtlpSpan[] = spans.map((s) =>\n spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []),\n )\n return {\n resourceSpans: [\n {\n resource: {\n attributes: toOtlpAttributes({\n 'service.name': 'agent-eval',\n 'run.id': run.runId,\n 'run.scenario_id': run.scenarioId,\n 'run.variant_id': run.variantId ?? '',\n 'run.dataset_version': run.datasetVersion ?? '',\n 'run.code_sha': run.codeSha ?? '',\n 'run.model_fingerprint': run.modelFingerprint ?? '',\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: otlpSpans }],\n },\n ],\n }\n}\n\nfunction spanToOtlp(span: Span, traceId: string, events: TraceEvent[]): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n return {\n traceId,\n spanId: spanIdForWire(span.spanId),\n parentSpanId: span.parentSpanId ? spanIdForWire(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToUnixNano(span.startedAt),\n endTimeUnixNano: msToUnixNano(endedAt),\n attributes: toOtlpAttributes(flattenSpanAttributes(span)),\n events: events.map((e) => ({\n timeUnixNano: msToUnixNano(e.timestamp),\n name: e.kind,\n attributes: toOtlpAttributes(flattenPayload(e.payload)),\n })),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction flattenSpanAttributes(span: Span): Record<string, string | number | boolean> {\n const base: Record<string, string | number | boolean> = {}\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') base[k] = v\n }\n }\n base[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(base, span)\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(base, span)\n } else if (span.kind === 'retrieval') {\n base['retrieval.query'] = span.query\n base['retrieval.hits'] = span.hits.length\n } else if (span.kind === 'judge') {\n base['judge.id'] = span.judgeId\n base['judge.dimension'] = span.dimension\n base['judge.score'] = span.score\n base['judge.target_span_id'] = span.targetSpanId\n } else if (span.kind === 'sandbox') {\n if (span.image) base['sandbox.image'] = span.image\n if (span.exitCode !== undefined) base['sandbox.exit_code'] = span.exitCode\n if (span.testsPassed !== undefined) base['sandbox.tests_passed'] = span.testsPassed\n if (span.testsTotal !== undefined) base['sandbox.tests_total'] = span.testsTotal\n }\n return base\n}\n\nfunction flattenPayload(\n payload: Record<string, unknown>,\n): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const [k, v] of Object.entries(payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') out[k] = v\n else out[k] = JSON.stringify(v)\n }\n return out\n}\n\nfunction runToTraceId(run: Run): string {\n return traceIdForWire(run.runId)\n}\n","/** General policy for recursive, evidence-backed trace analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `Answer the question by inspecting the OTLP trace dataset with the available tools.\n\n1. Call getDatasetOverview first. Use its real trace ids and dataset size to plan the investigation.\n2. Narrow with queryTraces and countTraces before scanning large payloads.\n3. For a small trace, use viewTrace. For a large trace, use searchTrace and then viewSpans or searchSpan.\n4. Never invent a trace id, span id, tool result, error, frequency, or final outcome.\n5. When a search reports has_more, refine the query before drawing a conclusion.\n6. Use llm_query only over evidence already loaded. A recursive query cannot inspect traces itself.\n7. Cite exact evidence URIs returned by the tools. Include a short exact excerpt when it supports the claim.\n8. Return no finding when the available evidence cannot support one.\n\nThe prose answer must directly answer the question and state important uncertainty.\nThe findings array contains only actionable or decision-relevant claims supported by inspected evidence.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-research-v1-2026-07-30'\n","import { randomUUID } from 'node:crypto'\nimport type {\n TraceAnalysisEngine,\n TraceAnalysisEngineResult,\n TraceAnalystLimits,\n} from '../analyst/engine'\nimport { runTraceAnalyst } from '../analyst/kind-factory'\nimport type { TraceToolGroupName } from '../analyst/tool-groups'\nimport type { AnalystFinding, AnalystUsageReceipt } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION } from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore } from './store-otlp'\n\nexport interface AnalyzeTracesInput {\n question: string\n id?: string\n description?: string\n area?: string\n}\n\nexport type AnalyzeTracesResult = TraceAnalysisEngineResult\n\nexport interface AnalyzeTracesOptions {\n /** OTLP JSONL path or a caller-owned store. */\n source: string | TraceAnalysisStore\n /** Recursive research engine. */\n engine: TraceAnalysisEngine\n /** Override the general trace-research policy. */\n instructions?: string\n /** Smallest tool set that can answer the question. Default: all. */\n toolGroup?: TraceToolGroupName\n limits?: Partial<TraceAnalystLimits>\n runId?: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n costPhase?: string\n priorFindings?: readonly AnalystFinding[]\n upstreamFindings?: readonly AnalystFinding[]\n recordUsage?: (receipt: AnalystUsageReceipt) => void\n tags?: Record<string, string>\n log?: (message: string, fields?: Record<string, unknown>) => void\n signal?: AbortSignal\n}\n\n/**\n * Answer one question by recursively inspecting a trace store.\n *\n * The returned answer, cited findings, engine steps, call counts, and runtime\n * identity are one audit record. A direct one-shot model call is not used.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (typeof input.question !== 'string' || !input.question.trim()) {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n const id = input.id?.trim() || 'trace-analysis'\n const store =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed(options.signal ? { signal: options.signal } : undefined)\n }\n\n return runTraceAnalyst({\n definition: {\n id,\n description:\n input.description?.trim() ||\n 'Answers a caller-defined question by recursively inspecting trace evidence.',\n area: input.area?.trim() || 'trace-analysis',\n version: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n question: input.question,\n instructions: options.instructions ?? TRACE_ANALYST_ACTOR_DESCRIPTION,\n toolGroup: options.toolGroup ?? 'all',\n limits: options.limits,\n },\n engine: options.engine,\n store,\n context: {\n runId: options.runId ?? id,\n correlationId: randomUUID(),\n budgetUsd: options.budgetUsd,\n costLedger: options.costLedger,\n costPhase: options.costPhase ?? 'trace-analysis',\n priorFindings: options.priorFindings,\n upstreamFindings: options.upstreamFindings,\n recordUsage: options.recordUsage,\n tags: options.tags,\n log: options.log,\n signal: options.signal,\n },\n })\n}\n","import type { SearchArtifactRef } from '../campaign/search-ledger-types'\nimport { LEDGER_HASH_PATTERN } from '../ledger-core/canonical'\n\nexport interface TraceInsightTask {\n id: string\n name: string\n prompt?: string\n difficulty?: string\n tags?: string[]\n outcome?: string\n score?: number\n gaps?: string[]\n}\n\nexport interface TraceInsightSuite {\n name: string\n collectionId?: string\n tasks: TraceInsightTask[]\n}\n\nexport interface TraceInsightFinding {\n kind: string\n severity?: string\n taskIds: string[]\n evidence?: string\n proposedFixClass?: string\n /** Narrative evidence remains a note; customer attribution uses byte-backed evidence only. */\n attribution?: TraceInsightAttribution\n}\n\n/** A byte-backed observation. Locators are not identities; every link carries a digest. */\nexport interface TraceInsightEvidence {\n subject: {\n verticalId: string\n taskId: string\n cellId: string | null\n attemptId: string | null\n company: string | null\n tool: string | null\n toolRevision: string | null\n }\n artifacts: Record<\n 'seed' | 'task' | 'cell' | 'request' | 'response' | 'document' | 'controls' | 'binding',\n SearchArtifactRef | null\n >\n spans: Array<{ traceId: string; spanId: string; artifact: SearchArtifactRef }>\n}\n\nexport type TraceInsightAttribution = TraceInsightEvidence &\n (\n | { outcome: 'unknown'; evidenceClass: 'unknown'; reasons: string[] }\n | {\n outcome: 'tool-failure'\n evidenceClass: 'validated-request-response'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'authoritative-execution'\n documentation: 'stale' | 'contradictory'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'paired-corrected-document'\n proof: SearchArtifactRef\n plan: SearchArtifactRef\n comparisonId: string\n correctedEvidence: SearchArtifactRef\n }\n )\n\nfunction evidenceRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction evidenceText(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\n/** Structural validation only. The producer must verify bytes and execute the evidence rule. */\nexport function isTraceInsightArtifact(value: unknown): value is SearchArtifactRef {\n if (\n !evidenceRecord(value) ||\n !evidenceText(value.role) ||\n !evidenceText(value.uri) ||\n typeof value.sha256 !== 'string' ||\n !LEDGER_HASH_PATTERN.test(value.sha256) ||\n !Number.isSafeInteger(value.byteLength) ||\n (value.byteLength as number) < 0\n )\n return false\n // Customer reports must not turn a locator into an executable link.\n try {\n const url = new URL(value.uri)\n return ['https:', 'file:'].includes(url.protocol) && !url.username && !url.password\n } catch {\n return /^artifacts\\/[a-f0-9]{64}$/.test(value.uri)\n }\n}\n\nexport function isTraceInsightEvidence(value: unknown): value is TraceInsightEvidence {\n if (\n !evidenceRecord(value) ||\n !evidenceRecord(value.subject) ||\n !evidenceRecord(value.artifacts) ||\n !Array.isArray(value.spans)\n )\n return false\n const subject = value.subject\n if (!evidenceText(subject.verticalId) || !evidenceText(subject.taskId)) return false\n for (const field of ['cellId', 'attemptId', 'company', 'tool', 'toolRevision']) {\n if (subject[field] !== null && !evidenceText(subject[field])) return false\n }\n for (const role of [\n 'seed',\n 'task',\n 'cell',\n 'request',\n 'response',\n 'document',\n 'controls',\n 'binding',\n ]) {\n const artifact = value.artifacts[role]\n if (artifact !== null && (!isTraceInsightArtifact(artifact) || artifact.role !== role))\n return false\n }\n return value.spans.every(\n (span) =>\n evidenceRecord(span) &&\n typeof span.traceId === 'string' &&\n /^[a-f0-9]{32}$/.test(span.traceId) &&\n !/^0+$/.test(span.traceId) &&\n typeof span.spanId === 'string' &&\n /^[a-f0-9]{16}$/.test(span.spanId) &&\n !/^0+$/.test(span.spanId) &&\n isTraceInsightArtifact(span.artifact) &&\n span.artifact.role === 'span',\n )\n}\n\nexport function isTraceInsightAttribution(value: unknown): value is TraceInsightAttribution {\n if (!isTraceInsightEvidence(value)) return false\n const attribution = value as TraceInsightEvidence & Record<string, unknown>\n if (attribution.outcome === 'unknown') {\n return (\n attribution.evidenceClass === 'unknown' &&\n Array.isArray(attribution.reasons) &&\n attribution.reasons.length > 0 &&\n attribution.reasons.every(evidenceText)\n )\n }\n if (\n Object.values(value.subject).some((entry) => entry === null) ||\n Object.values(value.artifacts).some((artifact) => artifact === null) ||\n value.spans.length === 0 ||\n !isTraceInsightArtifact(attribution.proof)\n )\n return false\n if (attribution.outcome === 'tool-failure') {\n return (\n attribution.evidenceClass === 'validated-request-response' &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n if (attribution.outcome !== 'documentation-failure') return false\n if (attribution.evidenceClass === 'authoritative-execution') {\n return (\n (attribution.documentation === 'stale' || attribution.documentation === 'contradictory') &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n return (\n attribution.evidenceClass === 'paired-corrected-document' &&\n attribution.proof.role === 'publication' &&\n isTraceInsightArtifact(attribution.plan) &&\n attribution.plan.role === 'plan' &&\n isTraceInsightArtifact(attribution.correctedEvidence) &&\n attribution.correctedEvidence.role === 'binding' &&\n evidenceText(attribution.comparisonId)\n )\n}\n\nexport interface TraceInsightQuestion {\n id: string\n question: string\n why: string\n}\n\nexport interface TraceInsightPanelRole {\n id: string\n name: string\n responsibility: string\n}\n\nexport interface TraceInsightPromptInput {\n suite: TraceInsightSuite\n findings?: TraceInsightFinding[]\n agent?: Record<string, unknown>\n totals?: Record<string, unknown>\n maxRepresentativeTraces?: number\n}\n\nexport interface TraceInsightContext {\n suite: TraceInsightSuite\n scope: string\n keywords: string[]\n questions: TraceInsightQuestion[]\n panel: TraceInsightPanelRole[]\n findings: TraceInsightFinding[]\n agent: Record<string, unknown> | null\n totals: Record<string, unknown> | null\n}\n\nexport interface TraceInsightQualityGate {\n id: string\n label: string\n passed: boolean\n severity: 'critical' | 'high' | 'medium' | 'low'\n detail: string\n}\n\nexport interface TraceInsightReadiness {\n score: number\n grade: 'external-ready' | 'internal-review' | 'raw-analysis'\n gates: TraceInsightQualityGate[]\n}\n\nconst DOMAIN_STOP_WORDS = new Set([\n 'and',\n 'advanced',\n 'app',\n 'build',\n 'create',\n 'easy',\n 'expert',\n 'extreme',\n 'for',\n 'from',\n 'hard',\n 'implementation',\n 'integrate',\n 'medium',\n 'project',\n 'task',\n 'the',\n 'this',\n 'with',\n 'workflow',\n])\n\nexport function tokenizeDomainWords(value: string): string[] {\n return [...value.matchAll(/[A-Za-z][A-Za-z0-9.+#-]{2,}/g)]\n .map((match) => match[0].toLowerCase())\n .filter((word) => !DOMAIN_STOP_WORDS.has(word))\n}\n\nexport function inferDomainKeywords(suite: TraceInsightSuite): string[] {\n const suiteWords = new Set(tokenizeDomainWords(`${suite.name} ${suite.collectionId ?? ''}`))\n const source = [\n suite.name,\n suite.collectionId ?? '',\n ...suite.tasks.flatMap((task) => [\n task.id,\n task.name,\n task.prompt ?? '',\n task.difficulty ?? '',\n ...(task.tags ?? []),\n ...(task.gaps ?? []),\n ]),\n ].join(' ')\n const counts = new Map<string, number>()\n for (const word of tokenizeDomainWords(source)) counts.set(word, (counts.get(word) ?? 0) + 1)\n return [...counts.entries()]\n .filter(([word, count]) => count >= 2 || suiteWords.has(word))\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([word]) => word)\n .slice(0, 18)\n}\n\nexport function domainEvidencePattern(keywords: string[]): RegExp {\n const escaped = keywords\n .filter((keyword) => keyword.length >= 3)\n .map((keyword) => keyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n return escaped.length > 0\n ? new RegExp(`(?<![A-Za-z0-9])(?:${escaped.join('|')})(?![A-Za-z0-9])`, 'i')\n : /(?<![A-Za-z0-9])(?:sdk|api|css|dns|xml|provider|client|service|integration|webhook|transaction|auth|oauth|graphql|rest)(?![A-Za-z0-9])/i\n}\n\nexport function describeTraceInsightScope(suite: TraceInsightSuite): string {\n const taskLabel =\n suite.tasks.length === 1\n ? '1 implementation task'\n : `${suite.tasks.length} implementation tasks`\n const tags = new Map<string, number>()\n for (const task of suite.tasks) {\n for (const tag of task.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)\n }\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 8)\n .map(([tag]) => tag)\n if (topTags.length > 0) return `${taskLabel} across ${topTags.join(', ')}.`\n const difficulties = [\n ...new Set(\n suite.tasks.map((task) => task.difficulty).filter((value): value is string => Boolean(value)),\n ),\n ].join(', ')\n return `${taskLabel} across ${difficulties || 'the selected benchmark scope'}.`\n}\n\nexport function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[] {\n const hasFailures = input.suite.tasks.some((task) => task.outcome && task.outcome !== 'satisfied')\n const hasMultipleShots = input.suite.tasks.some((task) =>\n (task.gaps ?? []).some((gap) => /shot|review|retry|continue/i.test(gap)),\n )\n const questions: TraceInsightQuestion[] = [\n {\n id: 'execution-path',\n question: 'What did the worker actually do before the first meaningful implementation edit?',\n why: 'Separates grounded execution from polished but shallow output.',\n },\n {\n id: 'research-grounding',\n question:\n 'Did the worker inspect docs, source, examples, or package references before committing to an implementation path?',\n why: 'Identifies whether failures came from weak retrieval, weak examples, or premature coding.',\n },\n {\n id: 'domain-proof',\n question:\n 'Which tasks produced executable domain proof versus UI copy, placeholders, or inferred behavior?',\n why: 'Keeps product-quality claims tied to concrete evidence.',\n },\n {\n id: 'root-cause',\n question:\n 'For each major failure cluster, is the likely root cause prompt/scaffold, docs/examples, SDK/API ergonomics, evaluator, runtime, or model behavior?',\n why: 'Turns trace observations into actionable ownership.',\n },\n {\n id: 'evidence-quality',\n question:\n 'Which external-facing claims are directly supported by trace ids, span ids, verifier findings, reviewer notes, or generated code?',\n why: 'Prevents unsupported customer-report conclusions.',\n },\n ]\n if (hasMultipleShots) {\n questions.push({\n id: 'reviewer-lift',\n question: 'Where did reviewer feedback improve score, stall, or regress across shots?',\n why: 'Shows whether the driver loop is learning or merely repeating work.',\n })\n }\n if (hasFailures) {\n questions.push({\n id: 'optimization-targets',\n question:\n 'Which prompt, evaluator, scaffold, or workflow changes should feed the next GEPA/autoresearch optimization run?',\n why: 'Connects benchmark evidence to the optimization loop.',\n })\n }\n return questions\n}\n\nexport function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext {\n return {\n suite: input.suite,\n scope: describeTraceInsightScope(input.suite),\n keywords: inferDomainKeywords(input.suite),\n questions: planTraceInsightQuestions(input),\n panel: defaultTraceInsightPanel(),\n findings: input.findings ?? [],\n agent: input.agent ?? null,\n totals: input.totals ?? null,\n }\n}\n\nexport function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness {\n const failedTasks = context.suite.tasks.filter(\n (task) => task.outcome && task.outcome !== 'satisfied',\n )\n const findingTaskIds = new Set(context.findings.flatMap((finding) => finding.taskIds))\n const failedTasksWithFindings = failedTasks.filter((task) => findingTaskIds.has(task.id))\n const tasksWithGaps = context.suite.tasks.filter((task) => (task.gaps ?? []).length > 0)\n const gates: TraceInsightQualityGate[] = [\n {\n id: 'domain-context',\n label: 'Domain context inferred',\n passed: context.keywords.length > 0,\n severity: 'high',\n detail:\n context.keywords.length > 0\n ? `${context.keywords.length} domain terms inferred: ${context.keywords.slice(0, 8).join(', ')}`\n : 'No domain terms were inferred from suite, tasks, prompts, tags, or gaps.',\n },\n {\n id: 'panel-coverage',\n label: 'Analyst panel planned',\n passed: context.panel.length >= 4 && context.questions.length >= 5,\n severity: 'high',\n detail: `${context.panel.length} panel roles and ${context.questions.length} investigation questions planned.`,\n },\n {\n id: 'failure-coverage',\n label: 'Failures mapped to findings',\n passed:\n failedTasks.length === 0 || failedTasksWithFindings.length / failedTasks.length >= 0.5,\n severity: 'critical',\n detail:\n failedTasks.length === 0\n ? 'No failed tasks in suite.'\n : `${failedTasksWithFindings.length}/${failedTasks.length} failed tasks appear in finding clusters.`,\n },\n {\n id: 'gap-evidence',\n label: 'Task gaps captured',\n passed: failedTasks.length === 0 || tasksWithGaps.length / failedTasks.length >= 0.5,\n severity: 'medium',\n detail: `${tasksWithGaps.length} tasks include explicit evaluator or analyst gaps.`,\n },\n {\n id: 'attribution-evidence',\n label: 'Evidence-classed customer findings',\n passed:\n failedTasks.every((task) =>\n context.findings.some(\n (finding) =>\n finding.taskIds.includes(task.id) && finding.attribution?.subject.taskId === task.id,\n ),\n ) &&\n context.findings.every(\n (finding) =>\n isTraceInsightAttribution(finding.attribution) &&\n finding.taskIds.length === 1 &&\n finding.taskIds[0] === finding.attribution.subject.taskId,\n ),\n severity: 'critical',\n detail:\n 'Every finding needs an explicit evidence class and byte-backed links, or an explicit unknown; prose is not attribution evidence.',\n },\n ]\n const penalty = gates.reduce((sum, gate) => {\n if (gate.passed) return sum\n if (gate.severity === 'critical') return sum + 35\n if (gate.severity === 'high') return sum + 20\n if (gate.severity === 'medium') return sum + 10\n return sum + 5\n }, 0)\n const score = Math.max(0, Math.min(1, 1 - penalty / 100))\n return {\n score,\n grade: score >= 0.9 ? 'external-ready' : score >= 0.7 ? 'internal-review' : 'raw-analysis',\n gates,\n }\n}\n\nexport function defaultTraceInsightPanel(): TraceInsightPanelRole[] {\n return [\n {\n id: 'trace-forensics',\n name: 'Trace Forensics',\n responsibility:\n 'Reconstruct what the worker did in order, including research, edits, reviewer interventions, verifier feedback, and stop reason.',\n },\n {\n id: 'root-cause',\n name: 'Root Cause',\n responsibility:\n 'Map failures to prompt/scaffold, docs/examples, SDK/API/product ergonomics, evaluator, runtime, or model behavior.',\n },\n {\n id: 'optimization',\n name: 'Optimization',\n responsibility:\n 'Identify prompt, reviewer, evaluator, scaffold, and GEPA/autoresearch changes that should be tested next.',\n },\n {\n id: 'external-evidence',\n name: 'External Evidence',\n responsibility:\n 'Separate customer-safe claims from internal harness findings and reject conclusions without task, trace, span, code, reviewer, or verifier evidence.',\n },\n ]\n}\n\nexport function buildTraceInsightPrompt(input: TraceInsightPromptInput): string {\n const context = buildTraceInsightContext(input)\n const maxRepresentativeTraces = input.maxRepresentativeTraces ?? 6\n return `Analyze this benchmark run and produce evidence-backed trace intelligence.\n\nAudience:\n- internal AI/product leadership\n- possible customer-facing report for ${input.suite.name}\n\nInvestigation plan:\n${context.questions.map((item, index) => `${index + 1}. ${item.question} (${item.why})`).join('\\n')}\n\nAnalyst panel:\n${context.panel.map((role) => `- ${role.name}: ${role.responsibility}`).join('\\n')}\n\nIf the task branches are independent, use subagents for the panel roles above and aggregate their findings. Do not run a panel role unless its answer will change the final report.\n\nRequired output:\n1. Executive verdict: what this run proves and does not prove.\n2. The investigation questions you answered and the evidence used.\n3. Failure taxonomy: agent prompting, evaluator/harness, docs/examples, SDK/API/product integration, infra.\n4. Evidence-backed examples with trace ids/task ids and concrete verifier findings.\n5. Highest-ROI fixes for the benchmark harness, prompt/GEPA optimization, and customer-facing product/docs surface.\n6. What is safe for an external report versus what must stay internal.\n7. One rerun plan that would validate lift after optimization.\n\nBudget:\n- Inspect the dataset overview, the failure summary, and at most ${maxRepresentativeTraces} representative traces.\n- Prefer traces named in the failure summary over broad exploration.\n- Do not do exhaustive trace sweeps.\n- Return the final report as soon as the taxonomy and examples are supported.\n\nRun summary:\n${JSON.stringify(\n {\n suite: input.suite.name,\n scope: context.scope,\n inferredKeywords: context.keywords,\n agent: context.agent,\n totals: context.totals,\n findings: context.findings.map((finding) => ({\n kind: finding.kind,\n severity: finding.severity,\n taskCount: finding.taskIds.length,\n proposedFixClass: finding.proposedFixClass,\n attribution: finding.attribution,\n })),\n failures: input.suite.tasks\n .filter((task) => task.outcome && task.outcome !== 'satisfied')\n .map((task) => ({\n task: task.id,\n difficulty: task.difficulty,\n outcome: task.outcome,\n score: task.score,\n gaps: task.gaps ?? [],\n })),\n },\n null,\n 2,\n)}\n\nUse the trace tools. Do not invent facts. Cite task ids. Separate customer-facing claims from internal harness/model findings.\nCustomer attribution must preserve the supplied evidence class and artifact links. A narrative, regex label, observational rate, or document age is not causal evidence. Without validated request/response execution or a supported registered corrected-document comparison, report unknown; do not guess a failing company or tool.`\n}\n","/** Canonical flattened OTLP span shape shared by trace producers and readers. */\n\nimport type { SpanStatus } from './schema'\n\nexport type OtlpStatusCode = 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET'\n\nexport interface OtlpFlatLine {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: string\n start_time: string\n end_time: string\n status: {\n code: OtlpStatusCode\n message?: string\n }\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n events?: Array<{ name: string; timeUnixNano?: string; attributes?: Record<string, unknown> }>\n}\n\nexport interface CreateOtlpFlatLineInput {\n traceId: string\n spanId: string\n parentSpanId: string | null\n name: string\n kind: string\n startTime: string\n endTime: string\n statusCode: OtlpStatusCode\n statusMessage?: string\n resource: OtlpFlatLine['resource']\n attributes: Record<string, unknown>\n events?: OtlpFlatLine['events']\n}\n\nexport function createOtlpFlatLine(input: CreateOtlpFlatLineInput): OtlpFlatLine {\n return {\n trace_id: input.traceId,\n span_id: input.spanId,\n parent_span_id: input.parentSpanId,\n name: input.name,\n kind: input.kind,\n start_time: input.startTime,\n end_time: input.endTime,\n status: {\n code: input.statusCode,\n ...(input.statusMessage !== undefined ? { message: input.statusMessage } : {}),\n },\n resource: input.resource,\n attributes: input.attributes,\n ...(input.events && input.events.length > 0 ? { events: input.events } : {}),\n }\n}\n\n/** Map the canonical trace status while letting each caller choose its legacy default. */\nexport function spanStatusToOtlp(\n status: SpanStatus | undefined,\n error: string | undefined,\n defaultCode: OtlpStatusCode,\n): OtlpStatusCode {\n if (status === 'error' || error) return 'STATUS_CODE_ERROR'\n if (status === 'ok') return 'STATUS_CODE_OK'\n return defaultCode\n}\n\n/** Convert epoch milliseconds, returning `undefined` for invalid or out-of-range values. */\nexport function epochMillisToIso(value: number): string | undefined {\n if (!Number.isFinite(value)) return undefined\n try {\n return new Date(value).toISOString()\n } catch {\n return undefined\n }\n}\n","import { CaptureIntegrityError } from '../errors'\nimport { applyToolSpanOtlpAttributes, OPENINFERENCE_SPAN_KIND } from '../trace/otlp-attributes'\nimport { createOtlpFlatLine, epochMillisToIso, spanStatusToOtlp } from '../trace/otlp-flat'\nimport type { ToolSpan } from '../trace/schema'\nimport type { TraceAnalysisStore } from './store'\nimport { createOtlpBufferTraceStore, type ToolSpansToTraceAnalysisStoreOptions } from './store-otlp'\n\n/** Missing tool spans cannot distinguish a tool-free run from broken capture. */\nexport class ToolTraceMissingError extends CaptureIntegrityError {\n constructor() {\n super('toolSpansToTraceAnalysisStore: no tool spans supplied; trace evidence is missing')\n }\n}\n\n/**\n * Snapshot canonical tool spans into the read interface used by trace analysts.\n * One run becomes one trace while arguments, results, errors, and timing remain searchable.\n */\nexport function toolSpansToTraceAnalysisStore(\n spans: readonly ToolSpan[] | null | undefined,\n options: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!spans || spans.length === 0) throw new ToolTraceMissingError()\n\n const seen = new Set<string>()\n const lines = spans.map((span, index) => {\n assertToolSpanIdentity(span, index)\n const identity = `${span.runId}\\u0000${span.spanId}`\n if (seen.has(identity)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: duplicate span '${span.spanId}' in run '${span.runId}'`,\n )\n }\n seen.add(identity)\n\n const attributes = { ...(span.attributes ?? {}) }\n applyToolSpanOtlpAttributes(attributes, span)\n attributes[OPENINFERENCE_SPAN_KIND] = 'TOOL'\n\n const endedAt = span.endedAt ?? span.startedAt + (span.latencyMs ?? 0)\n const line = createOtlpFlatLine({\n traceId: span.runId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: toolSpanTimeIso(span.startedAt, span.spanId, 'startedAt'),\n endTime: toolSpanTimeIso(endedAt, span.spanId, 'endedAt'),\n statusCode: spanStatusToOtlp(span.status, span.error, 'STATUS_CODE_UNSET'),\n statusMessage: span.error,\n resource: { attributes: {} },\n attributes,\n })\n try {\n return JSON.stringify(line)\n } catch (cause) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' in run '${span.runId}' is not JSON-serializable`,\n { cause },\n )\n }\n })\n\n return createOtlpBufferTraceStore(Buffer.from(`${lines.join('\\n')}\\n`, 'utf8'), options)\n}\n\nfunction assertToolSpanIdentity(span: ToolSpan, index: number): void {\n if (span.kind !== 'tool') {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} has kind '${String(span.kind)}', not 'tool'`,\n )\n }\n if (!span.runId || !span.spanId || !span.name || !span.toolName) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} is missing runId, spanId, name, or toolName`,\n )\n }\n if (!Number.isFinite(span.startedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid startedAt`,\n )\n }\n if (span.endedAt !== undefined && !Number.isFinite(span.endedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid endedAt`,\n )\n }\n if (span.endedAt !== undefined && span.endedAt < span.startedAt) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' ends before it starts`,\n )\n }\n if (span.latencyMs !== undefined && (!Number.isFinite(span.latencyMs) || span.latencyMs < 0)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid latencyMs`,\n )\n }\n}\n\nfunction toolSpanTimeIso(value: number, spanId: string, field: string): string {\n const iso = epochMillisToIso(value)\n if (iso) return iso\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${spanId}' has invalid ${field}`,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0DA,MAAM,mBAAmB;AAEzB,SAAS,gBAAgB,SAAkE;CACzF,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,MAA8B,CAAC;CACrC,QAAQ,SAAS,OAAO,QAAQ;EAC9B,IAAI,IAAI,YAAY,KAAK;CAC3B,CAAC;CACD,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,IAAI,MAAM,KAAA;AAC7C;AAEA,SAAS,eAAe,MAAuB;CAC7C,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAC9B,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAe,gBACb,OACA,MACkB;CAClB,IAAI,OAAO,MAAM,SAAS,UAAU,OAAO,eAAe,KAAK,IAAI;CACnE,IAAI,MAAM,QAAQ,MAAM,OAAO,KAAA;CAC/B,IAAI,iBAAiB,SACnB,IAAI;EACF,OAAO,eAAe,MAAM,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC;CAClD,QAAQ;EACN;CACF;AAGJ;AAEA,SAAS,gBAAgB,KAAa,SAAyB;CAC7D,MAAM,iBAAiB,QAAQ,QAAQ,QAAQ,EAAE;CACjD,IAAI,IAAI,WAAW,cAAc,GAAG,OAAO,IAAI,MAAM,eAAe,MAAM,KAAK;CAC/E,IAAI;EACF,OAAO,I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,KAAK,OAAO,GAC7D,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,sBACtD;CAEF,IAAI,KAAK,YAAY,KAAA,KAAa,KAAK,UAAU,KAAK,WACpD,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;CAEF,IAAI,KAAK,cAAc,KAAA,MAAc,CAAC,OAAO,SAAS,KAAK,SAAS,KAAK,KAAK,YAAY,IACxF,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;AAEJ;AAEA,SAAS,gBAAgB,OAAe,QAAgB,OAAuB;CAC7E,MAAM,MAAM,iBAAiB,KAAK;CAClC,IAAI,KAAK,OAAO;CAChB,MAAM,IAAI,sBACR,wCAAwC,OAAO,gBAAgB,OACjE;AACF"}
|
package/dist/traces.js
CHANGED
|
@@ -3,15 +3,15 @@ import { a as hasCapturedToolArgs, c as runFailureClass, d as toolSpans, i as gr
|
|
|
3
3
|
import { c as validateRunRecord, i as modelHasSnapshot } from "./run-record-DlTZ_lqe.js";
|
|
4
4
|
import { a as combineVerdicts, c as emptyRedactionReport, d as redactForShare, f as redactText, i as classifyKey, l as normalizeKey, n as REDACTION_VERSION, o as detectCredential, p as shareAllowed, r as assessShareSafety, s as detectPersonalData, t as REDACTION_PROFILES, u as redact } from "./redact-Dk1ZdJEm.js";
|
|
5
5
|
import { t as TraceEmitter } from "./emitter-DbMXUIVP.js";
|
|
6
|
-
import { A as spanEpochMillis, C as TraceFileTooLargeError, D as extractOtlpAttributes, E as compareSpanTime, O as firstStringAttr, S as TraceFileMissingError, T as asString, _ as SpanNotFoundError, a as TRACE_ANALYST_TOOL_NAMESPACE, b as TraceAnalysisValidationError, g as TRACE_ANALYSIS_LIMITS, h as TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, j as stringField, k as projectOtlpFlatLine, l as createBoundedTraceAnalysisStore, m as DEFAULT_TRACE_ANALYST_BUDGETS, o as UNTRUSTED_TRACE_TEXT, s as buildTraceAnalysisToolDescriptors, v as TraceAnalysisLimitError, w as TraceNotFoundError, x as TraceFileMalformedError, y as TraceAnalysisStoreContractError } from "./kind-factory-
|
|
6
|
+
import { A as spanEpochMillis, C as TraceFileTooLargeError, D as extractOtlpAttributes, E as compareSpanTime, O as firstStringAttr, S as TraceFileMissingError, T as asString, _ as SpanNotFoundError, a as TRACE_ANALYST_TOOL_NAMESPACE, b as TraceAnalysisValidationError, g as TRACE_ANALYSIS_LIMITS, h as TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, j as stringField, k as projectOtlpFlatLine, l as createBoundedTraceAnalysisStore, m as DEFAULT_TRACE_ANALYST_BUDGETS, o as UNTRUSTED_TRACE_TEXT, s as buildTraceAnalysisToolDescriptors, v as TraceAnalysisLimitError, w as TraceNotFoundError, x as TraceFileMalformedError, y as TraceAnalysisStoreContractError } from "./kind-factory-CMlOx08-.js";
|
|
7
7
|
import { INPUT_VALUE, LLM_CACHED_TOKENS, LLM_CACHED_TOKEN_ATTR_KEYS, LLM_CACHE_WRITE_TOKENS, LLM_CACHE_WRITE_TOKEN_ATTR_KEYS, LLM_CONTEXT_TOKENS, LLM_COST_ATTR_KEYS, LLM_COST_USD, LLM_INPUT_TOKENS, LLM_INPUT_TOKEN_ATTR_KEYS, LLM_MODEL_ATTR_KEYS, LLM_MODEL_NAME, LLM_OUTPUT_TOKENS, LLM_OUTPUT_TOKEN_ATTR_KEYS, LLM_REASONING_TOKENS, LLM_REASONING_TOKEN_ATTR_KEYS, OPENINFERENCE_SPAN_KIND, OUTPUT_VALUE, RUN_COST_ATTR_KEYS, SPAN_KIND_ATTR_KEYS, TOOL_ARGS_CAPTURED, TOOL_LATENCY_MS, TOOL_NAME, TOOL_NAME_ATTR_KEYS, applyLlmSpanOtlpAttributes, asNumber, contextInputTokens, firstNumberAttr } from "./trace-attributes.js";
|
|
8
8
|
import { n as extractUsageFromResponse, r as extractUsageFromSse, t as extractUsage } from "./extract-usage-BrnzRJ6H.js";
|
|
9
9
|
import { a as providerFromBaseUrl, i as defaultProviderRedactor, n as InMemoryRawProviderSink, r as NoopRawProviderSink, t as FileSystemRawProviderSink } from "./raw-provider-sink-rB2DYxr6.js";
|
|
10
|
-
import { C as spanIdForWire, S as exportRunAsOtlp, T as captureFetchToRawSink, _ as tokenizeDomainWords, a as spanStatusToOtlp, b as TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, c as defaultTraceInsightPanel, d as inferDomainKeywords, f as isTraceInsightArtifact, g as scoreTraceInsightReadiness, h as planTraceInsightQuestions, i as epochMillisToIso, l as describeTraceInsightScope, m as isTraceInsightEvidence, n as toolSpansToTraceAnalysisStore, o as buildTraceInsightContext, p as isTraceInsightAttribution, r as createOtlpFlatLine, s as buildTraceInsightPrompt, t as ToolTraceMissingError, u as domainEvidencePattern, v as analyzeTraces, w as traceIdForWire, x as OTEL_AGENT_EVAL_SCOPE, y as TRACE_ANALYST_ACTOR_DESCRIPTION } from "./store-tool-spans-
|
|
10
|
+
import { C as spanIdForWire, S as exportRunAsOtlp, T as captureFetchToRawSink, _ as tokenizeDomainWords, a as spanStatusToOtlp, b as TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, c as defaultTraceInsightPanel, d as inferDomainKeywords, f as isTraceInsightArtifact, g as scoreTraceInsightReadiness, h as planTraceInsightQuestions, i as epochMillisToIso, l as describeTraceInsightScope, m as isTraceInsightEvidence, n as toolSpansToTraceAnalysisStore, o as buildTraceInsightContext, p as isTraceInsightAttribution, r as createOtlpFlatLine, s as buildTraceInsightPrompt, t as ToolTraceMissingError, u as domainEvidencePattern, v as analyzeTraces, w as traceIdForWire, x as OTEL_AGENT_EVAL_SCOPE, y as TRACE_ANALYST_ACTOR_DESCRIPTION } from "./store-tool-spans-BAcBBSM8.js";
|
|
11
11
|
import { n as assertRunCaptured, r as throwIfRunIncomplete, t as RunIntegrityError } from "./integrity-BvnVARVl.js";
|
|
12
12
|
import { n as traceSpanKindToOpenInferenceKind, t as applyToolSpanOtlpAttributes } from "./otlp-attributes-D9ptWaIJ.js";
|
|
13
13
|
import { n as InMemoryTraceStore, t as FileSystemTraceStore } from "./store-BhNuLdJw.js";
|
|
14
|
-
import { a as spanRecordsToTraceAnalysisStore, i as otlpTextToTraceAnalysisStore, n as OtlpFileTraceStore } from "./store-otlp-
|
|
14
|
+
import { a as spanRecordsToTraceAnalysisStore, i as otlpTextToTraceAnalysisStore, n as OtlpFileTraceStore } from "./store-otlp-0AiS29kg.js";
|
|
15
15
|
import { i as summarizeTraceErrors, n as recordAggregateMeasurements, r as summarizeExecutionMeasurements, t as readTaskFailureLabels } from "./task-failure-attributes-DngaLdE4.js";
|
|
16
16
|
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
17
17
|
import { join } from "node:path";
|
package/dist/wire/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as WIRE_VERSION, C as RUBRIC_VERSION_SCHEME, D as TracesIngestRequestSchema, E as TraceEventSchema, O as TracesIngestResponseSchema, S as ListRubricsResponseSchema, T as RubricSchema, _ as FeedbackIngestResponseSchema, a as runRpcBatch, b as JudgeRequestSchema, c as WireError, d as handleListRubrics, f as handleTracesIngest, g as ErrorResponseSchema, h as listBuiltinRubrics, i as dispatchRpc, j as hashRubric, k as VersionResponseSchema, l as handleFeedbackIngest, m as getBuiltinRubric, n as startServer, o as runRpcOnce, p as handleVersion, r as startServerAsync, s as buildOpenApi, t as createApp, u as handleJudge, v as FeedbackTrajectorySchema, w as RubricDimensionSchema, x as JudgeResultSchema, y as HealthResponseSchema } from "../server-
|
|
1
|
+
import { A as WIRE_VERSION, C as RUBRIC_VERSION_SCHEME, D as TracesIngestRequestSchema, E as TraceEventSchema, O as TracesIngestResponseSchema, S as ListRubricsResponseSchema, T as RubricSchema, _ as FeedbackIngestResponseSchema, a as runRpcBatch, b as JudgeRequestSchema, c as WireError, d as handleListRubrics, f as handleTracesIngest, g as ErrorResponseSchema, h as listBuiltinRubrics, i as dispatchRpc, j as hashRubric, k as VersionResponseSchema, l as handleFeedbackIngest, m as getBuiltinRubric, n as startServer, o as runRpcOnce, p as handleVersion, r as startServerAsync, s as buildOpenApi, t as createApp, u as handleJudge, v as FeedbackTrajectorySchema, w as RubricDimensionSchema, x as JudgeResultSchema, y as HealthResponseSchema } from "../server-BRpadnVt.js";
|
|
2
2
|
export { ErrorResponseSchema, FeedbackIngestResponseSchema, FeedbackTrajectorySchema, HealthResponseSchema, JudgeRequestSchema, JudgeResultSchema, ListRubricsResponseSchema, RUBRIC_VERSION_SCHEME, RubricDimensionSchema, RubricSchema, TraceEventSchema, TracesIngestRequestSchema, TracesIngestResponseSchema, VersionResponseSchema, WIRE_VERSION, WireError, buildOpenApi, createApp, dispatchRpc, getBuiltinRubric, handleFeedbackIngest, handleJudge, handleListRubrics, handleTracesIngest, handleVersion, hashRubric, listBuiltinRubrics, runRpcBatch, runRpcOnce, startServer, startServerAsync };
|
package/docs/concepts.md
CHANGED
|
@@ -362,7 +362,8 @@ The `/meta-eval` gate contract (also exported from the package root) provides it
|
|
|
362
362
|
It reports accuracy over runs, Cohen's κ for the pass/fail pair (null when one side used a single verdict), the confusion table, an exact 95% interval over examples, variance between runs and between a run's samples, and every disagreement.
|
|
363
363
|
3. **Decide whether it may gate.** `judgeGateDecision({ judgeId, judgeModel, rubricVersion, agreement, asOf, history })` refuses with named reasons when the judge was never measured, was measured on another model or rubric, has fewer judged examples than the policy requires (by default 10, and at least one of each verdict), has a report older than 30 days, falls below 90% accuracy or κ 0.6, or has an alarmed drift history.
|
|
364
364
|
`assertJudgeMayGate(decision)` throws `JudgeGateRefusedError`; a refused judge's verdict is advisory.
|
|
365
|
-
|
|
365
|
+
A judge that only blocks, such as a copy or policy check that never passes work on its own, takes `policy: { decides: 'veto' }`: owners reject for reasons it does not cover, so it is held instead to its false-fail rate on owner passes (at most 10%, over at least 10 owner passes), and its catch rate is reported.
|
|
366
|
+
4. **Record drift.** `snapshotFromJudgeAgreement(agreement, { decides })` stores accuracy (for a veto judge, the share of owner passes it let through) as `sentinelPassRate` and κ as `calibrationKappa` in the judge sentinel, so each calibration run appends one snapshot and `judgeSentinelReport` alarms on decay, a silent model change or staleness.
|
|
366
367
|
|
|
367
368
|
| Probe | Input | Observation |
|
|
368
369
|
|---|---|---|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-eval",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.211.2",
|
|
4
4
|
"description": "Evaluate and improve AI agents from runs, traces, judges, and feedback. Compare candidates, cluster failures, measure lift, and gate releases.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-eval#readme",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"judge-gate-C59znGmR.js","names":["parseIso"],"sources":["../src/series-convergence.ts","../src/meta-eval/sentinel.ts","../src/meta-eval/judge-gate.ts"],"sourcesContent":["/**\n * Series convergence — detects whether a sequence of scalar measurements\n * is stabilizing, drifting, or noisy. It reads drift *across* runs, e.g.\n * \"are my nightly eval scores stabilizing?\".\n *\n * Three signals:\n * - stabilized: last K values have low variance (< epsilon) — done\n * - drifting: recent trend is monotonic and beyond noise — regressing or improving\n * - noisy: neither — keep iterating, but flag as untrustworthy for gating\n */\n\nexport interface SeriesConvergenceOptions {\n /** Window size for \"recent\" analysis (default 5). */\n window?: number\n /** Coefficient-of-variation threshold below which the window is stabilized (default 0.05 = 5%). */\n stableCv?: number\n /** Minimum monotone run length to call drift (default 3). */\n driftRun?: number\n}\n\nexport interface SeriesConvergenceResult {\n state: 'stabilized' | 'drifting-up' | 'drifting-down' | 'noisy' | 'insufficient-data'\n windowMean: number\n windowCv: number\n /** Longest monotonic run at the tail of the series (positive for up, negative for down). */\n tailRun: number\n /** True when n ≥ window AND windowCv ≤ stableCv. */\n stable: boolean\n}\n\nexport function analyzeSeries(\n values: number[],\n options: SeriesConvergenceOptions = {},\n): SeriesConvergenceResult {\n const window = options.window ?? 5\n const stableCv = options.stableCv ?? 0.05\n const driftRun = options.driftRun ?? 3\n\n if (values.length < Math.max(2, Math.min(window, 3))) {\n return { state: 'insufficient-data', windowMean: 0, windowCv: 0, tailRun: 0, stable: false }\n }\n\n const tail = values.slice(-window)\n const mean = tail.reduce((a, b) => a + b, 0) / tail.length\n const variance = tail.reduce((acc, v) => acc + (v - mean) ** 2, 0) / tail.length\n const stdDev = Math.sqrt(variance)\n const refMean = Math.abs(mean) > 1e-9 ? Math.abs(mean) : 1\n const cv = stdDev / refMean\n const stable = tail.length >= window && cv <= stableCv\n\n // Tail monotonic run: count how many consecutive strictly-increasing (or decreasing)\n // steps end at the final value.\n let tailRun = 0\n let direction: 1 | -1 | 0 = 0\n for (let i = values.length - 1; i > 0; i--) {\n const delta = values[i]! - values[i - 1]!\n if (delta === 0) break\n const dir = delta > 0 ? 1 : -1\n if (direction === 0) direction = dir\n if (dir !== direction) break\n tailRun += dir\n }\n\n let state: SeriesConvergenceResult['state']\n if (stable) {\n state = 'stabilized'\n } else if (Math.abs(tailRun) >= driftRun) {\n state = tailRun > 0 ? 'drifting-up' : 'drifting-down'\n } else {\n state = 'noisy'\n }\n\n return { state, windowMean: mean, windowCv: cv, tailRun, stable }\n}\n","/**\n * Judge sentinel — eval trustworthiness as a continuously measured,\n * alarmed trend.\n *\n * Judges are models; models change underneath us; calibration decays.\n * This module composes three existing instruments into one loop:\n *\n * snapshot — adapters turn real instrument outputs (`calibrateJudge` /\n * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /\n * `continuousAgreement`, a rerun sentinel golden set) into\n * `SentinelSnapshot`s\n * series — `analyzeSeries` (src/series-convergence) classifies each\n * judge×metric history as stabilized / drifting / noisy\n * alarm — `judgeSentinelReport` turns trends + thresholds into named\n * alarms; `evalHealthStamp` is the tiny object a campaign\n * attaches to its verdicts\n *\n * Alarm conditions:\n * - convergence state `drifting-down` on any tracked metric\n * - irr below `minIrr`\n * - calibrationKappa / sentinelPassRate dropped vs the series baseline\n * beyond `maxKappaDrop` / `maxSentinelDrop`\n * - judge model changed with no post-change golden-grounded snapshot\n * (the silent-upgrade trap: judges agreeing with each other after a\n * model swap proves nothing — only re-measuring against gold does)\n * - newest snapshot older than `staleAfterDays` relative to `asOf`\n *\n * Wire-in: run the snapshot adapters from a post-campaign hook or a\n * nightly job, append to a `SentinelStore`, then compute\n * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =\n * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign\n * verdicts: an alarmed sentinel means every downstream verdict carries\n * an integrity warning until the judge is recalibrated.\n *\n * The module is clock-free — every timestamp (`at`, `asOf`) is\n * caller-supplied ISO-8601, so reports are reproducible.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n CalibrationResult,\n CandidateScore,\n ContinuousAgreement,\n ContinuousCalibrationResult,\n GoldenItem,\n} from '../judge-calibration'\nimport {\n analyzeSeries,\n type SeriesConvergenceOptions,\n type SeriesConvergenceResult,\n} from '../series-convergence'\nimport type { CorpusAgreementReport } from '../statistics'\n\nconst SENTINEL_METRIC_NAMES = ['irr', 'calibrationKappa', 'sentinelPassRate'] as const\n\nexport type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number]\n\nexport interface SentinelMetrics {\n /** Inter-rater reliability — ICC(2,1) from agreement instruments. */\n irr?: number\n /** Weighted κ vs the human golden set (`calibrateJudge*`). */\n calibrationKappa?: number\n /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */\n sentinelPassRate?: number\n}\n\nexport interface SentinelSnapshot {\n /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */\n at: string\n judgeId: string\n /** Exact model identity behind the judge (pin the full version string). */\n judgeModel: string\n /**\n * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a\n * model-change marker — it records the new `judgeModel` immediately and\n * the silent-upgrade alarm stays raised until a golden-grounded snapshot\n * (calibrationKappa or sentinelPassRate) follows.\n */\n metrics: SentinelMetrics\n}\n\n/** Identity + timestamp the caller supplies alongside an instrument output. */\nexport interface SnapshotMeta {\n at: string\n judgeId: string\n judgeModel: string\n}\n\nfunction parseIso(value: string, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\n/** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */\nexport function validateSentinelSnapshot(snapshot: SentinelSnapshot, source = 'snapshot'): void {\n parseIso(snapshot.at, `${source}.at`)\n if (typeof snapshot.judgeId !== 'string' || snapshot.judgeId.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`)\n }\n if (typeof snapshot.judgeModel !== 'string' || snapshot.judgeModel.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`)\n }\n if (snapshot.metrics === null || typeof snapshot.metrics !== 'object') {\n throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`)\n }\n for (const [key, value] of Object.entries(snapshot.metrics)) {\n if (!(SENTINEL_METRIC_NAMES as readonly string[]).includes(key)) {\n // A typo'd key would silently never trend — reject instead.\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics carries unknown key \"${key}\" — known: ${SENTINEL_METRIC_NAMES.join(', ')}`,\n )\n }\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`,\n )\n }\n }\n}\n\n// ── Snapshot adapters — real instrument output → SentinelSnapshot ───\n\n/**\n * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the\n * un-rounded continuous κ_w when the report carries one (integer κ\n * discards information for [0,1] judges).\n */\nexport function snapshotFromCalibration(\n report: CalibrationResult | ContinuousCalibrationResult,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const kappa = 'weightedKappaContinuous' in report ? report.weightedKappaContinuous : report.kappa\n if (!Number.isFinite(kappa)) {\n throw new ValidationError(\n `snapshotFromCalibration: κ is not finite (n=${report.n}) — calibrate against ≥2 joined golden items before snapshotting`,\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { calibrationKappa: kappa } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n/**\n * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`\n * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability\n * coefficient both instruments compute. For ensemble-level agreement,\n * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its\n * composition (e.g. a joined list of member model strings).\n */\nexport function snapshotFromAgreement(\n report: CorpusAgreementReport | ContinuousAgreement,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const irr = 'overallIcc' in report ? report.overallIcc : report.icc\n if (!Number.isFinite(irr)) {\n throw new ValidationError(\n 'snapshotFromAgreement: ICC is not finite — agreement needs ≥2 raters and ≥2 complete items',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { irr } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\nexport interface SentinelSetOptions {\n /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */\n tolerance?: number\n}\n\n/**\n * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the\n * judge was originally calibrated on, re-scored periodically. Pass rate =\n * fraction of joined items where the judge stays within `tolerance` of the\n * human score. Items the judge didn't score are excluded from the\n * denominator; zero joined items is an error, not a 0% pass rate.\n */\nexport function snapshotFromSentinelSet(\n scores: CandidateScore[],\n golden: GoldenItem[],\n meta: SnapshotMeta,\n options: SentinelSetOptions = {},\n): SentinelSnapshot {\n const tolerance = options.tolerance ?? 0.1\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError(\n `snapshotFromSentinelSet: tolerance must be a finite number ≥ 0, got ${tolerance}`,\n )\n }\n const goldenById = new Map<string, number>()\n for (const item of golden) {\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: golden item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (goldenById.has(item.itemId)) {\n throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId \"${item.itemId}\"`)\n }\n goldenById.set(item.itemId, item.humanScore)\n }\n let joined = 0\n let passed = 0\n for (const s of scores) {\n const human = goldenById.get(s.itemId)\n if (human === undefined) continue\n if (!Number.isFinite(s.score)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: judge score for item \"${s.itemId}\" is not finite`,\n )\n }\n joined++\n if (Math.abs(s.score - human) <= tolerance) passed++\n }\n if (joined === 0) {\n throw new ValidationError(\n 'snapshotFromSentinelSet: no judge scores joined the golden set — itemIds mismatch or empty sentinel run',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n// ── Persistence ──────────────────────────────────────────────────────\n\nexport interface SentinelStore {\n append(snapshot: SentinelSnapshot): Promise<void>\n /** All snapshots (optionally for one judge), in append order. */\n history(judgeId?: string): Promise<SentinelSnapshot[]>\n}\n\nexport function inMemorySentinelStore(initial: SentinelSnapshot[] = []): SentinelStore {\n for (const s of initial) validateSentinelSnapshot(s)\n const items = initial.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n items.push({ ...snapshot, metrics: { ...snapshot.metrics } })\n },\n async history(judgeId) {\n const all = items.map((s) => ({ ...s, metrics: { ...s.metrics } }))\n return judgeId === undefined ? all : all.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n/**\n * JSONL store — one snapshot per line, appended atomically per call.\n * A corrupt or shape-invalid line is a loud error naming the file and\n * line number: a sentinel history that silently drops records would\n * defeat the drift detection it exists to provide.\n */\nexport function fileSentinelStore(path: string): SentinelStore {\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n const fs = await import('node:fs/promises')\n const pathMod = await import('node:path')\n await fs.mkdir(pathMod.dirname(path), { recursive: true })\n await fs.appendFile(path, `${JSON.stringify(snapshot)}\\n`, 'utf8')\n },\n async history(judgeId) {\n const fs = await import('node:fs/promises')\n let raw: string\n try {\n raw = await fs.readFile(path, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw err\n }\n const lines = raw.split('\\n')\n const snapshots: SentinelSnapshot[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n if (line.trim().length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${(err as Error).message}`,\n )\n }\n const snapshot = parsed as SentinelSnapshot\n validateSentinelSnapshot(snapshot, `${path}:${i + 1}`)\n snapshots.push(snapshot)\n }\n return judgeId === undefined ? snapshots : snapshots.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n// ── Trend report ─────────────────────────────────────────────────────\n\nexport interface SentinelThresholds {\n /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */\n minIrr?: number\n /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */\n maxKappaDrop?: number\n /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */\n maxSentinelDrop?: number\n /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */\n staleAfterDays?: number\n}\n\nexport interface JudgeSentinelOptions {\n /** Caller-supplied ISO timestamp staleness is measured against. */\n asOf: string\n thresholds?: SentinelThresholds\n /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */\n convergence?: SeriesConvergenceOptions\n}\n\nexport interface SentinelTrend {\n judgeId: string\n metric: SentinelMetricName\n /** Verbatim `analyzeSeries` state for this judge×metric history. */\n state: SeriesConvergenceResult['state']\n /** Newest value in the series. */\n current: number\n /** Oldest value in the series — the reference the drop thresholds compare against. */\n baseline: number\n /** current − baseline (signed; negative = decayed). */\n drift: number\n alarmed: boolean\n reason?: string\n}\n\nexport interface SentinelReport {\n perJudge: SentinelTrend[]\n alarms: string[]\n healthy: boolean\n /**\n * `judgeId:metric` pairs with too few snapshots for the convergence\n * machine. Named, not counted — a blind spot you can't see is a blind\n * spot you won't fix. Floor/drop checks still apply to thin series, so\n * insufficient history alone never masks an alarm.\n */\n insufficientHistory: string[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\nexport function judgeSentinelReport(\n history: SentinelSnapshot[],\n opts: JudgeSentinelOptions,\n): SentinelReport {\n const asOfMs = parseIso(opts.asOf, 'asOf')\n const minIrr = opts.thresholds?.minIrr ?? 0.6\n const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15\n const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1\n const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30\n\n const byJudge = new Map<string, Array<SentinelSnapshot & { atMs: number }>>()\n for (const snapshot of history) {\n validateSentinelSnapshot(snapshot)\n const atMs = parseIso(snapshot.at, `snapshot.at (judge \"${snapshot.judgeId}\")`)\n const arr = byJudge.get(snapshot.judgeId) ?? []\n arr.push({ ...snapshot, atMs })\n byJudge.set(snapshot.judgeId, arr)\n }\n\n const perJudge: SentinelTrend[] = []\n const alarms: string[] = []\n const insufficientHistory: string[] = []\n\n for (const judgeId of [...byJudge.keys()].sort()) {\n const snaps = byJudge.get(judgeId)!.sort((a, b) => a.atMs - b.atMs)\n const newest = snaps[snaps.length - 1]!\n\n const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY\n if (ageDays > staleAfterDays) {\n alarms.push(\n `judge \"${judgeId}\": stale — newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`,\n )\n }\n\n // Silent-upgrade trap: only the latest model change matters for current\n // trust, and only golden-grounded metrics clear it — irr alone proves\n // judges still agree with each other, not that they're still right.\n let changeIdx = -1\n for (let i = 1; i < snaps.length; i++) {\n if (snaps[i]!.judgeModel !== snaps[i - 1]!.judgeModel) changeIdx = i\n }\n if (changeIdx >= 0) {\n const recalibrated = snaps\n .slice(changeIdx)\n .some(\n (s) =>\n Number.isFinite(s.metrics.calibrationKappa) ||\n Number.isFinite(s.metrics.sentinelPassRate),\n )\n if (!recalibrated) {\n alarms.push(\n `judge \"${judgeId}\": model changed \"${snaps[changeIdx - 1]!.judgeModel}\" → \"${snaps[changeIdx]!.judgeModel}\" at ${snaps[changeIdx]!.at} with no post-change calibration snapshot — silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`,\n )\n }\n }\n\n for (const metric of SENTINEL_METRIC_NAMES) {\n const values = snaps\n .filter((s) => typeof s.metrics[metric] === 'number')\n .map((s) => s.metrics[metric]!)\n if (values.length === 0) continue\n\n const convergence = analyzeSeries(values, opts.convergence)\n if (convergence.state === 'insufficient-data')\n insufficientHistory.push(`${judgeId}:${metric}`)\n\n const current = values[values.length - 1]!\n const baseline = values[0]!\n const drift = current - baseline\n const reasons: string[] = []\n if (convergence.state === 'drifting-down') {\n reasons.push(\n `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`,\n )\n }\n if (metric === 'irr' && current < minIrr) {\n reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`)\n }\n if (metric === 'calibrationKappa' && baseline - current > maxKappaDrop) {\n reasons.push(\n `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`,\n )\n }\n if (metric === 'sentinelPassRate' && baseline - current > maxSentinelDrop) {\n reasons.push(\n `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`,\n )\n }\n\n const alarmed = reasons.length > 0\n const trend: SentinelTrend = {\n judgeId,\n metric,\n state: convergence.state,\n current,\n baseline,\n drift,\n alarmed,\n }\n if (alarmed) {\n trend.reason = reasons.join('; ')\n alarms.push(`judge \"${judgeId}\" ${metric}: ${trend.reason}`)\n }\n perJudge.push(trend)\n }\n }\n\n return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory }\n}\n\n// ── Verdict stamp ────────────────────────────────────────────────────\n\nexport interface EvalHealthStamp {\n healthy: boolean\n alarms: string[]\n}\n\n/**\n * The object a campaign attaches to its verdicts. Compute it from the\n * sentinel report in a post-campaign hook (or a nightly job feeding the\n * next day's campaigns) and store it alongside the verdict payload.\n * `healthy: false` means the judges that produced those verdicts have an\n * unresolved drift / decay / silent-upgrade / staleness alarm — treat the\n * verdicts as carrying an integrity warning until recalibration clears it.\n */\nexport function evalHealthStamp(report: SentinelReport): EvalHealthStamp {\n return { healthy: report.healthy, alarms: [...report.alarms] }\n}\n","/**\n * Judge calibration gate: a judge may gate only while its measured agreement\n * with its owner's verdicts holds.\n *\n * A judge (a model judge or a deterministic grader) registers a calibration\n * set: items its owner has decided, each verdict with its provenance. A\n * calibration run replays the judge on those items, once or several times, and\n * `measureJudgeAgreement` reports how often it reached the owner's verdict\n * (accuracy, and Cohen's κ for the pass/fail pair), how much its own verdict\n * moves between runs and between samples, and where it disagreed.\n *\n * `judgeGateDecision` turns that report into the one decision a consumer acts\n * on. It refuses when the judge has no measured agreement, too few decided\n * items of either verdict, a report measured on a different model or rubric\n * than the one the judge now runs, a report older than the policy allows,\n * agreement below the policy floors, or an alarmed drift history. A refused\n * judge's verdict is advisory: the consumer reports it but does not let it\n * pass or block anything.\n *\n * Drift is the judge sentinel (`./sentinel`): `snapshotFromJudgeAgreement`\n * records accuracy as `sentinelPassRate` and κ as `calibrationKappa`, so each\n * calibration run appends one snapshot to a `SentinelStore` and the gate reads\n * the alarms `judgeSentinelReport` raises over that history.\n *\n * Every timestamp is caller-supplied ISO-8601, so decisions are reproducible.\n */\n\nimport { JudgeError, ValidationError } from '../errors'\nimport { type ComputedInterval, computeInterval } from '../experiment/ast'\nimport {\n judgeSentinelReport,\n type SentinelSnapshot,\n type SentinelThresholds,\n validateSentinelSnapshot,\n} from './sentinel'\n\nexport type OwnerVerdict = 'pass' | 'fail'\n\n/** One item the owner decided, with where that decision is recorded. */\nexport interface CalibrationExample {\n /** Stable id of the decided item; a judge run names it in `exampleId`. */\n id: string\n verdict: OwnerVerdict\n /** The person whose verdict this is. Never a model. */\n labeledBy: string\n /** ISO-8601 time the verdict was given. */\n labeledAt: string\n /** Where the verdict is recorded, e.g. `gtm:asset_decision:<id>`. */\n source: string\n /** What the owner judged (an image digest, a run id), so a replay judges the same thing. */\n evidenceRef?: string\n note?: string\n}\n\nexport interface JudgeCalibrationSet {\n judgeId: string\n /** Whose verdicts the judge stands in for. */\n owner: string\n examples: readonly CalibrationExample[]\n}\n\nfunction parseIso(value: unknown, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : Number.NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-gate: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\nfunction requireText(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`judge-gate: ${label} must be a non-empty string`)\n }\n return value\n}\n\nfunction requireVerdict(value: unknown, label: string): OwnerVerdict {\n if (value !== 'pass' && value !== 'fail') {\n throw new ValidationError(\n `judge-gate: ${label} must be 'pass' or 'fail', got ${JSON.stringify(value)}`,\n )\n }\n return value\n}\n\nfunction checkExample(example: CalibrationExample, label: string): CalibrationExample {\n if (example === null || typeof example !== 'object') {\n throw new ValidationError(`judge-gate: ${label} must be an object`)\n }\n requireText(example.id, `${label}.id`)\n requireVerdict(example.verdict, `${label}.verdict`)\n requireText(example.labeledBy, `${label}.labeledBy`)\n parseIso(example.labeledAt, `${label}.labeledAt`)\n requireText(example.source, `${label}.source`)\n if (example.evidenceRef !== undefined) requireText(example.evidenceRef, `${label}.evidenceRef`)\n const copy: CalibrationExample = {\n id: example.id,\n verdict: example.verdict,\n labeledBy: example.labeledBy,\n labeledAt: example.labeledAt,\n source: example.source,\n }\n if (example.evidenceRef !== undefined) copy.evidenceRef = example.evidenceRef\n if (example.note !== undefined) copy.note = example.note\n return copy\n}\n\n/**\n * Validate a calibration set and return a normalized copy ordered by example\n * id. Every verdict needs its person, time and source; ids are unique.\n */\nexport function registerCalibrationSet(set: JudgeCalibrationSet): JudgeCalibrationSet {\n if (set === null || typeof set !== 'object') {\n throw new ValidationError('judge-gate: calibration set must be an object')\n }\n const judgeId = requireText(set.judgeId, 'calibration set judgeId')\n const owner = requireText(set.owner, `calibration set \"${judgeId}\" owner`)\n if (!Array.isArray(set.examples)) {\n throw new ValidationError(`judge-gate: calibration set \"${judgeId}\" examples must be an array`)\n }\n const seen = new Set<string>()\n const examples = set.examples.map((example, index) => {\n const checked = checkExample(example, `calibration set \"${judgeId}\" example ${index}`)\n if (seen.has(checked.id)) {\n throw new ValidationError(\n `judge-gate: calibration set \"${judgeId}\" has duplicate example id \"${checked.id}\"`,\n )\n }\n seen.add(checked.id)\n return checked\n })\n examples.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n return { judgeId, owner, examples }\n}\n\nexport interface CalibrationMerge {\n set: JudgeCalibrationSet\n /** Ids that joined the set. */\n added: string[]\n /** Ids whose verdict a later decision replaced. */\n superseded: string[]\n /** Ids whose incoming verdict was already recorded, or older than the recorded one. */\n unchanged: string[]\n}\n\n/**\n * Join new owner verdicts to a set. A verdict already recorded from the same\n * source is unchanged, so ingestion can rerun. A later verdict on an item\n * replaces an earlier one: the owner changed their mind, and the set keeps\n * what they decided last.\n */\nexport function addCalibrationVerdicts(\n set: JudgeCalibrationSet,\n verdicts: readonly CalibrationExample[],\n): CalibrationMerge {\n const base = registerCalibrationSet(set)\n const byId = new Map(base.examples.map((example) => [example.id, example]))\n const added: string[] = []\n const superseded: string[] = []\n const unchanged: string[] = []\n for (const [index, verdict] of verdicts.entries()) {\n const incoming = checkExample(verdict, `incoming verdict ${index} for \"${base.judgeId}\"`)\n const current = byId.get(incoming.id)\n if (!current) {\n byId.set(incoming.id, incoming)\n added.push(incoming.id)\n continue\n }\n const sameDecision = current.source === incoming.source && current.verdict === incoming.verdict\n if (\n sameDecision ||\n parseIso(incoming.labeledAt, 'labeledAt') <= parseIso(current.labeledAt, 'labeledAt')\n ) {\n unchanged.push(incoming.id)\n continue\n }\n byId.set(incoming.id, incoming)\n superseded.push(incoming.id)\n }\n return {\n set: registerCalibrationSet({ ...base, examples: [...byId.values()] }),\n added,\n superseded,\n unchanged,\n }\n}\n\n/** One gate decision the judge made on a calibration example. */\nexport interface JudgeRun {\n exampleId: string\n /** The judge's decision after its own sample aggregation (median, majority). */\n verdict: OwnerVerdict\n /** The per-sample verdicts behind that decision, when the judge samples. */\n samples?: readonly OwnerVerdict[]\n}\n\nexport interface JudgeRunMeta {\n judgeId: string\n /** Exact model identity, or `deterministic` for a grader without one. */\n judgeModel: string\n rubricVersion: string\n measuredAt: string\n}\n\nexport interface JudgeConfusion {\n /** Judge pass, owner pass. */\n truePass: number\n /** Judge fail, owner fail. */\n trueFail: number\n /** Judge pass, owner fail: the judge let through what the owner rejected. */\n falsePass: number\n /** Judge fail, owner pass: the judge blocked what the owner accepted. */\n falseFail: number\n}\n\nexport interface JudgeExampleAgreement {\n id: string\n verdict: OwnerVerdict\n runs: number\n /** Share of runs that passed. */\n passRate: number\n /** Share of runs that reached the owner's verdict. */\n agreement: number\n}\n\nexport interface JudgeAgreement extends JudgeRunMeta {\n owner: string\n /** Examples in the calibration set. */\n examples: number\n /** Examples the judge ran on at least once. */\n judged: number\n /** Judged examples per owner verdict. */\n judgedByVerdict: Record<OwnerVerdict, number>\n runs: number\n /** Runs that reached the owner's verdict, over all runs; null with no runs. */\n accuracy: number | null\n /**\n * Exact (Clopper-Pearson) 95% interval for the share of judged examples on\n * which every run reached the owner's verdict. Examples, not runs, are the\n * independent units.\n */\n exampleAccuracy: { agreed: number; judged: number; interval: ComputedInterval } | null\n /**\n * Cohen's κ between the judge and the owner over runs. Null when undefined:\n * no runs, or both sides used a single verdict.\n */\n kappa: number | null\n confusion: JudgeConfusion\n variance: {\n /** Mean over judged examples of p(1 − p), p the example's run pass rate. 0 = no run changed its mind. */\n betweenRuns: number | null\n /** Mean over runs that reported samples of p(1 − p) across those samples; null when none did. */\n withinRun: number | null\n /** Examples whose runs disagree with each other. */\n unstable: string[]\n }\n /** Examples with at least one run against the owner, least agreement first. */\n disagreements: JudgeExampleAgreement[]\n /** Examples without any run. */\n unjudged: string[]\n}\n\nfunction bernoulliVariance(passes: number, n: number): number {\n const p = passes / n\n return p * (1 - p)\n}\n\n/** Cohen's κ for two raters over a binary pass/fail table. */\nfunction binaryKappa(confusion: JudgeConfusion): number | null {\n const n = confusion.truePass + confusion.trueFail + confusion.falsePass + confusion.falseFail\n if (n === 0) return null\n const observed = (confusion.truePass + confusion.trueFail) / n\n const judgePass = (confusion.truePass + confusion.falsePass) / n\n const ownerPass = (confusion.truePass + confusion.falseFail) / n\n const expected = judgePass * ownerPass + (1 - judgePass) * (1 - ownerPass)\n if (expected === 1) return null\n return (observed - expected) / (1 - expected)\n}\n\n/**\n * Agreement between a judge's runs and the owner's verdicts on one\n * calibration set. A run that names an example outside the set is an error:\n * a silently dropped run would overstate agreement.\n */\nexport function measureJudgeAgreement(\n set: JudgeCalibrationSet,\n runs: readonly JudgeRun[],\n meta: JudgeRunMeta,\n): JudgeAgreement {\n const registered = registerCalibrationSet(set)\n if (meta.judgeId !== registered.judgeId) {\n throw new ValidationError(\n `judge-gate: runs are for judge \"${meta.judgeId}\" but the set belongs to \"${registered.judgeId}\"`,\n )\n }\n requireText(meta.judgeModel, 'judgeModel')\n requireText(meta.rubricVersion, 'rubricVersion')\n parseIso(meta.measuredAt, 'measuredAt')\n const byId = new Map(registered.examples.map((example) => [example.id, example]))\n const runsById = new Map<string, JudgeRun[]>()\n const confusion: JudgeConfusion = { truePass: 0, trueFail: 0, falsePass: 0, falseFail: 0 }\n const withinRun: number[] = []\n for (const [index, run] of runs.entries()) {\n const example = byId.get(run?.exampleId)\n if (!example) {\n throw new ValidationError(\n `judge-gate: run ${index} names example ${JSON.stringify(run?.exampleId)}, which is not in \"${registered.judgeId}\"'s calibration set`,\n )\n }\n const verdict = requireVerdict(run.verdict, `run ${index} verdict`)\n if (run.samples !== undefined) {\n if (!Array.isArray(run.samples) || run.samples.length === 0) {\n throw new ValidationError(`judge-gate: run ${index} samples must be a non-empty array`)\n }\n const samples = run.samples.map((sample, s) =>\n requireVerdict(sample, `run ${index} sample ${s}`),\n )\n withinRun.push(\n bernoulliVariance(samples.filter((sample) => sample === 'pass').length, samples.length),\n )\n }\n const list = runsById.get(example.id) ?? []\n list.push({ ...run, verdict })\n runsById.set(example.id, list)\n if (verdict === 'pass') {\n if (example.verdict === 'pass') confusion.truePass++\n else confusion.falsePass++\n } else if (example.verdict === 'fail') confusion.trueFail++\n else confusion.falseFail++\n }\n\n const perExample: JudgeExampleAgreement[] = []\n const unjudged: string[] = []\n const judgedByVerdict: Record<OwnerVerdict, number> = { pass: 0, fail: 0 }\n for (const example of registered.examples) {\n const list = runsById.get(example.id)\n if (!list) {\n unjudged.push(example.id)\n continue\n }\n judgedByVerdict[example.verdict]++\n const passes = list.filter((run) => run.verdict === 'pass').length\n perExample.push({\n id: example.id,\n verdict: example.verdict,\n runs: list.length,\n passRate: passes / list.length,\n agreement: list.filter((run) => run.verdict === example.verdict).length / list.length,\n })\n }\n\n const total = runs.length\n const agreedRuns = confusion.truePass + confusion.trueFail\n const agreedExamples = perExample.filter((example) => example.agreement === 1).length\n const mean = (values: readonly number[]) =>\n values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n return {\n ...meta,\n owner: registered.owner,\n examples: registered.examples.length,\n judged: perExample.length,\n judgedByVerdict,\n runs: total,\n accuracy: total === 0 ? null : agreedRuns / total,\n exampleAccuracy:\n perExample.length === 0\n ? null\n : {\n agreed: agreedExamples,\n judged: perExample.length,\n interval: computeInterval(\n { kind: 'clopper-pearson', level: 0.95 },\n { kind: 'binomial', successes: agreedExamples, trials: perExample.length },\n ),\n },\n kappa: binaryKappa(confusion),\n confusion,\n variance: {\n betweenRuns: mean(perExample.map((example) => example.passRate * (1 - example.passRate))),\n withinRun: mean(withinRun),\n unstable: perExample\n .filter((example) => example.passRate > 0 && example.passRate < 1)\n .map((example) => example.id),\n },\n disagreements: perExample\n .filter((example) => example.agreement < 1)\n .sort((a, b) => a.agreement - b.agreement || (a.id < b.id ? -1 : 1)),\n unjudged,\n }\n}\n\nexport interface JudgeGatePolicy {\n /** Judged examples required before the judge may gate. */\n minExamples: number\n /** Judged examples required of each owner verdict, so κ is defined. */\n minPerVerdict: number\n /** Floor on run accuracy. */\n minAccuracy: number\n /** Floor on Cohen's κ. */\n minKappa: number\n /** A report older than this (days, vs `asOf`) no longer calibrates the judge. */\n maxAgeDays: number\n /** Drift thresholds forwarded to `judgeSentinelReport` over the history. */\n drift?: SentinelThresholds\n}\n\nexport const DEFAULT_JUDGE_GATE_POLICY: Readonly<JudgeGatePolicy> = Object.freeze({\n minExamples: 10,\n minPerVerdict: 1,\n minAccuracy: 0.9,\n minKappa: 0.6,\n maxAgeDays: 30,\n})\n\nexport type JudgeGateStatus = 'calibrated' | 'uncalibrated' | 'below-threshold' | 'drifted'\n\nexport interface JudgeGateDecision {\n judgeId: string\n judgeModel: string\n rubricVersion: string\n /** True only for `calibrated`. */\n mayGate: boolean\n status: JudgeGateStatus\n /** Why the judge may not gate; empty when it may. */\n reasons: string[]\n agreement: JudgeAgreement | null\n policy: JudgeGatePolicy\n}\n\nexport interface JudgeGateInput {\n judgeId: string\n /** The model the judge runs now. */\n judgeModel: string\n /** The rubric the judge runs now. */\n rubricVersion: string\n /** The latest calibration report; null when the judge was never measured. */\n agreement: JudgeAgreement | null\n asOf: string\n /** Sentinel snapshots for this judge, oldest first or in any order. */\n history?: readonly SentinelSnapshot[]\n policy?: Partial<JudgeGatePolicy>\n}\n\nconst DAY_MS = 86_400_000\n\nfunction percent(value: number): string {\n return `${(value * 100).toFixed(1)}%`\n}\n\n/** Whether a judge may gate now, and every reason it may not. */\nexport function judgeGateDecision(input: JudgeGateInput): JudgeGateDecision {\n const judgeId = requireText(input.judgeId, 'judgeId')\n const judgeModel = requireText(input.judgeModel, 'judgeModel')\n const rubricVersion = requireText(input.rubricVersion, 'rubricVersion')\n const asOf = parseIso(input.asOf, 'asOf')\n const policy: JudgeGatePolicy = { ...DEFAULT_JUDGE_GATE_POLICY, ...input.policy }\n const agreement = input.agreement\n const decide = (status: JudgeGateStatus, reasons: string[]): JudgeGateDecision => ({\n judgeId,\n judgeModel,\n rubricVersion,\n mayGate: status === 'calibrated',\n status,\n reasons,\n agreement,\n policy,\n })\n\n if (!agreement) return decide('uncalibrated', ['no measured agreement with owner verdicts'])\n if (agreement.judgeId !== judgeId) {\n throw new ValidationError(\n `judge-gate: agreement belongs to \"${agreement.judgeId}\", not \"${judgeId}\"`,\n )\n }\n\n const uncalibrated: string[] = []\n if (agreement.judgeModel !== judgeModel) {\n uncalibrated.push(\n `agreement was measured on model ${agreement.judgeModel}; the judge now runs ${judgeModel}`,\n )\n }\n if (agreement.rubricVersion !== rubricVersion) {\n uncalibrated.push(\n `agreement was measured on rubric ${agreement.rubricVersion}; the judge now runs ${rubricVersion}`,\n )\n }\n const ageDays = (asOf - parseIso(agreement.measuredAt, 'agreement.measuredAt')) / DAY_MS\n if (ageDays > policy.maxAgeDays) {\n uncalibrated.push(`agreement is ${ageDays.toFixed(1)} days old (limit ${policy.maxAgeDays})`)\n }\n if (agreement.judged < policy.minExamples) {\n uncalibrated.push(\n `${agreement.judged} judged ${agreement.judged === 1 ? 'example' : 'examples'}; at least ${policy.minExamples} required`,\n )\n }\n for (const verdict of ['pass', 'fail'] as const) {\n if (agreement.judgedByVerdict[verdict] < policy.minPerVerdict) {\n uncalibrated.push(\n `${agreement.judgedByVerdict[verdict]} judged examples the owner marked ${verdict}; at least ${policy.minPerVerdict} required`,\n )\n }\n }\n if (uncalibrated.length > 0) return decide('uncalibrated', uncalibrated)\n\n const below: string[] = []\n if (agreement.accuracy === null || agreement.accuracy < policy.minAccuracy) {\n below.push(\n `accuracy ${agreement.accuracy === null ? 'unmeasured' : percent(agreement.accuracy)} is below ${percent(policy.minAccuracy)}`,\n )\n }\n if (agreement.kappa === null || agreement.kappa < policy.minKappa) {\n below.push(\n `kappa ${agreement.kappa === null ? 'undefined' : agreement.kappa.toFixed(2)} is below ${policy.minKappa}`,\n )\n }\n if (below.length > 0) return decide('below-threshold', below)\n\n const history = (input.history ?? []).filter((snapshot) => snapshot.judgeId === judgeId)\n if (history.length > 0) {\n const report = judgeSentinelReport([...history], {\n asOf: input.asOf,\n ...(policy.drift ? { thresholds: policy.drift } : {}),\n })\n if (!report.healthy) return decide('drifted', report.alarms)\n }\n return decide('calibrated', [])\n}\n\n/** Thrown by `assertJudgeMayGate`; carries the refused decision. */\nexport class JudgeGateRefusedError extends JudgeError {\n readonly decision: JudgeGateDecision\n\n constructor(decision: JudgeGateDecision) {\n super(\n `judge \"${decision.judgeId}\" may not gate (${decision.status}): ${decision.reasons.join('; ')}`,\n )\n this.decision = decision\n }\n}\n\n/** Throw unless the decision lets the judge gate. */\nexport function assertJudgeMayGate(decision: JudgeGateDecision): void {\n if (!decision.mayGate) throw new JudgeGateRefusedError(decision)\n}\n\n/**\n * The sentinel snapshot for one calibration run: accuracy as\n * `sentinelPassRate`, κ as `calibrationKappa` when it is defined. Append it to\n * the judge's `SentinelStore`; the gate reads drift from that history.\n */\nexport function snapshotFromJudgeAgreement(agreement: JudgeAgreement): SentinelSnapshot {\n if (agreement.accuracy === null) {\n throw new ValidationError(\n `snapshotFromJudgeAgreement: judge \"${agreement.judgeId}\" has no runs to snapshot`,\n )\n }\n const snapshot: SentinelSnapshot = {\n at: agreement.measuredAt,\n judgeId: agreement.judgeId,\n judgeModel: agreement.judgeModel,\n metrics: {\n sentinelPassRate: agreement.accuracy,\n ...(agreement.kappa === null ? {} : { calibrationKappa: agreement.kappa }),\n },\n }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n"],"mappings":";;;AA8BA,SAAgB,cACd,QACA,UAAo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AS,GAAG,OAAO,OAAO,mBAAmB,KAAK;CAE5D,MAAM,WAAW,MAAM,WAAW,CAAC,EAAA,CAAG,QAAQ,aAAa,SAAS,YAAY,OAAO;CACvF,IAAI,QAAQ,SAAS,GAAG;EACtB,MAAM,SAAS,oBAAoB,CAAC,GAAG,OAAO,GAAG;GAC/C,MAAM,MAAM;GACZ,GAAI,OAAO,QAAQ,EAAE,YAAY,OAAO,MAAM,IAAI,CAAC;EACrD,CAAC;EACD,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,WAAW,OAAO,MAAM;CAC7D;CACA,OAAO,OAAO,cAAc,CAAC,CAAC;AAChC;;AAGA,IAAa,wBAAb,cAA2C,WAAW;CACpD;CAEA,YAAY,UAA6B;EACvC,MACE,UAAU,SAAS,QAAQ,kBAAkB,SAAS,OAAO,KAAK,SAAS,QAAQ,KAAK,IAAI,GAC9F;EACA,KAAK,WAAW;CAClB;AACF;;AAGA,SAAgB,mBAAmB,UAAmC;CACpE,IAAI,CAAC,SAAS,SAAS,MAAM,IAAI,sBAAsB,QAAQ;AACjE;;;;;;AAOA,SAAgB,2BAA2B,WAA6C;CACtF,IAAI,UAAU,aAAa,MACzB,MAAM,IAAI,gBACR,sCAAsC,UAAU,QAAQ,0BAC1D;CAEF,MAAM,WAA6B;EACjC,IAAI,UAAU;EACd,SAAS,UAAU;EACnB,YAAY,UAAU;EACtB,SAAS;GACP,kBAAkB,UAAU;GAC5B,GAAI,UAAU,UAAU,OAAO,CAAC,IAAI,EAAE,kBAAkB,UAAU,MAAM;EAC1E;CACF;CACA,yBAAyB,QAAQ;CACjC,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metrics-DOMpkoeb.js","names":[],"sources":["../src/metrics.ts"],"sourcesContent":["interface TokenPrice {\n input: number\n output: number\n}\n\n/** Per-1K token pricing for exact model ids. */\nexport const MODEL_PRICING: Record<string, TokenPrice> = {\n 'gpt-4o': { input: 0.0025, output: 0.01 },\n 'gpt-4o-mini': { input: 0.00015, output: 0.0006 },\n 'gpt-4-turbo': { input: 0.01, output: 0.03 },\n 'claude-sonnet-4-20250514': { input: 0.003, output: 0.015 },\n 'claude-opus-4-20250514': { input: 0.015, output: 0.075 },\n 'claude-3-haiku-20240307': { input: 0.00025, output: 0.00125 },\n // Router response-header rates observed for the exact served model on\n // 2026-08-15. Keep this exact row ahead of the deliberately coarse family\n // fallback so glm-5.3 campaign costs are not understated by ~2.5x.\n 'glm-5.3': { input: 0.00168, output: 0.00528 },\n}\n\n/** Family-level pricing fallbacks (per-1K), matched against a normalized id\n * after exact lookup misses. Ordered — first match wins. Covers the model\n * ids actually used through the Tangle router + cli-bridge harnesses\n * (`claude-code/sonnet`, `opencode/zai-coding-plan/glm-5.1`,\n * `kimi-code/kimi-k2.6`, `deepseek-v4-pro`, `anthropic/claude-sonnet-4-6`, …),\n * none of which appear in the exact table above — without this they priced\n * to a silent $0, blanking every cost/Pareto axis downstream. */\nconst FAMILY_PRICING: Array<[RegExp, TokenPrice]> = [\n // OpenRouter stealth previews (`stealth/union-alpha`, …) bill $0 during\n // their preview window. A real zero row lets the budget ledger admit them;\n // an unpriced id is refused before the first call.\n [/^stealth\\//, { input: 0, output: 0 }],\n [/claude.*opus/, { input: 0.015, output: 0.075 }],\n [/claude.*haiku/, { input: 0.0008, output: 0.004 }],\n [/claude.*sonnet|claude-code|claude-sonnet/, { input: 0.003, output: 0.015 }],\n [/gpt-4o-mini/, { input: 0.00015, output: 0.0006 }],\n [/gpt-5|gpt-4\\.1|o[134]\\b/, { input: 0.00125, output: 0.01 }],\n [/gpt-4o|gpt-4/, { input: 0.0025, output: 0.01 }],\n [/deepseek/, { input: 0.0003, output: 0.0011 }],\n [/glm|zhipu|zai/, { input: 0.0006, output: 0.0022 }],\n [/kimi|moonshot/, { input: 0.0006, output: 0.0025 }],\n [/qwen/, { input: 0.0004, output: 0.0012 }],\n [/gemini.*flash/, { input: 0.0001, output: 0.0004 }],\n [/gemini/, { input: 0.00125, output: 0.005 }],\n [/llama/, { input: 0.0002, output: 0.0006 }],\n]\n\n/** Normalize a model id for pricing: drop a `@snapshot` suffix, lowercase,\n * and return both the complete harness/provider-prefixed id and its final\n * served-model segment (`opencode/zai-coding-plan/glm-5.3` → full id plus\n * `glm-5.3`). Exact rows are checked against both before family fallback. */\nfunction normalizedModelIds(model: string): string[] {\n const id = (model.split('@')[0] ?? model).trim().toLowerCase()\n const finalSegment = id.slice(id.lastIndexOf('/') + 1)\n return finalSegment === id ? [id] : [id, finalSegment]\n}\n\n/** Resolve pricing for a model id: exact table, then family fallback.\n * Returns null when the id matches nothing (caller decides — never a\n * silent-zero masquerading as a real $0 cost). */\nexport function resolveModelPricing(model: string): TokenPrice | null {\n if (MODEL_PRICING[model]) return MODEL_PRICING[model]\n const ids = normalizedModelIds(model)\n for (const id of ids) {\n if (MODEL_PRICING[id]) return MODEL_PRICING[id]\n }\n for (const [pattern, price] of FAMILY_PRICING) {\n if (ids.some((id) => pattern.test(id))) return price\n }\n return null\n}\n\n/** True when `model` has known pricing (exact or family). Lets cost-aware\n * callers distinguish a real $0 from an unpriced model. */\nexport function isModelPriced(model: string): boolean {\n return resolveModelPricing(model) !== null\n}\n\nconst warnedUnpricedModels = new Set<string>()\n\n/** Estimate token count from string length (chars / 4 approximation) */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/** Calculate cost in USD from token counts and model. Unknown models warn\n * once (not a silent zero) and return 0 so callers that ignore pricing keep\n * working; cost-sensitive callers should gate on {@link isModelPriced}. */\nexport function estimateCost(inputTokens: number, outputTokens: number, model: string): number {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n if (!warnedUnpricedModels.has(model)) {\n warnedUnpricedModels.add(model)\n console.warn(\n `estimateCost: no pricing for model \"${model}\" — returning 0; add it to ` +\n 'MODEL_PRICING/FAMILY_PRICING (cost/Pareto axes will be blank until then)',\n )\n }\n return 0\n }\n return (inputTokens / 1000) * pricing.input + (outputTokens / 1000) * pricing.output\n}\n\n/**\n * TokenCounter — accumulates token usage and cost across turns.\n */\nexport class TokenCounter {\n private totalInput = 0\n private totalOutput = 0\n private totalCost = 0\n private model: string\n\n constructor(model = 'gpt-4o') {\n this.model = model\n }\n\n /** Record tokens for a turn, returns per-turn cost */\n record(inputTokens: number, outputTokens: number): number {\n this.totalInput += inputTokens\n this.totalOutput += outputTokens\n const cost = estimateCost(inputTokens, outputTokens, this.model)\n this.totalCost += cost\n return cost\n }\n\n /** Estimate and record from raw text */\n recordFromText(\n inputText: string,\n outputText: string,\n ): { inputTokens: number; outputTokens: number; cost: number } {\n const inputTokens = estimateTokens(inputText)\n const outputTokens = estimateTokens(outputText)\n const cost = this.record(inputTokens, outputTokens)\n return { inputTokens, outputTokens, cost }\n }\n\n getTotalInput(): number {\n return this.totalInput\n }\n getTotalOutput(): number {\n return this.totalOutput\n }\n getTotalCost(): number {\n return this.totalCost\n }\n}\n"],"mappings":";;AAMA,MAAa,gBAA4C;CACvD,UAAU;EAAE,OAAO;EAAQ,QAAQ;CAAK;CACxC,eAAe;EAAE,OAAO;EAAS,QAAQ;CAAO;CAChD,eAAe;EAAE,OAAO;EAAM,QAAQ;CAAK;CAC3C,4BAA4B;EAAE,OAAO;EAAO,QAAQ;CAAM;CAC1D,0BAA0B;EAAE,OAAO;EAAO,QAAQ;CAAM;CACxD,2BAA2B;EAAE,OAAO;EAAS,QAAQ;CAAQ;CAI7D,WAAW;EAAE,OAAO;EAAS,QAAQ;CAAQ;AAC/C;;;;;;;;AASA,MAAM,iBAA8C;CAIlD,CAAC,cAAc;EAAE,OAAO;EAAG,QAAQ;CAAE,CAAC;CACtC,CAAC,gBAAgB;EAAE,OAAO;EAAO,QAAQ;CAAM,CAAC;CAChD,CAAC,iBAAiB;EAAE,OAAO;EAAQ,QAAQ;CAAM,CAAC;CAClD,CAAC,4CAA4C;EAAE,OAAO;EAAO,QAAQ;CAAM,CAAC;CAC5E,CAAC,eAAe;EAAE,OAAO;EAAS,Q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