@tangle-network/agent-eval 0.173.3 → 0.175.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +1 -1
  3. package/dist/{proposal-findings-bko3GGy-.js → abort-signal-CtzAM_sJ.js} +11 -11
  4. package/dist/abort-signal-CtzAM_sJ.js.map +1 -0
  5. package/dist/adapters/http.d.ts +2 -2
  6. package/dist/agent-profile-_xPxqVJt.d.ts +488 -0
  7. package/dist/agent-profile-_xPxqVJt.d.ts.map +1 -0
  8. package/dist/analyst/index.d.ts +7 -9
  9. package/dist/analyst/index.d.ts.map +1 -1
  10. package/dist/analyst/index.js +8 -8
  11. package/dist/{benchmark-C4wk_Sjr.js → benchmark-DQKzykkO.js} +2 -2
  12. package/dist/{benchmark-C4wk_Sjr.js.map → benchmark-DQKzykkO.js.map} +1 -1
  13. package/dist/{benchmark-command-BY9oscke.js → benchmark-command-D_5xG9LG.js} +13 -13
  14. package/dist/{benchmark-command-BY9oscke.js.map → benchmark-command-D_5xG9LG.js.map} +1 -1
  15. package/dist/benchmarks/index.d.ts +3 -4
  16. package/dist/benchmarks/index.d.ts.map +1 -1
  17. package/dist/benchmarks/index.js +3 -3
  18. package/dist/campaign/index.d.ts +5 -9
  19. package/dist/campaign/index.js +7 -7
  20. package/dist/{campaign-B3kPMU8S.js → campaign-BzMSCejE.js} +8 -8
  21. package/dist/{campaign-B3kPMU8S.js.map → campaign-BzMSCejE.js.map} +1 -1
  22. package/dist/{opencode-sqlite-eK6HW6dr.js → claude-jsonl-CxZZrDJ3.js} +9 -149
  23. package/dist/claude-jsonl-CxZZrDJ3.js.map +1 -0
  24. package/dist/cli.js +9 -2
  25. package/dist/cli.js.map +1 -1
  26. package/dist/{client-DlqdbM7n.d.ts → client-vyYQg3bm.d.ts} +2 -2
  27. package/dist/{client-DlqdbM7n.d.ts.map → client-vyYQg3bm.d.ts.map} +1 -1
  28. package/dist/contract/index.d.ts +9 -10
  29. package/dist/contract/index.js +8 -8
  30. package/dist/{default-registry-B0bKikCb.js → default-registry-DBqVI4pq.js} +5 -5
  31. package/dist/{default-registry-B0bKikCb.js.map → default-registry-DBqVI4pq.js.map} +1 -1
  32. package/dist/{default-registry-BKwc8bN5.d.ts → default-registry-FfNzaUHV.d.ts} +3 -3
  33. package/dist/{default-registry-BKwc8bN5.d.ts.map → default-registry-FfNzaUHV.d.ts.map} +1 -1
  34. package/dist/{define-agent-eval-CY6qdlGV.d.ts → define-agent-eval-V1jQyCDR.d.ts} +102 -11
  35. package/dist/define-agent-eval-V1jQyCDR.d.ts.map +1 -0
  36. package/dist/{define-agent-eval-8h3lXXee.js → define-agent-eval-ox5McL6e.js} +331 -144
  37. package/dist/define-agent-eval-ox5McL6e.js.map +1 -0
  38. package/dist/{dspy-rlm-engine-CF0t2ITD.js → dspy-rlm-engine-Caz2pl4L.js} +3 -3
  39. package/dist/{dspy-rlm-engine-CF0t2ITD.js.map → dspy-rlm-engine-Caz2pl4L.js.map} +1 -1
  40. package/dist/{engine-DhFir3Ys.d.ts → engine-CvW_I72-.d.ts} +2 -2
  41. package/dist/{engine-DhFir3Ys.d.ts.map → engine-CvW_I72-.d.ts.map} +1 -1
  42. package/dist/experiment/index.d.ts +1 -4
  43. package/dist/experiment/index.d.ts.map +1 -1
  44. package/dist/{external-optimizer-process-BwITA9Jp.js → external-optimizer-process-CxnFL1hd.js} +2 -2
  45. package/dist/{external-optimizer-process-BwITA9Jp.js.map → external-optimizer-process-CxnFL1hd.js.map} +1 -1
  46. package/dist/{external-optimizer-subprocess-wBWeoG6A.js → external-optimizer-subprocess-CQi27uEI.js} +2 -2
  47. package/dist/{external-optimizer-subprocess-wBWeoG6A.js.map → external-optimizer-subprocess-CQi27uEI.js.map} +1 -1
  48. package/dist/fuzz.js +1 -1
  49. package/dist/fuzz.js.map +1 -1
  50. package/dist/hosted/index.d.ts +1 -1
  51. package/dist/{index-D0Db5X-4.d.ts → index-BAAiSF3_.d.ts} +5 -5
  52. package/dist/{index-D0Db5X-4.d.ts.map → index-BAAiSF3_.d.ts.map} +1 -1
  53. package/dist/{index-BQqOjerE.d.ts → index-BTrx5s8m.d.ts} +8 -9
  54. package/dist/index-BTrx5s8m.d.ts.map +1 -0
  55. package/dist/index-DKXuBPXf.d.ts +3840 -0
  56. package/dist/index-DKXuBPXf.d.ts.map +1 -0
  57. package/dist/index.d.ts +11 -13
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +11 -11
  60. package/dist/{integrity-BWywb34E.js → integrity-DsHWCebQ.js} +11 -435
  61. package/dist/integrity-DsHWCebQ.js.map +1 -0
  62. package/dist/{kind-factory-gP6lDySe.js → kind-factory-BLvL-E44.js} +2 -2
  63. package/dist/{kind-factory-gP6lDySe.js.map → kind-factory-BLvL-E44.js.map} +1 -1
  64. package/dist/{llm-judge-BfqMFo4h.js → llm-judge-DmNaBrXB.js} +2541 -2435
  65. package/dist/llm-judge-DmNaBrXB.js.map +1 -0
  66. package/dist/{matrix-DGu8KhSs.d.ts → matrix-CJtXz1ky.d.ts} +2 -2
  67. package/dist/{matrix-DGu8KhSs.d.ts.map → matrix-CJtXz1ky.d.ts.map} +1 -1
  68. package/dist/multishot/golden/index.d.ts +1 -1
  69. package/dist/multishot/index.d.ts +2 -2
  70. package/dist/openapi.json +1 -1
  71. package/dist/opencode-sqlite-CNw3vubS.js +145 -0
  72. package/dist/opencode-sqlite-CNw3vubS.js.map +1 -0
  73. package/dist/{produced-state-D91uDvQw.js → produced-state-B8mw6zj9.js} +2 -2
  74. package/dist/{produced-state-D91uDvQw.js.map → produced-state-B8mw6zj9.js.map} +1 -1
  75. package/dist/report-command-DKlXfU5r.js +1528 -0
  76. package/dist/report-command-DKlXfU5r.js.map +1 -0
  77. package/dist/rl.d.ts +1 -1
  78. package/dist/rl.d.ts.map +1 -1
  79. package/dist/rl.js.map +1 -1
  80. package/dist/rollout/index.js +3 -2
  81. package/dist/{rollout-C-znbbYg.js → rollout-CGlDq1GI.js} +3 -2
  82. package/dist/{rollout-C-znbbYg.js.map → rollout-CGlDq1GI.js.map} +1 -1
  83. package/dist/{semantic-concept-judge-Dok7_35a.js → semantic-concept-judge-E3s_fEjB.js} +3 -3
  84. package/dist/{semantic-concept-judge-Dok7_35a.js.map → semantic-concept-judge-E3s_fEjB.js.map} +1 -1
  85. package/dist/{skillopt-optimization-method-DDw3v3gA.js → skillopt-optimization-method-f7399oGb.js} +5 -5
  86. package/dist/{skillopt-optimization-method-DDw3v3gA.js.map → skillopt-optimization-method-f7399oGb.js.map} +1 -1
  87. package/dist/statistical-heldout-Cqb73yE9.d.ts +1127 -0
  88. package/dist/statistical-heldout-Cqb73yE9.d.ts.map +1 -0
  89. package/dist/{store-otlp-Dow0pk_5.js → store-otlp-DV_H2HDu.js} +2 -2
  90. package/dist/{store-otlp-Dow0pk_5.js.map → store-otlp-DV_H2HDu.js.map} +1 -1
  91. package/dist/{store-tool-spans-CCZNsihA.d.ts → store-tool-spans-4o55ABER.d.ts} +3 -3
  92. package/dist/{store-tool-spans-CCZNsihA.d.ts.map → store-tool-spans-4o55ABER.d.ts.map} +1 -1
  93. package/dist/{store-tool-spans-CeNj_m2L.js → store-tool-spans-B9tjys_h.js} +3 -3
  94. package/dist/{store-tool-spans-CeNj_m2L.js.map → store-tool-spans-B9tjys_h.js.map} +1 -1
  95. package/dist/supervisor-run/index.d.ts +71 -6
  96. package/dist/supervisor-run/index.d.ts.map +1 -1
  97. package/dist/supervisor-run/index.js +6 -1357
  98. package/dist/supervisor-run/index.js.map +1 -1
  99. package/dist/{task-failure-attributes-CZjZeBsY.js → task-failure-attributes-CUy9mkIY.js} +2 -2
  100. package/dist/{task-failure-attributes-CZjZeBsY.js.map → task-failure-attributes-CUy9mkIY.js.map} +1 -1
  101. package/dist/terminal-record-Ce9_UjRz.js +539 -0
  102. package/dist/terminal-record-Ce9_UjRz.js.map +1 -0
  103. package/dist/{tool-groups-Cp4Xdzrp.d.ts → tool-groups-DAe1t6zb.d.ts} +2 -2
  104. package/dist/tool-groups-DAe1t6zb.d.ts.map +1 -0
  105. package/dist/trace-repair/index.d.ts +1 -1
  106. package/dist/traces.d.ts +2 -2
  107. package/dist/traces.js +4 -4
  108. package/dist/{types-Ba5UQyVD.d.ts → types-BJz2CPTM.d.ts} +2 -2
  109. package/dist/{types-Ba5UQyVD.d.ts.map → types-BJz2CPTM.d.ts.map} +1 -1
  110. package/dist/{types-CiWITkGo.js → types-DQ0e2E7y.js} +2 -2
  111. package/dist/types-DQ0e2E7y.js.map +1 -0
  112. package/dist/{types-BDV4PiMR.d.ts → types-Dd1ejaeI.d.ts} +2 -2
  113. package/dist/{types-BDV4PiMR.d.ts.map → types-Dd1ejaeI.d.ts.map} +1 -1
  114. package/dist/{types-CoPUTiXb.d.ts → types-vUdAx2Cj.d.ts} +65 -3
  115. package/dist/types-vUdAx2Cj.d.ts.map +1 -0
  116. package/docs/campaign-proposers.md +42 -0
  117. package/package.json +1 -1
  118. package/dist/agent-profile-B9_GGsG8.d.ts +0 -84
  119. package/dist/agent-profile-B9_GGsG8.d.ts.map +0 -1
  120. package/dist/backend-integrity-CeuTgqsd.d.ts +0 -280
  121. package/dist/backend-integrity-CeuTgqsd.d.ts.map +0 -1
  122. package/dist/benchmark-BjLGkfnN.d.ts +0 -236
  123. package/dist/benchmark-BjLGkfnN.d.ts.map +0 -1
  124. package/dist/define-agent-eval-8h3lXXee.js.map +0 -1
  125. package/dist/define-agent-eval-CY6qdlGV.d.ts.map +0 -1
  126. package/dist/external-optimizer-contracts-CQCpyrIL.d.ts +0 -172
  127. package/dist/external-optimizer-contracts-CQCpyrIL.d.ts.map +0 -1
  128. package/dist/heldout-gate-Df5hsqmm.d.ts +0 -453
  129. package/dist/heldout-gate-Df5hsqmm.d.ts.map +0 -1
  130. package/dist/index-BQqOjerE.d.ts.map +0 -1
  131. package/dist/index-CFDffsKz.d.ts +0 -1135
  132. package/dist/index-CFDffsKz.d.ts.map +0 -1
  133. package/dist/integrity-BWywb34E.js.map +0 -1
  134. package/dist/llm-judge-BfqMFo4h.js.map +0 -1
  135. package/dist/opencode-sqlite-eK6HW6dr.js.map +0 -1
  136. package/dist/power-preflight-Ptse_Kq7.d.ts +0 -117
  137. package/dist/power-preflight-Ptse_Kq7.d.ts.map +0 -1
  138. package/dist/pre-registration-BoI4ucR3.d.ts +0 -592
  139. package/dist/pre-registration-BoI4ucR3.d.ts.map +0 -1
  140. package/dist/promotion-policy-CvMda3kU.d.ts +0 -134
  141. package/dist/promotion-policy-CvMda3kU.d.ts.map +0 -1
  142. package/dist/proposal-findings-bko3GGy-.js.map +0 -1
  143. package/dist/provenance-CRY67X50.d.ts +0 -1995
  144. package/dist/provenance-CRY67X50.d.ts.map +0 -1
  145. package/dist/statistical-heldout-DTyB_6-1.d.ts +0 -295
  146. package/dist/statistical-heldout-DTyB_6-1.d.ts.map +0 -1
  147. package/dist/tool-groups-Cp4Xdzrp.d.ts.map +0 -1
  148. package/dist/types-CiWITkGo.js.map +0 -1
  149. package/dist/types-CoPUTiXb.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"store-tool-spans-CeNj_m2L.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","export 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}\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 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 })),\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.`\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,IAAI,OAAO;AAEpC,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,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,sBACd,OACA,MACA,KACA,OAA4B,CAAC,GACJ;CACzB,MAAM,WAAW,IAAI,YAAY,oBAAoB,IAAI,OAAO;CAChE,MAAM,WAAW,KAAK,YAAY;CA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I;GACF,OAAO,KAAK,UAAU,IAAI;EAC5B,SAAS,OAAO;GACd,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,YAAY,KAAK,MAAM,6BAC3E,EAAE,MAAM,CACV;EACF;CACF,CAAC;CAED,OAAO,2BAA2B,OAAO,KAAK,GAAG,MAAM,KAAK,IAAI,EAAE,KAAK,MAAM,GAAG,OAAO;AACzF;AAEA,SAAS,uBAAuB,MAAgB,OAAqB;CACnE,IAAI,KAAK,SAAS,QAChB,MAAM,IAAI,sBACR,gDAAgD,MAAM,aAAa,OAAO,KAAK,IAAI,EAAE,cACvF;CAEF,IAAI,CAAC,KAAK,SAAS,CAAC,KAAK,UAAU,CAAC,KAAK,QAAQ,CAAC,KAAK,UACrD,MAAM,IAAI,sBACR,gDAAgD,MAAM,6CACxD;CAEF,IAAI,CAAC,OAAO,SAAS,KAAK,SAAS,GACjC,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;CAEF,IAAI,KAAK,YAAY,KAAA,KAAa,CAAC,OAAO,SAAS,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"}
1
+ {"version":3,"file":"store-tool-spans-B9tjys_h.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","export 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}\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 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 })),\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.`\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,IAAI,OAAO;AAEpC,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,CA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,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"}
@@ -1,5 +1,5 @@
1
1
  import { y as RolloutSplit } from "../schema-BzWDXhOR.js";
2
- import { A as unavailable, C as SupervisorRunTreeGap, D as WorkerLogSource, E as WallDistribution, O as isUnavailable, S as SupervisorRunTree, T as Unavailable, _ as SupervisorRunNodeRole, a as OrchestrationMetrics, b as SupervisorRunRollup, c as PerWorkerRow, d as SUPERVISOR_RUN_ROLLUP_SCHEMA, f as SUPERVISOR_RUN_SCHEMA, g as SteerBreakdown, h as SpendMeasurements, i as NO_SOURCE_LIMITS, k as showMeasured, l as RoleSpend, m as SpendMeasurement, n as EconomicsMetrics, o as OutcomeMetrics, p as SourceLimits, r as Measured, s as PatchStats, t as DecisionMetrics, u as RollupCellRow, v as SupervisorRunReader, w as SupervisorRunTreeGapCode, x as SupervisorRunSources, y as SupervisorRunReport } from "../types-CoPUTiXb.js";
2
+ import { A as isUnavailable, C as SupervisorRunTreeGap, D as Unavailable, E as TerminalFailure, M as unavailable, O as WallDistribution, S as SupervisorRunTree, T as SupervisorStatusSource, _ as SupervisorRunNodeRole, a as OrchestrationMetrics, b as SupervisorRunRollup, c as PerWorkerRow, d as SUPERVISOR_RUN_ROLLUP_SCHEMA, f as SUPERVISOR_RUN_SCHEMA, g as SteerBreakdown, h as SpendMeasurements, i as NO_SOURCE_LIMITS, j as showMeasured, k as WorkerLogSource, l as RoleSpend, m as SpendMeasurement, n as EconomicsMetrics, o as OutcomeMetrics, p as SourceLimits, r as Measured, s as PatchStats, t as DecisionMetrics, u as RollupCellRow, v as SupervisorRunReader, w as SupervisorRunTreeGapCode, x as SupervisorRunSources, y as SupervisorRunReport } from "../types-vUdAx2Cj.js";
3
3
  //#region src/supervisor-run/source-facts.d.ts
4
4
  interface Tokens {
5
5
  input: number;
@@ -366,6 +366,29 @@ declare function renderSupervisorRunHeadline(r: SupervisorRunReport): string;
366
366
  declare function renderSupervisorRunMarkdown(r: SupervisorRunReport): string;
367
367
  declare function renderSupervisorRollupMarkdown(rollup: SupervisorRunRollup, title?: string): string;
368
368
  //#endregion
369
+ //#region src/supervisor-run/report-command.d.ts
370
+ /**
371
+ * `agent-eval supervisor-run report <runDir>` takes one run directory and
372
+ * prints the report the module already renders. The command reads through
373
+ * `analyzeSupervisorRun`, so a Runtime run dir and a loops run dir take the
374
+ * same path and the status comes from the record `terminal-record.ts` names.
375
+ *
376
+ * Exit codes follow the other self-parsing subcommands: 2 for a usage error,
377
+ * 1 when the directory cannot be read (missing, not a directory, or a corrupt
378
+ * journal or terminal record), 0 after the report was written to stdout.
379
+ */
380
+ type SupervisorRunReportFormat = 'headline' | 'markdown' | 'json';
381
+ /** Output sinks, injectable so tests read the exact bytes a terminal would. */
382
+ interface SupervisorRunCommandIo {
383
+ readonly stdout: (text: string) => void;
384
+ readonly stderr: (text: string) => void;
385
+ }
386
+ /**
387
+ * CLI driver for `agent-eval supervisor-run`. `argv` is everything after the
388
+ * command name, so `['report', runDir, ...flags]`. Returns the process exit code.
389
+ */
390
+ declare function runSupervisorRunCommand(argv: readonly string[], io?: SupervisorRunCommandIo): Promise<number>;
391
+ //#endregion
369
392
  //#region src/supervisor-run/rollout-nodes.d.ts
370
393
  interface SupervisorRolloutOptions {
371
394
  /** Benchmark/suite id for `task.suite`. Defaults to `'supervisor-run'`. */
@@ -415,9 +438,12 @@ interface RuntimeReaderOptions {
415
438
  * A run dir without `spawn-journal.jsonl` returns the same absent-shaped
416
439
  * sources `readLoopsSupervisorRun` returns for a missing store: `journal` and
417
440
  * `workers` null, each with its reason, so every dependent metric reads
418
- * `unavailable` — never 0 and never a throw. Pass `strict: true` to throw on
419
- * the missing journal instead. A journal that exists but cannot be parsed
420
- * always throws: a corrupt journal is a defect, not an absence.
441
+ * `unavailable` — never 0 and never a throw. Its `result.json` and
442
+ * `failure.json` are still read, so a run that died before its first spawn
443
+ * reports the failure Runtime recorded. Pass `strict: true` to throw on the
444
+ * missing journal instead. A journal, result, or failure document that exists
445
+ * but cannot be parsed always throws: a corrupt record is a defect, not an
446
+ * absence.
421
447
  *
422
448
  * The reader translates storage envelopes only. It does not assign research
423
449
  * roles, interpret artifacts, or turn process completion into a quality
@@ -426,8 +452,47 @@ interface RuntimeReaderOptions {
426
452
  declare function readRuntimeSupervisorRun(runDir: string, opts?: RuntimeReaderOptions): Promise<SupervisorRunSources>;
427
453
  /** The agent-runtime file-backed layout as a `SupervisorRunReader`. */
428
454
  declare function runtimeSupervisorRunReader(runDir: string, opts?: RuntimeReaderOptions): SupervisorRunReader;
429
- /** True when a directory contains Runtime's canonical file-backed journal. */
455
+ /**
456
+ * True when a directory holds any file only Runtime's durable layer writes:
457
+ * the spawn journal, the observer journal, or the failure record. A run that
458
+ * threw before its first spawn has no journal yet and is still a Runtime run.
459
+ */
430
460
  declare function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean>;
431
461
  //#endregion
432
- export { type ClaudeCodeReaderOptions, type CloseRow, type DecisionMetrics, type EconomicsMetrics, type LoopsReaderOptions, type Measured, NO_SOURCE_LIMITS, type OrchestrationMetrics, type OutcomeMetrics, type PatchStats, type PerWorkerRow, type RoleSpend, type RollupCellRow, type RuntimeReaderOptions, SUPERVISOR_RUN_INTEGRITY_SCHEMA, SUPERVISOR_RUN_ROLLUP_SCHEMA, SUPERVISOR_RUN_SCHEMA, type SourceLimits, type SpawnRow, type SpendMeasurement, type SpendMeasurements, type SteerAcknowledgementFact, type SteerBreakdown, type SteerRequestFact, type SupervisorJournalDialect, type SupervisorRolloutOptions, type SupervisorRunIntegrityEvidence, type SupervisorRunIntegrityIssue, type SupervisorRunIntegrityIssueCode, type SupervisorRunIntegrityOptions, type SupervisorRunIntegrityReport, type SupervisorRunIntegritySeverity, type SupervisorRunNodeRole, type SupervisorRunReader, type SupervisorRunReport, type SupervisorRunRollup, type SupervisorRunSourceOnlyCheckCode, type SupervisorRunSources, type SupervisorRunTree, type SupervisorRunTreeGap, type SupervisorRunTreeGapCode, type SupervisorTreeFacts, type Unavailable, type WallDistribution, type WorkerLogFacts, type WorkerLogSource, type WriteSupervisorRunOptions, analyzeSupervisorRun, analyzeSupervisorRunIntegrity, analyzeSupervisorRunSources, claudeCodeSupervisorRunReader, findSupervisorRunDirIn, findSupervisorRunDirs, isRuntimeSupervisorRunDir, isUnavailable, loopsSupervisorRunReader, parsePatch, parseSupervisorTree, readClaudeCodeSupervisorRun, readLoopsSupervisorRun, readRuntimeSupervisorRun, renderSupervisorRollupMarkdown, renderSupervisorRunHeadline, renderSupervisorRunMarkdown, reportSupervisorRound, rollupSupervisorRuns, runtimeSupervisorRunReader, showMeasured, supervisorRunRolloutLines, unavailable, writeSupervisorRunReport, writeSupervisorRunReportSafe };
462
+ //#region src/supervisor-run/terminal-record.d.ts
463
+ /** The reason every terminal field reads `unavailable` when no store wrote one. */
464
+ declare const NO_TERMINAL_RECORD = "no terminal record: Runtime result.json kind, Runtime failure.json, or legacy state.json / result.json status";
465
+ /** The status reported for a run whose directory holds Runtime's failure record and no result. */
466
+ declare const RUNTIME_FAILED_STATUS = "failed";
467
+ interface TerminalRecordInput {
468
+ /** Legacy loops `state.json`, parsed; null when absent. */
469
+ readonly state: Record<string, unknown> | null;
470
+ /** `result.json`, parsed; Runtime's `SupervisedResult` or the legacy loops result. */
471
+ readonly result: Record<string, unknown> | null;
472
+ /**
473
+ * Runtime's `failure.json`, parsed. `null` when the store was read and holds
474
+ * none; `undefined` when the store has no such document type.
475
+ */
476
+ readonly failure: Record<string, unknown> | null | undefined;
477
+ }
478
+ interface TerminalRecord {
479
+ readonly supStatus: Measured<string>;
480
+ readonly supStatusSource: Measured<SupervisorStatusSource>;
481
+ /**
482
+ * Runtime's `reason` on a `no-winner` result. `null` when the record carries
483
+ * none (a winner, a failure record, or a legacy document).
484
+ */
485
+ readonly supReason: Measured<string | null>;
486
+ /** The recorded error. `null` when the run recorded a result and no error. */
487
+ readonly failure: Measured<TerminalFailure | null>;
488
+ /**
489
+ * True when the run recorded a delivered result (Runtime `winner`, legacy
490
+ * `completed`); false on every other recorded terminal state; null when no
491
+ * terminal record exists.
492
+ */
493
+ readonly completed: boolean | null;
494
+ }
495
+ declare function readTerminalRecord(input: TerminalRecordInput): TerminalRecord;
496
+ //#endregion
497
+ export { type ClaudeCodeReaderOptions, type CloseRow, type DecisionMetrics, type EconomicsMetrics, type LoopsReaderOptions, type Measured, NO_SOURCE_LIMITS, NO_TERMINAL_RECORD, type OrchestrationMetrics, type OutcomeMetrics, type PatchStats, type PerWorkerRow, RUNTIME_FAILED_STATUS, type RoleSpend, type RollupCellRow, type RuntimeReaderOptions, SUPERVISOR_RUN_INTEGRITY_SCHEMA, SUPERVISOR_RUN_ROLLUP_SCHEMA, SUPERVISOR_RUN_SCHEMA, type SourceLimits, type SpawnRow, type SpendMeasurement, type SpendMeasurements, type SteerAcknowledgementFact, type SteerBreakdown, type SteerRequestFact, type SupervisorJournalDialect, type SupervisorRolloutOptions, type SupervisorRunCommandIo, type SupervisorRunIntegrityEvidence, type SupervisorRunIntegrityIssue, type SupervisorRunIntegrityIssueCode, type SupervisorRunIntegrityOptions, type SupervisorRunIntegrityReport, type SupervisorRunIntegritySeverity, type SupervisorRunNodeRole, type SupervisorRunReader, type SupervisorRunReport, type SupervisorRunReportFormat, type SupervisorRunRollup, type SupervisorRunSourceOnlyCheckCode, type SupervisorRunSources, type SupervisorRunTree, type SupervisorRunTreeGap, type SupervisorRunTreeGapCode, type SupervisorStatusSource, type SupervisorTreeFacts, type TerminalFailure, type TerminalRecord, type TerminalRecordInput, type Unavailable, type WallDistribution, type WorkerLogFacts, type WorkerLogSource, type WriteSupervisorRunOptions, analyzeSupervisorRun, analyzeSupervisorRunIntegrity, analyzeSupervisorRunSources, claudeCodeSupervisorRunReader, findSupervisorRunDirIn, findSupervisorRunDirs, isRuntimeSupervisorRunDir, isUnavailable, loopsSupervisorRunReader, parsePatch, parseSupervisorTree, readClaudeCodeSupervisorRun, readLoopsSupervisorRun, readRuntimeSupervisorRun, readTerminalRecord, renderSupervisorRollupMarkdown, renderSupervisorRunHeadline, renderSupervisorRunMarkdown, reportSupervisorRound, rollupSupervisorRuns, runSupervisorRunCommand, runtimeSupervisorRunReader, showMeasured, supervisorRunRolloutLines, unavailable, writeSupervisorRunReport, writeSupervisorRunReportSafe };
433
498
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/supervisor-run/source-facts.ts","../../src/supervisor-run/analyze.ts","../../src/supervisor-run/claude-code-reader.ts","../../src/supervisor-run/integrity-types.ts","../../src/supervisor-run/integrity.ts","../../src/supervisor-run/loops-reader.ts","../../src/supervisor-run/render.ts","../../src/supervisor-run/rollout-nodes.ts","../../src/supervisor-run/runtime-reader.ts"],"mappings":";;;UAwBU;EACR;EACA;EACA;EACA;;EAEA;;;;;;EAMA;;UAGe;EACf,QAAQ;;;;;;EAMR;EACA;;;;;;EAMA;;UAmFe;;EAEf;EACA;EACA;EACA;;EAEA,MAAM;;EAEN;;EAEA;EACA;;EAEA;EACA;;UAGe;EACf;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA,OAAO;;EAEP;;UAGe;;EAEf;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;;EAEA;EACA;EACA;EACA;EACA,eAAe;EACf,uBAAuB;;UAGR;;EAEf;EACA;;UAGe;;EAEf;;EAEA;EACA;;;;;;UAOe;WACN;WACA,iBAAiB;WACjB,iBAAiB;WACjB,uBAA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A+BW,sBAAsB,eAAe;;;;;;;iBCzY3C,4BAA4B,GAAG;iBAiC/B,4BAA4B,GAAG;iBA+K/B,+BACd,QAAQ,qBACR;;;UC9Le;;WAEN;;WAEA,QAAQ;;WAER;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;WACA;WACA;WACA;WACA;;WAEA;;;;;;;iBAwBK,0BACd,KAAK,sBACL,OAAM,2BACL;;;UCiYc;;;;;;WAMN;;;;;;;;;;;;;;;;iBAsDW,yBACpB,gBACA,OAAM,uBACL,QAAQ;;iBAkEK,2BACd,gBACA,OAAM,uBACL;;iBAKmB,0BAA0B,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/supervisor-run/source-facts.ts","../../src/supervisor-run/analyze.ts","../../src/supervisor-run/claude-code-reader.ts","../../src/supervisor-run/integrity-types.ts","../../src/supervisor-run/integrity.ts","../../src/supervisor-run/loops-reader.ts","../../src/supervisor-run/render.ts","../../src/supervisor-run/report-command.ts","../../src/supervisor-run/rollout-nodes.ts","../../src/supervisor-run/runtime-reader.ts","../../src/supervisor-run/terminal-record.ts"],"mappings":";;;UAwBU;EACR;EACA;EACA;EACA;;EAEA;;;;;;EAMA;;UAGe;EACf,QAAQ;;;;;;EAMR;EACA;;;;;;EAMA;;UAmFe;;EAEf;EACA;EACA;EACA;;EAEA,MAAM;;EAEN;;EAEA;EACA;;EAEA;EACA;;UAGe;EACf;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA,OAAO;;EAEP;;UAGe;;EAEf;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;;EAEA;EACA;EACA;EACA;EACA,eAAe;EACf,uBAAuB;;UAGR;;EAEf;EACA;;UAGe;;EAEf;;EAEA;EACA;;;;;;UAOe;WACN;WACA,iBAAiB;WACjB,iBAAiB;WACjB,uBAAuB;WACvB,uBAAuB;WACvB;;;;;;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