@tangle-network/agent-eval 0.128.1 → 0.129.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 (137) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/README.md +18 -0
  3. package/dist/analyst/index.d.ts +107 -165
  4. package/dist/analyst/index.js +5 -9
  5. package/dist/analyst/index.js.map +1 -1
  6. package/dist/belief-state/index.d.ts +2 -19
  7. package/dist/belief-state/index.js +30 -31
  8. package/dist/belief-state/index.js.map +1 -1
  9. package/dist/benchmarks/index.d.ts +5 -8
  10. package/dist/benchmarks/index.js +12 -11
  11. package/dist/builder-eval/index.js +1 -1
  12. package/dist/campaign/index.d.ts +30 -39
  13. package/dist/campaign/index.js +11 -10
  14. package/dist/{chunk-NKAGIDE2.js → chunk-2QU3YOPR.js} +15 -274
  15. package/dist/chunk-2QU3YOPR.js.map +1 -0
  16. package/dist/{chunk-EJGRPCO3.js → chunk-3OCR4R5I.js} +245 -134
  17. package/dist/chunk-3OCR4R5I.js.map +1 -0
  18. package/dist/{chunk-2JX3CFMB.js → chunk-56TAVBOK.js} +5 -2
  19. package/dist/chunk-56TAVBOK.js.map +1 -0
  20. package/dist/{chunk-DPUHNQLN.js → chunk-7FO3TNPI.js} +2 -2
  21. package/dist/{chunk-DJKY2TSY.js → chunk-BSO5JDQH.js} +27 -120
  22. package/dist/chunk-BSO5JDQH.js.map +1 -0
  23. package/dist/{chunk-EZJEIH2R.js → chunk-C6LXANRU.js} +11 -20
  24. package/dist/chunk-C6LXANRU.js.map +1 -0
  25. package/dist/{chunk-ZUUWPZCV.js → chunk-DODXQREJ.js} +4 -4
  26. package/dist/{chunk-2MKQIFS4.js → chunk-E7QXT7SX.js} +2 -2
  27. package/dist/{chunk-NYLOYM6N.js → chunk-EG66UGL4.js} +37 -28
  28. package/dist/chunk-EG66UGL4.js.map +1 -0
  29. package/dist/{chunk-P5W7RQKK.js → chunk-FXTVJPYD.js} +2 -2
  30. package/dist/{chunk-VZSRQ272.js → chunk-G7MGMCZD.js} +6 -2
  31. package/dist/chunk-G7MGMCZD.js.map +1 -0
  32. package/dist/{chunk-IHQDPH7D.js → chunk-H23X7XKK.js} +85 -75
  33. package/dist/chunk-H23X7XKK.js.map +1 -0
  34. package/dist/{chunk-VBQ3CRKH.js → chunk-HPWUNB47.js} +4 -6
  35. package/dist/chunk-HPWUNB47.js.map +1 -0
  36. package/dist/{chunk-XPRT64IE.js → chunk-IYCLP2N2.js} +3 -3
  37. package/dist/chunk-IYCLP2N2.js.map +1 -0
  38. package/dist/{chunk-XDWDC2MP.js → chunk-JQSF5DQT.js} +11 -5
  39. package/dist/chunk-JQSF5DQT.js.map +1 -0
  40. package/dist/{chunk-NACAGYSY.js → chunk-M4YBQKIJ.js} +11 -11
  41. package/dist/chunk-M4YBQKIJ.js.map +1 -0
  42. package/dist/{chunk-YJBNWCAA.js → chunk-NY44NC4A.js} +3 -3
  43. package/dist/chunk-OIUOT4QD.js +44 -0
  44. package/dist/chunk-OIUOT4QD.js.map +1 -0
  45. package/dist/chunk-OWN5NPMC.js +152 -0
  46. package/dist/chunk-OWN5NPMC.js.map +1 -0
  47. package/dist/chunk-PC5DOSM7.js +579 -0
  48. package/dist/chunk-PC5DOSM7.js.map +1 -0
  49. package/dist/{chunk-UB2LOJ6Q.js → chunk-QB6BDBP2.js} +23 -20
  50. package/dist/chunk-QB6BDBP2.js.map +1 -0
  51. package/dist/chunk-RXHCETDZ.js +536 -0
  52. package/dist/chunk-RXHCETDZ.js.map +1 -0
  53. package/dist/{chunk-PBE2LOSS.js → chunk-SFLLL76A.js} +7 -7
  54. package/dist/chunk-SFLLL76A.js.map +1 -0
  55. package/dist/{chunk-VGRCHJON.js → chunk-T6RLYGAD.js} +3 -8
  56. package/dist/chunk-T6RLYGAD.js.map +1 -0
  57. package/dist/{chunk-VLOATJQ2.js → chunk-TJVT4QFF.js} +21 -18
  58. package/dist/chunk-TJVT4QFF.js.map +1 -0
  59. package/dist/{chunk-S5YLIBFX.js → chunk-TQ7LNKZ3.js} +2 -2
  60. package/dist/{chunk-EOSZT7PL.js → chunk-U4L7JRPZ.js} +2 -297
  61. package/dist/chunk-U4L7JRPZ.js.map +1 -0
  62. package/dist/chunk-U4PHLT2N.js +419 -0
  63. package/dist/chunk-U4PHLT2N.js.map +1 -0
  64. package/dist/{chunk-WS3NZZQQ.js → chunk-VCZ5FQYW.js} +3 -4
  65. package/dist/chunk-VCZ5FQYW.js.map +1 -0
  66. package/dist/{chunk-BYT7ELPS.js → chunk-WVATSFCP.js} +2 -2
  67. package/dist/{chunk-TSN7JT6D.js → chunk-X4YIBDER.js} +21 -5
  68. package/dist/{chunk-TSN7JT6D.js.map → chunk-X4YIBDER.js.map} +1 -1
  69. package/dist/{chunk-TBL77AUT.js → chunk-YQN4ICPP.js} +5 -5
  70. package/dist/{chunk-MHELPNRP.js → chunk-ZHTZ4EYI.js} +1 -1
  71. package/dist/chunk-ZHTZ4EYI.js.map +1 -0
  72. package/dist/cli.js +6 -5
  73. package/dist/cli.js.map +1 -1
  74. package/dist/contract/index.d.ts +47 -87
  75. package/dist/contract/index.js +14 -13
  76. package/dist/contract/index.js.map +1 -1
  77. package/dist/control.js +3 -2
  78. package/dist/fuzz.js +3 -2
  79. package/dist/fuzz.js.map +1 -1
  80. package/dist/index.d.ts +659 -203
  81. package/dist/index.js +145 -117
  82. package/dist/index.js.map +1 -1
  83. package/dist/meta-eval/index.js +2 -2
  84. package/dist/multishot/index.d.ts +3 -4
  85. package/dist/multishot/index.js.map +1 -1
  86. package/dist/openapi.json +1 -1
  87. package/dist/pipelines/index.js +5 -5
  88. package/dist/reporting.d.ts +14 -0
  89. package/dist/reporting.js +7 -6
  90. package/dist/rl.d.ts +652 -82
  91. package/dist/rl.js +415 -171
  92. package/dist/rl.js.map +1 -1
  93. package/dist/rollout/index.d.ts +1071 -32
  94. package/dist/rollout/index.js +68 -10
  95. package/dist/run-campaign-OJJ7CZF4.js +18 -0
  96. package/dist/supervisor-run/index.d.ts +114 -4
  97. package/dist/supervisor-run/index.js +4 -3
  98. package/dist/traces.d.ts +1 -1
  99. package/dist/traces.js +6 -5
  100. package/dist/wire/index.d.ts +10 -11
  101. package/dist/wire/index.js +3 -3
  102. package/docs/feature-guide.md +1 -1
  103. package/docs/rollout.md +116 -2
  104. package/package.json +4 -4
  105. package/dist/chunk-2JX3CFMB.js.map +0 -1
  106. package/dist/chunk-DJKY2TSY.js.map +0 -1
  107. package/dist/chunk-EJGRPCO3.js.map +0 -1
  108. package/dist/chunk-EOSZT7PL.js.map +0 -1
  109. package/dist/chunk-EZJEIH2R.js.map +0 -1
  110. package/dist/chunk-IHQDPH7D.js.map +0 -1
  111. package/dist/chunk-MHELPNRP.js.map +0 -1
  112. package/dist/chunk-NACAGYSY.js.map +0 -1
  113. package/dist/chunk-NKAGIDE2.js.map +0 -1
  114. package/dist/chunk-NYLOYM6N.js.map +0 -1
  115. package/dist/chunk-PBE2LOSS.js.map +0 -1
  116. package/dist/chunk-TT4KNT67.js +0 -124
  117. package/dist/chunk-TT4KNT67.js.map +0 -1
  118. package/dist/chunk-UB2LOJ6Q.js.map +0 -1
  119. package/dist/chunk-UWZZKKU7.js +0 -237
  120. package/dist/chunk-UWZZKKU7.js.map +0 -1
  121. package/dist/chunk-VBQ3CRKH.js.map +0 -1
  122. package/dist/chunk-VGRCHJON.js.map +0 -1
  123. package/dist/chunk-VLOATJQ2.js.map +0 -1
  124. package/dist/chunk-VZSRQ272.js.map +0 -1
  125. package/dist/chunk-WS3NZZQQ.js.map +0 -1
  126. package/dist/chunk-XDWDC2MP.js.map +0 -1
  127. package/dist/chunk-XPRT64IE.js.map +0 -1
  128. package/dist/run-campaign-ISHFZ7FJ.js +0 -17
  129. /package/dist/{chunk-DPUHNQLN.js.map → chunk-7FO3TNPI.js.map} +0 -0
  130. /package/dist/{chunk-ZUUWPZCV.js.map → chunk-DODXQREJ.js.map} +0 -0
  131. /package/dist/{chunk-2MKQIFS4.js.map → chunk-E7QXT7SX.js.map} +0 -0
  132. /package/dist/{chunk-P5W7RQKK.js.map → chunk-FXTVJPYD.js.map} +0 -0
  133. /package/dist/{chunk-YJBNWCAA.js.map → chunk-NY44NC4A.js.map} +0 -0
  134. /package/dist/{chunk-S5YLIBFX.js.map → chunk-TQ7LNKZ3.js.map} +0 -0
  135. /package/dist/{chunk-BYT7ELPS.js.map → chunk-WVATSFCP.js.map} +0 -0
  136. /package/dist/{chunk-TBL77AUT.js.map → chunk-YQN4ICPP.js.map} +0 -0
  137. /package/dist/{run-campaign-ISHFZ7FJ.js.map → run-campaign-OJJ7CZF4.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rollout/exporters.ts","../src/rollout/ledger.ts","../src/rollout/release/card.ts","../src/rollout/release/scrub.ts","../src/rollout/release/hf-dataset.ts"],"sourcesContent":["/**\n * Pure exporters over `tangle.rollout.v1` lines → the training-data shapes\n * the improvement loops feed:\n * - SFT chat JSONL (clean trainable successes, {messages, metadata})\n * - reward rows (every scored line, success or failure, with steps)\n * - Prime Intellect verifiers RolloutOutput (prompt/completion split + reward)\n * - OpenAI RFT items (prompt turns + verdict reference fields)\n *\n * All exporters are pure functions of the lines — filtering (never train on\n * holdout, reward thresholds, the realness gate) happens HERE, on inline\n * labels, no joins.\n */\n\nimport type { ChatMessage, RolloutLine, RolloutSplit, RolloutStep, ToolDef } from './schema'\n\n// ---------------------------------------------------------------------------\n// (a) SFT chat JSONL\n// ---------------------------------------------------------------------------\n\nexport interface TrainingExportOptions {\n /** Include held-out evaluation data in training output. Default false. */\n allowHeldOutTrainingData?: boolean\n /** Require reward to be strictly greater than this value. Default 0. */\n minimumQualityExclusive?: number\n}\n\nexport type SftExportOptions = TrainingExportOptions\n\nexport interface SftRow {\n messages: ChatMessage[]\n metadata: {\n rollout_id: string\n run_id: string\n candidate_id: string | null\n instance_id: string\n reward: number\n }\n}\n\n/**\n * Supervised fine-tune rows: the completed conversation of each qualifying\n * line. Fail-closed filters: trainable split only (never holdout/canary),\n * positive reward, realness-gated lines never qualify, gap lines carry\n * no trainable content.\n */\nexport function toSftRows(lines: RolloutLine[], options: SftExportOptions = {}): SftRow[] {\n return lines\n .filter((line) => isTrainingLineEligible(line, options) && line.messages.length > 0)\n .map((line) => ({\n messages: line.messages,\n metadata: {\n rollout_id: line.rollout_id,\n run_id: line.run_id,\n candidate_id: line.candidate_id ?? null,\n instance_id: line.task.instance_id,\n reward: line.outcome.reward as number,\n },\n }))\n}\n\n// ---------------------------------------------------------------------------\n// (b) Reward rows\n// ---------------------------------------------------------------------------\n\nexport interface RewardRow {\n /** First user turn — the task prompt. */\n prompt: string\n steps: RolloutStep[]\n reward: number\n metadata: {\n rollout_id: string\n run_id: string\n candidate_id: string | null\n instance_id: string\n split: RolloutSplit\n }\n}\n\n/**\n * Reward-labeled rows for completed, positive-quality training runs.\n */\nexport function toRewardRows(\n lines: RolloutLine[],\n options: TrainingExportOptions = {},\n): RewardRow[] {\n return lines\n .filter(\n (line) =>\n isTrainingLineEligible(line, options) &&\n line.messages.some(\n (message) =>\n message.role === 'user' &&\n typeof message.content === 'string' &&\n message.content.length > 0,\n ),\n )\n .map((line) => ({\n prompt: line.messages.find((m) => m.role === 'user')?.content ?? '',\n steps: line.steps ?? [],\n reward: line.outcome.reward as number,\n metadata: {\n rollout_id: line.rollout_id,\n run_id: line.run_id,\n candidate_id: line.candidate_id ?? null,\n instance_id: line.task.instance_id,\n split: line.task.split,\n },\n }))\n}\n\n// ---------------------------------------------------------------------------\n// (c) Prime Intellect verifiers RolloutOutput\n// ---------------------------------------------------------------------------\n\nexport interface VerifiersTokenUsage {\n input_tokens: number | null\n output_tokens: number | null\n reasoning_tokens: number | null\n cache_read_tokens: number | null\n cache_write_tokens: number | null\n}\n\nexport interface VerifiersRolloutOutput {\n /** Messages through the last turn BEFORE the first assistant turn. */\n prompt: ChatMessage[]\n /** The first assistant turn onward — what the policy produced. */\n completion: ChatMessage[]\n reward: number | null\n metrics: Record<string, unknown>\n tool_defs: ToolDef[]\n token_usage: VerifiersTokenUsage\n info: {\n task: RolloutLine['task']\n policy: RolloutLine['policy']\n rollout_id: string\n run_id: string\n experiment_id: string | null\n candidate_id: string | null\n generation: number | null\n candidate_index: number | null\n role: RolloutLine['role']\n }\n}\n\n/** Index of the first assistant turn; messages.length when none exists. */\nfunction firstAssistantIndex(messages: ChatMessage[]): number {\n const index = messages.findIndex((m) => m.role === 'assistant')\n return index === -1 ? messages.length : index\n}\n\nexport function toVerifiersRolloutOutput(line: RolloutLine): VerifiersRolloutOutput {\n const split = firstAssistantIndex(line.messages)\n return {\n prompt: line.messages.slice(0, split),\n completion: line.messages.slice(split),\n reward: line.outcome.reward,\n metrics: line.outcome.metrics,\n tool_defs: line.tool_defs,\n token_usage: {\n input_tokens: line.cost.tokens_in,\n output_tokens: line.cost.tokens_out,\n reasoning_tokens: line.cost.tokens_reasoning,\n cache_read_tokens: line.cost.cache_read,\n cache_write_tokens: line.cost.cache_write,\n },\n info: {\n task: line.task,\n policy: line.policy,\n rollout_id: line.rollout_id,\n run_id: line.run_id,\n experiment_id: line.experiment_id ?? null,\n candidate_id: line.candidate_id ?? null,\n generation: line.generation,\n candidate_index: line.candidate_index,\n role: line.role,\n },\n }\n}\n\nexport function toVerifiersRolloutOutputs(\n lines: RolloutLine[],\n options: TrainingExportOptions = {},\n): VerifiersRolloutOutput[] {\n return lines\n .filter(\n (line) =>\n isTrainingLineEligible(line, options) &&\n firstAssistantIndex(line.messages) > 0 &&\n firstAssistantIndex(line.messages) < line.messages.length,\n )\n .map(toVerifiersRolloutOutput)\n}\n\n// ---------------------------------------------------------------------------\n// (d) OpenAI RFT items\n// ---------------------------------------------------------------------------\n\nexport interface RftItem {\n /** Prompt turns only — the graded completion is re-sampled during RFT. */\n messages: ChatMessage[]\n /** Verdict/label fields the grader references as item.reference.* */\n reference: {\n reward: number | null\n reward_source: string | null\n verdict: unknown\n instance_id: string\n suite: string\n split: RolloutSplit\n rollout_id: string\n }\n}\n\nexport function toRftItem(line: RolloutLine): RftItem {\n const split = firstAssistantIndex(line.messages)\n return {\n messages: line.messages.slice(0, split),\n reference: {\n reward: line.outcome.reward,\n reward_source: line.outcome.reward_source,\n verdict: line.outcome.verdict,\n instance_id: line.task.instance_id,\n suite: line.task.suite,\n split: line.task.split,\n rollout_id: line.rollout_id,\n },\n }\n}\n\n/** RFT needs a real prompt: lines whose transcript starts with prompt turns. */\nexport function toRftItems(lines: RolloutLine[], options: TrainingExportOptions = {}): RftItem[] {\n return lines\n .filter(\n (line) =>\n isTrainingLineEligible(line, options) &&\n line.messages.length > 0 &&\n firstAssistantIndex(line.messages) > 0,\n )\n .map(toRftItem)\n}\n\n// ---------------------------------------------------------------------------\n// Serialization — one JSON object per line, the interchange format for\n// every export. `tangle.rollout.v1` lines and export rows alike.\n// ---------------------------------------------------------------------------\n\nexport function toJsonl(rows: ReadonlyArray<unknown>): string {\n return rows.map((r) => JSON.stringify(r)).join('\\n') + (rows.length ? '\\n' : '')\n}\n\nfunction isTrainingLineEligible(\n line: RolloutLine,\n options: TrainingExportOptions,\n): line is RolloutLine & { outcome: RolloutLine['outcome'] & { reward: number } } {\n const minimumQualityExclusive = options.minimumQualityExclusive ?? 0\n if (!Number.isFinite(minimumQualityExclusive)) {\n throw new Error('minimumQualityExclusive must be finite')\n }\n\n const reward = line.outcome.reward\n if (reward === null) return false\n if (!Number.isFinite(reward)) {\n throw new Error(`training reward for rollout \"${line.rollout_id}\" must be finite`)\n }\n if (reward <= minimumQualityExclusive) return false\n if (!line.outcome.is_completed || line.outcome.is_truncated || line.outcome.error !== null) {\n return false\n }\n if (line.outcome.realness_gated === true) return false\n if (line.task.split === 'search') return true\n return line.task.split === 'holdout' && options.allowHeldOutTrainingData === true\n}\n","/**\n * Rollout-ledger file API — append-only JSONL of validated `tangle.rollout.v1`\n * lines. Writes validate BEFORE touching disk (a bad line never lands);\n * reads validate line-by-line and fail loud with the line number, because a\n * silently-skipped rollout is a corrupted dataset.\n */\n\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport { assertRolloutLine, type RolloutLine } from './schema'\n\nfunction serialize(lines: RolloutLine[]): string {\n for (const [i, line] of lines.entries()) assertRolloutLine(line, `rollout line [${i}]`)\n return lines.map((line) => JSON.stringify(line)).join('\\n') + (lines.length > 0 ? '\\n' : '')\n}\n\n/** Replace the ledger file with exactly `lines`. */\nexport async function writeRolloutLedger(path: string, lines: RolloutLine[]): Promise<void> {\n const payload = serialize(lines)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, payload)\n}\n\n/** Append `lines` to the ledger file (created if absent). */\nexport async function appendRolloutLines(path: string, lines: RolloutLine[]): Promise<void> {\n if (lines.length === 0) return\n const payload = serialize(lines)\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, payload)\n}\n\n/**\n * Read and validate every line. Throws on the first malformed/invalid line\n * (with its 1-based line number) — fail-closed, never a silent drop.\n */\nexport async function readRolloutLedger(path: string): Promise<RolloutLine[]> {\n const raw = await readFile(path, 'utf8')\n const lines: RolloutLine[] = []\n const rawLines = raw.split('\\n')\n for (let i = 0; i < rawLines.length; i++) {\n const text = rawLines[i]\n if (!text?.trim()) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (error) {\n throw new Error(\n `${path}:${i + 1}: malformed JSON — ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n assertRolloutLine(parsed, `${path}:${i + 1}`)\n lines.push(parsed)\n }\n return lines\n}\n","/**\n * HuggingFace dataset-card (README.md) generation for a rollout-ledger release.\n *\n * The card is a pure function of the SCRUBBED lines plus the release options —\n * no timestamps, no environment reads — so rebuilding from the same ledger\n * yields byte-identical output. It documents the schema, provenance (run ids,\n * generations, the official judge), per-role reward semantics including the\n * inherited/contribution caveat, and a role × reward counts table.\n */\n\nimport { ROLLOUT_ROLES, ROLLOUT_SCHEMA, type RolloutLine, type RolloutRole } from '../schema'\nimport type { ScrubCounts } from './scrub'\n\nexport const RELEASE_FORMATS = ['sft', 'verifiers', 'rft', 'raw'] as const\nexport type ReleaseFormat = (typeof RELEASE_FORMATS)[number]\n\n/** Format → data file path inside the dataset dir (train split only). */\nexport const FORMAT_FILES: Record<ReleaseFormat, string> = {\n sft: 'sft/train.jsonl',\n verifiers: 'verifiers/train.jsonl',\n rft: 'rft/train.jsonl',\n raw: 'raw/train.jsonl',\n}\n\nconst FORMAT_DESCRIPTIONS: Record<ReleaseFormat, string> = {\n sft: 'Successful trainable-split transcripts (`reward >= 1`, never realness-gated) as `{messages, metadata}` chat JSONL.',\n verifiers:\n 'Prime Intellect verifiers `RolloutOutput`: prompt/completion split at the first assistant turn, plus reward, metrics, tool defs, and token usage.',\n rft: 'OpenAI RFT items: prompt turns plus `reference.*` verdict fields for a grader (completions are re-sampled during RFT).',\n raw: `Full \\`${ROLLOUT_SCHEMA}\\` ledger lines (scrubbed), one per agent invocation.`,\n}\n\nexport interface DatasetCardInputs {\n /** Scrubbed, release-filtered lines (what actually ships). */\n lines: RolloutLine[]\n formats: ReleaseFormat[]\n includeProposers: boolean\n /** Source ledger basenames, for provenance. */\n sourceFiles: string[]\n scrubTotals: ScrubCounts\n excluded: { proposers: number; nonTrain: number }\n formatCounts: Partial<Record<ReleaseFormat, number>>\n}\n\nfunction unique(values: Array<string | null>): string[] {\n return [...new Set(values.filter((v): v is string => v !== null))].sort()\n}\n\nfunction formatReward(reward: number | null): string {\n if (reward === null) return 'null'\n return Number.isInteger(reward) ? String(reward) : reward.toFixed(4)\n}\n\nfunction markdownTable(header: string[], rows: string[][]): string {\n return [\n `| ${header.join(' | ')} |`,\n `| ${header.map(() => '---').join(' | ')} |`,\n ...rows.map((row) => `| ${row.join(' | ')} |`),\n ].join('\\n')\n}\n\nfunction roleRewardRows(lines: RolloutLine[]): string[][] {\n const counts = new Map<RolloutRole, Map<string, number>>()\n for (const line of lines) {\n const byReward = counts.get(line.role) ?? new Map<string, number>()\n const key = formatReward(line.outcome.reward)\n byReward.set(key, (byReward.get(key) ?? 0) + 1)\n counts.set(line.role, byReward)\n }\n const rows: string[][] = []\n for (const role of ROLLOUT_ROLES) {\n const byReward = counts.get(role)\n if (!byReward) continue\n const keys = [...byReward.keys()].sort((a, b) => {\n if (a === 'null') return 1\n if (b === 'null') return -1\n return Number(b) - Number(a)\n })\n for (const key of keys) rows.push([role, key, String(byReward.get(key))])\n }\n return rows\n}\n\nexport function buildDatasetCard(inputs: DatasetCardInputs): string {\n const { lines, formats, includeProposers, sourceFiles, scrubTotals, excluded, formatCounts } =\n inputs\n\n const runIds = unique(lines.map((line) => line.run_id))\n const generations = [...new Set(lines.map((line) => line.generation))]\n .filter((g): g is number => g !== null)\n .sort((a, b) => a - b)\n const models = unique(lines.map((line) => line.policy.model))\n const harnesses = unique(lines.map((line) => line.policy.harness))\n const captures = unique(lines.map((line) => line.provenance.capture))\n const rewardSources = unique(lines.map((line) => line.outcome.reward_source))\n const gapLines = lines.filter((line) => line.messages.length === 0).length\n\n const configs = formats\n .map((format) =>\n [\n ` - config_name: ${format}`,\n ' data_files:',\n ' - split: train',\n ` path: ${FORMAT_FILES[format]}`,\n ].join('\\n'),\n )\n .join('\\n')\n\n const frontmatter = [\n '---',\n 'license: unknown',\n 'pretty_name: Tangle rollout ledger — agent trajectories',\n 'configs:',\n configs,\n '---',\n ].join('\\n')\n\n const formatsTable = markdownTable(\n ['config', 'path', 'rows', 'contents'],\n formats.map((format) => [\n format,\n `\\`${FORMAT_FILES[format]}\\``,\n String(formatCounts[format] ?? 0),\n FORMAT_DESCRIPTIONS[format],\n ]),\n )\n\n const countsTable = markdownTable(['role', 'reward', 'lines'], roleRewardRows(lines))\n\n const scrubTable = markdownTable(\n ['rule', 'rewrites'],\n Object.entries(scrubTotals).map(([rule, count]) => [rule, String(count)]),\n )\n\n const proposerNote = includeProposers\n ? 'Proposer sessions are INCLUDED (`--include-proposers`); their transcripts contain improvement-loop harness source.'\n : `Proposer sessions are excluded by default (${excluded.proposers} lines dropped); they contain improvement-loop harness source. Rebuild with \\`--include-proposers\\` to keep them.`\n\n return `${frontmatter}\n\n# Tangle rollout ledger — agent trajectories\n\nOne line per agent invocation (supervisor episode, worker session, proposer shot, judge call, analyst pass) captured by the \\`${ROLLOUT_SCHEMA}\\` rollout ledger, labeled with improvement-loop coordinates and the official-judge reward, with the full message transcript inline.\n\nThis release contains the **trainable split only** (\\`search\\`). Holdout, dev, and canary splits are structurally excluded at build time, and the build additionally drops any non-trainable line as a fail-closed filter (${excluded.nonTrain} dropped here).\n\n## Formats\n\n${formatsTable}\n\n## Schema (\\`${ROLLOUT_SCHEMA}\\`)\n\nEach raw line carries:\n\n- \\`rollout_id\\` / \\`parent_rollout_id\\` — invocation identity; workers point at their spawning supervisor episode.\n- \\`run_id\\`, \\`experiment_id\\`, \\`candidate_id\\` — run/experiment/candidate identity from the producing RunRecord, when present.\n- \\`generation\\`, \\`candidate_index\\` — improvement-loop coordinates (\\`-1\\` = baseline campaign; \\`null\\` = not an improvement loop).\n- \\`role\\` — one of ${ROLLOUT_ROLES.map((role) => `\\`${role}\\``).join(', ')}.\n- \\`task\\` — suite, instance id, split, seed, replicate index.\n- \\`policy\\` — harness, model, provider, profile commit, prompt/config hashes, sampling params.\n- \\`messages\\` / \\`tool_defs\\` — full transcript in canonical OpenAI chat-with-tools form (including \\`reasoning_content\\`). An empty \\`messages\\` array is a labeled gap line; \\`provenance.gap\\` says why the transcript could not be recovered (${gapLines} gap lines in this release).\n- \\`outcome\\` — \\`reward\\` (the single scalar), \\`reward_source\\`, the verbatim judge \\`verdict\\`, non-scalar \\`metrics\\`, and \\`realness_gated\\` (anti-Goodhart flag: reward forced to 0, never SFT-eligible).\n- \\`cost\\` — usd, token counts, wall time.\n- \\`artifacts\\` / \\`provenance\\` — patch/run-dir/transcript pointers (scrubbed) and capture metadata.\n\n## Provenance\n\n- Source ledgers: ${sourceFiles.map((file) => `\\`${file}\\``).join(', ')}\n- Run ids: ${runIds.map((id) => `\\`${id}\\``).join(', ')}\n- Generations: ${generations.join(', ')} (\\`-1\\` = baseline campaign)\n- Models: ${models.map((m) => `\\`${m}\\``).join(', ')}\n- Harnesses: ${harnesses.map((h) => `\\`${h}\\``).join(', ')}\n- Capture modes: ${captures.join(', ')}\n- Every reward traces to a named source (reward sources in this release: ${rewardSources.map((s) => `\\`${s}\\``).join(', ')}).\n\n${proposerNote}\n\n## Reward semantics per role\n\n- **agent** — the producing RunRecord's holdout/search score, with the realness gate forcing gamed successes to 0.\n- **supervisor** — the official-judge verdict on the episode's delivered artifact (1 = resolved, 0 = not).\n- **worker** — INHERITED from the parent supervisor episode (\\`…/inherited\\`). Caveat: reward 1 does not establish this worker's individual contribution (sibling workers in the same episode share the episode outcome), and reward 0 does not prove this worker failed.\n- **proposer** — the fraction of improvement-set instances the proposed candidate resolved (\\`…/candidate-resolved-fraction\\`); a scalar in [0, 1], not a binary verdict.\n- **judge / analyst** — carry the episode verdict where one applies; otherwise \\`reward: null\\` (a labeled gap, never 0).\n\n## Counts\n\n${countsTable}\n\nTotal lines: ${lines.length}\n\n## Scrubbing\n\nAbsolute home paths were rewritten to \\`$WORK\\`, credential-shaped strings were replaced with \\`[REDACTED:<kind>]\\` markers, internal hostnames were normalized to \\`*.internal.example\\`, and username-bearing incidentals (\\`ls -l\\` owner columns, per-user pytest tmpdirs) were normalized to \\`user\\` / \\`$USER\\`. Rewrite counts for this release (full per-file breakdown in \\`scrub-report.json\\`):\n\n${scrubTable}\n\n## License\n\n\\`license: unknown\\` is a placeholder — the releasing operator must set the real SPDX license id in the frontmatter above before publishing.\n\n## Citation\n\n\\`\\`\\`bibtex\n@misc{tangle_rollout_ledger,\n title = {Tangle rollout ledger — agent trajectories},\n author = {{Tangle Network}},\n howpublished = {HuggingFace Datasets},\n note = {Operator: fill in the repository URL, authors, and year before publishing}\n}\n\\`\\`\\`\n`\n}\n","/**\n * Deterministic scrubbing pass over rollout-ledger lines before public release.\n *\n * Every rule is a pure regex rewrite applied to every string value in a line\n * (messages, artifacts, run ids, tool arguments — everywhere), so the scrubbed\n * line is still a valid `tangle.rollout.v1` line. Rules are idempotent:\n * scrub(scrub(x)) === scrub(x), and a second pass counts zero hits — that is\n * the property the release pipeline relies on to prove nothing half-scrubbed\n * ships. Rule order matters: whole `KEY=value` env pairs are redacted before\n * the bare-key rule so one secret is never counted twice.\n */\n\nimport type { RolloutLine } from '../schema'\n\nexport interface ScrubRule {\n name: string\n pattern: RegExp\n /** Rewrite for one match; `g1` is the first capture group when present. */\n rewrite: (match: string, g1?: string) => string\n}\n\nexport const SCRUB_RULES: readonly ScrubRule[] = [\n {\n // /home/<user> and /Users/<user> prefixes → $WORK ($HOME-derived paths).\n name: 'home-path',\n pattern: /\\/(?:home|Users)\\/[A-Za-z0-9._-]+/g,\n rewrite: () => '$WORK',\n },\n {\n // Harness stores encode cwd as a dashed path segment (-home-drew-…);\n // strip the leading -home-<user> so the username never ships.\n name: 'home-path-encoded',\n pattern: /(?<=\\/)-(?:home|Users)-[A-Za-z0-9_.]+/g,\n rewrite: () => '$WORK',\n },\n {\n // pytest names its tmpdir after the invoking user (/tmp/pytest-of-drew).\n name: 'tmp-user-dir',\n pattern: /\\/tmp\\/pytest-of-[A-Za-z0-9._-]+/g,\n rewrite: () => '/tmp/pytest-of-$USER',\n },\n {\n // `ls -l` owner/group columns leak the username in captured tool output.\n // The `(?!user user…)` guard keeps a second pass at zero rewrites.\n name: 'ls-owner',\n pattern:\n /([-bcdlps][-rwxsStT]{9}[.+@]?\\s+\\d+\\s+)(?!user user(?=\\s))[A-Za-z0-9._-]+\\s+[A-Za-z0-9._-]+(?=\\s)/g,\n rewrite: (_match, prefix) => `${prefix}user user`,\n },\n {\n // Env-var-shaped secrets: NAME=value where NAME looks credential-bearing.\n // The (?!\\[REDACTED:) guard keeps the rule idempotent on its own output.\n name: 'env-secret',\n pattern:\n /\\b([A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?))=(?!\\[REDACTED:)(\"[^\"]*\"|'[^']*'|[^\\s\"']+)/g,\n rewrite: (_match, name) => `${name}=[REDACTED:env]`,\n },\n {\n name: 'bearer-token',\n pattern: /\\b(Bearer|Basic)\\s+(?!\\[REDACTED:)[A-Za-z0-9\\-._~+/=]{8,}/g,\n rewrite: (_match, scheme) => `${scheme} [REDACTED:bearer]`,\n },\n {\n // Bare provider-prefixed keys (OpenAI/Anthropic sk-, GitHub ghp_/gho_/…,\n // fine-grained PATs, HuggingFace hf_, Slack xox*, AWS AKIA).\n name: 'api-key',\n pattern:\n /\\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|hf_[A-Za-z0-9]{16,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})\\b/g,\n rewrite: () => '[REDACTED:api-key]',\n },\n {\n // Our infra hostnames → placeholder domain, subdomain preserved\n // (router.tangle.tools → router.internal.example).\n name: 'infra-host',\n pattern: /(?<![A-Za-z0-9.-])((?:[A-Za-z0-9-]+\\.)*)tangle\\.(?:tools|network)(?![A-Za-z0-9-])/g,\n rewrite: (_match, prefix) => `${prefix ?? ''}internal.example`,\n },\n {\n // Known workstation hostnames leak through email Message-IDs and fqdn\n // lookups inside captured test output; extend the list as machines join.\n name: 'machine-host',\n pattern: /\\b[A-Za-z0-9]+-GTR-Pro\\b/g,\n rewrite: () => 'workstation',\n },\n]\n\n/** Rule name → number of matches rewritten. Always carries every rule (0 is data). */\nexport type ScrubCounts = Record<string, number>\n\nexport function emptyScrubCounts(): ScrubCounts {\n return Object.fromEntries(SCRUB_RULES.map((rule) => [rule.name, 0]))\n}\n\nexport function addScrubCounts(into: ScrubCounts, from: ScrubCounts): ScrubCounts {\n for (const [name, count] of Object.entries(from)) into[name] = (into[name] ?? 0) + count\n return into\n}\n\nexport function scrubText(text: string, counts: ScrubCounts): string {\n let out = text\n for (const rule of SCRUB_RULES) {\n out = out.replace(rule.pattern, (match: string, ...rest: unknown[]) => {\n counts[rule.name] = (counts[rule.name] ?? 0) + 1\n return rule.rewrite(match, typeof rest[0] === 'string' ? rest[0] : undefined)\n })\n }\n return out\n}\n\nfunction scrubValue(value: unknown, counts: ScrubCounts): unknown {\n if (typeof value === 'string') return scrubText(value, counts)\n if (Array.isArray(value)) return value.map((item) => scrubValue(item, counts))\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value)) out[key] = scrubValue(item, counts)\n return out\n }\n return value\n}\n\n/** Scrub every string value in a line; structure and key order are preserved. */\nexport function scrubRolloutLine(line: RolloutLine, counts: ScrubCounts): RolloutLine {\n return scrubValue(line, counts) as RolloutLine\n}\n\nexport function scrubLines(lines: RolloutLine[]): { lines: RolloutLine[]; counts: ScrubCounts } {\n const counts = emptyScrubCounts()\n return { lines: lines.map((line) => scrubRolloutLine(line, counts)), counts }\n}\n\n/**\n * A `RolloutScrubber` (text → text) applying the full rule set — the\n * default hook to pass to `mintRolloutRows({ scrub })` so lines are\n * scrubbed at mint time, before they ever reach a ledger file. Release\n * builds re-run `scrubLines` regardless (idempotent), so double-scrubbing\n * is safe and counted as zero.\n */\nexport function defaultRolloutScrubber(text: string): string {\n return scrubText(text, emptyScrubCounts())\n}\n","/**\n * One-command HuggingFace dataset release from rollout ledgers:\n *\n * agent-eval rollout-release <ledger.jsonl...> --out <dir> \\\n * [--formats sft,verifiers,rft,raw] [--include-proposers] [--push <org/name>]\n *\n * Pipeline per input ledger: read + validate → fail-closed filters\n * (trainable split only; proposer sessions dropped unless\n * --include-proposers, they contain improvement-loop harness source) →\n * deterministic scrub → export the requested formats + scrub-report.json +\n * auto-generated README.md card. Deterministic: same inputs and flags →\n * byte-identical output dir.\n *\n * --push uploads the built dir with `huggingface-cli upload` only when the\n * CLI exists on PATH and HF_TOKEN is present in the env; the token is\n * never printed. Everything else runs fully offline.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\nimport { toJsonl, toRftItems, toSftRows, toVerifiersRolloutOutputs } from '../exporters'\nimport { readRolloutLedger, writeRolloutLedger } from '../ledger'\nimport { isTrainableSplit, type RolloutLine } from '../schema'\nimport { buildDatasetCard, FORMAT_FILES, RELEASE_FORMATS, type ReleaseFormat } from './card'\nimport { addScrubCounts, emptyScrubCounts, type ScrubCounts, scrubLines } from './scrub'\n\nexport interface BuildOptions {\n out: string\n formats: ReleaseFormat[]\n includeProposers: boolean\n}\n\nexport interface ScrubReport {\n /** Input ledger path → rule → rewrite count (only shipped lines are scrubbed). */\n files: Record<string, ScrubCounts>\n totals: ScrubCounts\n excluded: { proposers: number; nonTrain: number }\n}\n\nexport interface BuildSummary {\n inputs: string[]\n read: number\n kept: number\n scrub: ScrubReport\n formatCounts: Partial<Record<ReleaseFormat, number>>\n files: string[]\n}\n\nexport async function buildHfDataset(\n inputs: string[],\n options: BuildOptions,\n): Promise<BuildSummary> {\n if (inputs.length === 0) throw new Error('no input ledgers given')\n if (options.formats.length === 0) throw new Error('no formats selected')\n\n const report: ScrubReport = {\n files: {},\n totals: emptyScrubCounts(),\n excluded: { proposers: 0, nonTrain: 0 },\n }\n const kept: RolloutLine[] = []\n let read = 0\n\n for (const input of inputs) {\n const lines = await readRolloutLedger(input)\n read += lines.length\n const shippable = lines.filter((line) => {\n if (!isTrainableSplit(line.task.split)) {\n report.excluded.nonTrain += 1\n return false\n }\n if (!options.includeProposers && line.role === 'proposer') {\n report.excluded.proposers += 1\n return false\n }\n return true\n })\n const scrubbed = scrubLines(shippable)\n report.files[input] = scrubbed.counts\n addScrubCounts(report.totals, scrubbed.counts)\n kept.push(...scrubbed.lines)\n }\n\n const formatCounts: Partial<Record<ReleaseFormat, number>> = {}\n const files: string[] = []\n\n for (const format of options.formats) {\n const path = join(options.out, FORMAT_FILES[format])\n await mkdir(dirname(path), { recursive: true })\n if (format === 'raw') {\n // writeRolloutLedger re-validates every scrubbed line before it lands.\n await writeRolloutLedger(path, kept)\n formatCounts.raw = kept.length\n } else if (format === 'sft') {\n const rows = toSftRows(kept)\n await writeFile(path, toJsonl(rows))\n formatCounts.sft = rows.length\n } else if (format === 'verifiers') {\n const outputs = toVerifiersRolloutOutputs(kept)\n await writeFile(path, toJsonl(outputs))\n formatCounts.verifiers = outputs.length\n } else {\n const items = toRftItems(kept)\n await writeFile(path, toJsonl(items))\n formatCounts.rft = items.length\n }\n files.push(path)\n }\n\n const reportPath = join(options.out, 'scrub-report.json')\n await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\\n`)\n files.push(reportPath)\n\n const cardPath = join(options.out, 'README.md')\n await writeFile(\n cardPath,\n buildDatasetCard({\n lines: kept,\n formats: options.formats,\n includeProposers: options.includeProposers,\n sourceFiles: inputs.map((input) => basename(input)),\n scrubTotals: report.totals,\n excluded: report.excluded,\n formatCounts,\n }),\n )\n files.push(cardPath)\n\n return { inputs, read, kept: kept.length, scrub: report, formatCounts, files }\n}\n\nexport function planPushCommand(repo: string, outDir: string): string[] {\n return ['huggingface-cli', 'upload', repo, outDir, '.', '--repo-type', 'dataset']\n}\n\nexport function pushDataset(repo: string, outDir: string): void {\n const found = spawnSync('which', ['huggingface-cli'], { stdio: 'ignore' })\n if (found.status !== 0) {\n throw new Error(\n 'huggingface-cli not found on PATH — install huggingface_hub[cli] before --push',\n )\n }\n if (!process.env.HF_TOKEN) {\n throw new Error('HF_TOKEN not present in env — refusing to push')\n }\n const [command, ...args] = planPushCommand(repo, outDir) as [string, ...string[]]\n // Token stays in the inherited env; it is never echoed or interpolated.\n const run = spawnSync(command, args, { stdio: 'inherit' })\n if (run.status !== 0) throw new Error(`huggingface-cli upload exited ${String(run.status)}`)\n}\n\nexport interface RolloutReleaseCliArgs extends BuildOptions {\n inputs: string[]\n push: string | null\n}\n\nexport const ROLLOUT_RELEASE_USAGE =\n 'usage: agent-eval rollout-release <ledger.jsonl...> --out <dir> [--formats sft,verifiers,rft,raw] [--include-proposers] [--push <org/name>]'\n\nexport function parseRolloutReleaseArgs(argv: string[]): RolloutReleaseCliArgs {\n const args: RolloutReleaseCliArgs = {\n inputs: [],\n out: '',\n formats: [...RELEASE_FORMATS],\n includeProposers: false,\n push: null,\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!\n if (arg === '--out') {\n args.out = argv[++i] ?? ''\n } else if (arg === '--formats') {\n const raw = (argv[++i] ?? '').split(',').filter(Boolean)\n for (const format of raw) {\n if (!RELEASE_FORMATS.includes(format as ReleaseFormat)) {\n throw new Error(\n `unknown format \"${format}\" — expected one of ${RELEASE_FORMATS.join(',')}`,\n )\n }\n }\n args.formats = raw as ReleaseFormat[]\n } else if (arg === '--include-proposers') {\n args.includeProposers = true\n } else if (arg === '--push') {\n args.push = argv[++i] ?? null\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else {\n args.inputs.push(arg)\n }\n }\n if (args.inputs.length === 0 || !args.out) {\n throw new Error(ROLLOUT_RELEASE_USAGE)\n }\n if (args.push !== null && !/^[\\w.-]+\\/[\\w.-]+$/.test(args.push)) {\n throw new Error(`--push expects <org/name>, got \"${args.push}\"`)\n }\n return args\n}\n\n/** CLI driver for `agent-eval rollout-release`. Returns the process exit code. */\nexport async function runRolloutReleaseCli(argv: string[]): Promise<number> {\n let args: RolloutReleaseCliArgs\n try {\n args = parseRolloutReleaseArgs(argv)\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n return 2\n }\n const summary = await buildHfDataset(args.inputs, args)\n process.stdout.write(\n `${JSON.stringify(\n {\n read: summary.read,\n kept: summary.kept,\n formatCounts: summary.formatCounts,\n scrub: summary.scrub,\n },\n null,\n 2,\n )}\\n`,\n )\n process.stdout.write(`dataset → ${args.out} (${summary.files.length} files)\\n`)\n if (args.push !== null) {\n pushDataset(args.push, args.out)\n process.stdout.write(`pushed → ${args.push}\\n`)\n }\n return 0\n}\n"],"mappings":";;;;;;;;AA6CO,SAAS,UAAU,OAAs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AAC,KAAK,KAAK;AACzC,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AACA,MAAI,KAAK,SAAS,QAAQ,CAAC,qBAAqB,KAAK,KAAK,IAAI,GAAG;AAC/D,UAAM,IAAI,MAAM,mCAAmC,KAAK,IAAI,GAAG;AAAA,EACjE;AACA,SAAO;AACT;AAGA,eAAsB,qBAAqB,MAAiC;AAC1E,MAAI;AACJ,MAAI;AACF,WAAO,wBAAwB,IAAI;AAAA,EACrC,SAAS,OAAO;AACd,YAAQ,OAAO,MAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAClF,WAAO;AAAA,EACT;AACA,QAAM,UAAU,MAAM,eAAe,KAAK,QAAQ,IAAI;AACtD,UAAQ,OAAO;AAAA,IACb,GAAG,KAAK;AAAA,MACN;AAAA,QACE,MAAM,QAAQ;AAAA,QACd,MAAM,QAAQ;AAAA,QACd,cAAc,QAAQ;AAAA,QACtB,OAAO,QAAQ;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA;AAAA,EACH;AACA,UAAQ,OAAO,MAAM,kBAAa,KAAK,GAAG,KAAK,QAAQ,MAAM,MAAM;AAAA,CAAW;AAC9E,MAAI,KAAK,SAAS,MAAM;AACtB,gBAAY,KAAK,MAAM,KAAK,GAAG;AAC/B,YAAQ,OAAO,MAAM,iBAAY,KAAK,IAAI;AAAA,CAAI;AAAA,EAChD;AACA,SAAO;AACT;","names":["mkdir","writeFile","dirname","mkdir","dirname","writeFile"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/trace-analyst/hook.ts","../src/trace-analyst/insights.ts","../src/trace-analyst/otlp-flatten.ts","../src/trace-analyst/otlp-to-run-records.ts","../src/trace/store.ts","../src/trace/capture-fetch.ts","../src/trace/otel.ts","../src/trace/otel-bridge.ts","../src/trace/otel-export.ts","../src/trace/store-to-otlp.ts","../src/replay.ts"],"sourcesContent":["/**\n * Trace-analyst auto-execution hook.\n *\n * Wires `analyzeTraces` into a `TraceEmitter`'s `onRunComplete` so a\n * direct matrix run produces an analysis artifact without an out-of-band\n * step. Designed for the case where the consumer reports \"the analyst\n * never ran\" — the cause is almost always orchestration, not the analyst.\n *\n * Usage:\n *\n * const emitter = new TraceEmitter(store, {\n * onRunComplete: [traceAnalystOnRunComplete({ analyze: opts, save })],\n * })\n *\n * Hooks are best-effort by default — they never crash the underlying run.\n * The caller decides whether to gate the run on the analysis result via\n * the `gateOn` callback.\n */\n\nimport type { RunCompleteHook, RunCompleteHookContext } from '../trace/emitter'\nimport { type AnalyzeTracesOptions, type AnalyzeTracesResult, analyzeTraces } from './analyst'\n\nexport interface TraceAnalystHookOptions {\n /**\n * Options forwarded to `analyzeTraces`. The hook supplies the question\n * if you don't pass one — defaulting to a launch-grade prompt that asks\n * for failure modes, surprising findings, and a recommendation.\n */\n analyze: Omit<AnalyzeTracesOptions, 'source'> & { source?: AnalyzeTracesOptions['source'] }\n /**\n * Override the question. The default is intentionally generic:\n * \"Summarise what happened in this run, surface any failure modes,\n * surprising findings, or evidence the verdict is wrong.\"\n */\n question?: string\n /**\n * Persist the result. The hook calls this with the analysis output and\n * the run context. Common implementations write to a TraceAnalysisStore\n * or append to a per-run JSONL.\n */\n save?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => Promise<void>\n /**\n * Predicate gating execution per run. Default: every completed run.\n * Use to skip aborted runs, debug runs, or runs without LLM activity.\n */\n shouldRun?: (ctx: RunCompleteHookContext) => boolean\n /**\n * Optional gate: if set and returns false, the hook records the failure\n * as a log event on the run instead of staying quiet. The caller can\n * then trigger downstream alerts off `analyst_gate_failed` log events.\n */\n gateOn?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => boolean\n}\n\nconst DEFAULT_QUESTION =\n \"Summarise what happened in this run. Surface any failure modes, surprising findings, or evidence that the run's verdict is wrong.\"\n\nexport function traceAnalystOnRunComplete(opts: TraceAnalystHookOptions): RunCompleteHook {\n return async (ctx: RunCompleteHookContext) => {\n if (opts.shouldRun && !opts.shouldRun(ctx)) return\n const source = opts.analyze.source\n if (source === undefined) {\n // The analyst needs a source. If the caller didn't supply one we don't\n // run — but we do leave a breadcrumb so the absence is visible.\n await ctx.store.appendEvent({\n eventId: `analyst-skip-${ctx.runId}`,\n runId: ctx.runId,\n kind: 'log',\n timestamp: Date.now(),\n payload: { source: 'trace_analyst_hook', reason: 'no source configured' },\n })\n return\n }\n const result = await analyzeTraces({ question: opts.question ?? DEFAULT_QUESTION }, {\n ...opts.analyze,\n source,\n } as AnalyzeTracesOptions)\n if (opts.save) await opts.save(result, ctx)\n if (opts.gateOn && !opts.gateOn(result, ctx)) {\n await ctx.store.appendEvent({\n eventId: `analyst-gate-${ctx.runId}`,\n runId: ctx.runId,\n kind: 'log',\n timestamp: Date.now(),\n payload: {\n source: 'trace_analyst_hook',\n reason: 'analyst_gate_failed',\n findings: result.findings,\n },\n })\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","/**\n * `flattenOtlpExportToNdjson` — flatten an `OtlpExport` (the shape\n * `exportRunAsOtlp` produces) into the per-line JSON the analyst's\n * `OtlpFileTraceStore` index reads. Replaces three per-consumer OTLP\n * flatteners with one canonical projection.\n *\n * Pure function, no I/O — the caller does `.map(JSON.stringify).join('\\n')`\n * and writes the file (consumers want control over rotation + naming).\n */\n\nimport type { OtlpExport, OtlpSpan } from '../trace/otel'\nimport {\n LLM_INPUT_TOKENS,\n LLM_MODEL_NAME,\n LLM_OUTPUT_TOKENS,\n OPENINFERENCE_SPAN_KIND,\n TOOL_NAME,\n} from '../trace/otlp-attributes'\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: 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET'\n message?: string\n }\n resource: { attributes: Record<string, string | number | boolean> }\n attributes: Record<string, string | number | boolean>\n events?: Array<{ name: string; timeUnixNano?: string; attributes?: Record<string, unknown> }>\n}\n\nexport interface FlattenOtlpOptions {\n /** `'openinference'` (default) mirrors legacy per-span attributes into the\n * canonical OpenInference vocabulary the analyst readers consume. `'none'`\n * passes attributes through untouched. */\n attributeVocabulary?: 'openinference' | 'none'\n /** Override the numeric-kind → otlp-string mapping. */\n kindMap?: Partial<Record<number, string>>\n}\n\nconst DEFAULT_KIND_MAP: Record<number, string> = {\n 0: 'SPAN_KIND_UNSPECIFIED',\n 1: 'SPAN_KIND_INTERNAL',\n 2: 'SPAN_KIND_SERVER',\n 3: 'SPAN_KIND_CLIENT',\n 4: 'SPAN_KIND_PRODUCER',\n 5: 'SPAN_KIND_CONSUMER',\n}\n\nconst STATUS_MAP: Record<number, OtlpFlatLine['status']['code']> = {\n 0: 'STATUS_CODE_UNSET',\n 1: 'STATUS_CODE_OK',\n 2: 'STATUS_CODE_ERROR',\n}\n\n/** Unwrap an OTLP attribute-value union to a scalar. */\nfunction attrValue(v: OtlpSpan['attributes'][number]['value']): string | number | boolean {\n if (v.stringValue !== undefined) return v.stringValue\n if (v.intValue !== undefined) return Number(v.intValue)\n if (v.doubleValue !== undefined) return v.doubleValue\n if (v.boolValue !== undefined) return v.boolValue\n return ''\n}\n\nfunction attrsToRecord(attrs: OtlpSpan['attributes']): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const a of attrs) out[a.key] = attrValue(a.value)\n return out\n}\n\nfunction nanoToIso(nano: string): string {\n const ms = Number(nano) / 1_000_000\n return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date(0).toISOString()\n}\n\n/** Mirror selected attributes into the OpenInference vocabulary in place. */\nfunction applyOpenInference(attrs: Record<string, string | number | boolean>): void {\n if ('llm.model' in attrs && !(LLM_MODEL_NAME in attrs)) {\n attrs[LLM_MODEL_NAME] = attrs['llm.model']!\n }\n if ('llm.input_tokens' in attrs && !(LLM_INPUT_TOKENS in attrs)) {\n attrs[LLM_INPUT_TOKENS] = attrs['llm.input_tokens']!\n }\n if ('inference.llm.input_tokens' in attrs && !(LLM_INPUT_TOKENS in attrs)) {\n attrs[LLM_INPUT_TOKENS] = attrs['inference.llm.input_tokens']!\n }\n if ('llm.output_tokens' in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {\n attrs[LLM_OUTPUT_TOKENS] = attrs['llm.output_tokens']!\n }\n if ('inference.llm.output_tokens' in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {\n attrs[LLM_OUTPUT_TOKENS] = attrs['inference.llm.output_tokens']!\n }\n if (TOOL_NAME in attrs && !('inference.tool.name' in attrs)) {\n attrs['inference.tool.name'] = attrs[TOOL_NAME]!\n }\n if ('span.kind' in attrs && !(OPENINFERENCE_SPAN_KIND in attrs)) {\n attrs[OPENINFERENCE_SPAN_KIND] = String(attrs['span.kind']).toUpperCase()\n }\n}\n\nexport function flattenOtlpExportToNdjson(\n otlpExport: OtlpExport,\n opts: FlattenOtlpOptions = {},\n): OtlpFlatLine[] {\n const vocab = opts.attributeVocabulary ?? 'openinference'\n const kindMap = { ...DEFAULT_KIND_MAP, ...opts.kindMap }\n const lines: OtlpFlatLine[] = []\n\n for (const rs of otlpExport.resourceSpans ?? []) {\n const resource = { attributes: attrsToRecord(rs.resource?.attributes ?? []) }\n for (const scope of rs.scopeSpans ?? []) {\n for (const span of scope.spans ?? []) {\n const attributes = attrsToRecord(span.attributes ?? [])\n if (vocab === 'openinference') applyOpenInference(attributes)\n const line: OtlpFlatLine = {\n trace_id: span.traceId,\n span_id: span.spanId,\n parent_span_id: span.parentSpanId ?? null,\n name: span.name,\n kind: kindMap[span.kind] ?? 'SPAN_KIND_UNSPECIFIED',\n start_time: nanoToIso(span.startTimeUnixNano),\n end_time: nanoToIso(span.endTimeUnixNano),\n status: {\n code: STATUS_MAP[span.status?.code ?? 0] ?? 'STATUS_CODE_UNSET',\n ...(span.status?.message ? { message: span.status.message } : {}),\n },\n resource,\n attributes,\n }\n if (span.events && span.events.length > 0) {\n line.events = span.events.map((e) => ({\n name: e.name,\n timeUnixNano: e.timeUnixNano,\n ...(e.attributes ? { attributes: attrsToRecord(e.attributes) } : {}),\n }))\n }\n lines.push(line)\n }\n }\n }\n\n return lines\n}\n","/**\n * `otlpToRunRecords` — fold an OTLP traces.jsonl (one OTLP span per line;\n * the form AppWorld / HALO emit via their OpenInference OTLP exporter, the\n * same shape `flattenOtlpExportToNdjson` produces) into validated\n * `RunRecord[]` — one record per `trace_id` by default, or per caller-defined\n * logical run when one task is fragmented across multiple OTLP traces.\n *\n * This is the offline ingestion primitive the AppWorld proposer bench and the\n * hosted Intelligence product both stand on: traces in, paper-grade rows\n * out, ready for `compareOptimizationMethods` / `analyzeRuns` / the promotion gate.\n *\n * Aggregation per trace:\n * - tokenUsage: reconcile input, output, cache-read, and cache-write across\n * nested model-call wrappers without double-counting parent aggregates.\n * - costUsd: reconcile complete observed model-call cost when present; else priced via\n * `opts.priceUsdPerToken` from the aggregated tokens; else `null` with a\n * loud `raw.cost_unpriced = 1` marker.\n * - task failure class and detail: read from process-root\n * `tangle.task.failure_*` attributes; malformed or conflicting values throw.\n * - terminalFailureReason: the failed root's normalized status message,\n * when one unambiguous root supplies terminal failure evidence.\n * - terminalOutcome: reduced from root-span status only. Child tool errors\n * remain visible in `error_span_count` and `execution_error_count` without\n * changing the run outcome. Root, guardrail, evaluator, propagated, and\n * unknown errors retain separate counters.\n * - model: the dominant LLM model in the trace (snapshot-padded to satisfy\n * `validateRunRecord` when the trace's model is a bare alias).\n * - outcome score: `opts.scoreForTrace` (AppWorld `world.evaluate()` →\n * TGC/SGC) when supplied. Traces without an external task-quality signal\n * remain unlabeled; execution errors never become a task score.\n * - prompt / completion: carried into `raw` as token-count signals and,\n * when the first/last LLM span exposes `input.value` / `output.value`,\n * the verbatim text is preserved on the optional `promptText` /\n * `completionText` of the returned `OtlpTraceRunRecord`.\n *\n * Fail-loud: an OTLP file with zero valid spans throws. A trace with no\n * spans is impossible (a trace exists only because a span referenced it).\n * `validateRunRecord` runs on every row — a malformed projection throws\n * rather than silently producing a half-record.\n */\n\nimport {\n type RunCostProvenance,\n type RunRecord,\n type RunSplitTag,\n type RunTerminalOutcome,\n type RunTokenUsage,\n validateRunRecord,\n} from '../run-record'\nimport { summarizeTraceErrors, type TraceErrorRole } from '../trace/error-classification'\nimport {\n type MeasurementCoverage,\n recordAggregateMeasurements,\n summarizeExecutionMeasurements,\n} from '../trace/execution-measurements'\nimport {\n classifyOtlpSpanRole,\n isOtlpModelCall,\n LLM_MODEL_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { readTaskFailureLabels } from '../trace/task-failure-attributes'\nimport {\n compareSpanTime,\n firstStringAttr,\n type ProjectedOtlpSpan,\n projectOtlpFlatLine,\n spanEpochMillis,\n} from './otlp-span'\n\nexport interface OtlpToRunRecordsOptions {\n /** Logical experiment grouping for every produced record. */\n experimentId: string\n /** Candidate (variant) id — the surface these traces exercised. The\n * bench passes the proposer label here so `compareOptimizationMethods` can pair rows. */\n candidateId: string\n /** Split assignment for every produced record. Default `'holdout'` —\n * ingested traces are evidence, not the optimizer's training pool. */\n splitTag?: RunSplitTag\n /** Git SHA the traces were produced from. Default `'unknown'`. */\n commitSha?: string\n /** sha256 of the effective prompt surface. Default `'unknown'`. */\n promptHash?: string\n /** sha256 of the effective config. Default `'unknown'`. */\n configHash?: string\n /** RNG seed recorded on every row. Default 0. */\n seed?: number\n /**\n * Fallback model snapshot when the trace exposes no LLM model attribute\n * OR exposes a bare alias `validateRunRecord` would reject. The trace's\n * own model wins when it already carries a snapshot. Default\n * `'unknown@otlp'` (opaque-snapshot form the validator accepts).\n */\n fallbackModel?: string\n /**\n * USD per total token (input+output) used to price a trace when no\n * per-span cost attribute is present. When unset, an unpriced trace\n * records `costUsd: null` and `raw.cost_unpriced = 1`.\n */\n priceUsdPerToken?: number\n /**\n * Map each OTLP `trace_id` to the logical run it belongs to. Use this when a\n * provider emits several traces for one task attempt. All mapped traces are\n * aggregated into one record; duplicate span ids remain isolated by their\n * source trace. The callback must return a non-empty id for every trace.\n *\n * When omitted, every `trace_id` remains an independent run.\n */\n logicalRunIdForTrace?: (traceId: string) => string\n /**\n * Score for a produced run's outcome (AppWorld `world.evaluate()` →\n * TGC/SGC, or\n * any [0,1] task-success signal). Keyed by the logical run id when\n * `logicalRunIdForTrace` is supplied, otherwise by `trace_id`. When the map\n * has no entry or the function returns undefined, the record remains\n * unlabeled.\n */\n scoreForTrace?: (runId: string, span: TraceAggregate) => number | undefined\n /**\n * Per-record judge metadata when an external judge produced the score.\n * Keyed by the logical run id when supplied, otherwise by `trace_id`.\n */\n judgeMetadataForTrace?: (runId: string) => RunRecord['judgeMetadata'] | undefined\n}\n\n/** A `RunRecord` plus the verbatim prompt/completion text when the trace's\n * LLM spans exposed it. The text is NOT on the validated `RunRecord`\n * (`outcome.raw` is numeric-only) but consumers ingesting full traces want\n * it — so it rides alongside. */\nexport interface OtlpTraceRunRecord {\n record: RunRecord\n /** Verbatim first-LLM-span `input.value`, when present. */\n promptText?: string\n /** Verbatim last-LLM-span `output.value`, when present. */\n completionText?: string\n}\n\n/** Per-trace rollup the score callback can inspect. */\nexport interface TraceAggregate {\n traceId: string\n /** Number of source OTLP traces folded into this run. */\n sourceTraceCount: number\n /** Source OTLP trace ids folded into this run, sorted for deterministic audit output. */\n sourceTraceIds: readonly string[]\n spanCount: number\n llmSpanCount: number\n toolSpanCount: number\n agentSpanCount: number\n errorSpanCount: number\n executionErrorCount: number\n processErrorCount: number\n guardrailErrorCount: number\n judgeErrorCount: number\n propagatedErrorCount: number\n unclassifiedErrorCount: number\n tokenUsage: RunTokenUsage\n /** First error span's normalized status message, if any. */\n firstErrorMessage?: string\n model: string\n startTime: string\n endTime: string\n wallMs: number\n /** Root-span terminal result. Child span errors do not change this value. */\n terminalOutcome: RunTerminalOutcome\n}\n\ninterface AggregatedTrace extends TraceAggregate {\n callSpanIds: string[]\n costMeasurement: MeasurementCoverage\n aggregateMeasurement?: ReturnType<typeof summarizeExecutionMeasurements>['aggregate']\n terminalFailureMessage?: string\n}\n\n/**\n * Parse + aggregate an OTLP traces.jsonl string into validated\n * `RunRecord[]` (one per trace). Use {@link otlpToTraceRunRecords} when you\n * also want the verbatim prompt/completion text alongside each record.\n */\nexport function otlpToRunRecords(otlpJsonl: string, opts: OtlpToRunRecordsOptions): RunRecord[] {\n return otlpToTraceRunRecords(otlpJsonl, opts).map((r) => r.record)\n}\n\n/**\n * Aggregate already-parsed OTLP flat rows without serializing them back to\n * JSONL. This is the in-memory counterpart to {@link otlpToRunRecords}; both\n * paths share projection, reconciliation, validation, and ordering.\n */\nexport function otlpRowsToRunRecords(\n rows: Iterable<object>,\n opts: OtlpToRunRecordsOptions,\n): RunRecord[] {\n return otlpRowsToTraceRunRecords(rows, opts).map((row) => row.record)\n}\n\n/** As {@link otlpToRunRecords} but returns the prompt/completion text too. */\nexport function otlpToTraceRunRecords(\n otlpJsonl: string,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n return traceRunRecordsFromSpans(\n groupSpansByLogicalRun(groupJsonlSpansByTrace(otlpJsonl), opts.logicalRunIdForTrace),\n opts,\n )\n}\n\n/** Parsed-row counterpart to {@link otlpToTraceRunRecords}. */\nexport function otlpRowsToTraceRunRecords(\n rows: Iterable<object>,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n return traceRunRecordsFromSpans(\n groupSpansByLogicalRun(groupRowsByTrace(rows), opts.logicalRunIdForTrace),\n opts,\n )\n}\n\nfunction traceRunRecordsFromSpans(\n byTrace: Map<string, ProjectedOtlpSpan[]>,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n const splitTag = opts.splitTag ?? 'holdout'\n const commitSha = opts.commitSha ?? 'unknown'\n const promptHash = opts.promptHash ?? 'unknown'\n const configHash = opts.configHash ?? 'unknown'\n const seed = opts.seed ?? 0\n const fallbackModel = opts.fallbackModel ?? 'unknown@otlp'\n\n if (byTrace.size === 0) {\n throw new Error(\n 'otlpToRunRecords: OTLP input produced zero valid spans — every row was empty, malformed, or missing trace_id/span_id',\n )\n }\n\n // Stable trace order (insertion order of first appearance is preserved by\n // Map; sort by trace_id for determinism across producers).\n const traceIds = [...byTrace.keys()].sort()\n const out: OtlpTraceRunRecord[] = []\n\n for (const traceId of traceIds) {\n const spans = byTrace.get(traceId)!\n const agg = aggregateTrace(traceId, spans, fallbackModel)\n\n const score = resolveScore(opts, traceId, agg)\n const { costUsd, costProvenance } = resolveCost(opts, agg)\n\n const raw: Record<string, number> = {\n source_trace_count: agg.sourceTraceCount,\n span_count: agg.spanCount,\n llm_span_count: agg.llmSpanCount,\n tool_span_count: agg.toolSpanCount,\n agent_span_count: agg.agentSpanCount,\n error_span_count: agg.errorSpanCount,\n execution_error_count: agg.executionErrorCount,\n process_error_count: agg.processErrorCount,\n guardrail_error_count: agg.guardrailErrorCount,\n judge_error_count: agg.judgeErrorCount,\n propagated_error_count: agg.propagatedErrorCount,\n unclassified_error_count: agg.unclassifiedErrorCount,\n prompt_tokens: agg.tokenUsage.input,\n completion_tokens: agg.tokenUsage.output,\n }\n if (agg.tokenUsage.reasoning !== undefined) raw.reasoning_tokens = agg.tokenUsage.reasoning\n if (agg.tokenUsage.cached !== undefined) raw.cached_tokens = agg.tokenUsage.cached\n if (agg.tokenUsage.cacheWrite !== undefined) {\n raw.cache_write_tokens = agg.tokenUsage.cacheWrite\n }\n if (agg.costMeasurement.value !== undefined && !agg.costMeasurement.complete) {\n raw.partial_observed_cost_usd = agg.costMeasurement.value\n }\n recordAggregateMeasurements(raw, agg.aggregateMeasurement)\n if (costProvenance.kind === 'uncaptured') raw.cost_unpriced = 1\n\n const outcome: RunRecord['outcome'] = { raw }\n if (score !== undefined) {\n if (splitTag === 'holdout') outcome.holdoutScore = score\n else outcome.searchScore = score\n }\n\n const { promptText, completionText } = extractPromptCompletion(spans, agg.callSpanIds)\n const judgeMetadata = opts.judgeMetadataForTrace?.(traceId)\n const taskFailure = readTaskFailureLabels(\n spans.filter((span) => span.parent_span_id === null && isTerminalRootCandidate(span)),\n `otlpToRunRecords: run '${traceId}'`,\n )\n\n const record = validateRunRecord({\n runId: `otlp:${opts.experimentId}:${opts.candidateId}:${traceId}`,\n experimentId: opts.experimentId,\n candidateId: opts.candidateId,\n seed,\n model: ensureSnapshot(agg.model, fallbackModel),\n promptHash,\n configHash,\n commitSha,\n wallMs: agg.wallMs,\n costUsd,\n costProvenance,\n tokenUsage: agg.tokenUsage,\n terminalOutcome: agg.terminalOutcome,\n ...(agg.terminalFailureMessage ? { terminalFailureReason: agg.terminalFailureMessage } : {}),\n ...(judgeMetadata ? { judgeMetadata } : {}),\n outcome,\n ...taskFailure,\n splitTag,\n scenarioId: traceId,\n })\n\n out.push({\n record,\n ...(promptText !== undefined ? { promptText } : {}),\n ...(completionText !== undefined ? { completionText } : {}),\n })\n }\n\n return out\n}\n\n// ── Internals ──────────────────────────────────────────────────────────\n\nfunction* yieldJsonlRows(otlpJsonl: string): Iterable<Record<string, unknown>> {\n for (const line of otlpJsonl.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n // Tolerate a stray malformed line — mirrors the store's index, which\n // skips unparseable lines rather than nuking a whole dataset. A file\n // that is ENTIRELY malformed still throws (zero valid spans).\n continue\n }\n if (parsed && typeof parsed === 'object') yield parsed as Record<string, unknown>\n }\n}\n\nfunction groupJsonlSpansByTrace(otlpJsonl: string): Map<string, ProjectedOtlpSpan[]> {\n return groupRowsByTrace(yieldJsonlRows(otlpJsonl))\n}\n\nfunction groupRowsByTrace(rows: Iterable<object>): Map<string, ProjectedOtlpSpan[]> {\n const byTrace = new Map<string, ProjectedOtlpSpan[]>()\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue\n const span = projectOtlpFlatLine(row as Record<string, unknown>)\n if (!span) continue\n const arr = byTrace.get(span.trace_id)\n if (arr) arr.push(span)\n else byTrace.set(span.trace_id, [span])\n }\n return byTrace\n}\n\nfunction groupSpansByLogicalRun(\n byTrace: Map<string, ProjectedOtlpSpan[]>,\n logicalRunIdForTrace: OtlpToRunRecordsOptions['logicalRunIdForTrace'],\n): Map<string, ProjectedOtlpSpan[]> {\n if (!logicalRunIdForTrace) return byTrace\n\n const byRun = new Map<string, ProjectedOtlpSpan[]>()\n for (const [traceId, spans] of byTrace) {\n const suppliedRunId = logicalRunIdForTrace(traceId)\n if (typeof suppliedRunId !== 'string' || suppliedRunId.trim().length === 0) {\n throw new Error(\n `otlpToRunRecords: logicalRunIdForTrace('${traceId}') returned an empty run id`,\n )\n }\n const runId = suppliedRunId.trim()\n const target = byRun.get(runId) ?? []\n for (const span of spans) {\n target.push({\n ...span,\n span_id: qualifySpanId(traceId, span.span_id),\n parent_span_id: span.parent_span_id ? qualifySpanId(traceId, span.parent_span_id) : null,\n })\n }\n byRun.set(runId, target)\n }\n return byRun\n}\n\nfunction qualifySpanId(traceId: string, spanId: string): string {\n const prefix = `${traceId}:`\n return spanId.startsWith(prefix) ? spanId : `${prefix}${spanId}`\n}\n\nfunction aggregateTrace(\n traceId: string,\n spans: ProjectedOtlpSpan[],\n fallbackModel: string,\n): AggregatedTrace {\n // Span order within a trace is by start time (epoch-aware across ISO/epoch\n // dialects), then a stable tiebreak.\n const ordered = [...spans].sort(\n (a, b) => compareSpanTime(a.start_time, b.start_time) || a.span_id.localeCompare(b.span_id),\n )\n\n const measurements = summarizeExecutionMeasurements(\n ordered.map((span) => ({\n id: span.span_id,\n ...(span.parent_span_id ? { parentId: span.parent_span_id } : {}),\n attributes: span.attributes,\n modelCall: isOtlpModelCall({\n kind: span.kind,\n name: span.name,\n attributes: span.attributes,\n }),\n aggregate: span.kind !== 'LLM' && span.kind !== 'UNKNOWN',\n })),\n )\n let toolSpanCount = 0\n let agentSpanCount = 0\n let firstErrorMessage: string | undefined\n const modelVotes = new Map<string, number>()\n let earliest = ordered[0]?.start_time ?? ''\n let latest = ordered[0]?.end_time ?? ''\n\n for (const s of ordered) {\n if (s.start_time && (!earliest || compareSpanTime(s.start_time, earliest) < 0))\n earliest = s.start_time\n if (s.end_time && (!latest || compareSpanTime(s.end_time, latest) > 0)) latest = s.end_time\n\n if (s.kind === 'TOOL') {\n toolSpanCount += 1\n } else if (s.kind === 'AGENT') {\n agentSpanCount += 1\n }\n\n if (s.status === 'ERROR') {\n if (firstErrorMessage === undefined) {\n firstErrorMessage = (s.status_message ?? `${s.name} — STATUS_CODE_ERROR`).slice(0, 500)\n }\n }\n }\n\n const callSpanIds = new Set(measurements.callSpanIds)\n for (const span of ordered) {\n if (!callSpanIds.has(span.span_id)) continue\n const model = firstStringAttr(span.attributes, LLM_MODEL_ATTR_KEYS) ?? span.model_name\n if (model) modelVotes.set(model, (modelVotes.get(model) ?? 0) + 1)\n }\n\n // Dominant model across LLM spans; falls back to any model attribute on a\n // non-LLM span, then the supplied fallback snapshot.\n const model = topVote(modelVotes) ?? firstModelAttr(ordered) ?? fallbackModel\n\n let wallMs = 0\n // epoch-aware: Date.parse returns NaN for a bare epoch-millis string, which\n // silently zeroed wallMs for traces emitted with epoch timestamps.\n const a = spanEpochMillis(earliest)\n const b = spanEpochMillis(latest)\n if (a !== null && b !== null) wallMs = Math.max(0, b - a)\n\n const sourceTraceIds = [...new Set(spans.map((span) => span.trace_id))].sort()\n\n const terminal = terminalEvidenceFromRoots(ordered)\n const errorSummary = summarizeTraceErrors(\n ordered.map((span) => ({\n id: span.span_id,\n ...(span.parent_span_id ? { parentId: span.parent_span_id } : {}),\n role: errorRoleForProjectedSpan(span),\n error: span.status === 'ERROR',\n processRoot: span.parent_span_id === null && isTerminalRootCandidate(span),\n })),\n )\n return {\n traceId,\n sourceTraceCount: sourceTraceIds.length,\n sourceTraceIds,\n spanCount: spans.length,\n llmSpanCount: measurements.modelCallCount,\n toolSpanCount,\n agentSpanCount,\n errorSpanCount: errorSummary.total,\n executionErrorCount: errorSummary.execution,\n processErrorCount: errorSummary.process,\n guardrailErrorCount: errorSummary.guardrail,\n judgeErrorCount: errorSummary.evaluation,\n propagatedErrorCount: errorSummary.propagated,\n unclassifiedErrorCount: errorSummary.unclassified,\n tokenUsage: measurements.tokenUsage,\n firstErrorMessage,\n model,\n startTime: earliest,\n endTime: latest,\n wallMs,\n terminalOutcome: terminal.outcome,\n ...(terminal.failureMessage ? { terminalFailureMessage: terminal.failureMessage } : {}),\n callSpanIds: measurements.callSpanIds,\n costMeasurement: measurements.cost,\n ...(measurements.aggregate ? { aggregateMeasurement: measurements.aggregate } : {}),\n }\n}\n\nfunction terminalEvidenceFromRoots(spans: ProjectedOtlpSpan[]): {\n outcome: RunTerminalOutcome\n failureMessage?: string\n} {\n const roots = spans.filter(\n (span) => span.parent_span_id === null && isTerminalRootCandidate(span),\n )\n if (roots.length !== 1) return { outcome: 'unknown' }\n const root = roots[0]!\n if (root.status === 'ERROR') {\n return {\n outcome: 'failed',\n failureMessage: (root.status_message ?? `${root.name} — STATUS_CODE_ERROR`).slice(0, 500),\n }\n }\n if (root.status === 'OK') return { outcome: 'succeeded' }\n return { outcome: 'unknown' }\n}\n\nfunction isTerminalRootCandidate(span: ProjectedOtlpSpan): boolean {\n const role = errorRoleForProjectedSpan(span)\n return role !== 'LLM' && role !== 'TOOL' && role !== 'EVALUATOR' && role !== 'GUARDRAIL'\n}\n\nfunction errorRoleForProjectedSpan(span: ProjectedOtlpSpan): TraceErrorRole {\n return classifyOtlpSpanRole({\n kind: span.kind,\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction resolveScore(\n opts: OtlpToRunRecordsOptions,\n traceId: string,\n agg: TraceAggregate,\n): number | undefined {\n const supplied = opts.scoreForTrace?.(traceId, agg)\n if (supplied !== undefined) {\n if (!Number.isFinite(supplied)) {\n throw new Error(\n `otlpToRunRecords: scoreForTrace('${traceId}') returned non-finite ${supplied}`,\n )\n }\n return supplied\n }\n return undefined\n}\n\nfunction resolveCost(\n opts: OtlpToRunRecordsOptions,\n agg: AggregatedTrace,\n): { costUsd: number | null; costProvenance: RunCostProvenance } {\n const observedCost = agg.costMeasurement\n if (observedCost.complete && observedCost.value !== undefined) {\n return {\n costUsd: observedCost.value,\n costProvenance: { kind: 'observed', usd: observedCost.value },\n }\n }\n if (agg.aggregateMeasurement?.costUsd !== undefined) {\n return {\n costUsd: agg.aggregateMeasurement.costUsd,\n costProvenance: { kind: 'observed', usd: agg.aggregateMeasurement.costUsd },\n }\n }\n\n if (opts.priceUsdPerToken !== undefined) {\n const totalTokens = agg.tokenUsage.input + agg.tokenUsage.output\n const costUsd = totalTokens * opts.priceUsdPerToken\n return { costUsd, costProvenance: { kind: 'estimated', usd: costUsd } }\n }\n\n return { costUsd: null, costProvenance: { kind: 'uncaptured', usd: null } }\n}\n\nfunction extractPromptCompletion(\n spans: ProjectedOtlpSpan[],\n callSpanIds: string[],\n): {\n promptText?: string\n completionText?: string\n} {\n const callIds = new Set(callSpanIds)\n const measuredCalls = spans.filter((span) => callIds.has(span.span_id))\n const llm = (\n measuredCalls.length > 0 ? measuredCalls : spans.filter((s) => s.kind === 'LLM')\n ).sort(\n (a, b) => compareSpanTime(a.start_time, b.start_time) || a.span_id.localeCompare(b.span_id),\n )\n if (llm.length === 0) return {}\n const promptText =\n firstStringAttr(llm[0]!.attributes, ['input.value', 'llm.input_messages', 'gen_ai.prompt']) ??\n undefined\n const last = llm[llm.length - 1]!\n const completionText =\n firstStringAttr(last.attributes, [\n 'output.value',\n 'llm.output_messages',\n 'gen_ai.completion',\n ]) ?? undefined\n return {\n ...(promptText !== undefined ? { promptText } : {}),\n ...(completionText !== undefined ? { completionText } : {}),\n }\n}\n\nfunction topVote(votes: Map<string, number>): string | null {\n let best: string | null = null\n let bestN = 0\n for (const [k, n] of votes) {\n // Strict > keeps the higher count; lexicographic tie-break makes the winner\n // independent of Map insertion order (reproducible across producers).\n if (n > bestN || (n === bestN && best !== null && k < best)) {\n best = k\n bestN = n\n }\n }\n return best\n}\n\nfunction firstModelAttr(spans: ProjectedOtlpSpan[]): string | null {\n for (const s of spans) {\n const m = firstStringAttr(s.attributes, LLM_MODEL_ATTR_KEYS) ?? s.model_name\n if (m) return m\n }\n return null\n}\n\n/**\n * `validateRunRecord` rejects bare model aliases (`gpt-4o`) that remap\n * silently. AppWorld/HALO traces frequently carry such bare ids (or a null\n * model). When the model already encodes a snapshot we keep it; otherwise we\n * append the fallback snapshot token so the row is admissible without lying\n * about the model — the bare base name is preserved verbatim before `@`.\n */\nfunction ensureSnapshot(model: string, fallbackModel: string): string {\n if (modelHasSnapshot(model)) return model\n const fallbackTag = fallbackModel.includes('@')\n ? fallbackModel.slice(fallbackModel.indexOf('@'))\n : '@otlp'\n return `${model}${fallbackTag}`\n}\n\nfunction modelHasSnapshot(model: string): boolean {\n if (model.includes('@')) return true\n if (/-\\d{8}$/.test(model)) return true\n if (/-\\d{4}-\\d{2}-\\d{2}$/.test(model)) return true\n if (/:date-/.test(model)) return true\n return false\n}\n","/**\n * TraceStore — persistence + query over the TraceSchema v1 corpus.\n *\n * Two implementations ship in the core:\n * - InMemoryTraceStore: dev + tests, fully in-process\n * - FileSystemTraceStore: NDJSON append-only files per entity, suitable\n * for long-running CI jobs; rolled over at 32MB\n *\n * Downstream adapters (DuckDB, Langfuse, R2 parquet) implement this same\n * interface — the rest of the framework is storage-agnostic.\n */\n\nimport type {\n Artifact,\n BudgetLedgerEntry,\n EventKind,\n Run,\n RunStatus,\n Span,\n SpanKind,\n TraceEvent,\n} from './schema'\n\nexport interface RunFilter {\n scenarioId?: string\n variantId?: string\n status?: RunStatus\n since?: number\n until?: number\n tag?: { key: string; value: string }\n parentRunId?: string\n projectId?: string\n chatId?: string\n layer?: import('./schema').RunLayer\n}\n\nexport interface SpanFilter {\n runId?: string\n parentSpanId?: string\n kind?: SpanKind\n name?: string\n toolName?: string\n judgeId?: string\n since?: number\n until?: number\n}\n\nexport interface EventFilter {\n runId?: string\n spanId?: string\n kind?: EventKind\n since?: number\n until?: number\n}\n\nexport interface TraceStore {\n appendRun(run: Run): Promise<void>\n updateRun(runId: string, patch: Partial<Run>): Promise<void>\n appendSpan(span: Span): Promise<void>\n updateSpan(spanId: string, patch: Partial<Span>): Promise<void>\n appendEvent(event: TraceEvent): Promise<void>\n appendArtifact(artifact: Artifact): Promise<void>\n appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>\n\n getRun(runId: string): Promise<Run | undefined>\n listRuns(filter?: RunFilter): Promise<Run[]>\n spans(filter?: SpanFilter): Promise<Span[]>\n events(filter?: EventFilter): Promise<TraceEvent[]>\n budget(runId: string): Promise<BudgetLedgerEntry[]>\n artifacts(runId: string): Promise<Artifact[]>\n}\n\n// ── In-memory ────────────────────────────────────────────────────────\n\nexport class InMemoryTraceStore implements TraceStore {\n private runs = new Map<string, Run>()\n private allSpans: Span[] = []\n private allEvents: TraceEvent[] = []\n private allArtifacts: Artifact[] = []\n private allBudget: BudgetLedgerEntry[] = []\n\n async appendRun(run: Run): Promise<void> {\n if (this.runs.has(run.runId)) throw new Error(`run ${run.runId} already exists`)\n this.runs.set(run.runId, { ...run })\n }\n\n async updateRun(runId: string, patch: Partial<Run>): Promise<void> {\n const existing = this.runs.get(runId)\n if (!existing) throw new Error(`run ${runId} not found`)\n this.runs.set(runId, { ...existing, ...patch })\n }\n\n async appendSpan(span: Span): Promise<void> {\n this.allSpans.push({ ...span })\n }\n\n async updateSpan(spanId: string, patch: Partial<Span>): Promise<void> {\n const idx = this.allSpans.findIndex((s) => s.spanId === spanId)\n if (idx < 0) throw new Error(`span ${spanId} not found`)\n this.allSpans[idx] = { ...this.allSpans[idx], ...patch } as Span\n }\n\n async appendEvent(event: TraceEvent): Promise<void> {\n this.allEvents.push({ ...event })\n }\n\n async appendArtifact(artifact: Artifact): Promise<void> {\n this.allArtifacts.push({ ...artifact })\n }\n\n async appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void> {\n this.allBudget.push({ ...entry })\n }\n\n async getRun(runId: string): Promise<Run | undefined> {\n const r = this.runs.get(runId)\n return r ? { ...r } : undefined\n }\n\n async listRuns(filter: RunFilter = {}): Promise<Run[]> {\n return [...this.runs.values()].filter((r) => matchesRun(r, filter))\n }\n\n async spans(filter: SpanFilter = {}): Promise<Span[]> {\n return this.allSpans.filter((s) => matchesSpan(s, filter)).map((s) => ({ ...s }))\n }\n\n async events(filter: EventFilter = {}): Promise<TraceEvent[]> {\n return this.allEvents.filter((e) => matchesEvent(e, filter)).map((e) => ({ ...e }))\n }\n\n async budget(runId: string): Promise<BudgetLedgerEntry[]> {\n return this.allBudget.filter((b) => b.runId === runId).map((b) => ({ ...b }))\n }\n\n async artifacts(runId: string): Promise<Artifact[]> {\n return this.allArtifacts.filter((a) => a.runId === runId).map((a) => ({ ...a }))\n }\n}\n\nfunction matchesRun(r: Run, f: RunFilter): boolean {\n if (f.scenarioId && r.scenarioId !== f.scenarioId) return false\n if (f.variantId && r.variantId !== f.variantId) return false\n if (f.status && r.status !== f.status) return false\n if (f.since !== undefined && r.startedAt < f.since) return false\n if (f.until !== undefined && r.startedAt > f.until) return false\n if (f.tag && r.tags?.[f.tag.key] !== f.tag.value) return false\n if (f.parentRunId && r.parentRunId !== f.parentRunId) return false\n if (f.projectId && r.projectId !== f.projectId) return false\n if (f.chatId && r.chatId !== f.chatId) return false\n if (f.layer && r.layer !== f.layer) return false\n return true\n}\n\nfunction matchesSpan(s: Span, f: SpanFilter): boolean {\n if (f.runId && s.runId !== f.runId) return false\n if (f.parentSpanId && s.parentSpanId !== f.parentSpanId) return false\n if (f.kind && s.kind !== f.kind) return false\n if (f.name && s.name !== f.name) return false\n if (f.toolName && (s.kind !== 'tool' || s.toolName !== f.toolName)) return false\n if (f.judgeId && (s.kind !== 'judge' || s.judgeId !== f.judgeId)) return false\n if (f.since !== undefined && s.startedAt < f.since) return false\n if (f.until !== undefined && s.startedAt > f.until) return false\n return true\n}\n\nfunction matchesEvent(e: TraceEvent, f: EventFilter): boolean {\n if (f.runId && e.runId !== f.runId) return false\n if (f.spanId && e.spanId !== f.spanId) return false\n if (f.kind && e.kind !== f.kind) return false\n if (f.since !== undefined && e.timestamp < f.since) return false\n if (f.until !== undefined && e.timestamp > f.until) return false\n return true\n}\n\n// ── Filesystem (NDJSON append-only, one file per entity) ─────────────\n\nexport interface FileSystemTraceStoreOptions {\n dir: string\n /** Roll over NDJSON files when they exceed this size in bytes. Default 32 MB. */\n maxBytes?: number\n}\n\nexport class FileSystemTraceStore implements TraceStore {\n private dir: string\n private maxBytes: number\n /** Lazy in-memory index for queries — populated on first read. */\n private index?: InMemoryTraceStore\n /** Memoized index build — concurrent first reads share one build, and an\n * append racing an in-flight load awaits this so its row isn't lost. */\n private indexPromise?: Promise<InMemoryTraceStore>\n /** Strictly-increasing rollover stamp. Date.now() alone collides when two\n * rollovers land in the same millisecond, overwriting a rolled file. */\n private lastRolloverStamp = 0\n /**\n * Per-file append serialization. stat → conditional-rename → appendFile is a\n * read-modify-write on the active file; without a lock two concurrent appends\n * to the same `name` can both pass the size check (exceeding maxBytes) or one\n * can append to a file the other just renamed away. Each entry chains the\n * next append behind the prior one for that file.\n */\n private appendLocks = new Map<string, Promise<void>>()\n\n constructor(options: FileSystemTraceStoreOptions) {\n this.dir = options.dir\n this.maxBytes = options.maxBytes ?? 32 * 1024 * 1024\n }\n\n private async ensureDir(): Promise<void> {\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n }\n\n private async append(name: string, record: unknown): Promise<void> {\n // If an index load is in flight, wait for it. The row must hit disk AFTER\n // the load finished reading, so it lands in the completed index via the\n // mirror below — never lost in the gap before `this.index` is assigned.\n if (this.indexPromise) await this.indexPromise\n // Chain this append behind any in-flight append for the same file. The tail\n // promise never rejects (errors are isolated to each caller's `result`), so\n // one failed append can't break the lock chain for the next one.\n const prior = this.appendLocks.get(name) ?? Promise.resolve()\n const result = prior.then(() => this.appendLocked(name, record))\n const tail = result.then(\n () => {},\n () => {},\n )\n this.appendLocks.set(name, tail)\n try {\n await result\n } finally {\n // Drop the slot once this append is the current tail, so the map doesn't\n // grow without bound across many appends to the same file.\n if (this.appendLocks.get(name) === tail) this.appendLocks.delete(name)\n }\n }\n\n private async appendLocked(name: string, record: unknown): Promise<void> {\n await this.ensureDir()\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const active = path.join(this.dir, `${name}.ndjson`)\n try {\n const stat = await fs.stat(active)\n if (stat.size >= this.maxBytes) {\n // Strictly-increasing, collision-free even within one millisecond — a\n // bare Date.now() would let two same-ms rollovers overwrite each other.\n const stamp = Math.max(Date.now(), this.lastRolloverStamp + 1)\n this.lastRolloverStamp = stamp\n const rolled = path.join(this.dir, `${name}.${stamp}.ndjson`)\n await fs.rename(active, rolled)\n }\n } catch {\n /* file doesn't exist yet */\n }\n await fs.appendFile(active, `${JSON.stringify(record)}\\n`, 'utf8')\n // Mirror genuinely-new rows into the lazy index. Update rows (marked\n // with `_update: true` by updateRun/updateSpan) are applied by those\n // methods directly via the index's update* APIs — re-inserting them\n // here triggers a duplicate-id error once the first read populates\n // the index. Await the mirror: a fire-and-forget would let an index\n // rejection go unhandled and let disk + index diverge silently.\n if (this.index && !(record as { _update?: boolean })?._update) {\n await this.insertInto(name, record)\n }\n }\n\n private async insertInto(name: string, record: unknown): Promise<void> {\n if (!this.index) return\n switch (name) {\n case 'runs':\n await this.index.appendRun(record as Run)\n break\n case 'spans':\n await this.index.appendSpan(record as Span)\n break\n case 'events':\n await this.index.appendEvent(record as TraceEvent)\n break\n case 'artifacts':\n await this.index.appendArtifact(record as Artifact)\n break\n case 'budget':\n await this.index.appendBudgetEntry(record as BudgetLedgerEntry)\n break\n }\n }\n\n private load(): Promise<InMemoryTraceStore> {\n // Memoize: concurrent first reads share one build, and an append racing an\n // in-flight load awaits this same promise (see append()).\n this.indexPromise ??= this.buildIndex()\n return this.indexPromise\n }\n\n private async buildIndex(): Promise<InMemoryTraceStore> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n const store = new InMemoryTraceStore()\n let entries: string[]\n try {\n entries = await fs.readdir(this.dir)\n } catch {\n // No dir yet (first run / empty corpus). Anything past this point — parse\n // errors, missing patch bases — is real corruption and must fail loud.\n this.index = store\n return store\n }\n // Replay files in write order. For one entity, rolled files\n // (`name.<ts>.ndjson`) are older than the active bare file (`name.ndjson`),\n // and readdir order is not chronological — so without this sort a patch in\n // an older rolled file could be applied AFTER (overwrite) a newer patch in\n // the active file, silently restoring a stale field. Sort: per entity,\n // rolled ascending by timestamp, then the bare active file last.\n entries.sort((a, b) => {\n // Group by the same entity base the loop uses (`split('.')[0]`); within an\n // entity, real rollover files (`<base>.<ms>.ndjson`) sort by timestamp\n // ascending and the bare active file (no numeric segment) sorts last.\n // Non-rollover names tie (Infinity) and a stable sort preserves their\n // readdir order.\n const baseA = a.split('.')[0]!\n const baseB = b.split('.')[0]!\n if (baseA !== baseB) return baseA < baseB ? -1 : 1\n const ta = a.match(/^[^.]+\\.(\\d+)\\.ndjson$/)\n const tb = b.match(/^[^.]+\\.(\\d+)\\.ndjson$/)\n const tsA = ta ? Number(ta[1]) : Number.POSITIVE_INFINITY\n const tsB = tb ? Number(tb[1]) : Number.POSITIVE_INFINITY\n return tsA - tsB\n })\n {\n // Two-pass load. Pass 1 indexes all full (base) rows; pass 2 replays the\n // `_update` patch rows that updateRun/updateSpan append. readdir order is\n // not deterministic and rollover splits a stream across files, so a patch\n // can be read before its base. Applying patches in a separate pass — after\n // every base row is indexed — means a patch always finds its target.\n // Doing it in one pass let a patch hit the catch and append a runId-less\n // fragment, corrupting span/run counts cross-instance.\n const runUpdates: Array<Record<string, unknown>> = []\n const spanUpdates: Array<Record<string, unknown>> = []\n for (const file of entries) {\n if (!file.endsWith('.ndjson')) continue\n const full = path.join(this.dir, file)\n const content = await fs.readFile(full, 'utf8')\n const base = file.split('.')[0]\n const lines = content.split('\\n')\n for (let ln = 0; ln < lines.length; ln++) {\n const line = lines[ln]!\n if (!line.trim()) continue\n let record: ReturnType<typeof JSON.parse>\n try {\n record = JSON.parse(line)\n } catch (err) {\n // Fail loud WITH context — a bare SyntaxError loses which file/line\n // is corrupt and which valid rows surround it.\n throw new Error(\n `FileSystemTraceStore: corrupt NDJSON in ${file} line ${ln + 1}: ${\n err instanceof Error ? err.message : String(err)\n } — ${line.slice(0, 120)}`,\n )\n }\n if (base === 'runs') {\n if (record?._update) {\n runUpdates.push(record)\n continue\n }\n // A duplicate full row (same dir loaded twice into one stream) is\n // collapsed last-write-wins rather than thrown.\n try {\n await store.appendRun(record)\n } catch {\n await store.updateRun(record.runId, record)\n }\n } else if (base === 'spans') {\n // `updateSpan` appends an `_update: true` patch row instead of\n // rewriting the original span. Deferred to pass 2 so it collapses\n // onto the original span — otherwise a fresh FileSystemTraceStore\n // reading the same dir reports duplicate spans (one full, one\n // fragment with no runId/kind/name), which breaks any downstream\n // consumer that re-opens the store cross-process (e.g. the OTLP\n // converter).\n if (record?._update) {\n spanUpdates.push(record)\n continue\n }\n await store.appendSpan(record)\n } else if (base === 'events') {\n await store.appendEvent(record)\n } else if (base === 'artifacts') {\n await store.appendArtifact(record)\n } else if (base === 'budget') {\n await store.appendBudgetEntry(record)\n }\n }\n }\n // Pass 2: every base row is now indexed. A patch whose base is genuinely\n // absent (truncated/partial corpus) throws inside update* — we let it\n // propagate rather than silently appending a fragment, so a corrupt\n // corpus fails loud instead of polluting counts.\n for (const record of runUpdates) {\n await store.updateRun(record.runId as string, record as Partial<Run>)\n }\n for (const record of spanUpdates) {\n await store.updateSpan(record.spanId as string, record as Partial<Span>)\n }\n }\n this.index = store\n return store\n }\n\n async appendRun(run: Run): Promise<void> {\n await this.append('runs', run)\n }\n async updateRun(runId: string, patch: Partial<Run>): Promise<void> {\n // NDJSON is append-only; record updates as new rows with the same runId —\n // readers collapse by last-write-wins on load.\n await this.append('runs', { runId, ...patch, _update: true })\n if (this.index) await this.index.updateRun(runId, patch)\n }\n async appendSpan(span: Span): Promise<void> {\n await this.append('spans', span)\n }\n async updateSpan(spanId: string, patch: Partial<Span>): Promise<void> {\n await this.append('spans', { spanId, ...patch, _update: true })\n if (this.index) await this.index.updateSpan(spanId, patch)\n }\n async appendEvent(event: TraceEvent): Promise<void> {\n await this.append('events', event)\n }\n async appendArtifact(artifact: Artifact): Promise<void> {\n await this.append('artifacts', artifact)\n }\n async appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void> {\n await this.append('budget', entry)\n }\n\n async getRun(runId: string): Promise<Run | undefined> {\n return (await this.load()).getRun(runId)\n }\n async listRuns(filter?: RunFilter): Promise<Run[]> {\n return (await this.load()).listRuns(filter)\n }\n async spans(filter?: SpanFilter): Promise<Span[]> {\n return (await this.load()).spans(filter)\n }\n async events(filter?: EventFilter): Promise<TraceEvent[]> {\n return (await this.load()).events(filter)\n }\n async budget(runId: string): Promise<BudgetLedgerEntry[]> {\n return (await this.load()).budget(runId)\n }\n async artifacts(runId: string): Promise<Artifact[]> {\n return (await this.load()).artifacts(runId)\n }\n}\n","/**\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 * 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 type { Run, Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\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: toAttributes({\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: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToNs(span.startedAt),\n endTimeUnixNano: msToNs(endedAt),\n attributes: toAttributes(flattenSpanAttributes(span)),\n events: events.map((e) => ({\n timeUnixNano: msToNs(e.timestamp),\n name: e.kind,\n attributes: toAttributes(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 toAttributes(record: Record<string, string | number | boolean>): OtlpSpan['attributes'] {\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\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n // OTLP wants 16-hex spanIds. UUIDs are 32-hex; strip dashes and take first 16.\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction runToTraceId(run: Run): string {\n // OTLP wants 32-hex traceIds. Use runId directly when it's 32-hex already,\n // else SHA-ish truncate.\n const cleaned = run.runId.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n","/**\n * OTEL bridge — connects TraceEmitter span lifecycle to the OtelExporter.\n *\n * When an OtelExporter is active, every span that closes through the\n * TraceEmitter is also pushed to the exporter for real-time streaming to\n * the user's OTEL collector.\n *\n * The bridge is opt-in: attach via `otelRunCompleteHook(exporter)` as a\n * RunCompleteHook, or wrap the store with `createOtelTracingStore` for\n * real-time per-span export.\n */\n\nimport type { RunCompleteHook } from './emitter'\nimport type { ExportableSpan, OtelExporter } from './otel-export'\nimport type { LlmSpan, Span, ToolSpan } from './schema'\nimport type { TraceStore } from './store'\n\n/**\n * Create a RunCompleteHook that exports all spans from the completed run\n * to the OTEL exporter, then flushes.\n */\nexport function otelRunCompleteHook(exporter: OtelExporter): RunCompleteHook {\n return async (ctx) => {\n const spans = await ctx.store.spans({ runId: ctx.runId })\n for (const span of spans) {\n if (span.endedAt) {\n exporter.exportSpan(storeSpanToExportable(span, ctx.runId))\n }\n }\n await exporter.flush()\n }\n}\n\n/**\n * Create an auto-exporting TraceStore wrapper that intercepts updateSpan\n * calls. When a span gets an endedAt, it's exported immediately. This\n * gives real-time streaming instead of batch-at-end.\n *\n * This is the preferred integration path: wrap the store before\n * constructing the TraceEmitter.\n */\nexport function createOtelTracingStore(\n inner: TraceStore,\n exporter: OtelExporter,\n traceId: string,\n): TraceStore {\n return {\n async appendRun(run) {\n return inner.appendRun(run)\n },\n async updateRun(runId, patch) {\n return inner.updateRun(runId, patch)\n },\n async appendSpan(span) {\n if (span.endedAt) {\n exporter.exportSpan(storeSpanToExportable(span, traceId))\n }\n return inner.appendSpan(span)\n },\n async updateSpan(spanId, patch) {\n await inner.updateSpan(spanId, patch)\n if (patch.endedAt) {\n const spans = await inner.spans({ runId: traceId })\n const found = spans.find((s) => s.spanId === spanId)\n if (found) {\n exporter.exportSpan(storeSpanToExportable(found, traceId))\n }\n }\n },\n async appendEvent(event) {\n return inner.appendEvent(event)\n },\n async appendBudgetEntry(entry) {\n return inner.appendBudgetEntry(entry)\n },\n async appendArtifact(artifact) {\n return inner.appendArtifact(artifact)\n },\n getRun: inner.getRun.bind(inner),\n listRuns: inner.listRuns.bind(inner),\n spans: inner.spans.bind(inner),\n events: inner.events.bind(inner),\n budget: inner.budget.bind(inner),\n artifacts: inner.artifacts.bind(inner),\n }\n}\n\nfunction storeSpanToExportable(span: Span, traceId: string): ExportableSpan {\n const llm = span.kind === 'llm' ? (span as LlmSpan) : undefined\n const tool = span.kind === 'tool' ? (span as ToolSpan) : undefined\n return {\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: span.kind,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n status: span.status,\n error: span.error,\n model: llm?.model,\n inputTokens: llm?.inputTokens,\n outputTokens: llm?.outputTokens,\n reasoningTokens: llm?.reasoningTokens,\n cachedTokens: llm?.cachedTokens,\n cacheWriteTokens: llm?.cacheWriteTokens,\n costUsd: llm?.costUsd,\n tool: tool\n ? {\n toolName: tool.toolName,\n args: tool.args,\n argsCaptured: tool.argsCaptured,\n result: tool.result,\n latencyMs: tool.latencyMs,\n }\n : undefined,\n attributes: span.attributes as Record<string, unknown> | undefined,\n }\n}\n","/**\n * OTEL span exporter — streams spans to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Batches spans and flushes periodically\n * or when the batch fills. No @opentelemetry SDK dependency — minimal\n * OTLP/JSON serializer (~120 LOC) using the existing otel.ts helpers.\n */\n\nimport { OTEL_AGENT_EVAL_SCOPE, type OtlpExport, type OtlpSpan } from './otel'\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n type ToolSpanOtlpInput,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-eval'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Called by the TraceEmitter on every span close. */\n exportSpan(span: ExportableSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly — flushes remaining spans and stops the timer. */\n shutdown(): Promise<void>\n}\n\nexport interface ExportableSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: string\n startedAt: number\n endedAt?: number\n status?: string\n error?: string\n model?: string\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cachedTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n tool?: ToolSpanOtlpInput\n attributes?: Record<string, unknown>\n}\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured\n * (neither via config nor env) — callers should check before attaching.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-eval'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtlpSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: ExportableSpan): void {\n if (stopped) return\n pending.push(toOtlpSpan(span))\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n // Unref so the timer doesn't keep the process alive.\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the pipeline.\n }\n }\n\n return exporter\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toOtlpSpan(span: ExportableSpan): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n const attrs: 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') attrs[k] = v\n }\n }\n attrs[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n applyLlmSpanOtlpAttributes(attrs, span)\n if (span.tool) applyToolSpanOtlpAttributes(attrs, span.tool)\n return {\n traceId: padTraceId(span.traceId),\n spanId: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToNs(span.startedAt),\n endTimeUnixNano: msToNs(endedAt),\n attributes: toAttributes(attrs),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtlpSpan['attributes'] {\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\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n","/**\n * Convert agent-eval's internal trace shape (`FileSystemTraceStore` → `Run`,\n * `Span`, `TraceEvent`) into the OTLP-flat JSONL the trace analyst\n * (`analyzeTraces` + `OtlpFileTraceStore`) reads.\n *\n * Eval harnesses shard a `FileSystemTraceStore` per cell (persona / variant)\n * under a run directory. The analyst consumes a single OTLP-NDJSON file keyed\n * on `trace_id` + `span_id` with `start_time`/`end_time` in ISO-8601 and\n * resource + `attributes` rolled up per-span. This module walks every shard,\n * projects each `Span` (plus events pinned to it) into the flat OTLP shape,\n * and emits one NDJSON file.\n *\n * Generic OTLP/OpenInference fields are always emitted (`service.name`,\n * `agent.name`, `run.id`/`run.status`, `openinference.span.kind`,\n * `llm.model_name`, …). Domain attributes (`legal.*`, `tax.*`, …) are injected\n * per-run via {@link TraceStoreToOtlpOptions.resourceAttributes} /\n * {@link TraceStoreToOtlpOptions.runAttributes} so consumers don't re-roll the\n * walker.\n */\n\nimport { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport type { Run, Span, TraceEvent } from './schema'\n\n/** Marker `FileSystemTraceStore` stamps on partial-update NDJSON rows. */\ninterface MaybeUpdate {\n _update?: boolean\n}\n\ninterface OtlpFlatSpan {\n trace_id: string\n span_id: string\n parent_span_id: string\n name: string\n kind: string\n start_time: string\n end_time: string\n status: { code: 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR'; message: string }\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n}\n\nexport interface TracesToOtlpResult {\n /** Total spans emitted across every cell. */\n spanCount: number\n /** Total run-anchor spans (one per Run) appended for analyst visibility. */\n runCount: number\n /** Cells whose shards parsed cleanly. */\n cellCount: number\n /** Cells that errored mid-conversion — surfaced so a partial conversion\n * isn't silently masked. */\n cellErrorCount: number\n}\n\n/**\n * A trace source the analyst should ingest. Two layouts are supported:\n *\n * - `celled` (default): the root holds one cell subdirectory per\n * persona/variant, each a `FileSystemTraceStore` (`runs.ndjson`,\n * `spans.ndjson`, `events.ndjson`).\n * - `flat`: the root is itself a single `FileSystemTraceStore` (e.g. a\n * production-ingestion sidecar that appends one ndjson set directly under\n * the chosen directory).\n */\nexport interface TraceStoreSource {\n /** Absolute path to the trace store root. */\n root: string\n /** Layout — `celled` (default) or `flat`. */\n layout?: 'celled' | 'flat'\n /** OTLP `service.name` for this source. Overrides the options default. */\n serviceName?: string\n}\n\n/** Domain hooks. The walker is generic; consumers inject the namespaced\n * attributes that ride along on every run + span for analyst discovery. */\nexport interface TraceStoreToOtlpOptions {\n /** Default OTLP `service.name` when a source doesn't set its own.\n * Default `agent-eval`. */\n serviceName?: string\n /** Extra resource attributes per run, e.g.\n * `(run) => ({ 'legal.persona_id': run.tags?.personaId ?? '' })`. */\n resourceAttributes?: (run: Run) => Record<string, unknown>\n /** Extra attributes on the per-run anchor span, e.g. domain outcome fields. */\n runAttributes?: (run: Run) => Record<string, unknown>\n}\n\n/**\n * Read every per-cell shard under each source root and write a flat OTLP-JSONL\n * view of the corpus to `outPath`. Each cell directory is a\n * `FileSystemTraceStore` — NDJSON append-only with size-based rotation;\n * `updateRun`/`updateSpan` append `{ id, ...patch, _update: true }` rows\n * rather than rewriting, so readers must merge those patches in (done here).\n *\n * A `string` source is treated as a celled root.\n */\nexport function convertTraceStoresToOtlp(\n source: string | TraceStoreSource | readonly TraceStoreSource[],\n outPath: string,\n opts: TraceStoreToOtlpOptions = {},\n): TracesToOtlpResult {\n const sources: TraceStoreSource[] = Array.isArray(source)\n ? [...source]\n : typeof source === 'string'\n ? [{ root: source, layout: 'celled' }]\n : [source as TraceStoreSource]\n\n const defaultServiceName = opts.serviceName ?? 'agent-eval'\n const resourceAttributes = opts.resourceAttributes ?? (() => ({}))\n const runAttributes = opts.runAttributes ?? (() => ({}))\n\n const lines: string[] = []\n let spanCount = 0\n let runCount = 0\n let cellCount = 0\n let cellErrorCount = 0\n\n for (const src of sources) {\n const serviceName = src.serviceName ?? defaultServiceName\n const cellDirs: Array<{ label: string; dir: string }> =\n src.layout === 'flat'\n ? [{ label: '<root>', dir: src.root }]\n : listCells(src.root).map((name) => ({ label: name, dir: join(src.root, name) }))\n\n for (const cell of cellDirs) {\n try {\n const result = projectCell({\n cellDir: cell.dir,\n serviceName,\n resourceAttributes,\n runAttributes,\n })\n for (const line of result.lines) lines.push(line)\n spanCount += result.spanCount\n runCount += result.runCount\n cellCount += 1\n } catch (err) {\n console.warn(\n `[traces-to-otlp] cell ${cell.label} (${cell.dir}) skipped: ${err instanceof Error ? err.message : String(err)}`,\n )\n cellErrorCount += 1\n }\n }\n }\n\n writeFileSync(outPath, lines.join('\\n') + (lines.length > 0 ? '\\n' : ''))\n return { spanCount, runCount, cellCount, cellErrorCount }\n}\n\ninterface ProjectCellResult {\n lines: string[]\n runCount: number\n spanCount: number\n}\n\nfunction projectCell(args: {\n cellDir: string\n serviceName: string\n resourceAttributes: (run: Run) => Record<string, unknown>\n runAttributes: (run: Run) => Record<string, unknown>\n}): ProjectCellResult {\n const { cellDir, serviceName, resourceAttributes, runAttributes } = args\n const lines: string[] = []\n let runCount = 0\n let spanCount = 0\n\n const runs = readMergedShards<Run & MaybeUpdate>(cellDir, 'runs', 'runId')\n const spans = readMergedShards<Span & MaybeUpdate>(cellDir, 'spans', 'spanId')\n const events = readShards<TraceEvent>(cellDir, 'events')\n\n const runByRunId = new Map<string, Run>()\n for (const r of runs) runByRunId.set(r.runId, r)\n const spanBySpanId = new Map<string, Span>()\n for (const s of spans) spanBySpanId.set(s.spanId, s)\n const eventsBySpanId = new Map<string, TraceEvent[]>()\n\n // An HTTP-backed trace store can only POST `TraceEvent`s through the wire;\n // run/span lifecycle is projected into `state_mutation` events with\n // `payload.entity ∈ { run, run.update, span, span.update }`. Fold those back\n // so the analyst sees a complete Run + Span tree.\n for (const e of events) {\n if (e.kind === 'state_mutation' && e.payload && typeof e.payload === 'object') {\n const entity = (e.payload as Record<string, unknown>).entity\n if (entity === 'run') {\n const run = (e.payload as { run?: Run }).run\n if (run?.runId) runByRunId.set(run.runId, run)\n continue\n }\n if (entity === 'run.update') {\n const patch = (e.payload as { patch?: Partial<Run> }).patch\n if (patch && e.runId) {\n const prior = runByRunId.get(e.runId)\n if (prior) runByRunId.set(e.runId, { ...prior, ...patch })\n }\n continue\n }\n if (entity === 'span') {\n const span = (e.payload as { span?: Span }).span\n if (span?.spanId) spanBySpanId.set(span.spanId, span)\n continue\n }\n if (entity === 'span.update') {\n const spanId = (e.payload as { spanId?: string }).spanId\n const patch = (e.payload as { patch?: Partial<Span> }).patch\n if (spanId && patch) {\n const prior = spanBySpanId.get(spanId)\n if (prior) spanBySpanId.set(spanId, { ...prior, ...patch } as Span)\n }\n continue\n }\n }\n if (!e.spanId) continue\n const arr = eventsBySpanId.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpanId.set(e.spanId, arr)\n }\n\n for (const run of runByRunId.values()) {\n const traceId = padTraceId(run.runId)\n const agentName = run.variantId ?? run.scenarioId\n const sharedResource = {\n attributes: {\n 'service.name': serviceName,\n 'agent.name': agentName,\n 'run.id': run.runId,\n 'run.status': run.status,\n ...resourceAttributes(run),\n },\n }\n\n const runSpanId = padSpanId(`run-${run.runId}`)\n const runStart = msToIso(run.startedAt)\n const runEnd = msToIso(run.endedAt ?? run.startedAt)\n const runStatus =\n run.outcome?.failureClass && run.outcome.failureClass !== 'success'\n ? 'STATUS_CODE_ERROR'\n : 'STATUS_CODE_OK'\n const runAttrs: Record<string, unknown> = {\n [OPENINFERENCE_SPAN_KIND]: 'AGENT',\n 'agent.name': agentName,\n 'agent.workflow.name': serviceName,\n ...runAttributes(run),\n }\n lines.push(\n JSON.stringify(\n toLine({\n traceId,\n spanId: runSpanId,\n parentSpanId: '',\n name: `run.${agentName}`,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: runStart,\n endTime: runEnd,\n statusCode: runStatus,\n statusMessage: run.outcome?.notes ?? '',\n resource: sharedResource,\n attributes: runAttrs,\n }),\n ),\n )\n runCount += 1\n\n for (const span of spanBySpanId.values()) {\n if (span.runId !== run.runId) continue\n const spanAttrs = spanToAttributes(span, eventsBySpanId.get(span.spanId) ?? [])\n const statusCode = span.status === 'error' ? 'STATUS_CODE_ERROR' : 'STATUS_CODE_OK'\n lines.push(\n JSON.stringify(\n toLine({\n traceId,\n spanId: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : runSpanId,\n name: span.name,\n kind: spanKindToOtlpKind(span.kind),\n startTime: msToIso(span.startedAt),\n endTime: msToIso(span.endedAt ?? span.startedAt),\n statusCode,\n statusMessage: span.error ?? '',\n resource: sharedResource,\n attributes: spanAttrs,\n }),\n ),\n )\n spanCount += 1\n }\n }\n\n return { lines, runCount, spanCount }\n}\n\nfunction listCells(root: string): string[] {\n try {\n return readdirSync(root, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort()\n } catch {\n return []\n }\n}\n\n/**\n * Read every NDJSON shard for `name` under `cellDir`, ordered by mtime so\n * rotated files apply before the active one. Yields raw rows including any\n * `_update: true` patches.\n */\nfunction readShards<T>(cellDir: string, name: string): T[] {\n let entries: string[]\n try {\n entries = readdirSync(cellDir)\n } catch {\n return []\n }\n const shards = entries\n .filter((f) => (f === `${name}.ndjson` || f.startsWith(`${name}.`)) && f.endsWith('.ndjson'))\n .map((f) => ({ file: f, path: join(cellDir, f) }))\n .map((s) => {\n let mtime = 0\n try {\n mtime = statSync(s.path).mtimeMs\n } catch {\n /* skip stat errors */\n }\n return { ...s, mtime }\n })\n .sort((a, b) => a.mtime - b.mtime || a.file.localeCompare(b.file))\n\n const rows: T[] = []\n for (const shard of shards) {\n let text: string\n try {\n text = readFileSync(shard.path, 'utf-8')\n } catch {\n continue\n }\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n rows.push(JSON.parse(trimmed) as T)\n } catch {\n /* skip partial line */\n }\n }\n }\n return rows\n}\n\n/**\n * Read NDJSON shards and merge `{ ...patch, _update: true }` rows into the\n * prior record keyed on `idKey` — mirrors the in-memory merge\n * `FileSystemTraceStore` keeps but doesn't replay on cross-process load.\n */\nfunction readMergedShards<T extends { _update?: boolean }>(\n cellDir: string,\n name: string,\n idKey: keyof T,\n): T[] {\n const rows = readShards<T>(cellDir, name)\n const byId = new Map<string, T>()\n for (const row of rows) {\n const id = row[idKey] as unknown as string\n if (!id) continue\n const prior = byId.get(id)\n if (prior && row._update) {\n byId.set(id, { ...prior, ...row, _update: undefined } as T)\n } else {\n byId.set(id, row)\n }\n }\n return [...byId.values()]\n}\n\nfunction spanToAttributes(span: Span, events: TraceEvent[]): Record<string, unknown> {\n const attrs: Record<string, unknown> = {\n [OPENINFERENCE_SPAN_KIND]: traceSpanKindToOpenInferenceKind(span.kind),\n }\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(attrs, span)\n if (Array.isArray(span.messages)) {\n attrs['llm.input_messages'] = JSON.stringify(span.messages.slice(-6))\n }\n if (typeof span.output === 'string') {\n attrs['llm.output_messages'] = JSON.stringify([{ role: 'assistant', content: span.output }])\n }\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(attrs, span)\n } else if (span.kind === 'judge') {\n attrs['judge.id'] = span.judgeId\n attrs['judge.dimension'] = span.dimension\n attrs['judge.score'] = span.score\n attrs['judge.target_span_id'] = span.targetSpanId\n }\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n attrs[`agent_eval.${k}`] = v\n }\n }\n if (events.length > 0) {\n attrs['agent_eval.event_count'] = events.length\n attrs['agent_eval.event_kinds'] = JSON.stringify(events.map((e) => e.kind))\n }\n return attrs\n}\n\nfunction spanKindToOtlpKind(kind: Span['kind']): string {\n switch (kind) {\n case 'llm':\n return 'SPAN_KIND_CLIENT'\n case 'retrieval':\n return 'SPAN_KIND_CLIENT'\n default:\n return 'SPAN_KIND_INTERNAL'\n }\n}\n\ninterface ToLineArgs {\n traceId: string\n spanId: string\n parentSpanId: string\n name: string\n kind: string\n startTime: string\n endTime: string\n statusCode: 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR'\n statusMessage: string\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n}\n\nfunction toLine(args: ToLineArgs): OtlpFlatSpan {\n return {\n trace_id: args.traceId,\n span_id: args.spanId,\n parent_span_id: args.parentSpanId,\n name: args.name,\n kind: args.kind,\n start_time: args.startTime,\n end_time: args.endTime,\n status: { code: args.statusCode, message: args.statusMessage },\n resource: args.resource,\n attributes: args.attributes,\n }\n}\n\nfunction msToIso(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return new Date(0).toISOString()\n return new Date(ms).toISOString()\n}\n\n/** OTLP wants 16-hex span ids; eval traces use UUID-ish strings. Hex-strip +\n * take 16, else deterministic FNV fold. */\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/[^a-f0-9]/gi, '').toLowerCase()\n if (cleaned.length >= 16) return cleaned.slice(0, 16)\n return foldTo16Hex(id)\n}\n\n/** OTLP wants 32-hex trace ids; fold deterministically when too short. */\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/[^a-f0-9]/gi, '').toLowerCase()\n if (cleaned.length >= 32) return cleaned.slice(0, 32)\n return foldTo32Hex(id)\n}\n\nfunction foldTo16Hex(s: string): string {\n let h1 = 0x811c9dc5\n for (const ch of s) {\n h1 ^= ch.charCodeAt(0)\n h1 = Math.imul(h1, 0x01000193) >>> 0\n }\n const part = h1.toString(16).padStart(8, '0')\n return (part + part).slice(0, 16)\n}\n\nfunction foldTo32Hex(s: string): string {\n return foldTo16Hex(s) + foldTo16Hex(`${s}::trace`).slice(0, 16)\n}\n","/**\n * Replay-from-raw-events — turn every captured campaign run into a\n * re-runnable artifact.\n *\n * `RawProviderSink` captures every provider HTTP envelope; `runEvalCampaign`\n * makes that capture the default. Together they make every past run a\n * complete fingerprint of what happened on the wire — enough to replay\n * the run without burning new LLM cost.\n *\n * Three use cases this primitive enables:\n *\n * 1. **Post-hoc judging** — apply a new judge / rubric / scoring callback\n * to last week's runs without re-calling any LLM. The cost of trying\n * a new rubric drops from \"another full sweep\" to a CPU-bound replay.\n * 2. **Determinism audits** — replay the same campaign and verify the\n * raw responses match byte-for-byte. Any drift is a non-determinism\n * bug (in the harness, the prompt builder, the sandbox, …).\n * 3. **Free judge calibration** — run two judges on identical responses\n * and measure inter-judge agreement without doubling LLM spend.\n *\n * The interface is deliberately fetch-shaped. Inject `createReplayFetch`\n * into `LlmClientOptions.fetch` and every `callLlm` transparently reads\n * from the cache instead of calling the network. No new code path through\n * the LLM client is needed; the cache hit is invisible to the runner.\n */\n\nimport { ReplayError } from './errors'\nimport { canonicalize, hashJson } from './pre-registration'\nimport type { RawProviderEvent, RawProviderSink } from './trace/raw-provider-sink'\n\nexport class ReplayCacheMissError extends ReplayError {\n constructor(\n public readonly url: string,\n public readonly requestKey: string,\n message?: string,\n ) {\n super(message ?? `replay cache miss for ${url} (key=${requestKey})`)\n }\n}\n\nexport interface ReplayCacheEntry {\n request: RawProviderEvent\n response: RawProviderEvent\n}\n\nexport interface ReplayCacheStats {\n total: number\n byProvider: Record<string, number>\n byModel: Record<string, number>\n /** Spans for which we have a request but no response (run aborted mid-call). */\n orphanRequests: number\n}\n\n/**\n * In-memory deterministic cache of (request → response) keyed on a stable\n * hash of the request body. Built from a `RawProviderSink` containing\n * paired `request` and `response` events from a previous run.\n *\n * The cache is the source of truth for replay; `createReplayFetch` is a\n * thin wrapper that reads from it.\n */\nexport class ReplayCache {\n private byKey = new Map<string, ReplayCacheEntry>()\n private orphans = 0\n private byProvider: Record<string, number> = {}\n private byModel: Record<string, number> = {}\n\n /**\n * Build a cache from a sink's events. The sink must implement `list()`.\n * Filter by `runId` / `spanId` to scope to a specific replay.\n */\n static async fromSink(\n sink: RawProviderSink,\n filter: { runId?: string; spanId?: string } = {},\n ): Promise<ReplayCache> {\n if (!sink.list) {\n throw new ReplayError('ReplayCache.fromSink: sink must implement list() to be replayable.')\n }\n const events = await sink.list(filter)\n return ReplayCache.fromEvents(events)\n }\n\n /** Build a cache from an in-memory event list. */\n static async fromEvents(events: RawProviderEvent[]): Promise<ReplayCache> {\n const cache = new ReplayCache()\n // Group by (runId, spanId, attemptIndex) so request/response/error pairs are matched.\n // A cell can have many spans; each retry attempt within a span is a separate group.\n type GroupKey = string\n const groups = new Map<GroupKey, { req?: RawProviderEvent; res?: RawProviderEvent }>()\n for (const e of events) {\n const k = `${e.runId ?? ''}::${e.spanId ?? ''}::${e.attemptIndex}`\n const g = groups.get(k) ?? {}\n if (e.direction === 'request') g.req = e\n else g.res = e\n groups.set(k, g)\n }\n for (const g of groups.values()) {\n if (!g.req) continue\n if (!g.res) {\n cache.orphans += 1\n continue\n }\n const key = await requestKey(g.req)\n cache.byKey.set(key, { request: g.req, response: g.res })\n cache.byProvider[g.req.provider] = (cache.byProvider[g.req.provider] ?? 0) + 1\n cache.byModel[g.req.model] = (cache.byModel[g.req.model] ?? 0) + 1\n }\n return cache\n }\n\n /** Number of cacheable (request, response) pairs in the cache. */\n size(): number {\n return this.byKey.size\n }\n\n stats(): ReplayCacheStats {\n return {\n total: this.byKey.size,\n byProvider: { ...this.byProvider },\n byModel: { ...this.byModel },\n orphanRequests: this.orphans,\n }\n }\n\n /** Iterate every cached `(request, response)` pair in insertion order. */\n *entries(): IterableIterator<ReplayCacheEntry> {\n for (const entry of this.byKey.values()) yield entry\n }\n\n /**\n * Look up a cached response by hashing the (model, messages, temperature,\n * maxTokens, response_format) shape. Returns `undefined` on miss; the\n * caller decides whether to throw, fall back to the network, or skip.\n */\n async lookup(requestBody: unknown): Promise<ReplayCacheEntry | undefined> {\n const key = await keyFromBody(requestBody)\n return this.byKey.get(key)\n }\n}\n\nexport interface ReplayFetchOptions {\n /**\n * Behaviour on cache miss. Default `'throw'`. `'fallback'` calls the\n * `fallbackFetch` (typically `globalThis.fetch`) so a partial replay can\n * still complete; `'fail-closed'` returns a synthetic 599 response so the\n * call site sees a non-retriable failure.\n */\n onMiss?: 'throw' | 'fallback' | 'fail-closed'\n fallbackFetch?: typeof fetch\n /** Optional callback fired once per replayed call (for telemetry / counters). */\n onHit?: (info: { url: string; provider: string; model: string }) => void\n /** Optional callback fired on cache miss before the `onMiss` policy applies. */\n onMissNotify?: (info: { url: string; requestBody: unknown }) => void\n}\n\n/**\n * Build a `fetch`-shaped function that serves cached responses out of a\n * `ReplayCache` for any URL ending in `/chat/completions`. Pass through\n * `LlmClientOptions.fetch` and `callLlm` becomes free.\n *\n * Non-`/chat/completions` URLs are passed straight to the fallback fetch\n * (default: `globalThis.fetch`). This matters because non-LLM HTTP work\n * (judge HTTP servers, sandbox callbacks) sometimes flows through the same\n * `fetch` and shouldn't be intercepted.\n */\nexport function createReplayFetch(cache: ReplayCache, opts: ReplayFetchOptions = {}): typeof fetch {\n const onMiss = opts.onMiss ?? 'throw'\n const fallback = opts.fallbackFetch ?? globalThis.fetch?.bind(globalThis)\n\n return (async (input: RequestInfo | URL, init?: RequestInit) => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n if (!/\\/chat\\/completions(?:[?#].*)?$/.test(url)) {\n if (!fallback)\n throw new ReplayError(\n `replay fetch: non-completions URL ${url} but no fallbackFetch configured`,\n )\n return fallback(input as RequestInfo, init)\n }\n let bodyParsed: unknown\n if (init?.body && typeof init.body === 'string') {\n try {\n bodyParsed = JSON.parse(init.body)\n } catch {\n /* raw body, not JSON */\n }\n }\n const hit = bodyParsed === undefined ? undefined : await cache.lookup(bodyParsed)\n if (hit) {\n opts.onHit?.({ url, provider: hit.request.provider, model: hit.request.model })\n const status = hit.response.statusCode ?? 200\n const headers = new Headers(\n Object.entries(hit.response.responseHeaders ?? { 'Content-Type': 'application/json' }),\n )\n const bodyText =\n typeof hit.response.responseBody === 'string'\n ? hit.response.responseBody\n : JSON.stringify(hit.response.responseBody ?? {})\n return new Response(bodyText, { status, headers })\n }\n opts.onMissNotify?.({ url, requestBody: bodyParsed })\n if (onMiss === 'throw') {\n const key = bodyParsed === undefined ? '<unparseable>' : await keyFromBody(bodyParsed)\n throw new ReplayCacheMissError(url, key)\n }\n if (onMiss === 'fail-closed') {\n return new Response(JSON.stringify({ error: 'replay_cache_miss' }), { status: 599 })\n }\n if (!fallback)\n throw new ReplayError('replay fetch: onMiss=fallback but no fallbackFetch configured')\n return fallback(input as RequestInfo, init)\n }) as typeof fetch\n}\n\n/**\n * Convenience iterator over `(request, response)` pairs in a sink — for\n * post-hoc scoring that doesn't need a `fetch` shim. The judge or scorer\n * runs purely in-process over cached LLM outputs.\n */\nexport async function* iterateRawCalls(\n sink: RawProviderSink,\n filter: { runId?: string; spanId?: string } = {},\n): AsyncGenerator<ReplayCacheEntry> {\n if (!sink.list) {\n throw new ReplayError('iterateRawCalls: sink must implement list().')\n }\n const events = await sink.list(filter)\n const cache = await ReplayCache.fromEvents(events)\n for (const entry of cache.entries()) yield entry\n}\n\n// ── Hashing ──────────────────────────────────────────────────────────────\n\n/**\n * Canonical request key.\n *\n * `model + messages + temperature + max_tokens|max_completion_tokens +\n * response_format` are the dimensions that affect the response shape.\n * Other fields (timestamp headers, provider-specific metadata) are\n * intentionally excluded so a request hashes the same across re-runs.\n */\nasync function requestKey(event: RawProviderEvent): Promise<string> {\n return keyFromBody(event.requestBody)\n}\n\nasync function keyFromBody(body: unknown): Promise<string> {\n if (body == null || typeof body !== 'object') return hashJson({ raw: String(body) })\n const b = body as Record<string, unknown>\n const reduced = canonicalize({\n model: b.model ?? null,\n messages: b.messages ?? null,\n temperature: b.temperature ?? null,\n max_tokens: b.max_tokens ?? null,\n max_completion_tokens: b.max_completion_tokens ?? null,\n response_format: b.response_format ?? null,\n })\n return hashJson(reduced)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAM,mBACJ;AAEK,SAAS,0BAA0B,MAAgD;AACxF,SAAO,OAAO,QAAgC;AAC5C,QAAI,KAAK,aAAa,CAAC,KAAK,UAAU,GAAG,EAAG;AAC5C,UAAM,SAAS,KAAK,QAAQ;AAC5B,QAAI,W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