@tangle-network/agent-eval 0.203.2 → 0.205.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 (126) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/analyst/index.d.ts +1 -1
  3. package/dist/analyst/index.d.ts.map +1 -1
  4. package/dist/analyst/index.js +5 -5
  5. package/dist/{analyze-runs-BrIibNd0.js → analyze-runs-d5dcMlxi.js} +9 -9
  6. package/dist/{analyze-runs-BrIibNd0.js.map → analyze-runs-d5dcMlxi.js.map} +1 -1
  7. package/dist/baseline-Dm8966du.js +259 -0
  8. package/dist/baseline-Dm8966du.js.map +1 -0
  9. package/dist/{benchmark-command-6OBcB0sG.js → benchmark-command-BQhi_BVO.js} +9 -6
  10. package/dist/benchmark-command-BQhi_BVO.js.map +1 -0
  11. package/dist/benchmarks/index.js +2 -2
  12. package/dist/builder-eval/index.js +1 -1
  13. package/dist/campaign/index.js +9 -9
  14. package/dist/{campaign-DYhg4SjN.js → campaign-0lmkAMpE.js} +11 -11
  15. package/dist/{campaign-DYhg4SjN.js.map → campaign-0lmkAMpE.js.map} +1 -1
  16. package/dist/{campaign-evidence-Dt_rWPk2.js → campaign-evidence-C__cUpCt.js} +2 -2
  17. package/dist/{campaign-evidence-Dt_rWPk2.js.map → campaign-evidence-C__cUpCt.js.map} +1 -1
  18. package/dist/cli.js +5 -5
  19. package/dist/contract/index.js +10 -10
  20. package/dist/{default-registry-wInsQWlQ.js → default-registry-BthquIoC.js} +2 -2
  21. package/dist/{default-registry-wInsQWlQ.js.map → default-registry-BthquIoC.js.map} +1 -1
  22. package/dist/{define-agent-eval-B25Cc3ki.js → define-agent-eval-CeYrXpl7.js} +4 -4
  23. package/dist/{define-agent-eval-B25Cc3ki.js.map → define-agent-eval-CeYrXpl7.js.map} +1 -1
  24. package/dist/{descriptive-D9LUFk1-.js → descriptive-CnU8Yq29.js} +2 -2
  25. package/dist/{descriptive-D9LUFk1-.js.map → descriptive-CnU8Yq29.js.map} +1 -1
  26. package/dist/diagnosis/index.js +1 -1
  27. package/dist/{dspy-rlm-engine-D0h-P2Mz.js → dspy-rlm-engine-DCQKNQMn.js} +2 -2
  28. package/dist/{dspy-rlm-engine-D0h-P2Mz.js.map → dspy-rlm-engine-DCQKNQMn.js.map} +1 -1
  29. package/dist/{eval-campaign-ha_aWtk7.js → eval-campaign-DsRmYsQI.js} +2 -2
  30. package/dist/{eval-campaign-ha_aWtk7.js.map → eval-campaign-DsRmYsQI.js.map} +1 -1
  31. package/dist/experiment/index.js +9 -9
  32. package/dist/index.d.ts +61 -3
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +102 -25
  35. package/dist/index.js.map +1 -1
  36. package/dist/{internal-BOe3zmjQ.js → internal-CRHwS9iz.js} +3 -3
  37. package/dist/internal-CRHwS9iz.js.map +1 -0
  38. package/dist/jev.js +1 -1
  39. package/dist/judge-calibration-DFtEMlde.d.ts.map +1 -1
  40. package/dist/{judge-calibration-C5zgtiJT.js → judge-calibration-N44V04Se.js} +7 -17
  41. package/dist/judge-calibration-N44V04Se.js.map +1 -0
  42. package/dist/{kind-factory-CdPPHtGZ.js → kind-factory-Cn1lbsAd.js} +5 -5
  43. package/dist/kind-factory-Cn1lbsAd.js.map +1 -0
  44. package/dist/{llm-judge-DyZdrp6I.js → llm-judge-Bka5q-ds.js} +8 -8
  45. package/dist/{llm-judge-DyZdrp6I.js.map → llm-judge-Bka5q-ds.js.map} +1 -1
  46. package/dist/matrix/index.js +1 -1
  47. package/dist/{matrix-DnlHn5x1.js → matrix-_BV9-Lk5.js} +12 -9
  48. package/dist/matrix-_BV9-Lk5.js.map +1 -0
  49. package/dist/meta-eval/index.js +2 -2
  50. package/dist/multishot/golden/index.js +1 -1
  51. package/dist/multishot/index.js +1 -1
  52. package/dist/normal-DsJZtrJc.js +25 -0
  53. package/dist/normal-DsJZtrJc.js.map +1 -0
  54. package/dist/openapi.json +1 -1
  55. package/dist/{paired-arms-DpS_h8ON.js → paired-arms-Dsu-r6xd.js} +6 -27
  56. package/dist/paired-arms-Dsu-r6xd.js.map +1 -0
  57. package/dist/{paired-binary-OMBVRtc-.js → paired-binary-DpwwK1fU.js} +2 -2
  58. package/dist/{paired-binary-OMBVRtc-.js.map → paired-binary-DpwwK1fU.js.map} +1 -1
  59. package/dist/{paired-promotion-decision-DhrmjdV8.js → paired-promotion-decision-CO0kA0bq.js} +3 -3
  60. package/dist/{paired-promotion-decision-DhrmjdV8.js.map → paired-promotion-decision-CO0kA0bq.js.map} +1 -1
  61. package/dist/{paired-tests-Ccr16gcW.js → paired-tests-jbwPdSz5.js} +3 -3
  62. package/dist/{paired-tests-Ccr16gcW.js.map → paired-tests-jbwPdSz5.js.map} +1 -1
  63. package/dist/pipelines/index.d.ts +1 -1
  64. package/dist/pipelines/index.js +2 -2
  65. package/dist/{power-and-mde-bie6i965.js → power-and-mde-fK5Qocwo.js} +3 -3
  66. package/dist/{power-and-mde-bie6i965.js.map → power-and-mde-fK5Qocwo.js.map} +1 -1
  67. package/dist/{produced-state-DLToUXrD.js → produced-state-FdbE-88t.js} +3 -3
  68. package/dist/{produced-state-DLToUXrD.js.map → produced-state-FdbE-88t.js.map} +1 -1
  69. package/dist/{promotion-policy-BI1RxzwD.js → promotion-policy-BSbTAMtE.js} +4 -4
  70. package/dist/{promotion-policy-BI1RxzwD.js.map → promotion-policy-BSbTAMtE.js.map} +1 -1
  71. package/dist/quantile--0yb07pD.js +15 -0
  72. package/dist/quantile--0yb07pD.js.map +1 -0
  73. package/dist/{report-command-D0XL2Cvi.js → report-command-JrjiWReS.js} +2 -2
  74. package/dist/{report-command-D0XL2Cvi.js.map → report-command-JrjiWReS.js.map} +1 -1
  75. package/dist/reporting.js +4 -4
  76. package/dist/{reward-hacking-C-a__ShZ.js → reward-hacking-BFcQgkux.js} +2 -2
  77. package/dist/{reward-hacking-C-a__ShZ.js.map → reward-hacking-BFcQgkux.js.map} +1 -1
  78. package/dist/rl.js +7 -7
  79. package/dist/{rubric-predictive-validity-B0Pg-3I5.js → rubric-predictive-validity-BsgkBfT0.js} +3 -3
  80. package/dist/{rubric-predictive-validity-B0Pg-3I5.js.map → rubric-predictive-validity-BsgkBfT0.js.map} +1 -1
  81. package/dist/search/index.js +2 -2
  82. package/dist/{search-kernel-Dpniloks.js → search-kernel-CsISc5t8.js} +5 -5
  83. package/dist/{search-kernel-Dpniloks.js.map → search-kernel-CsISc5t8.js.map} +1 -1
  84. package/dist/{search-summary-C1nAHgkB.js → search-summary-BZkoLwbB.js} +4 -4
  85. package/dist/{search-summary-C1nAHgkB.js.map → search-summary-BZkoLwbB.js.map} +1 -1
  86. package/dist/{semantic-concept-judge-BgWxa4L_.js → semantic-concept-judge-BbiYuv7U.js} +3 -3
  87. package/dist/{semantic-concept-judge-BgWxa4L_.js.map → semantic-concept-judge-BbiYuv7U.js.map} +1 -1
  88. package/dist/{sequential-DWn_np6P.js → sequential-7uxpO0Vm.js} +2 -2
  89. package/dist/{sequential-DWn_np6P.js.map → sequential-7uxpO0Vm.js.map} +1 -1
  90. package/dist/{skillopt-optimization-method-Dz5CGZb8.js → skillopt-optimization-method-bEm4jYV4.js} +4 -4
  91. package/dist/{skillopt-optimization-method-Dz5CGZb8.js.map → skillopt-optimization-method-bEm4jYV4.js.map} +1 -1
  92. package/dist/{statistical-heldout-CNLOvRq_.js → statistical-heldout-C26hOFWD.js} +3 -3
  93. package/dist/{statistical-heldout-CNLOvRq_.js.map → statistical-heldout-C26hOFWD.js.map} +1 -1
  94. package/dist/{store-otlp-yd9lDziN.js → store-otlp-BA7G1Du-.js} +44 -11
  95. package/dist/store-otlp-BA7G1Du-.js.map +1 -0
  96. package/dist/{store-tool-spans-CAF3T-BS.d.ts → store-tool-spans-BYIarVrG.d.ts} +17 -8
  97. package/dist/{store-tool-spans-CAF3T-BS.d.ts.map → store-tool-spans-BYIarVrG.d.ts.map} +1 -1
  98. package/dist/{store-tool-spans-D5kOU0mr.js → store-tool-spans-DKoVbE-w.js} +3 -3
  99. package/dist/{store-tool-spans-D5kOU0mr.js.map → store-tool-spans-DKoVbE-w.js.map} +1 -1
  100. package/dist/{student-t-BBZYka0E.js → student-t-BQeKJx2N.js} +2 -2
  101. package/dist/{student-t-BBZYka0E.js.map → student-t-BQeKJx2N.js.map} +1 -1
  102. package/dist/{summary-report-DLzptLSA.js → summary-report-BG6-hOkm.js} +6 -6
  103. package/dist/{summary-report-DLzptLSA.js.map → summary-report-BG6-hOkm.js.map} +1 -1
  104. package/dist/supervisor-run/index.js +1 -1
  105. package/dist/{tool-waste-CP5DO383.d.ts → tool-waste-DxlebQkx.d.ts} +42 -2
  106. package/dist/tool-waste-DxlebQkx.d.ts.map +1 -0
  107. package/dist/{tool-waste-B-u3rzCz.js → tool-waste-x_E8h9Ih.js} +3 -3
  108. package/dist/{tool-waste-B-u3rzCz.js.map → tool-waste-x_E8h9Ih.js.map} +1 -1
  109. package/dist/trace-repair/index.js +1 -1
  110. package/dist/traces.d.ts +2 -2
  111. package/dist/traces.js +4 -4
  112. package/dist/{tree-D48IJUK0.js → tree-CAQflhLR.js} +5 -5
  113. package/dist/{tree-D48IJUK0.js.map → tree-CAQflhLR.js.map} +1 -1
  114. package/docs/concepts.md +21 -0
  115. package/docs/trace-analysis.md +10 -0
  116. package/package.json +1 -1
  117. package/dist/baseline-CVKsfWTg.js +0 -150
  118. package/dist/baseline-CVKsfWTg.js.map +0 -1
  119. package/dist/benchmark-command-6OBcB0sG.js.map +0 -1
  120. package/dist/internal-BOe3zmjQ.js.map +0 -1
  121. package/dist/judge-calibration-C5zgtiJT.js.map +0 -1
  122. package/dist/kind-factory-CdPPHtGZ.js.map +0 -1
  123. package/dist/matrix-DnlHn5x1.js.map +0 -1
  124. package/dist/paired-arms-DpS_h8ON.js.map +0 -1
  125. package/dist/store-otlp-yd9lDziN.js.map +0 -1
  126. package/dist/tool-waste-CP5DO383.d.ts.map +0 -1
@@ -1,5 +1,5 @@
1
- import { r as pairedBootstrap } from "./paired-tests-Ccr16gcW.js";
2
- import { t as decidePairedPromotion } from "./paired-promotion-decision-DhrmjdV8.js";
1
+ import { r as pairedBootstrap } from "./paired-tests-jbwPdSz5.js";
2
+ import { t as decidePairedPromotion } from "./paired-promotion-decision-CO0kA0bq.js";
3
3
  //#region src/campaign/gates/statistical-heldout.ts
4
4
  /**
5
5
  * Held-out inference pairs execution cells and judge identities before taking
@@ -253,4 +253,4 @@ function dimensionRegressions(candidate, baseline, scenarioIds, criticalDimensio
253
253
  //#endregion
254
254
  export { heldoutSignificance as a, dimensionRegressions as i, aggregatePairedHoldout as n, pairHoldout as o, detectScale as r, TIE_WARN_FRACTION as t };
255
255
 
256
- //# sourceMappingURL=statistical-heldout-CNLOvRq_.js.map
256
+ //# sourceMappingURL=statistical-heldout-C26hOFWD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"statistical-heldout-CNLOvRq_.js","names":[],"sources":["../src/campaign/gates/statistical-heldout.ts"],"sourcesContent":["/**\n * Held-out inference pairs execution cells and judge identities before taking\n * means within registered independent units. Repetitions can improve a unit's\n * precision without increasing n. Ungrouped inference concerns independently\n * sampled execution cells conditional on a fixed scenario roster.\n *\n * The shared paired decision rule selects the estimator and statistical test.\n * Dimension reports retain missing coverage so required safety checks cannot\n * pass through absent evidence. Thresholds use the judge's native score scale.\n */\n\nimport {\n decidePairedPromotion,\n type PairedDecisionMethod,\n type PairedDecisionStatistic,\n type PairedMcNemarEvidence,\n type PairedPromotionDecision,\n} from '../../paired-promotion-decision'\nimport {\n DECISION_PAIRED_DELTA_STATISTIC,\n type PairedBootstrapResult,\n pairedBootstrap,\n} from '../../statistics'\nimport type { JudgeScore } from '../types'\n\n/** Tie fraction at/above which a gate annotates its verdict with the tie share.\n * Tie-domination of the median bites structurally at >= 0.5 (the median is then\n * 0 by construction); 0.4 is a softer warn threshold that flags a run APPROACHING\n * that regime, so an operator sees it before the median goes fully blind. */\nexport const TIE_WARN_FRACTION = 0.4\n\nexport interface PairedHoldout {\n /** Baseline scalar per paired cell (same order as `after`/`cellIds`). */\n before: number[]\n /** Candidate scalar per paired cell. */\n after: number[]\n /** The full cellIds (`scenario:rep`) that paired, in order. */\n cellIds: string[]\n}\n\n/** Campaign cell IDs append a numeric repetition after the scenario's full ID. */\nexport function scenarioIdFromCellId(cellId: string): string {\n const separator = cellId.lastIndexOf(':')\n const repetition = cellId.slice(separator + 1)\n if (\n separator < 1 ||\n cellId.trim() !== cellId ||\n !/^(0|[1-9]\\d*)$/.test(repetition) ||\n !Number.isSafeInteger(Number(repetition))\n ) {\n throw new Error(`pairHoldout: malformed cellId '${cellId}'; expected scenarioId:rep`)\n }\n return cellId.slice(0, separator)\n}\n\n/** Preserve cell pairing before taking equal-weight independent-unit means. */\nexport function aggregatePairedHoldout(\n paired: PairedHoldout,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n): { before: number[]; after: number[]; unitIds: string[] } {\n if (\n paired.before.length !== paired.after.length ||\n paired.before.length !== paired.cellIds.length\n ) {\n throw new Error('aggregatePairedHoldout: scores and cellIds must have the same length')\n }\n if (new Set(paired.cellIds).size !== paired.cellIds.length) {\n throw new Error('aggregatePairedHoldout: duplicate cellIds cannot count as new observations')\n }\n if (\n paired.before.some((value) => !Number.isFinite(value)) ||\n paired.after.some((value) => !Number.isFinite(value))\n ) {\n throw new Error('aggregatePairedHoldout: paired scores must be finite')\n }\n if (independentUnitByScenarioId === undefined) {\n return { before: [...paired.before], after: [...paired.after], unitIds: [...paired.cellIds] }\n }\n const scenarioIds = paired.cellIds.map(scenarioIdFromCellId)\n const groups = new Map<string, { before: number; after: number; n: number }>()\n for (let i = 0; i < paired.cellIds.length; i++) {\n const scenarioId = scenarioIds[i]!\n const unitId = independentUnitByScenarioId.get(scenarioId)\n if (typeof unitId !== 'string' || unitId.length === 0 || unitId.trim() !== unitId) {\n throw new Error(\n `aggregatePairedHoldout: missing independent unit for scenario '${scenarioId}'`,\n )\n }\n const group = groups.get(unitId) ?? { before: 0, after: 0, n: 0 }\n group.before += paired.before[i]!\n group.after += paired.after[i]!\n group.n += 1\n groups.set(unitId, group)\n }\n const unitIds = [...groups.keys()].sort()\n return {\n before: unitIds.map((id) => groups.get(id)!.before / groups.get(id)!.n),\n after: unitIds.map((id) => groups.get(id)!.after / groups.get(id)!.n),\n unitIds,\n }\n}\n\n/**\n * Pair candidate vs baseline holdout observations by FULL cellId. `select`\n * pulls the scalar from a cell's judge reports (composite, or a named\n * dimension); a cell contributes the mean of `select` across its judges. Cells\n * whose scenario is not in `scenarioIds`, or where `select` is undefined for\n * every judge on both sides, are skipped. The selected judge IDs must agree\n * within each pair. Throws when the two maps disagree on holdout cell IDs — a\n * load-bearing invariant: the baseline + winner holdout campaigns run the same\n * scenarios with the same seed base, so their cellIds MUST align; a mismatch\n * means a silent pairing bug, not a soft fallback.\n */\nexport function pairHoldout(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n select: (s: JudgeScore) => number | undefined,\n): PairedHoldout {\n const cellValues = (\n byCell: Map<string, Record<string, JudgeScore>>,\n cellId: string,\n ): Map<string, number> => {\n const scores = byCell.get(cellId)\n const values = new Map<string, number>()\n if (!scores) return values\n for (const [judgeId, s] of Object.entries(scores)) {\n if (s.failed === true) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a failed judge score`)\n }\n const v = select(s)\n if (typeof v === 'number' && !Number.isFinite(v)) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a non-finite selected score`)\n }\n if (typeof v === 'number') values.set(judgeId, v)\n }\n return values\n }\n\n const inScope = (cellId: string) => scenarioIds.has(scenarioIdFromCellId(cellId))\n const candCells = [...candidate.keys()].filter(inScope).sort()\n const baseCells = [...baseline.keys()].filter(inScope).sort()\n // Alignment invariant — the holdout campaigns share scenarios + seed, so the\n // cell sets must be identical. Differ ⇒ a real pairing bug; fail loud.\n if (candCells.length !== baseCells.length || candCells.some((c, i) => c !== baseCells[i])) {\n throw new Error(\n `pairHoldout: candidate/baseline holdout cells do not align — ` +\n `candidate=[${candCells.join(',')}] baseline=[${baseCells.join(',')}]. ` +\n `Both holdout campaigns must run the same scenarios with the same seed base.`,\n )\n }\n\n const before: number[] = []\n const after: number[] = []\n const cellIds: string[] = []\n for (const cellId of candCells) {\n const b = cellValues(baseline, cellId)\n const a = cellValues(candidate, cellId)\n // A scalar absent on both sides means that dimension was not scored. A\n // one-sided absence is asymmetric evidence loss, never a row to discard.\n if (b.size === 0 && a.size === 0) continue\n if (b.size === 0 || a.size === 0) {\n throw new Error(`pairHoldout: cell '${cellId}' has a selected score on only one arm`)\n }\n if (b.size !== a.size || [...b.keys()].some((id) => !a.has(id))) {\n throw new Error(`pairHoldout: cell '${cellId}' selected judge IDs do not align`)\n }\n const judgeIds = [...b.keys()].sort()\n before.push(meanSelectedScores(judgeIds.map((id) => b.get(id)!)))\n after.push(meanSelectedScores(judgeIds.map((id) => a.get(id)!)))\n cellIds.push(cellId)\n }\n return { before, after, cellIds }\n}\n\nfunction meanSelectedScores(values: number[]): number {\n const first = values[0]!\n // Summing identical fractional scores can round their mean outside the\n // declared binary support. An agreeing judge set preserves its exact value.\n return values.every((value) => value === first)\n ? first\n : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nexport interface HeldoutSignificance {\n paired: PairedHoldout\n /**\n * The paired bootstrap on the requested statistic (MEAN by default — see the\n * tie note on `heldoutSignificance`).\n *\n * DIAGNOSTIC, not necessarily the interval the verdict keyed on. On a\n * two-point (pass/fail) outcome the decision routes to Tango's score interval\n * instead, because a percentile bootstrap of the mean over a three-atom\n * lattice is not a valid interval at a nonzero margin. Read\n * `decision.low`/`decision.high` for the interval that actually decided, and\n * `decisionStatistic` for which one it is.\n */\n bootstrap: PairedBootstrapResult\n /** The MEDIAN paired-delta bootstrap, reported as a diagnostic. When many\n * scenarios are tied (both sides solve them), the median is pinned near 0\n * regardless of the mean lift — comparing the two exposes tie-domination. */\n medianBootstrap: PairedBootstrapResult\n /**\n * The full promotion decision: which estimator the outcome's shape admits,\n * the interval it produced, McNemar's exact veto on the two-point path, and\n * whether the interval was zero-width (no evidence in either direction). The\n * single source of `significant`.\n */\n decision: PairedPromotionDecision\n /** Which paired estimator the verdict was decided on. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on the two-point path; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** Fraction of paired observations that are exact ties (|delta| < 1e-9). A\n * high tie fraction is WHY a median-based gate would have missed a real lift;\n * it is the observability the tie fix adds. */\n tieFraction: number\n /** Number of paired observation units, after configured aggregation. */\n n: number\n /** Original matched execution cells, before aggregation. */\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Registered unit IDs, or cell IDs on the ungrouped path. */\n unitIds: string[]\n /** Effective minimum for the requested target and chosen estimator. */\n minimumRequired: number\n /** Statistical method that carried the decision. */\n decisionMethod: PairedDecisionMethod\n /** Exact one-sided p-value on the small-sample path; otherwise null. */\n pValue: number | null\n /** True iff n >= minimumRequired, the DECIDING interval has nonzero width,\n * its lower bound clears the threshold, and McNemar's exact test does not\n * veto at a non-negative threshold. */\n significant: boolean\n /** Set when n < minimumRequired — too little evidence to claim significance. */\n fewRuns: boolean\n}\n\nexport interface HeldoutSignificanceOptions {\n deltaThreshold?: number\n minProductiveRuns?: number\n confidence?: number\n resamples?: number\n /** Fixed by default for a deterministic, reproducible gate verdict. */\n seed?: number\n statistic?: 'mean' | 'median'\n /** Group full cell pairs into equal-weight independent units before inference. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * Significance of the held-out composite lift: ship only when the lower bound\n * of the interval the outcome's shape ADMITS exceeds `deltaThreshold` (default\n * 0 ⇒ \"confidently positive\"). Interpret `deltaThreshold` in the judge's native\n * scale.\n *\n * The decision is delegated whole to {@link decidePairedPromotion}, the one\n * copy of the rule (`src/paired-promotion-decision.ts`), which `HeldOutGate`\n * also calls. That module's header carries the measurements; the short version\n * is three guards a bare `bootstrap.low > threshold` does not have:\n *\n * - a two-point (pass/fail) outcome decides on Tango's SCORE interval, the\n * only paired-binary construction that stays valid at a nonzero margin;\n * - McNemar's exact test VETOES at any non-negative threshold;\n * - a ZERO-WIDTH interval is refused rather than promoted, in either\n * direction — [0,0] clears every negative threshold and [g,g] clears every\n * threshold below g, and both are an absence of evidence, not a result.\n *\n * Measured on this function before those guards landed, at a nominal 5 %:\n * 14.60 % false promotion at n = 40 on a paired-binary noninferiority boundary,\n * and 88.50 % at n = 6 under a bounded asymmetric null whose true mean paired\n * delta is exactly 0.\n *\n * Continuous mean targets require bootstrap eligibility. Explicit median\n * targets can use the exact sign test at its confidence-dependent minimum.\n */\nexport function heldoutSignificance(\n paired: PairedHoldout,\n opts: HeldoutSignificanceOptions = {},\n): HeldoutSignificance {\n const deltaThreshold = opts.deltaThreshold ?? 0\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const seed = opts.seed ?? 1337\n // DEFAULT to the MEAN paired delta, not the median. The median is destroyed by\n // TIES: whenever both baseline and candidate solve a holdout scenario (a common\n // case once the agent is decent — and INCREASINGLY common as you add holdout\n // scenarios for statistical power), that scenario contributes delta 0. When\n // >=50% of paired cells are ties the median is pinned at 0 regardless of a large,\n // consistent lift on the rest, and the gate holds a genuinely better candidate.\n // (Measured live, supervisor-lab run 6: 40 cells, 20 ties, MEAN +0.177, MEDIAN 0\n // → false hold. Doubling the holdout for \"power\" made it WORSE by adding ties.)\n // The mean equals the reported aggregate lift, ties correctly contribute 0\n // without dominating, and it is the textbook paired-comparison estimator; the\n // median is kept as a reported diagnostic. Callers wanting outlier-robustness at\n // the cost of tie-blindness can still pass `statistic: 'median'`.\n const statistic = opts.statistic ?? 'mean'\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const decision = decidePairedPromotion(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n threshold: deltaThreshold,\n minPairs: opts.minProductiveRuns,\n })\n // `decision.bootstrap` is null exactly when the score interval decided, so\n // the requested-statistic bootstrap is computed here for the diagnostic\n // field. Same two bootstraps as before on every path.\n const bootstrap =\n decision.bootstrap ??\n pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n })\n const medianBootstrap =\n statistic === 'median'\n ? bootstrap\n : pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic: 'median',\n seed,\n })\n const n = observations.before.length\n let ties = 0\n for (let i = 0; i < n; i += 1) {\n const after = observations.after[i]!\n const before = observations.before[i]!\n if (Math.abs(after - before) < 1e-9) ties += 1\n }\n const tieFraction = n === 0 ? 0 : ties / n\n return {\n paired,\n bootstrap,\n medianBootstrap,\n decision,\n decisionStatistic: decision.statistic,\n mcnemar: decision.mcnemar,\n tieFraction,\n n,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n unitIds: observations.unitIds,\n minimumRequired: decision.minimumPairs,\n decisionMethod: decision.method,\n pValue: decision.pValue,\n significant: decision.promote,\n fewRuns: !decision.sufficient,\n }\n}\n\nexport interface DimensionRegression {\n dimension: string\n /** Paired bootstrap on (candidate − baseline). DIAGNOSTIC on a pass/fail\n * dimension, where `ci` carries the interval that decided instead. */\n bootstrap: PairedBootstrapResult\n /** Which paired statistic `bootstrap.low` is the lower bound of. `'mean'`\n * unless the caller asked for the median. `bootstrap.median` still carries\n * the median point estimate either way. */\n bootstrapStatistic: 'median' | 'mean'\n /** The interval `regressed` was decided on, in the dimension's native units. */\n ci: { low: number; high: number }\n /** Which estimator produced `ci`. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on a pass/fail dimension; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** `ci` has zero width — no evidence in either direction. */\n indeterminate: boolean\n /** The bootstrap lower bound is below negative tolerance, or the shared\n * paired test supports a drop exceeding tolerance. Missing coverage and\n * insufficient observations are reported separately. */\n regressed: boolean\n tolerance: number\n n: number\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Statistical minimum for the configured independent observation unit. */\n minimumRequired: number\n fewRuns: boolean\n /** Both arms lack this dimension on these otherwise matched execution cells. */\n missingCellIds: string[]\n /** Configured scenarios with no paired dimension measurement at all. */\n missingScenarioIds: string[]\n}\n\n/** Detect the native scale of a set of scores: 0-100 when any magnitude clears\n * 1.5, else [0,1]. Used to auto-scale the regression tolerance so a default\n * expressed for [0,1] is not silently a no-op on a 0-100 dimension. */\nexport function detectScale(values: number[]): 1 | 100 {\n return values.some((v) => Math.abs(v) > 1.5) ? 100 : 1\n}\n\n/**\n * Report required-dimension evidence after full pairing and optional unit means.\n * A bootstrap floor breach or a shared paired test supporting a drop marks\n * regression. These two criteria are distinct; `ci` records the shared\n * estimator and `bootstrap` records the floor interval. Missing observations\n * and insufficient n remain explicit for the caller's evidence policy.\n * The default tolerance is 0.05 on [0,1] and 5 on a detected 0-100 scale.\n */\nexport function dimensionRegressions(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n criticalDimensions: string[],\n opts: {\n tolerance?: number\n confidence?: number\n resamples?: number\n seed?: number\n /** Paired statistic the CI is computed on. Default `'mean'` — see\n * {@link DECISION_PAIRED_DELTA_STATISTIC} for why the median is not. */\n statistic?: 'mean' | 'median'\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n minProductiveRuns?: number\n } = {},\n): DimensionRegression[] {\n const out: DimensionRegression[] = []\n const expectedCellIds = [...baseline.keys()]\n .filter((cellId) => scenarioIds.has(scenarioIdFromCellId(cellId)))\n .sort()\n for (const dim of criticalDimensions) {\n const paired = pairHoldout(candidate, baseline, scenarioIds, (s) => s.dimensions[dim])\n if (paired.before.length === 0) continue // dimension not scored on this judge\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const measuredCells = new Set(paired.cellIds)\n const measuredScenarios = new Set(paired.cellIds.map(scenarioIdFromCellId))\n const tolerance = opts.tolerance ?? 0.05 * detectScale([...paired.before, ...paired.after])\n const bootstrapStatistic = opts.statistic ?? DECISION_PAIRED_DELTA_STATISTIC\n const shared = {\n confidence: opts.confidence ?? 0.95,\n resamples: opts.resamples ?? 2000,\n statistic: bootstrapStatistic,\n seed: opts.seed ?? 1337,\n minPairs: opts.minProductiveRuns,\n }\n const guard = decidePairedPromotion(observations.before, observations.after, shared)\n const regression = decidePairedPromotion(observations.after, observations.before, {\n ...shared,\n threshold: tolerance,\n })\n const bootstrap =\n guard.bootstrap ?? pairedBootstrap(observations.before, observations.after, shared)\n out.push({\n dimension: dim,\n bootstrap,\n bootstrapStatistic,\n ci: { low: guard.low, high: guard.high },\n decisionStatistic: guard.statistic,\n mcnemar: guard.mcnemar,\n indeterminate: guard.indeterminate,\n // Fires on EITHER burden of proof — see `floorBreached` in\n // `promotion-policy.ts` for the same rule and the reasoning. The CI arm\n // is the contract this interface and `default-production-gate`'s reason\n // string both state (\"CI.low < -tolerance\"), read off the DECIDING\n // interval; the exact-test arm adds the small-sample path where the\n // bootstrap interval is descriptive only.\n // The credible-worst-case arm stays on the BOOTSTRAP — see the same\n // decision in `floorBreached` (`promotion-policy.ts`). On a pass/fail\n // dimension the score interval is ±z²/(n+z²) even when every pair is\n // concordant, so reading the floor off it would flag an unchanged safety\n // dimension as regressed at any realistic n. The PROVEN-drop arm does use\n // the shared rule, which is what closes the fail-open hole that mattered:\n // a genuine pass/fail regression is now judged on an interval valid at\n // the nonzero `tolerance`, instead of a bootstrap that is pinned wherever\n // ties dominate.\n regressed: bootstrap.low < -tolerance || regression.promote,\n tolerance,\n n: observations.before.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n minimumRequired: guard.minimumPairs,\n fewRuns: !guard.sufficient,\n missingCellIds: expectedCellIds.filter((cellId) => !measuredCells.has(cellId)),\n missingScenarioIds: [...scenarioIds].filter((id) => !measuredScenarios.has(id)).sort(),\n })\n }\n return out\n}\n"],"mappings":";;;;;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AY,SAAS;GAC3E,iBAAiB,MAAM;GACvB,SAAS,CAAC,MAAM;GAChB,gBAAgB,gBAAgB,QAAQ,WAAW,CAAC,cAAc,IAAI,MAAM,CAAC;GAC7E,oBAAoB,CAAC,GAAG,WAAW,CAAC,CAAC,QAAQ,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK;EACvF,CAAC;CACH;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"statistical-heldout-C26hOFWD.js","names":[],"sources":["../src/campaign/gates/statistical-heldout.ts"],"sourcesContent":["/**\n * Held-out inference pairs execution cells and judge identities before taking\n * means within registered independent units. Repetitions can improve a unit's\n * precision without increasing n. Ungrouped inference concerns independently\n * sampled execution cells conditional on a fixed scenario roster.\n *\n * The shared paired decision rule selects the estimator and statistical test.\n * Dimension reports retain missing coverage so required safety checks cannot\n * pass through absent evidence. Thresholds use the judge's native score scale.\n */\n\nimport {\n decidePairedPromotion,\n type PairedDecisionMethod,\n type PairedDecisionStatistic,\n type PairedMcNemarEvidence,\n type PairedPromotionDecision,\n} from '../../paired-promotion-decision'\nimport {\n DECISION_PAIRED_DELTA_STATISTIC,\n type PairedBootstrapResult,\n pairedBootstrap,\n} from '../../statistics'\nimport type { JudgeScore } from '../types'\n\n/** Tie fraction at/above which a gate annotates its verdict with the tie share.\n * Tie-domination of the median bites structurally at >= 0.5 (the median is then\n * 0 by construction); 0.4 is a softer warn threshold that flags a run APPROACHING\n * that regime, so an operator sees it before the median goes fully blind. */\nexport const TIE_WARN_FRACTION = 0.4\n\nexport interface PairedHoldout {\n /** Baseline scalar per paired cell (same order as `after`/`cellIds`). */\n before: number[]\n /** Candidate scalar per paired cell. */\n after: number[]\n /** The full cellIds (`scenario:rep`) that paired, in order. */\n cellIds: string[]\n}\n\n/** Campaign cell IDs append a numeric repetition after the scenario's full ID. */\nexport function scenarioIdFromCellId(cellId: string): string {\n const separator = cellId.lastIndexOf(':')\n const repetition = cellId.slice(separator + 1)\n if (\n separator < 1 ||\n cellId.trim() !== cellId ||\n !/^(0|[1-9]\\d*)$/.test(repetition) ||\n !Number.isSafeInteger(Number(repetition))\n ) {\n throw new Error(`pairHoldout: malformed cellId '${cellId}'; expected scenarioId:rep`)\n }\n return cellId.slice(0, separator)\n}\n\n/** Preserve cell pairing before taking equal-weight independent-unit means. */\nexport function aggregatePairedHoldout(\n paired: PairedHoldout,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n): { before: number[]; after: number[]; unitIds: string[] } {\n if (\n paired.before.length !== paired.after.length ||\n paired.before.length !== paired.cellIds.length\n ) {\n throw new Error('aggregatePairedHoldout: scores and cellIds must have the same length')\n }\n if (new Set(paired.cellIds).size !== paired.cellIds.length) {\n throw new Error('aggregatePairedHoldout: duplicate cellIds cannot count as new observations')\n }\n if (\n paired.before.some((value) => !Number.isFinite(value)) ||\n paired.after.some((value) => !Number.isFinite(value))\n ) {\n throw new Error('aggregatePairedHoldout: paired scores must be finite')\n }\n if (independentUnitByScenarioId === undefined) {\n return { before: [...paired.before], after: [...paired.after], unitIds: [...paired.cellIds] }\n }\n const scenarioIds = paired.cellIds.map(scenarioIdFromCellId)\n const groups = new Map<string, { before: number; after: number; n: number }>()\n for (let i = 0; i < paired.cellIds.length; i++) {\n const scenarioId = scenarioIds[i]!\n const unitId = independentUnitByScenarioId.get(scenarioId)\n if (typeof unitId !== 'string' || unitId.length === 0 || unitId.trim() !== unitId) {\n throw new Error(\n `aggregatePairedHoldout: missing independent unit for scenario '${scenarioId}'`,\n )\n }\n const group = groups.get(unitId) ?? { before: 0, after: 0, n: 0 }\n group.before += paired.before[i]!\n group.after += paired.after[i]!\n group.n += 1\n groups.set(unitId, group)\n }\n const unitIds = [...groups.keys()].sort()\n return {\n before: unitIds.map((id) => groups.get(id)!.before / groups.get(id)!.n),\n after: unitIds.map((id) => groups.get(id)!.after / groups.get(id)!.n),\n unitIds,\n }\n}\n\n/**\n * Pair candidate vs baseline holdout observations by FULL cellId. `select`\n * pulls the scalar from a cell's judge reports (composite, or a named\n * dimension); a cell contributes the mean of `select` across its judges. Cells\n * whose scenario is not in `scenarioIds`, or where `select` is undefined for\n * every judge on both sides, are skipped. The selected judge IDs must agree\n * within each pair. Throws when the two maps disagree on holdout cell IDs — a\n * load-bearing invariant: the baseline + winner holdout campaigns run the same\n * scenarios with the same seed base, so their cellIds MUST align; a mismatch\n * means a silent pairing bug, not a soft fallback.\n */\nexport function pairHoldout(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n select: (s: JudgeScore) => number | undefined,\n): PairedHoldout {\n const cellValues = (\n byCell: Map<string, Record<string, JudgeScore>>,\n cellId: string,\n ): Map<string, number> => {\n const scores = byCell.get(cellId)\n const values = new Map<string, number>()\n if (!scores) return values\n for (const [judgeId, s] of Object.entries(scores)) {\n if (s.failed === true) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a failed judge score`)\n }\n const v = select(s)\n if (typeof v === 'number' && !Number.isFinite(v)) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a non-finite selected score`)\n }\n if (typeof v === 'number') values.set(judgeId, v)\n }\n return values\n }\n\n const inScope = (cellId: string) => scenarioIds.has(scenarioIdFromCellId(cellId))\n const candCells = [...candidate.keys()].filter(inScope).sort()\n const baseCells = [...baseline.keys()].filter(inScope).sort()\n // Alignment invariant — the holdout campaigns share scenarios + seed, so the\n // cell sets must be identical. Differ ⇒ a real pairing bug; fail loud.\n if (candCells.length !== baseCells.length || candCells.some((c, i) => c !== baseCells[i])) {\n throw new Error(\n `pairHoldout: candidate/baseline holdout cells do not align — ` +\n `candidate=[${candCells.join(',')}] baseline=[${baseCells.join(',')}]. ` +\n `Both holdout campaigns must run the same scenarios with the same seed base.`,\n )\n }\n\n const before: number[] = []\n const after: number[] = []\n const cellIds: string[] = []\n for (const cellId of candCells) {\n const b = cellValues(baseline, cellId)\n const a = cellValues(candidate, cellId)\n // A scalar absent on both sides means that dimension was not scored. A\n // one-sided absence is asymmetric evidence loss, never a row to discard.\n if (b.size === 0 && a.size === 0) continue\n if (b.size === 0 || a.size === 0) {\n throw new Error(`pairHoldout: cell '${cellId}' has a selected score on only one arm`)\n }\n if (b.size !== a.size || [...b.keys()].some((id) => !a.has(id))) {\n throw new Error(`pairHoldout: cell '${cellId}' selected judge IDs do not align`)\n }\n const judgeIds = [...b.keys()].sort()\n before.push(meanSelectedScores(judgeIds.map((id) => b.get(id)!)))\n after.push(meanSelectedScores(judgeIds.map((id) => a.get(id)!)))\n cellIds.push(cellId)\n }\n return { before, after, cellIds }\n}\n\nfunction meanSelectedScores(values: number[]): number {\n const first = values[0]!\n // Summing identical fractional scores can round their mean outside the\n // declared binary support. An agreeing judge set preserves its exact value.\n return values.every((value) => value === first)\n ? first\n : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nexport interface HeldoutSignificance {\n paired: PairedHoldout\n /**\n * The paired bootstrap on the requested statistic (MEAN by default — see the\n * tie note on `heldoutSignificance`).\n *\n * DIAGNOSTIC, not necessarily the interval the verdict keyed on. On a\n * two-point (pass/fail) outcome the decision routes to Tango's score interval\n * instead, because a percentile bootstrap of the mean over a three-atom\n * lattice is not a valid interval at a nonzero margin. Read\n * `decision.low`/`decision.high` for the interval that actually decided, and\n * `decisionStatistic` for which one it is.\n */\n bootstrap: PairedBootstrapResult\n /** The MEDIAN paired-delta bootstrap, reported as a diagnostic. When many\n * scenarios are tied (both sides solve them), the median is pinned near 0\n * regardless of the mean lift — comparing the two exposes tie-domination. */\n medianBootstrap: PairedBootstrapResult\n /**\n * The full promotion decision: which estimator the outcome's shape admits,\n * the interval it produced, McNemar's exact veto on the two-point path, and\n * whether the interval was zero-width (no evidence in either direction). The\n * single source of `significant`.\n */\n decision: PairedPromotionDecision\n /** Which paired estimator the verdict was decided on. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on the two-point path; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** Fraction of paired observations that are exact ties (|delta| < 1e-9). A\n * high tie fraction is WHY a median-based gate would have missed a real lift;\n * it is the observability the tie fix adds. */\n tieFraction: number\n /** Number of paired observation units, after configured aggregation. */\n n: number\n /** Original matched execution cells, before aggregation. */\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Registered unit IDs, or cell IDs on the ungrouped path. */\n unitIds: string[]\n /** Effective minimum for the requested target and chosen estimator. */\n minimumRequired: number\n /** Statistical method that carried the decision. */\n decisionMethod: PairedDecisionMethod\n /** Exact one-sided p-value on the small-sample path; otherwise null. */\n pValue: number | null\n /** True iff n >= minimumRequired, the DECIDING interval has nonzero width,\n * its lower bound clears the threshold, and McNemar's exact test does not\n * veto at a non-negative threshold. */\n significant: boolean\n /** Set when n < minimumRequired — too little evidence to claim significance. */\n fewRuns: boolean\n}\n\nexport interface HeldoutSignificanceOptions {\n deltaThreshold?: number\n minProductiveRuns?: number\n confidence?: number\n resamples?: number\n /** Fixed by default for a deterministic, reproducible gate verdict. */\n seed?: number\n statistic?: 'mean' | 'median'\n /** Group full cell pairs into equal-weight independent units before inference. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * Significance of the held-out composite lift: ship only when the lower bound\n * of the interval the outcome's shape ADMITS exceeds `deltaThreshold` (default\n * 0 ⇒ \"confidently positive\"). Interpret `deltaThreshold` in the judge's native\n * scale.\n *\n * The decision is delegated whole to {@link decidePairedPromotion}, the one\n * copy of the rule (`src/paired-promotion-decision.ts`), which `HeldOutGate`\n * also calls. That module's header carries the measurements; the short version\n * is three guards a bare `bootstrap.low > threshold` does not have:\n *\n * - a two-point (pass/fail) outcome decides on Tango's SCORE interval, the\n * only paired-binary construction that stays valid at a nonzero margin;\n * - McNemar's exact test VETOES at any non-negative threshold;\n * - a ZERO-WIDTH interval is refused rather than promoted, in either\n * direction — [0,0] clears every negative threshold and [g,g] clears every\n * threshold below g, and both are an absence of evidence, not a result.\n *\n * Measured on this function before those guards landed, at a nominal 5 %:\n * 14.60 % false promotion at n = 40 on a paired-binary noninferiority boundary,\n * and 88.50 % at n = 6 under a bounded asymmetric null whose true mean paired\n * delta is exactly 0.\n *\n * Continuous mean targets require bootstrap eligibility. Explicit median\n * targets can use the exact sign test at its confidence-dependent minimum.\n */\nexport function heldoutSignificance(\n paired: PairedHoldout,\n opts: HeldoutSignificanceOptions = {},\n): HeldoutSignificance {\n const deltaThreshold = opts.deltaThreshold ?? 0\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const seed = opts.seed ?? 1337\n // DEFAULT to the MEAN paired delta, not the median. The median is destroyed by\n // TIES: whenever both baseline and candidate solve a holdout scenario (a common\n // case once the agent is decent — and INCREASINGLY common as you add holdout\n // scenarios for statistical power), that scenario contributes delta 0. When\n // >=50% of paired cells are ties the median is pinned at 0 regardless of a large,\n // consistent lift on the rest, and the gate holds a genuinely better candidate.\n // (Measured live, supervisor-lab run 6: 40 cells, 20 ties, MEAN +0.177, MEDIAN 0\n // → false hold. Doubling the holdout for \"power\" made it WORSE by adding ties.)\n // The mean equals the reported aggregate lift, ties correctly contribute 0\n // without dominating, and it is the textbook paired-comparison estimator; the\n // median is kept as a reported diagnostic. Callers wanting outlier-robustness at\n // the cost of tie-blindness can still pass `statistic: 'median'`.\n const statistic = opts.statistic ?? 'mean'\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const decision = decidePairedPromotion(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n threshold: deltaThreshold,\n minPairs: opts.minProductiveRuns,\n })\n // `decision.bootstrap` is null exactly when the score interval decided, so\n // the requested-statistic bootstrap is computed here for the diagnostic\n // field. Same two bootstraps as before on every path.\n const bootstrap =\n decision.bootstrap ??\n pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n })\n const medianBootstrap =\n statistic === 'median'\n ? bootstrap\n : pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic: 'median',\n seed,\n })\n const n = observations.before.length\n let ties = 0\n for (let i = 0; i < n; i += 1) {\n const after = observations.after[i]!\n const before = observations.before[i]!\n if (Math.abs(after - before) < 1e-9) ties += 1\n }\n const tieFraction = n === 0 ? 0 : ties / n\n return {\n paired,\n bootstrap,\n medianBootstrap,\n decision,\n decisionStatistic: decision.statistic,\n mcnemar: decision.mcnemar,\n tieFraction,\n n,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n unitIds: observations.unitIds,\n minimumRequired: decision.minimumPairs,\n decisionMethod: decision.method,\n pValue: decision.pValue,\n significant: decision.promote,\n fewRuns: !decision.sufficient,\n }\n}\n\nexport interface DimensionRegression {\n dimension: string\n /** Paired bootstrap on (candidate − baseline). DIAGNOSTIC on a pass/fail\n * dimension, where `ci` carries the interval that decided instead. */\n bootstrap: PairedBootstrapResult\n /** Which paired statistic `bootstrap.low` is the lower bound of. `'mean'`\n * unless the caller asked for the median. `bootstrap.median` still carries\n * the median point estimate either way. */\n bootstrapStatistic: 'median' | 'mean'\n /** The interval `regressed` was decided on, in the dimension's native units. */\n ci: { low: number; high: number }\n /** Which estimator produced `ci`. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on a pass/fail dimension; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** `ci` has zero width — no evidence in either direction. */\n indeterminate: boolean\n /** The bootstrap lower bound is below negative tolerance, or the shared\n * paired test supports a drop exceeding tolerance. Missing coverage and\n * insufficient observations are reported separately. */\n regressed: boolean\n tolerance: number\n n: number\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Statistical minimum for the configured independent observation unit. */\n minimumRequired: number\n fewRuns: boolean\n /** Both arms lack this dimension on these otherwise matched execution cells. */\n missingCellIds: string[]\n /** Configured scenarios with no paired dimension measurement at all. */\n missingScenarioIds: string[]\n}\n\n/** Detect the native scale of a set of scores: 0-100 when any magnitude clears\n * 1.5, else [0,1]. Used to auto-scale the regression tolerance so a default\n * expressed for [0,1] is not silently a no-op on a 0-100 dimension. */\nexport function detectScale(values: number[]): 1 | 100 {\n return values.some((v) => Math.abs(v) > 1.5) ? 100 : 1\n}\n\n/**\n * Report required-dimension evidence after full pairing and optional unit means.\n * A bootstrap floor breach or a shared paired test supporting a drop marks\n * regression. These two criteria are distinct; `ci` records the shared\n * estimator and `bootstrap` records the floor interval. Missing observations\n * and insufficient n remain explicit for the caller's evidence policy.\n * The default tolerance is 0.05 on [0,1] and 5 on a detected 0-100 scale.\n */\nexport function dimensionRegressions(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n criticalDimensions: string[],\n opts: {\n tolerance?: number\n confidence?: number\n resamples?: number\n seed?: number\n /** Paired statistic the CI is computed on. Default `'mean'` — see\n * {@link DECISION_PAIRED_DELTA_STATISTIC} for why the median is not. */\n statistic?: 'mean' | 'median'\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n minProductiveRuns?: number\n } = {},\n): DimensionRegression[] {\n const out: DimensionRegression[] = []\n const expectedCellIds = [...baseline.keys()]\n .filter((cellId) => scenarioIds.has(scenarioIdFromCellId(cellId)))\n .sort()\n for (const dim of criticalDimensions) {\n const paired = pairHoldout(candidate, baseline, scenarioIds, (s) => s.dimensions[dim])\n if (paired.before.length === 0) continue // dimension not scored on this judge\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const measuredCells = new Set(paired.cellIds)\n const measuredScenarios = new Set(paired.cellIds.map(scenarioIdFromCellId))\n const tolerance = opts.tolerance ?? 0.05 * detectScale([...paired.before, ...paired.after])\n const bootstrapStatistic = opts.statistic ?? DECISION_PAIRED_DELTA_STATISTIC\n const shared = {\n confidence: opts.confidence ?? 0.95,\n resamples: opts.resamples ?? 2000,\n statistic: bootstrapStatistic,\n seed: opts.seed ?? 1337,\n minPairs: opts.minProductiveRuns,\n }\n const guard = decidePairedPromotion(observations.before, observations.after, shared)\n const regression = decidePairedPromotion(observations.after, observations.before, {\n ...shared,\n threshold: tolerance,\n })\n const bootstrap =\n guard.bootstrap ?? pairedBootstrap(observations.before, observations.after, shared)\n out.push({\n dimension: dim,\n bootstrap,\n bootstrapStatistic,\n ci: { low: guard.low, high: guard.high },\n decisionStatistic: guard.statistic,\n mcnemar: guard.mcnemar,\n indeterminate: guard.indeterminate,\n // Fires on EITHER burden of proof — see `floorBreached` in\n // `promotion-policy.ts` for the same rule and the reasoning. The CI arm\n // is the contract this interface and `default-production-gate`'s reason\n // string both state (\"CI.low < -tolerance\"), read off the DECIDING\n // interval; the exact-test arm adds the small-sample path where the\n // bootstrap interval is descriptive only.\n // The credible-worst-case arm stays on the BOOTSTRAP — see the same\n // decision in `floorBreached` (`promotion-policy.ts`). On a pass/fail\n // dimension the score interval is ±z²/(n+z²) even when every pair is\n // concordant, so reading the floor off it would flag an unchanged safety\n // dimension as regressed at any realistic n. The PROVEN-drop arm does use\n // the shared rule, which is what closes the fail-open hole that mattered:\n // a genuine pass/fail regression is now judged on an interval valid at\n // the nonzero `tolerance`, instead of a bootstrap that is pinned wherever\n // ties dominate.\n regressed: bootstrap.low < -tolerance || regression.promote,\n tolerance,\n n: observations.before.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n minimumRequired: guard.minimumPairs,\n fewRuns: !guard.sufficient,\n missingCellIds: expectedCellIds.filter((cellId) => !measuredCells.has(cellId)),\n missingScenarioIds: [...scenarioIds].filter((id) => !measuredScenarios.has(id)).sort(),\n })\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,oBAAoB;;AAYjC,SAAgB,qBAAqB,QAAwB;CAC3D,MAAM,YAAY,OAAO,YAAY,GAAG;CACxC,MAAM,aAAa,OAAO,MAAM,YAAY,CAAC;CAC7C,IACE,YAAY,KACZ,OAAO,KAAK,MAAM,UAClB,CAAC,iBAAiB,KAAK,UAAU,KACjC,CAAC,OAAO,cAAc,OAAO,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,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { n as CaptureIntegrityError } from "./errors-Dngq5h35.js";
2
- import { A as spanEpochMillis, C as TraceFileTooLargeError, D as extractOtlpAttributes, E as compareSpanTime, S as TraceFileMissingError, _ as SpanNotFoundError, b as TraceAnalysisValidationError, d as compileSearchRegex, f as truncateForBudget, g as TRACE_ANALYSIS_LIMITS, k as projectOtlpFlatLine, l as bindSpanSourceReader, m as DEFAULT_TRACE_ANALYST_BUDGETS, p as validateInteger, v as TraceAnalysisLimitError, w as TraceNotFoundError, x as TraceFileMalformedError } from "./kind-factory-CdPPHtGZ.js";
2
+ import { A as projectOtlpFlatLine, C as TraceFileMissingError, D as compareSpanTime, O as extractOtlpAttributes, S as TraceFileMalformedError, T as TraceNotFoundError, _ as TRACE_ANALYSIS_LIMITS, d as traceSpanSchema, f as compileSearchRegex, h as DEFAULT_TRACE_ANALYST_BUDGETS, j as spanEpochMillis, l as bindSpanSourceReader, m as validateInteger, p as truncateForBudget, v as SpanNotFoundError, w as TraceFileTooLargeError, x as TraceAnalysisValidationError, y as TraceAnalysisLimitError } from "./kind-factory-Cn1lbsAd.js";
3
3
  import { readFile, stat } from "node:fs/promises";
4
4
  //#region src/trace-analyst/shared-abortable-task.ts
5
5
  function createSharedAbortableTask(factory) {
@@ -86,7 +86,7 @@ async function scanCheckpoint(signal, item) {
86
86
  }
87
87
  /** Default ceiling for {@link OtlpFileTraceStoreOptions.maxFileBytes}. */
88
88
  const DEFAULT_MAX_TRACE_FILE_BYTES = 268435456;
89
- var BufferedOtlpTraceStore = class {
89
+ var BufferedTraceStore = class {
90
90
  readSpanSource;
91
91
  perAttributeViewBudget;
92
92
  perAttributeSpanBudget;
@@ -142,7 +142,7 @@ var BufferedOtlpTraceStore = class {
142
142
  for (const t of matched) {
143
143
  await scanCheckpoint(context?.signal, traceIndex++);
144
144
  if (t.service_name) services.add(t.service_name);
145
- if (t.agent_name) agents.add(t.agent_name);
145
+ for (const agent of t.agents) agents.add(agent);
146
146
  for (const m of t.models) models.add(m);
147
147
  for (const tn of t.tools) tools.add(tn);
148
148
  rawBytes += t.raw_jsonl_bytes;
@@ -346,6 +346,9 @@ var BufferedOtlpTraceStore = class {
346
346
  }
347
347
  return waitForSharedTask(this.bufferTask, context?.signal);
348
348
  }
349
+ projectRecord(raw) {
350
+ return projectOtlpFlatLine(raw);
351
+ }
349
352
  async index(context) {
350
353
  context?.signal?.throwIfAborted();
351
354
  if (this.indexValue) return this.indexValue;
@@ -392,7 +395,7 @@ var BufferedOtlpTraceStore = class {
392
395
  throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset, cause);
393
396
  }
394
397
  if (!parsed || typeof parsed !== "object") throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset);
395
- const span = projectOtlpFlatLine(parsed);
398
+ const span = this.projectRecord(parsed);
396
399
  if (!span) throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset);
397
400
  let entry = byTrace.get(span.trace_id);
398
401
  if (!entry) {
@@ -406,6 +409,7 @@ var BufferedOtlpTraceStore = class {
406
409
  end_time: span.end_time,
407
410
  duration_ms: 0,
408
411
  raw_jsonl_bytes: 0,
412
+ agents: /* @__PURE__ */ new Set(),
409
413
  models: /* @__PURE__ */ new Set(),
410
414
  tools: /* @__PURE__ */ new Set(),
411
415
  spans: []
@@ -438,6 +442,7 @@ var BufferedOtlpTraceStore = class {
438
442
  if (span.status === "ERROR") entry.has_errors = true;
439
443
  if (compareSpanTime(span.start_time, entry.start_time) < 0) entry.start_time = span.start_time;
440
444
  if (compareSpanTime(span.end_time, entry.end_time) > 0) entry.end_time = span.end_time;
445
+ if (span.agent_name) entry.agents.add(span.agent_name);
441
446
  if (span.model_name) entry.models.add(span.model_name);
442
447
  if (span.tool_name) entry.tools.add(span.tool_name);
443
448
  }
@@ -476,7 +481,7 @@ var BufferedOtlpTraceStore = class {
476
481
  if (!t.service_name || !filters.service_names.includes(t.service_name)) continue;
477
482
  }
478
483
  if (filters.agent_names && filters.agent_names.length > 0) {
479
- if (!t.agent_name || !filters.agent_names.includes(t.agent_name)) continue;
484
+ if (![...t.agents].some((agent) => filters.agent_names.includes(agent))) continue;
480
485
  }
481
486
  if (filters.model_names && filters.model_names.length > 0) {
482
487
  if (![...t.models].some((m) => filters.model_names.includes(m))) continue;
@@ -610,7 +615,7 @@ var BufferedOtlpTraceStore = class {
610
615
  };
611
616
  }
612
617
  };
613
- var OtlpFileTraceStore = class extends BufferedOtlpTraceStore {
618
+ var OtlpFileTraceStore = class extends BufferedTraceStore {
614
619
  path;
615
620
  maxFileBytes;
616
621
  constructor(opts) {
@@ -637,7 +642,7 @@ var OtlpFileTraceStore = class extends BufferedOtlpTraceStore {
637
642
  return this.path;
638
643
  }
639
644
  };
640
- var OtlpBufferTraceStore = class extends BufferedOtlpTraceStore {
645
+ var BufferTraceStore = class extends BufferedTraceStore {
641
646
  source;
642
647
  constructor(source, opts) {
643
648
  super(opts);
@@ -651,13 +656,41 @@ var OtlpBufferTraceStore = class extends BufferedOtlpTraceStore {
651
656
  return "<memory>";
652
657
  }
653
658
  };
659
+ var SpanRecordTraceStore = class extends BufferTraceStore {
660
+ projectRecord(raw) {
661
+ return traceSpanSchema.parse(raw);
662
+ }
663
+ };
664
+ /**
665
+ * Snapshot canonical spans without reinterpreting their identifiers, kind, or duration.
666
+ * Reads use the same indexed, bounded engine as the OTLP adapters. Raw byte counts
667
+ * and searches refer to the canonical JSONL snapshot, not an external source artifact.
668
+ */
669
+ function spanRecordsToTraceAnalysisStore(records, options = {}) {
670
+ if (!records || records.length === 0) throw new CaptureIntegrityError("spanRecordsToTraceAnalysisStore: no span records supplied");
671
+ const seen = /* @__PURE__ */ new Map();
672
+ const lines = records.map((record, index) => {
673
+ try {
674
+ const span = traceSpanSchema.parse(record);
675
+ const traceSpans = seen.get(span.trace_id) ?? /* @__PURE__ */ new Set();
676
+ if (traceSpans.has(span.span_id)) throw new CaptureIntegrityError(`spanRecordsToTraceAnalysisStore: duplicate span '${span.span_id}' in trace '${span.trace_id}'`);
677
+ traceSpans.add(span.span_id);
678
+ seen.set(span.trace_id, traceSpans);
679
+ return JSON.stringify(span);
680
+ } catch (cause) {
681
+ if (cause instanceof CaptureIntegrityError) throw cause;
682
+ throw new CaptureIntegrityError(`spanRecordsToTraceAnalysisStore: invalid span record at index ${index}`, { cause });
683
+ }
684
+ });
685
+ return new SpanRecordTraceStore(Buffer.from(`${lines.join("\n")}\n`, "utf8"), options);
686
+ }
654
687
  /** Build the bounded trace store directly from OpenInference JSONL text. */
655
688
  function otlpTextToTraceAnalysisStore(text, opts = {}) {
656
689
  if (!text.trim()) throw new CaptureIntegrityError("OTLP trace text must not be empty");
657
- return new OtlpBufferTraceStore(Buffer.from(text, "utf8"), opts);
690
+ return new BufferTraceStore(Buffer.from(text, "utf8"), opts);
658
691
  }
659
692
  function createOtlpBufferTraceStore(source, options = {}) {
660
- return new OtlpBufferTraceStore(source, options);
693
+ return new BufferTraceStore(source, options);
661
694
  }
662
695
  /** A `"` at `idx` is a real JSON delimiter only when the run of `\`
663
696
  * immediately preceding it is even-length; an odd run means the quote
@@ -757,6 +790,6 @@ function finalizeErrorClusters(clusters, errorTraceCount) {
757
790
  return out;
758
791
  }
759
792
  //#endregion
760
- export { otlpTextToTraceAnalysisStore as i, OtlpFileTraceStore as n, createOtlpBufferTraceStore as r, DEFAULT_MAX_TRACE_FILE_BYTES as t };
793
+ export { spanRecordsToTraceAnalysisStore as a, otlpTextToTraceAnalysisStore as i, OtlpFileTraceStore as n, createOtlpBufferTraceStore as r, DEFAULT_MAX_TRACE_FILE_BYTES as t };
761
794
 
762
- //# sourceMappingURL=store-otlp-yd9lDziN.js.map
795
+ //# sourceMappingURL=store-otlp-BA7G1Du-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-otlp-BA7G1Du-.js","names":[],"sources":["../src/trace-analyst/shared-abortable-task.ts","../src/trace-analyst/store-otlp.ts"],"sourcesContent":["export interface SharedAbortableTask<T> {\n controller: AbortController\n promise: Promise<T>\n consumers: number\n settled: boolean\n}\n\nexport function createSharedAbortableTask<T>(\n factory: (signal: AbortSignal) => Promise<T>,\n): SharedAbortableTask<T> {\n const controller = new AbortController()\n const task: SharedAbortableTask<T> = {\n controller,\n promise: factory(controller.signal),\n consumers: 0,\n settled: false,\n }\n void task.promise.then(\n () => {\n task.settled = true\n },\n () => {\n task.settled = true\n },\n )\n return task\n}\n\nexport function waitForSharedTask<T>(\n task: SharedAbortableTask<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n signal?.throwIfAborted()\n task.consumers += 1\n\n return new Promise<T>((resolve, reject) => {\n let finished = false\n const finish = (callback: () => void): void => {\n if (finished) return\n finished = true\n signal?.removeEventListener('abort', onAbort)\n task.consumers -= 1\n callback()\n }\n const onAbort = (): void => {\n finish(() => {\n reject(signal?.reason)\n if (!task.settled && task.consumers === 0) {\n task.controller.abort(signal?.reason)\n }\n })\n }\n\n signal?.addEventListener('abort', onAbort, { once: true })\n task.promise.then(\n (value) => finish(() => resolve(value)),\n (error: unknown) => finish(() => reject(error)),\n )\n if (signal?.aborted) onAbort()\n })\n}\n","/**\n * `OtlpFileTraceStore` — read-only OTLP-JSONL trace store for the\n * trace-analyst.\n *\n * Wire shape. Each line of the input file is one OTLP-shaped span. The\n * store understands flattened OTLP JSONL plus the OpenInference vocab.\n * We project upstream's full\n * span shape down to `TraceAnalystSpan` lazily — full materialisation\n * only happens for the spans the agent actually requests.\n *\n * Indexing. On first read the store builds an in-memory index keyed\n * by `trace_id` carrying:\n * - byte offsets + lengths for each span line (for surgical reads\n * without re-parsing the whole file)\n * - a `TraceAnalystTraceSummary` rollup\n * - sets of services / agents / models / tools / has_errors\n * - byte size of the trace's JSONL slab\n *\n * Memory bound. The index keeps span metadata only — names, kinds,\n * offsets, status. Attribute payloads stay on disk until requested.\n * For a 50MB JSONL with 50k spans, the index is ~5MB.\n *\n * Concurrency. The store builds the index once on first read and\n * caches it. Subsequent reads reuse the index. The file is opened on\n * each read; we never hold a long-lived FD.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport type { RE2JS } from 're2js'\nimport { CaptureIntegrityError } from '../errors'\nimport {\n SpanNotFoundError,\n TraceAnalysisLimitError,\n TraceAnalysisValidationError,\n TraceFileMalformedError,\n TraceFileMissingError,\n TraceFileTooLargeError,\n TraceNotFoundError,\n} from './errors'\nimport {\n compareSpanTime,\n extractOtlpAttributes,\n projectOtlpFlatLine,\n spanEpochMillis,\n} from './otlp-span'\nimport {\n createSharedAbortableTask,\n type SharedAbortableTask,\n waitForSharedTask,\n} from './shared-abortable-task'\nimport {\n compileSearchRegex,\n TRACE_ANALYSIS_LIMITS,\n type TraceAnalysisStore,\n type TraceAnalysisStoreContext,\n truncateForBudget,\n validateInteger,\n} from './store'\nimport { bindSpanSourceReader } from './store-boundary'\nimport type { SpanSourceReader } from './store-contract'\nimport { traceSpanSchema } from './store-schemas'\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type ErrorCluster,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystSpanStatus,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceOversized,\n type ViewTraceResult,\n} from './types'\n\n/** Lines indexed between event-loop yields. Bounded synchronous work per\n * tick keeps the index build from starving other tasks on large files\n * while staying coarse enough that the yields are cheap. */\nconst INDEX_YIELD_LINES = 5000\nconst SCAN_YIELD_ITEMS = 500\n\n/** Hand control back to the event loop without busy-waiting. */\nfunction yieldToEventLoop(): Promise<void> {\n return new Promise((resolve) => setImmediate(resolve))\n}\n\nasync function scanCheckpoint(signal: AbortSignal | undefined, item: number): Promise<void> {\n signal?.throwIfAborted()\n if (item > 0 && item % SCAN_YIELD_ITEMS === 0) {\n await yieldToEventLoop()\n signal?.throwIfAborted()\n }\n}\n\ninterface SpanIndexEntry {\n span_id: string\n parent_span_id: string | null\n name: string\n kind: TraceAnalystSpanKind\n start_time: string\n end_time: string\n duration_ms: number\n status: TraceAnalystSpanStatus\n status_message: string | undefined\n service_name: string | null\n agent_name: string | null\n model_name: string | null\n tool_name: string | null\n /** Byte offset in the raw JSONL file to the start of this span's line. */\n line_byte_offset: number\n /** Length of this line in bytes (excluding the trailing newline). */\n line_byte_length: number\n}\n\ninterface TraceIndexEntry {\n trace_id: string\n service_name: string | null\n agent_name: string | null\n span_count: number\n has_errors: boolean\n start_time: string\n end_time: string\n duration_ms: number\n raw_jsonl_bytes: number\n agents: Set<string>\n models: Set<string>\n tools: Set<string>\n spans: SpanIndexEntry[]\n /** Sorted by line offset for stable iteration. */\n}\n\ninterface DatasetIndex {\n byTrace: Map<string, TraceIndexEntry>\n totalRawBytes: number\n // Pre-computed sorted trace_ids for sample/query stability.\n sortedTraceIds: string[]\n}\n\nexport interface ToolSpansToTraceAnalysisStoreOptions {\n /** Authorized original-record lookup, exposed only when supplied. */\n sourceReader?: SpanSourceReader\n /** Override the discovery (`viewTrace`) per-attribute byte cap. */\n perAttributeViewBudget?: number\n /** Override the surgical (`viewSpans`) per-attribute byte cap. */\n perAttributeSpanBudget?: number\n /** Override the per-call ceiling that triggers oversized summaries. */\n perCallByteCeiling?: number\n /** Override the per-match text budget. */\n perMatchTextBudget?: number\n}\n\n/** Budgets and authorized source access shared by canonical span-record stores. */\nexport type SpanRecordsToTraceAnalysisStoreOptions = ToolSpansToTraceAnalysisStoreOptions\n\ntype BufferedTraceStoreOptions = ToolSpansToTraceAnalysisStoreOptions\n\nexport interface OtlpFileTraceStoreOptions extends BufferedTraceStoreOptions {\n /** Path to the OTLP-JSONL file. */\n path: string\n /**\n * Hard ceiling on the trace file size in bytes. The store reads the\n * whole file into one Buffer and indexes it in memory, so an\n * unbounded file OOMs the process. Above this size the store fails\n * loud with `TraceFileTooLargeError` instead of degrading silently.\n * Default 256 MiB.\n */\n maxFileBytes?: number\n}\n\n/** Default ceiling for {@link OtlpFileTraceStoreOptions.maxFileBytes}. */\nexport const DEFAULT_MAX_TRACE_FILE_BYTES = 256 * 1024 * 1024\n\nabstract class BufferedTraceStore implements TraceAnalysisStore {\n readonly readSpanSource?: SpanSourceReader\n private readonly perAttributeViewBudget: number\n private readonly perAttributeSpanBudget: number\n private readonly perCallByteCeiling: number\n private readonly perMatchTextBudget: number\n private indexValue?: DatasetIndex\n private indexTask?: SharedAbortableTask<DatasetIndex>\n private bufferValue?: Buffer\n private bufferTask?: SharedAbortableTask<Buffer>\n\n constructor(opts: BufferedTraceStoreOptions) {\n this.perAttributeViewBudget = validateInteger(\n opts.perAttributeViewBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perAttributeViewBudget,\n 'perAttributeViewBudget',\n TRACE_ANALYSIS_LIMITS.minimumTextBudget,\n )\n this.perAttributeSpanBudget = validateInteger(\n opts.perAttributeSpanBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perAttributeSpanBudget,\n 'perAttributeSpanBudget',\n TRACE_ANALYSIS_LIMITS.minimumTextBudget,\n )\n this.perCallByteCeiling = validateInteger(\n opts.perCallByteCeiling ?? DEFAULT_TRACE_ANALYST_BUDGETS.perCallByteCeiling,\n 'perCallByteCeiling',\n 1,\n )\n this.perMatchTextBudget = validateInteger(\n opts.perMatchTextBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perMatchTextBudget,\n 'perMatchTextBudget',\n TRACE_ANALYSIS_LIMITS.minimumTextBudget,\n )\n if (opts.sourceReader !== undefined) {\n this.readSpanSource = bindSpanSourceReader(this, opts.sourceReader, {\n perAttributeSpanBudget: this.perAttributeSpanBudget,\n perCallByteCeiling: this.perCallByteCeiling,\n })\n }\n }\n\n // ─── Public API ────────────────────────────────────────────────────\n\n async hasTrace(trace_id: string, context?: TraceAnalysisStoreContext): Promise<boolean> {\n context?.signal?.throwIfAborted()\n const idx = await this.index(context)\n context?.signal?.throwIfAborted()\n return idx.byTrace.has(trace_id)\n }\n\n async hasSpans(\n opts: { trace_id: string; span_ids: readonly string[] },\n context?: TraceAnalysisStoreContext,\n ): Promise<string[]> {\n context?.signal?.throwIfAborted()\n const idx = await this.index(context)\n const trace = idx.byTrace.get(opts.trace_id)\n if (!trace) return []\n const requested = new Set(opts.span_ids)\n const found: string[] = []\n for (let index = 0; index < trace.spans.length; index += 1) {\n await scanCheckpoint(context?.signal, index)\n const spanId = trace.spans[index]!.span_id\n if (requested.has(spanId)) found.push(spanId)\n }\n return found\n }\n\n async getOverview(\n filters?: TraceAnalystFilters,\n context?: TraceAnalysisStoreContext,\n ): Promise<DatasetOverview> {\n const idx = await this.index(context)\n const matched = await this.matchedTraces(idx, filters, context)\n\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let rawBytes = 0\n let earliest: string | null = null\n let latest: string | null = null\n let errorTraceCount = 0\n let errorSpanCount = 0\n const clusters = new Map<string, ErrorClusterAccumulator>()\n\n let traceIndex = 0\n for (const t of matched) {\n await scanCheckpoint(context?.signal, traceIndex++)\n if (t.service_name) services.add(t.service_name)\n for (const agent of t.agents) agents.add(agent)\n for (const m of t.models) models.add(m)\n for (const tn of t.tools) tools.add(tn)\n rawBytes += t.raw_jsonl_bytes\n if (!earliest || compareSpanTime(t.start_time, earliest) < 0) earliest = t.start_time\n if (!latest || compareSpanTime(t.end_time, latest) > 0) latest = t.end_time\n if (t.has_errors) {\n errorTraceCount += 1\n let spanIndex = 0\n for (const s of t.spans) {\n await scanCheckpoint(context?.signal, spanIndex++)\n if (s.status !== 'ERROR') continue\n errorSpanCount += 1\n accumulateErrorCluster(clusters, t.trace_id, s)\n }\n }\n }\n\n const sample_trace_ids = matched.slice(0, 20).map((t) => t.trace_id)\n return {\n total_traces: matched.length,\n raw_jsonl_bytes: rawBytes,\n services: [...services].sort(),\n agents: [...agents].sort(),\n models: [...models].sort(),\n tool_names: [...tools].sort(),\n sample_trace_ids,\n errors: { trace_count: errorTraceCount, span_count: errorSpanCount },\n error_clusters: finalizeErrorClusters(clusters, errorTraceCount),\n time_range: earliest && latest ? { earliest, latest } : null,\n }\n }\n\n async queryTraces(\n opts: { filters?: TraceAnalystFilters; limit: number; offset?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<QueryTracesPage> {\n const limit = validateInteger(\n opts.limit,\n 'queryTraces.limit',\n 1,\n TRACE_ANALYSIS_LIMITS.queryTraces,\n )\n const offset = validateInteger(opts.offset ?? 0, 'queryTraces.offset', 0)\n\n const idx = await this.index(context)\n const matched = await this.matchedTraces(idx, opts.filters, context)\n const slice = matched.slice(offset, offset + limit)\n return {\n traces: slice.map((t) => this.toSummary(t)),\n total: matched.length,\n has_more: offset + slice.length < matched.length,\n }\n }\n\n async countTraces(\n filters?: TraceAnalystFilters,\n context?: TraceAnalysisStoreContext,\n ): Promise<number> {\n const idx = await this.index(context)\n const matched = await this.matchedTraces(idx, filters, context)\n return matched.length\n }\n\n async viewTrace(\n opts: { trace_id: string; per_attribute_byte_cap?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<ViewTraceResult> {\n context?.signal?.throwIfAborted()\n const idx = await this.index(context)\n const trace = idx.byTrace.get(opts.trace_id)\n if (!trace) {\n throw new TraceNotFoundError(opts.trace_id)\n }\n const cap = validateInteger(\n opts.per_attribute_byte_cap ?? this.perAttributeViewBudget,\n 'viewTrace.per_attribute_byte_cap',\n 1,\n )\n\n // Probe size first — if the materialised payload would exceed\n // the per-call ceiling we return an oversized summary rather than\n // blowing the agent's context.\n const buf = await this.buffer(context)\n const spans: TraceAnalystSpan[] = []\n let runningBytes = 0\n let span_response_bytes_max = 0\n const counter: TruncationCounter = { value: 0 }\n let spanIndex = 0\n for (const s of trace.spans) {\n await scanCheckpoint(context?.signal, spanIndex++)\n const projected = this.projectSpan(buf, trace.trace_id, s, cap, counter)\n const bytes = Buffer.byteLength(JSON.stringify(projected), 'utf8')\n span_response_bytes_max = Math.max(span_response_bytes_max, bytes)\n runningBytes += bytes\n if (runningBytes > this.perCallByteCeiling) {\n return {\n trace_id: trace.trace_id,\n oversized: this.buildOversizedSummary(trace, span_response_bytes_max),\n }\n }\n spans.push(projected)\n }\n return { trace_id: trace.trace_id, spans }\n }\n\n async viewSpans(\n opts: { trace_id: string; span_ids: readonly string[]; per_attribute_byte_cap?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<ViewSpansResult> {\n context?.signal?.throwIfAborted()\n const idx = await this.index(context)\n const trace = idx.byTrace.get(opts.trace_id)\n if (!trace) throw new TraceNotFoundError(opts.trace_id)\n if (opts.span_ids.length < 1 || opts.span_ids.length > TRACE_ANALYSIS_LIMITS.viewSpans) {\n throw new TraceAnalysisValidationError(\n `viewSpans.span_ids must contain 1..${TRACE_ANALYSIS_LIMITS.viewSpans} ids, got ${opts.span_ids.length}`,\n )\n }\n const cap = validateInteger(\n opts.per_attribute_byte_cap ?? this.perAttributeSpanBudget,\n 'viewSpans.per_attribute_byte_cap',\n 1,\n )\n\n const requested = [...new Set(opts.span_ids)]\n const wantSet = new Set(requested)\n const foundById = new Map<string, SpanIndexEntry>()\n for (let index = 0; index < trace.spans.length; index += 1) {\n await scanCheckpoint(context?.signal, index)\n const span = trace.spans[index]!\n if (wantSet.has(span.span_id)) foundById.set(span.span_id, span)\n }\n const missing = requested.filter((id) => !foundById.has(id))\n\n const buf = await this.buffer(context)\n const spans: TraceAnalystSpan[] = []\n let truncatedAttributeCount = 0\n const omitted = new Set(requested.filter((id) => foundById.has(id)))\n const buildResult = (): ViewSpansResult => ({\n trace_id: trace.trace_id,\n spans,\n missing_span_ids: missing,\n omitted_span_ids: requested.filter((id) => omitted.has(id)),\n has_more: omitted.size > 0,\n truncated_attribute_count: truncatedAttributeCount,\n })\n const metadataBytes = Buffer.byteLength(JSON.stringify(buildResult()), 'utf8')\n if (metadataBytes > this.perCallByteCeiling) {\n throw new TraceAnalysisLimitError(\n 'viewSpans',\n metadataBytes,\n this.perCallByteCeiling,\n `viewSpans accounting requires ${metadataBytes} bytes, over the ${this.perCallByteCeiling}-byte response limit`,\n )\n }\n let spanIndex = 0\n let smallestRejectedBytes = Number.POSITIVE_INFINITY\n for (const id of requested) {\n await scanCheckpoint(context?.signal, spanIndex++)\n const s = foundById.get(id)\n if (!s) continue\n const counter: TruncationCounter = { value: 0 }\n const projected = this.projectSpan(buf, trace.trace_id, s, cap, counter)\n spans.push(projected)\n omitted.delete(id)\n truncatedAttributeCount += counter.value\n const responseBytes = Buffer.byteLength(JSON.stringify(buildResult()), 'utf8')\n if (responseBytes <= this.perCallByteCeiling) {\n continue\n }\n smallestRejectedBytes = Math.min(smallestRejectedBytes, responseBytes)\n if (requested.length === 1) {\n throw new TraceAnalysisLimitError(\n 'viewSpans',\n responseBytes,\n this.perCallByteCeiling,\n `viewSpans cannot fit span ${JSON.stringify(id)} in the ${this.perCallByteCeiling}-byte response limit`,\n )\n }\n spans.pop()\n omitted.add(id)\n truncatedAttributeCount -= counter.value\n }\n if (foundById.size > 0 && spans.length === 0) {\n throw new TraceAnalysisLimitError(\n 'viewSpans',\n smallestRejectedBytes,\n this.perCallByteCeiling,\n `viewSpans cannot fit one requested span in the ${this.perCallByteCeiling}-byte response limit`,\n )\n }\n return buildResult()\n }\n\n async searchTrace(\n opts: { trace_id: string; regex_pattern: string; max_matches?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<SearchTraceResult> {\n const max_matches = validateInteger(\n opts.max_matches ?? 50,\n 'searchTrace.max_matches',\n 1,\n TRACE_ANALYSIS_LIMITS.searchMatches,\n )\n const idx = await this.index(context)\n const trace = idx.byTrace.get(opts.trace_id)\n if (!trace) throw new TraceNotFoundError(opts.trace_id)\n const re = compileSearchRegex(opts.regex_pattern)\n\n const buf = await this.buffer(context)\n const hits: SpanMatchRecord[] = []\n let hasMore = false\n let spanIndex = 0\n for (const s of trace.spans) {\n await scanCheckpoint(context?.signal, spanIndex++)\n const remaining = max_matches - hits.length\n const localHits = await this.scanSpanForMatches(\n buf,\n trace.trace_id,\n s,\n re,\n this.perMatchTextBudget,\n remaining,\n context,\n )\n for (const h of localHits.records) {\n if (hits.length >= max_matches) break\n hits.push(h)\n }\n if (localHits.hasMore) {\n hasMore = true\n break\n }\n }\n return {\n trace_id: trace.trace_id,\n hits,\n has_more: hasMore,\n }\n }\n\n async searchSpan(\n opts: { trace_id: string; span_id: string; regex_pattern: string; max_matches?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<SearchSpanResult> {\n const max_matches = validateInteger(\n opts.max_matches ?? 50,\n 'searchSpan.max_matches',\n 1,\n TRACE_ANALYSIS_LIMITS.searchMatches,\n )\n const idx = await this.index(context)\n const trace = idx.byTrace.get(opts.trace_id)\n if (!trace) throw new TraceNotFoundError(opts.trace_id)\n let span: SpanIndexEntry | undefined\n for (let index = 0; index < trace.spans.length; index += 1) {\n await scanCheckpoint(context?.signal, index)\n const candidate = trace.spans[index]!\n if (candidate.span_id === opts.span_id) {\n span = candidate\n break\n }\n }\n if (!span) {\n throw new SpanNotFoundError(opts.trace_id, opts.span_id)\n }\n const re = compileSearchRegex(opts.regex_pattern)\n const buf = await this.buffer(context)\n const localHits = await this.scanSpanForMatches(\n buf,\n trace.trace_id,\n span,\n re,\n this.perMatchTextBudget,\n max_matches,\n context,\n )\n return {\n trace_id: trace.trace_id,\n span_id: span.span_id,\n hits: localHits.records,\n has_more: localHits.hasMore,\n }\n }\n\n // ─── Index building ────────────────────────────────────────────────\n\n /** Force the index to materialise. Useful to amortise startup cost\n * before the first agent call. */\n async ensureIndexed(context?: TraceAnalysisStoreContext): Promise<void> {\n await this.index(context)\n }\n\n private async buffer(context?: TraceAnalysisStoreContext): Promise<Buffer> {\n context?.signal?.throwIfAborted()\n if (this.bufferValue) return this.bufferValue\n if (!this.bufferTask) {\n const task = createSharedAbortableTask((signal) => this.readBuffer(signal))\n this.bufferTask = task\n void task.promise.then(\n (value) => {\n this.bufferValue = value\n if (this.bufferTask === task) this.bufferTask = undefined\n },\n () => {\n if (this.bufferTask === task) this.bufferTask = undefined\n },\n )\n }\n return waitForSharedTask(this.bufferTask, context?.signal)\n }\n\n protected abstract readBuffer(signal?: AbortSignal): Promise<Buffer>\n\n protected abstract sourcePath(): string\n\n protected projectRecord(raw: Record<string, unknown>): TraceAnalystSpan | null {\n return projectOtlpFlatLine(raw)\n }\n\n private async index(context?: TraceAnalysisStoreContext): Promise<DatasetIndex> {\n context?.signal?.throwIfAborted()\n if (this.indexValue) return this.indexValue\n if (!this.indexTask) {\n const task = createSharedAbortableTask((signal) => this.buildIndex(signal))\n this.indexTask = task\n void task.promise.then(\n (value) => {\n this.indexValue = value\n if (this.indexTask === task) this.indexTask = undefined\n },\n () => {\n if (this.indexTask === task) this.indexTask = undefined\n },\n )\n }\n return waitForSharedTask(this.indexTask, context?.signal)\n }\n\n private async buildIndex(signal?: AbortSignal): Promise<DatasetIndex> {\n // readGuarded surfaces missing/oversized files as typed errors.\n const buf = await this.buffer({ signal })\n signal?.throwIfAborted()\n\n const byTrace = new Map<string, TraceIndexEntry>()\n let cursor = 0\n let lineNumber = 0\n let sinceYield = 0\n while (cursor < buf.length) {\n lineNumber += 1\n // Yield to the event loop every INDEX_YIELD_LINES lines so a huge\n // file doesn't monopolise the thread for the whole index build.\n if (++sinceYield >= INDEX_YIELD_LINES) {\n sinceYield = 0\n await yieldToEventLoop()\n signal?.throwIfAborted()\n }\n const newlineIndex = buf.indexOf(0x0a, cursor) // \\n\n const lineEnd = newlineIndex === -1 ? buf.length : newlineIndex\n const lineLength = lineEnd - cursor\n if (lineLength === 0) {\n cursor = lineEnd + 1\n continue\n }\n const lineSlice = buf.subarray(cursor, lineEnd).toString('utf8')\n const lineOffset = cursor\n cursor = lineEnd + 1\n\n let parsed: unknown\n try {\n parsed = JSON.parse(lineSlice)\n } catch (cause) {\n throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset, cause)\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset)\n }\n const span = this.projectRecord(parsed as Record<string, unknown>)\n if (!span) {\n throw new TraceFileMalformedError(this.sourcePath(), lineNumber, lineOffset)\n }\n\n let entry = byTrace.get(span.trace_id)\n if (!entry) {\n entry = {\n trace_id: span.trace_id,\n service_name: span.service_name,\n agent_name: span.agent_name,\n span_count: 0,\n has_errors: false,\n start_time: span.start_time,\n end_time: span.end_time,\n duration_ms: 0,\n raw_jsonl_bytes: 0,\n agents: new Set(),\n models: new Set(),\n tools: new Set(),\n spans: [],\n }\n byTrace.set(span.trace_id, entry)\n } else {\n // Pin the trace's service/agent to the first AGENT span we\n // Prefer the first agent/service fields that appear in the trace.\n if (!entry.service_name && span.service_name) entry.service_name = span.service_name\n if (!entry.agent_name && span.agent_name) entry.agent_name = span.agent_name\n }\n\n const indexEntry: SpanIndexEntry = {\n span_id: span.span_id,\n parent_span_id: span.parent_span_id,\n name: span.name,\n kind: span.kind,\n start_time: span.start_time,\n end_time: span.end_time,\n duration_ms: span.duration_ms,\n status: span.status,\n status_message: span.status_message,\n service_name: span.service_name,\n agent_name: span.agent_name,\n model_name: span.model_name,\n tool_name: span.tool_name,\n line_byte_offset: lineOffset,\n line_byte_length: lineLength,\n }\n entry.spans.push(indexEntry)\n entry.span_count += 1\n entry.raw_jsonl_bytes += lineLength + 1 // +1 newline byte\n if (span.status === 'ERROR') entry.has_errors = true\n if (compareSpanTime(span.start_time, entry.start_time) < 0) entry.start_time = span.start_time\n if (compareSpanTime(span.end_time, entry.end_time) > 0) entry.end_time = span.end_time\n if (span.agent_name) entry.agents.add(span.agent_name)\n if (span.model_name) entry.models.add(span.model_name)\n if (span.tool_name) entry.tools.add(span.tool_name)\n }\n\n // Compute trace duration once, sort spans by start time for\n // stable iteration.\n let totalRawBytes = 0\n for (const t of byTrace.values()) {\n signal?.throwIfAborted()\n totalRawBytes += t.raw_jsonl_bytes\n t.spans.sort(\n (a, b) =>\n compareSpanTime(a.start_time, b.start_time) || a.line_byte_offset - b.line_byte_offset,\n )\n // Duration is 0 unless BOTH bounds parse — a missing/garbage timestamp\n // yields 0, never a NaN (→ null in JSON) or a bogus epoch-from-zero span.\n const startMs = spanEpochMillis(t.start_time)\n const endMs = spanEpochMillis(t.end_time)\n t.duration_ms = startMs === null || endMs === null ? 0 : Math.max(0, endMs - startMs)\n }\n const sortedTraceIds = [...byTrace.keys()].sort()\n signal?.throwIfAborted()\n\n return { byTrace, totalRawBytes, sortedTraceIds }\n }\n\n // ─── Filter pipeline ───────────────────────────────────────────────\n\n private async matchedTraces(\n idx: DatasetIndex,\n filters: TraceAnalystFilters | undefined,\n context?: TraceAnalysisStoreContext,\n ): Promise<TraceIndexEntry[]> {\n context?.signal?.throwIfAborted()\n const traces: TraceIndexEntry[] = []\n for (let index = 0; index < idx.sortedTraceIds.length; index += 1) {\n await scanCheckpoint(context?.signal, index)\n const trace = idx.byTrace.get(idx.sortedTraceIds[index]!)\n if (trace) traces.push(trace)\n }\n if (!filters) return traces\n\n const indexedFiltered: TraceIndexEntry[] = []\n for (let index = 0; index < traces.length; index += 1) {\n await scanCheckpoint(context?.signal, index)\n const t = traces[index]!\n if (filters.has_errors !== undefined && t.has_errors !== filters.has_errors) continue\n if (filters.service_names && filters.service_names.length > 0) {\n if (!t.service_name || !filters.service_names.includes(t.service_name)) continue\n }\n if (filters.agent_names && filters.agent_names.length > 0) {\n if (![...t.agents].some((agent) => filters.agent_names!.includes(agent))) continue\n }\n if (filters.model_names && filters.model_names.length > 0) {\n if (![...t.models].some((m) => filters.model_names!.includes(m))) continue\n }\n if (filters.tool_names && filters.tool_names.length > 0) {\n if (![...t.tools].some((tn) => filters.tool_names!.includes(tn))) continue\n }\n if (filters.start_time_after && t.start_time < filters.start_time_after) continue\n if (filters.start_time_before && t.start_time > filters.start_time_before) continue\n indexedFiltered.push(t)\n }\n\n if (!filters.regex_pattern) return indexedFiltered\n\n // Opt-in raw-bytes scan — only over the already-narrowed set.\n const re = compileSearchRegex(filters.regex_pattern)\n const buf = await this.buffer(context)\n const out: TraceIndexEntry[] = []\n let traceIndex = 0\n for (const t of indexedFiltered) {\n await scanCheckpoint(context?.signal, traceIndex++)\n let matched = false\n let spanIndex = 0\n for (const s of t.spans) {\n await scanCheckpoint(context?.signal, spanIndex++)\n const slice = buf.subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length)\n // Buffer.toString allocates; tolerate it because regex_pattern\n // is opt-in. Future optimisation: byte-level fast-path for\n // ASCII-only patterns.\n if (re.test(slice.toString('utf8'))) {\n matched = true\n break\n }\n }\n if (matched) out.push(t)\n }\n return out\n }\n\n private toSummary(t: TraceIndexEntry): TraceAnalystTraceSummary {\n return {\n trace_id: t.trace_id,\n service_name: t.service_name,\n agent_name: t.agent_name,\n span_count: t.span_count,\n has_errors: t.has_errors,\n start_time: t.start_time,\n end_time: t.end_time,\n duration_ms: t.duration_ms,\n raw_jsonl_bytes: t.raw_jsonl_bytes,\n models: [...t.models].sort(),\n tools: [...t.tools].sort(),\n }\n }\n\n // ─── Span projection (lazy attribute reads) ────────────────────────\n\n private projectSpan(\n buf: Buffer,\n trace_id: string,\n s: SpanIndexEntry,\n perAttrCap: number,\n counter: TruncationCounter,\n ): TraceAnalystSpan {\n const slice = buf\n .subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length)\n .toString('utf8')\n let raw: Record<string, unknown> = {}\n try {\n const parsed = JSON.parse(slice)\n if (parsed && typeof parsed === 'object') raw = parsed as Record<string, unknown>\n } catch {\n // Should not happen — index pre-validated.\n }\n const attrs = extractOtlpAttributes(raw)\n const projected: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attrs)) {\n if (typeof v === 'string') {\n const trunc = truncateForBudget(v, perAttrCap)\n if (trunc !== v) counter.value += 1\n projected[k] = trunc\n } else if (Array.isArray(v) || (v && typeof v === 'object')) {\n const json = JSON.stringify(v)\n const trunc = truncateForBudget(json, perAttrCap)\n if (trunc !== json) {\n counter.value += 1\n projected[k] = trunc\n } else {\n projected[k] = v\n }\n } else {\n projected[k] = v\n }\n }\n return {\n trace_id,\n span_id: s.span_id,\n parent_span_id: s.parent_span_id,\n name: s.name,\n kind: s.kind,\n start_time: s.start_time,\n end_time: s.end_time,\n duration_ms: s.duration_ms,\n status: s.status,\n status_message: s.status_message,\n service_name: s.service_name,\n agent_name: s.agent_name,\n model_name: s.model_name,\n tool_name: s.tool_name,\n attributes: projected,\n }\n }\n\n private buildOversizedSummary(\n t: TraceIndexEntry,\n span_response_bytes_max: number,\n ): ViewTraceOversized {\n const counts = new Map<string, number>()\n let errorCount = 0\n for (const s of t.spans) {\n counts.set(s.name, (counts.get(s.name) ?? 0) + 1)\n if (s.status === 'ERROR') errorCount += 1\n }\n const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20)\n return {\n span_count: t.span_count,\n top_span_names: top,\n span_response_bytes_max,\n error_span_count: errorCount,\n }\n }\n\n private async scanSpanForMatches(\n buf: Buffer,\n trace_id: string,\n s: SpanIndexEntry,\n re: RE2JS,\n textBudget: number,\n recordCap: number,\n context?: TraceAnalysisStoreContext,\n ): Promise<{ records: SpanMatchRecord[]; hasMore: boolean }> {\n // We scan against the original raw JSONL slice for each span and\n // record byte positions; the matched_text + context window is\n // truncated to `textBudget` bytes per record so total tool output\n // stays bounded even if hits cluster.\n const slice = buf\n .subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length)\n .toString('utf8')\n const records: SpanMatchRecord[] = []\n let hasMore = false\n let matchIndex = 0\n for (const match of re.matchAll(slice)) {\n await scanCheckpoint(context?.signal, matchIndex++)\n if (records.length >= recordCap) {\n hasMore = true\n break\n }\n const offset = match.index ?? 0\n const before = slice.slice(Math.max(0, offset - textBudget / 2), offset)\n const after = slice.slice(\n offset + match[0].length,\n offset + match[0].length + Math.floor(textBudget / 2),\n )\n records.push({\n trace_id,\n span_id: s.span_id,\n span_name: s.name,\n span_kind: s.kind,\n attribute_path: bestAttributePathForOffset(slice, offset) ?? 'span.raw',\n matched_text: truncateForBudget(match[0], textBudget),\n context_before: truncateForBudget(before, textBudget),\n context_after: truncateForBudget(after, textBudget),\n match_offset: offset,\n })\n }\n return { records, hasMore }\n }\n}\n\nexport class OtlpFileTraceStore extends BufferedTraceStore {\n private readonly path: string\n private readonly maxFileBytes: number\n\n constructor(opts: OtlpFileTraceStoreOptions) {\n super(opts)\n this.path = opts.path\n this.maxFileBytes = validateInteger(\n opts.maxFileBytes ?? DEFAULT_MAX_TRACE_FILE_BYTES,\n 'maxFileBytes',\n 1,\n )\n }\n\n /** Stat-then-read so an oversized file fails loud before allocating the\n * source buffer. Missing files remain distinct from malformed traces. */\n protected async readBuffer(signal?: AbortSignal): Promise<Buffer> {\n signal?.throwIfAborted()\n let stats: Awaited<ReturnType<typeof stat>>\n try {\n stats = await stat(this.path)\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {\n throw new TraceFileMissingError(this.path)\n }\n throw err\n }\n if (stats.size > this.maxFileBytes) {\n throw new TraceFileTooLargeError(this.path, stats.size, this.maxFileBytes)\n }\n signal?.throwIfAborted()\n return readFile(this.path, { signal })\n }\n\n protected sourcePath(): string {\n return this.path\n }\n}\n\nclass BufferTraceStore extends BufferedTraceStore {\n constructor(\n private readonly source: Buffer,\n opts: BufferedTraceStoreOptions,\n ) {\n super(opts)\n }\n\n protected async readBuffer(signal?: AbortSignal): Promise<Buffer> {\n signal?.throwIfAborted()\n return this.source\n }\n\n protected sourcePath(): string {\n return '<memory>'\n }\n}\n\nclass SpanRecordTraceStore extends BufferTraceStore {\n protected override projectRecord(raw: Record<string, unknown>): TraceAnalystSpan {\n return traceSpanSchema.parse(raw)\n }\n}\n\n/**\n * Snapshot canonical spans without reinterpreting their identifiers, kind, or duration.\n * Reads use the same indexed, bounded engine as the OTLP adapters. Raw byte counts\n * and searches refer to the canonical JSONL snapshot, not an external source artifact.\n */\nexport function spanRecordsToTraceAnalysisStore(\n records: readonly TraceAnalystSpan[],\n options: SpanRecordsToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!records || records.length === 0) {\n throw new CaptureIntegrityError('spanRecordsToTraceAnalysisStore: no span records supplied')\n }\n const seen = new Map<string, Set<string>>()\n const lines = records.map((record, index) => {\n try {\n const span = traceSpanSchema.parse(record)\n const traceSpans = seen.get(span.trace_id) ?? new Set<string>()\n if (traceSpans.has(span.span_id)) {\n throw new CaptureIntegrityError(\n `spanRecordsToTraceAnalysisStore: duplicate span '${span.span_id}' in trace '${span.trace_id}'`,\n )\n }\n traceSpans.add(span.span_id)\n seen.set(span.trace_id, traceSpans)\n return JSON.stringify(span)\n } catch (cause) {\n if (cause instanceof CaptureIntegrityError) throw cause\n throw new CaptureIntegrityError(\n `spanRecordsToTraceAnalysisStore: invalid span record at index ${index}`,\n { cause },\n )\n }\n })\n return new SpanRecordTraceStore(Buffer.from(`${lines.join('\\n')}\\n`, 'utf8'), options)\n}\n\n/** Build the bounded trace store directly from OpenInference JSONL text. */\nexport function otlpTextToTraceAnalysisStore(\n text: string,\n opts: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!text.trim()) throw new CaptureIntegrityError('OTLP trace text must not be empty')\n return new BufferTraceStore(Buffer.from(text, 'utf8'), opts)\n}\n\nexport function createOtlpBufferTraceStore(\n source: Buffer,\n options: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n return new BufferTraceStore(source, options)\n}\n\nexport {\n SpanNotFoundError,\n TraceFileMalformedError,\n TraceFileMissingError,\n TraceFileTooLargeError,\n TraceNotFoundError,\n} from './errors'\n\n// ─── OTLP shape readers ──────────────────────────────────────────────\n//\n// The per-line projection lives in `./otlp-span` so the index here and\n// `otlpToRunRecords` read the same vocabulary off the same parser.\n\n// Per-call truncation counter. Each public read that projects spans\n// owns one of these and threads it through projectSpan; a store-keyed\n// counter would let two concurrent reads on the same store report each\n// other's truncation counts.\ninterface TruncationCounter {\n value: number\n}\n\n/** A `\"` at `idx` is a real JSON delimiter only when the run of `\\`\n * immediately preceding it is even-length; an odd run means the quote\n * is escaped (`\\\"`) and is part of a string value, not a boundary. */\nfunction isUnescapedQuote(slice: string, idx: number): boolean {\n if (slice[idx] !== '\"') return false\n let backslashes = 0\n let b = idx - 1\n while (b >= 0 && slice[b] === '\\\\') {\n backslashes += 1\n b -= 1\n }\n return backslashes % 2 === 0\n}\n\n/** Scan backwards from `from` (inclusive) for the nearest UNescaped `\"`.\n * Returns its index, or -1 when none is found. */\nfunction prevUnescapedQuote(slice: string, from: number): number {\n for (let i = from; i >= 0; i -= 1) {\n if (slice[i] === '\"' && isUnescapedQuote(slice, i)) return i\n }\n return -1\n}\n\n/**\n * Best-effort: locate the JSON path for the substring at `offset` in\n * a single span's JSONL slice. The slice is '...,\"key\":\"value...\"' — we\n * walk back from `offset` to the value-opening quote, past the `:`, to\n * the key's closing then opening quote, skipping `\\\"`-escaped quotes that\n * live inside string values. Returns `null` when the offset doesn't fall\n * inside a recognisable string field.\n */\nfunction bestAttributePathForOffset(slice: string, offset: number): string | null {\n // Value-opening quote: nearest unescaped '\"' at or before the offset.\n const valueQuote = prevUnescapedQuote(slice, Math.min(offset, slice.length - 1))\n if (valueQuote < 1) return null\n // The ':' separating key and value sits before the value quote.\n let j = valueQuote - 1\n while (j >= 0 && slice[j] !== ':') j -= 1\n if (j < 1) return null\n // Key closing quote, then key opening quote — both unescaped.\n const keyClose = prevUnescapedQuote(slice, j - 1)\n if (keyClose < 1) return null\n const keyOpen = prevUnescapedQuote(slice, keyClose - 1)\n if (keyOpen < 0) return null\n return slice.slice(keyOpen + 1, keyClose)\n}\n\n// ─── Error-cluster extraction ────────────────────────────────────────\n//\n// Deterministic failure-coverage population. The error-span loop in\n// getOverview already visits every ERROR span; bucketing them by a\n// normalized status_message signature turns \"N error spans\" into \"K\n// distinct failure modes\" — the checklist an analyst must close. No LLM.\n\nconst ERROR_CLUSTER_EXEMPLARS = 5\n\ninterface ErrorClusterAccumulator {\n signature: string\n sample: string\n traceIds: Set<string>\n spanIds: string[]\n spanCount: number\n spanNames: Map<string, number>\n toolNames: Map<string, number>\n}\n\n/** Collapse volatile tokens so semantically identical failures share a key:\n * hex/uuid ids → <id>, numbers → #, quoted/abs paths → <path>, durations →\n * <dur>, whitespace collapsed. Empty/absent messages fall back to the span\n * name so a no-message error still forms a real cluster. */\nfunction normalizeErrorSignature(message: string | undefined, spanName: string): string {\n const raw = (message ?? '').trim()\n const base = raw.length > 0 ? raw : `(${spanName || 'error'} — no message)`\n const norm = base\n .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<id>')\n .replace(/\\b[0-9a-f]{12,}\\b/gi, '<id>')\n .replace(/(?:\\/[\\w.\\-@]+){2,}/g, '<path>')\n .replace(/\\b\\d+(?:\\.\\d+)?(ms|s|m|h|kb|mb|gb)?\\b/gi, (_m, u) => (u ? `#${u}` : '#'))\n .replace(/\\s+/g, ' ')\n .trim()\n return norm\n}\n\nfunction bump(map: Map<string, number>, key: string | null): void {\n if (!key) return\n map.set(key, (map.get(key) ?? 0) + 1)\n}\n\nfunction topKey(map: Map<string, number>): string | null {\n let best: string | null = null\n let bestN = 0\n for (const [k, n] of map)\n if (n > bestN) {\n best = k\n bestN = n\n }\n return best\n}\n\nfunction accumulateErrorCluster(\n clusters: Map<string, ErrorClusterAccumulator>,\n traceId: string,\n span: SpanIndexEntry,\n): void {\n const signature = normalizeErrorSignature(span.status_message, span.name)\n let acc = clusters.get(signature)\n if (!acc) {\n acc = {\n signature,\n sample: span.status_message ?? span.name ?? '',\n traceIds: new Set(),\n spanIds: [],\n spanCount: 0,\n spanNames: new Map(),\n toolNames: new Map(),\n }\n clusters.set(signature, acc)\n }\n acc.traceIds.add(traceId)\n acc.spanCount += 1\n if (acc.spanIds.length < ERROR_CLUSTER_EXEMPLARS && !acc.spanIds.includes(span.span_id)) {\n acc.spanIds.push(span.span_id)\n }\n bump(acc.spanNames, span.name)\n bump(acc.toolNames, span.tool_name)\n}\n\nfunction finalizeErrorClusters(\n clusters: Map<string, ErrorClusterAccumulator>,\n errorTraceCount: number,\n): ErrorCluster[] {\n const out = [...clusters.values()].map(\n (acc): ErrorCluster => ({\n signature: acc.signature,\n status_message_sample: acc.sample,\n span_name: topKey(acc.spanNames),\n tool_name: topKey(acc.toolNames),\n trace_count: acc.traceIds.size,\n span_count: acc.spanCount,\n prevalence: errorTraceCount > 0 ? acc.traceIds.size / errorTraceCount : 0,\n exemplar_trace_ids: [...acc.traceIds].slice(0, ERROR_CLUSTER_EXEMPLARS),\n exemplar_span_ids: acc.spanIds.slice(0, ERROR_CLUSTER_EXEMPLARS),\n }),\n )\n out.sort((a, b) => b.trace_count - a.trace_count || b.span_count - a.span_count)\n return out\n}\n"],"mappings":";;;;AAOA,SAAgB,0BACd,SACwB;CACxB,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,OAA+B;EACnC;EACA,SAAS,QAAQ,WAAW,MAAM;EAClC,WAAW;EACX,SAAS;CACX;CACA,KAAU,QAAQ,WACV;EACJ,KAAK,UAAU;CACjB,SACM;EACJ,KAAK,UAAU;CACjB,CACF;CACA,OAAO;AACT;AAEA,SAAgB,kBACd,MACA,QACY;CACZ,QAAQ,eAAe;CACvB,KAAK,aAAa;CAElB,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,IAAI,WAAW;EACf,MAAM,UAAU,aAA+B;GAC7C,IAAI,UAAU;GACd,WAAW;GACX,QAAQ,oBAAoB,SAAS,OAAO;GAC5C,KAAK,aAAa;GAClB,SAAS;EACX;EACA,MAAM,gBAAsB;GAC1B,aAAa;IACX,OAAO,QAAQ,MAAM;IACrB,IAAI,CAAC,KAAK,WAAW,KAAK,cAAc,GACtC,KAAK,WAAW,MAAM,QAAQ,MAAM;GAExC,CAAC;EACH;EAEA,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACzD,KAAK,QAAQ,MACV,UAAU,aAAa,QAAQ,KAAK,CAAC,IACrC,UAAmB,aAAa,OAAO,KAAK,CAAC,CAChD;EACA,IAA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ors-DEE6u6ot.js";
2
2
  import { c as CostLedgerHandle } from "./cost-ledger-DbQdN3nO.js";
3
3
  import { C as ToolSpan } from "./schema-2g7trUwH.js";
4
4
  import { d as RunTokenUsage } from "./run-record-DF-fuu31.js";
5
- import { E as SpanSourceReader, F as SearchTraceResult, K as ViewTraceResult, N as QueryTracesPage, O as TraceAnalysisStore, P as SearchSpanResult, W as ViewSpansResult, f as AnalystUsageReceipt, i as AnalystFinding, j as DatasetOverview, k as TraceAnalysisStoreContext, z as TraceAnalystFilters } from "./types-6VEehmEg.js";
5
+ import { B as TraceAnalystSpan, E as SpanSourceReader, F as SearchTraceResult, K as ViewTraceResult, N as QueryTracesPage, O as TraceAnalysisStore, P as SearchSpanResult, W as ViewSpansResult, f as AnalystUsageReceipt, i as AnalystFinding, j as DatasetOverview, k as TraceAnalysisStoreContext, z as TraceAnalystFilters } from "./types-6VEehmEg.js";
6
6
  import { et as ProviderRedactor, rt as RawProviderSink } from "./types-DLxe96rp.js";
7
7
  import { i as SearchArtifactRef } from "./search-ledger-types-p2xKfiDJ.js";
8
8
  import { s as TraceStore } from "./store-C4avFjIi.js";
@@ -313,8 +313,10 @@ interface ToolSpansToTraceAnalysisStoreOptions {
313
313
  /** Override the per-match text budget. */
314
314
  perMatchTextBudget?: number;
315
315
  }
316
- type BufferedOtlpTraceStoreOptions = ToolSpansToTraceAnalysisStoreOptions;
317
- interface OtlpFileTraceStoreOptions extends BufferedOtlpTraceStoreOptions {
316
+ /** Budgets and authorized source access shared by canonical span-record stores. */
317
+ type SpanRecordsToTraceAnalysisStoreOptions = ToolSpansToTraceAnalysisStoreOptions;
318
+ type BufferedTraceStoreOptions = ToolSpansToTraceAnalysisStoreOptions;
319
+ interface OtlpFileTraceStoreOptions extends BufferedTraceStoreOptions {
318
320
  /** Path to the OTLP-JSONL file. */
319
321
  path: string;
320
322
  /**
@@ -326,7 +328,7 @@ interface OtlpFileTraceStoreOptions extends BufferedOtlpTraceStoreOptions {
326
328
  */
327
329
  maxFileBytes?: number;
328
330
  }
329
- declare abstract class BufferedOtlpTraceStore implements TraceAnalysisStore {
331
+ declare abstract class BufferedTraceStore implements TraceAnalysisStore {
330
332
  readonly readSpanSource?: SpanSourceReader;
331
333
  private readonly perAttributeViewBudget;
332
334
  private readonly perAttributeSpanBudget;
@@ -336,7 +338,7 @@ declare abstract class BufferedOtlpTraceStore implements TraceAnalysisStore {
336
338
  private indexTask?;
337
339
  private bufferValue?;
338
340
  private bufferTask?;
339
- constructor(opts: BufferedOtlpTraceStoreOptions);
341
+ constructor(opts: BufferedTraceStoreOptions);
340
342
  hasTrace(trace_id: string, context?: TraceAnalysisStoreContext): Promise<boolean>;
341
343
  hasSpans(opts: {
342
344
  trace_id: string;
@@ -375,6 +377,7 @@ declare abstract class BufferedOtlpTraceStore implements TraceAnalysisStore {
375
377
  private buffer;
376
378
  protected abstract readBuffer(signal?: AbortSignal): Promise<Buffer>;
377
379
  protected abstract sourcePath(): string;
380
+ protected projectRecord(raw: Record<string, unknown>): TraceAnalystSpan | null;
378
381
  private index;
379
382
  private buildIndex;
380
383
  private matchedTraces;
@@ -383,7 +386,7 @@ declare abstract class BufferedOtlpTraceStore implements TraceAnalysisStore {
383
386
  private buildOversizedSummary;
384
387
  private scanSpanForMatches;
385
388
  }
386
- declare class OtlpFileTraceStore extends BufferedOtlpTraceStore {
389
+ declare class OtlpFileTraceStore extends BufferedTraceStore {
387
390
  private readonly path;
388
391
  private readonly maxFileBytes;
389
392
  constructor(opts: OtlpFileTraceStoreOptions);
@@ -392,6 +395,12 @@ declare class OtlpFileTraceStore extends BufferedOtlpTraceStore {
392
395
  protected readBuffer(signal?: AbortSignal): Promise<Buffer>;
393
396
  protected sourcePath(): string;
394
397
  }
398
+ /**
399
+ * Snapshot canonical spans without reinterpreting their identifiers, kind, or duration.
400
+ * Reads use the same indexed, bounded engine as the OTLP adapters. Raw byte counts
401
+ * and searches refer to the canonical JSONL snapshot, not an external source artifact.
402
+ */
403
+ declare function spanRecordsToTraceAnalysisStore(records: readonly TraceAnalystSpan[], options?: SpanRecordsToTraceAnalysisStoreOptions): TraceAnalysisStore;
395
404
  /** Build the bounded trace store directly from OpenInference JSONL text. */
396
405
  declare function otlpTextToTraceAnalysisStore(text: string, opts?: ToolSpansToTraceAnalysisStoreOptions): TraceAnalysisStore;
397
406
  //#endregion
@@ -406,5 +415,5 @@ declare class ToolTraceMissingError extends CaptureIntegrityError {
406
415
  */
407
416
  declare function toolSpansToTraceAnalysisStore(spans: readonly ToolSpan[] | null | undefined, options?: ToolSpansToTraceAnalysisStoreOptions): TraceAnalysisStore;
408
417
  //#endregion
409
- export { AnalyzeTracesInput as A, CaptureFetchContext as B, inferDomainKeywords as C, planTraceInsightQuestions as D, isTraceInsightEvidence as E, OTEL_AGENT_EVAL_SCOPE as F, SseUsageMode as G, captureFetchToRawSink as H, OtlpExport as I, extractUsageFromSse as J, extractUsage as K, OtlpResourceSpans as L, AnalyzeTracesResult as M, analyzeTraces as N, scoreTraceInsightReadiness as O, OtlpFlatLine as P, OtlpSpan as R, domainEvidencePattern as S, isTraceInsightAttribution as T, ExtractUsageFromSseOptions as U, CaptureFetchOptions as V, ExtractedUsage as W, TraceInsightTask as _, ToolSpansToTraceAnalysisStoreOptions as a, defaultTraceInsightPanel as b, TraceInsightContext as c, TraceInsightPanelRole as d, TraceInsightPromptInput as f, TraceInsightSuite as g, TraceInsightReadiness as h, OtlpFileTraceStoreOptions as i, AnalyzeTracesOptions as j, tokenizeDomainWords as k, TraceInsightEvidence as l, TraceInsightQuestion as m, toolSpansToTraceAnalysisStore as n, otlpTextToTraceAnalysisStore as o, TraceInsightQualityGate as p, extractUsageFromResponse as q, OtlpFileTraceStore as r, TraceInsightAttribution as s, ToolTraceMissingError as t, TraceInsightFinding as u, buildTraceInsightContext as v, isTraceInsightArtifact as w, describeTraceInsightScope as x, buildTraceInsightPrompt as y, exportRunAsOtlp as z };
410
- //# sourceMappingURL=store-tool-spans-CAF3T-BS.d.ts.map
418
+ export { scoreTraceInsightReadiness as A, OtlpSpan as B, describeTraceInsightScope as C, isTraceInsightAttribution as D, isTraceInsightArtifact as E, analyzeTraces as F, ExtractUsageFromSseOptions as G, CaptureFetchContext as H, OtlpFlatLine as I, extractUsage as J, ExtractedUsage as K, OTEL_AGENT_EVAL_SCOPE as L, AnalyzeTracesInput as M, AnalyzeTracesOptions as N, isTraceInsightEvidence as O, AnalyzeTracesResult as P, OtlpExport as R, defaultTraceInsightPanel as S, inferDomainKeywords as T, CaptureFetchOptions as U, exportRunAsOtlp as V, captureFetchToRawSink as W, extractUsageFromSse as X, extractUsageFromResponse as Y, TraceInsightReadiness as _, SpanRecordsToTraceAnalysisStoreOptions as a, buildTraceInsightContext as b, spanRecordsToTraceAnalysisStore as c, TraceInsightEvidence as d, TraceInsightFinding as f, TraceInsightQuestion as g, TraceInsightQualityGate as h, OtlpFileTraceStoreOptions as i, tokenizeDomainWords as j, planTraceInsightQuestions as k, TraceInsightAttribution as l, TraceInsightPromptInput as m, toolSpansToTraceAnalysisStore as n, ToolSpansToTraceAnalysisStoreOptions as o, TraceInsightPanelRole as p, SseUsageMode as q, OtlpFileTraceStore as r, otlpTextToTraceAnalysisStore as s, ToolTraceMissingError as t, TraceInsightContext as u, TraceInsightSuite as v, domainEvidencePattern as w, buildTraceInsightPrompt as x, TraceInsightTask as y, OtlpResourceSpans as z };
419
+ //# sourceMappingURL=store-tool-spans-BYIarVrG.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"store-tool-spans-CAF3T-BS.d.ts","names":[],"sources":["../src/trace/extract-usage.ts","../src/trace/capture-fetch.ts","../src/trace/otel.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace-analyst/store-otlp.ts","../src/trace-analyst/store-tool-spans.ts"],"mappings":";;;;;;;;;;;KAgBY,iBAAiB;KACjB;UAEK;;EAEf,OAAO;;;;;;;iBAuDO,aAAa,gBAAgB;;;;;;iBAkD7B,oBACd,cACA,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,4BACT,QAAQ;EAuCL,UACJ;IAAQ;IAAkB;IAA6B;KACvD,UAAU,4BACT,QAAQ;EAsFL,YACJ;IAAQ;IAAkB;IAAuB;KACjD,UAAU,4BACT,QAAQ;EA4CL,WACJ;IAAQ;IAAkB;IAAiB;IAAuB;KAClE,UAAU,4BACT,QAAQ;;;EA6CL,cAAc,UAAU,4BAA4B;UAI5C;qBAmBK,WAAW,SAAS,cAAc,QAAQ;qBAE1C;UAEL;UAmBA;UAsHA;UA+DN;UAkBA;UAwDA;UAmBM;;cA+CH,2BAA2B;mBACrB;mBACA;EAEjB,YAAY,MAAM;;;YAYF,WAAW,SAAS,cAAc,QAAQ;YAkBhD;;;iBAwBI,6BACd,cACA,OAAM,uCACL;;;;cC18BU,8BAA8B;EACzC;;;;;;iBASc,8BACd,gBAAgB,+BAChB,UAAS,uCACR"}
1
+ {"version":3,"file":"store-tool-spans-BYIarVrG.d.ts","names":[],"sources":["../src/trace/extract-usage.ts","../src/trace/capture-fetch.ts","../src/trace/otel.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace-analyst/store-otlp.ts","../src/trace-analyst/store-tool-spans.ts"],"mappings":";;;;;;;;;;;KAgBY,iBAAiB;KACjB;UAEK;;EAEf,OAAO;;;;;;;iBAuDO,aAAa,gBAAgB;;;;;;iBAkD7B,oBACd,cACA,UAAS,6BACR;;;;;;;iBA4DmB,yBACpB,UAAU,UACV,aAAa,6BACZ,QAAQ;;;UC1KM;;;EAGf;;EAEA;;;EAGA;;EAEA;;EAEA;;UAGe;;EAEf,WAAW;;;EAGX;;;EAGA;;;;;;;;EAQA,WAAW,OAAO,gBAAgB,KAAK;;EAEvC,eAAe;;iBAkDD,sBACd,cAAc,WAAW,OACzB,MAAM,iBACN,KAAK,qBACL,OAAM,6BACE,WAAW;;;cCxFR;EAA0B;EAAoC;;UAE1D;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,YAAY;IACV;IACA;MA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;;cA+CH,2BAA2B;mBACrB;mBACA;EAEjB,YAAY,MAAM;;;YAYF,WAAW,SAAS,cAAc,QAAQ;YAkBhD;;;;;;;iBAkCI,gCACd,kBAAkB,oBAClB,UAAS,yCACR;;iBA6Ba,6BACd,cACA,OAAM,uCACL;;;;cC//BU,8BAA8B;EACzC;;;;;;iBASc,8BACd,gBAAgB,+BAChB,UAAS,uCACR"}
@@ -1,11 +1,11 @@
1
1
  import { n as CaptureIntegrityError } from "./errors-Dngq5h35.js";
2
2
  import { t as LEDGER_HASH_PATTERN } from "./canonical-BsZVgBhW.js";
3
- import { r as runTraceAnalyst } from "./kind-factory-CdPPHtGZ.js";
3
+ import { r as runTraceAnalyst } from "./kind-factory-Cn1lbsAd.js";
4
4
  import { OPENINFERENCE_SPAN_KIND, applyLlmSpanOtlpAttributes } from "./trace-attributes.js";
5
5
  import { r as extractUsageFromSse, t as extractUsage } from "./extract-usage-BrnzRJ6H.js";
6
6
  import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-rB2DYxr6.js";
7
7
  import { n as traceSpanKindToOpenInferenceKind, t as applyToolSpanOtlpAttributes } from "./otlp-attributes-D9ptWaIJ.js";
8
- import { n as OtlpFileTraceStore, r as createOtlpBufferTraceStore } from "./store-otlp-yd9lDziN.js";
8
+ import { n as OtlpFileTraceStore, r as createOtlpBufferTraceStore } from "./store-otlp-BA7G1Du-.js";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { deriveHexId, isW3CSpanId, isW3CTraceId } from "@tangle-network/agent-trace-contract";
11
11
  //#region src/trace/capture-fetch.ts
@@ -731,4 +731,4 @@ function toolSpanTimeIso(value, spanId, field) {
731
731
  //#endregion
732
732
  export { spanIdForWire as C, exportRunAsOtlp as S, captureFetchToRawSink as T, tokenizeDomainWords as _, spanStatusToOtlp as a, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION as b, defaultTraceInsightPanel as c, inferDomainKeywords as d, isTraceInsightArtifact as f, scoreTraceInsightReadiness as g, planTraceInsightQuestions as h, epochMillisToIso as i, describeTraceInsightScope as l, isTraceInsightEvidence as m, toolSpansToTraceAnalysisStore as n, buildTraceInsightContext as o, isTraceInsightAttribution as p, createOtlpFlatLine as r, buildTraceInsightPrompt as s, ToolTraceMissingError as t, domainEvidencePattern as u, analyzeTraces as v, traceIdForWire as w, OTEL_AGENT_EVAL_SCOPE as x, TRACE_ANALYST_ACTOR_DESCRIPTION as y };
733
733
 
734
- //# sourceMappingURL=store-tool-spans-D5kOU0mr.js.map
734
+ //# sourceMappingURL=store-tool-spans-DKoVbE-w.js.map