@tangle-network/agent-eval 0.95.1 → 0.96.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/adapters/http.d.ts +1 -1
  2. package/dist/adapters/langchain.d.ts +1 -1
  3. package/dist/adapters/otel.d.ts +1 -1
  4. package/dist/analyst/index.js +1 -1
  5. package/dist/belief-state/index.js +1 -1
  6. package/dist/builder-eval/index.js +4 -29
  7. package/dist/builder-eval/index.js.map +1 -1
  8. package/dist/campaign/index.d.ts +6 -6
  9. package/dist/campaign/index.js +5 -5
  10. package/dist/{chunk-AQ5WQAIV.js → chunk-3NHEO6ZC.js} +2 -2
  11. package/dist/chunk-3NHEO6ZC.js.map +1 -0
  12. package/dist/{chunk-URWVKRCS.js → chunk-6GT4NI4V.js} +2 -2
  13. package/dist/{chunk-5HRORJQY.js → chunk-AIGWQEME.js} +5 -16
  14. package/dist/{chunk-5HRORJQY.js.map → chunk-AIGWQEME.js.map} +1 -1
  15. package/dist/{chunk-2T4EZACH.js → chunk-HRGTA6U5.js} +2 -2
  16. package/dist/{chunk-56GC6VYO.js → chunk-HRGUJTER.js} +669 -665
  17. package/dist/chunk-HRGUJTER.js.map +1 -0
  18. package/dist/{chunk-NACM5RS7.js → chunk-IH7LYRHL.js} +2 -2
  19. package/dist/{chunk-7QTQKIDD.js → chunk-JMIUM2HE.js} +3 -3
  20. package/dist/{chunk-YRZ4M5GS.js → chunk-NF7OZ4J7.js} +7 -29
  21. package/dist/chunk-NF7OZ4J7.js.map +1 -0
  22. package/dist/{chunk-X74V6ESX.js → chunk-OKQ2LAT7.js} +2 -2
  23. package/dist/{chunk-Z6L6YSU6.js → chunk-QZYXA7ZO.js} +11 -45
  24. package/dist/chunk-QZYXA7ZO.js.map +1 -0
  25. package/dist/{chunk-KKWJD5E6.js → chunk-RPZMBW27.js} +5 -5
  26. package/dist/{chunk-QTMYW64F.js → chunk-VDGPPGE3.js} +2 -2
  27. package/dist/contract/index.d.ts +144 -9
  28. package/dist/contract/index.js +152 -8
  29. package/dist/contract/index.js.map +1 -1
  30. package/dist/diagnose.js +1 -1
  31. package/dist/{gepa-C1NCIZ9o.d.ts → gepa-Dprxvz8r.d.ts} +2 -2
  32. package/dist/hosted/index.d.ts +1 -1
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +15 -9
  35. package/dist/index.js.map +1 -1
  36. package/dist/meta-eval/index.d.ts +1 -1
  37. package/dist/meta-eval/index.js +6 -28
  38. package/dist/meta-eval/index.js.map +1 -1
  39. package/dist/multishot/index.d.ts +1 -1
  40. package/dist/openapi.json +1 -1
  41. package/dist/pipelines/index.js +5 -19
  42. package/dist/pipelines/index.js.map +1 -1
  43. package/dist/{provenance-CncDq9qE.d.ts → provenance-DJ--Jcbg.d.ts} +3 -3
  44. package/dist/reporting.d.ts +1 -1
  45. package/dist/reporting.js +4 -4
  46. package/dist/rl.d.ts +1 -1
  47. package/dist/rl.js +5 -5
  48. package/dist/{run-campaign-WXY7KI67.js → run-campaign-OWCFOEQG.js} +3 -3
  49. package/dist/{statistics-CCJpTGOS.d.ts → statistics-xP-cWc5k.d.ts} +17 -1
  50. package/dist/{types-DQRY8ZT-.d.ts → types-BMahhhio.d.ts} +1 -1
  51. package/dist/workflow/index.d.ts +1 -1
  52. package/dist/workflow/index.js +1 -1
  53. package/package.json +1 -1
  54. package/dist/chunk-56GC6VYO.js.map +0 -1
  55. package/dist/chunk-AQ5WQAIV.js.map +0 -1
  56. package/dist/chunk-YRZ4M5GS.js.map +0 -1
  57. package/dist/chunk-Z6L6YSU6.js.map +0 -1
  58. /package/dist/{chunk-URWVKRCS.js.map → chunk-6GT4NI4V.js.map} +0 -0
  59. /package/dist/{chunk-2T4EZACH.js.map → chunk-HRGTA6U5.js.map} +0 -0
  60. /package/dist/{chunk-NACM5RS7.js.map → chunk-IH7LYRHL.js.map} +0 -0
  61. /package/dist/{chunk-7QTQKIDD.js.map → chunk-JMIUM2HE.js.map} +0 -0
  62. /package/dist/{chunk-X74V6ESX.js.map → chunk-OKQ2LAT7.js.map} +0 -0
  63. /package/dist/{chunk-KKWJD5E6.js.map → chunk-RPZMBW27.js.map} +0 -0
  64. /package/dist/{chunk-QTMYW64F.js.map → chunk-VDGPPGE3.js.map} +0 -0
  65. /package/dist/{run-campaign-WXY7KI67.js.map → run-campaign-OWCFOEQG.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contamination-guard.ts","../src/contract/analyze-runs.ts"],"sourcesContent":["/**\n * ContaminationGuard — ensures held-out scenarios don't leak into\n * training/prompt paths, and flags model memorization.\n *\n * Three probes:\n * 1. `checkCanaries(output, scenario)` — if the scenario carries a\n * canary token, it MUST NOT appear in the agent's output.\n * Canaries are strings that are statistically impossible to\n * reconstruct from the scenario description alone — so if they\n * echo back, the model memorized them.\n * 2. `canaryLeakView(store)` — cross-corpus view of every run whose\n * output contained a canary, with the offending scenario + run.\n * 3. `HoldoutAuditor` — wraps a Dataset and emits a structured error\n * on any code path that reads holdout scenarios but doesn't flag\n * `purpose: 'evaluation'`. Keeps engineers honest.\n */\n\nimport type { DatasetScenario } from './dataset'\nimport { llmSpans } from './trace/query'\nimport type { TraceStore } from './trace/store'\n\nexport interface CanaryLeak {\n scenarioId: string\n canary: string\n runId?: string\n evidence: string\n}\n\nexport function checkCanaries(output: string, scenarios: DatasetScenario[]): CanaryLeak[] {\n const leaks: CanaryLeak[] = []\n for (const s of scenarios) {\n if (!s.canary) continue\n if (output.includes(s.canary)) {\n leaks.push({ scenarioId: s.id, canary: s.canary, evidence: excerpt(output, s.canary) })\n }\n }\n return leaks\n}\n\n/**\n * Behavioral canary: tests the AGENT, not the eval grep.\n *\n * - `forbiddenPattern` PRESENT in output ⇒ AGENT EMITTED BAD CONTENT ⇒ LEAK.\n * - `forbiddenPattern` ABSENT from output ⇒ AGENT HELD THE LINE ⇒ PASS.\n *\n * Use when running known-bad-prompt scenarios against the agent under\n * test and you want to know if the agent misbehaved. The classical\n * {@link checkCanaries} / {@link import('./canary').runCanaries | runCanaries}\n * test whether the eval check fires when the bad output is forced\n * into the eval flow — different question, different answer.\n *\n * Pattern resolution order (first match wins):\n * 1. `scenario.forbiddenPattern` — if it parses as `/body/flags`,\n * treated as a regex; otherwise a literal substring.\n * 2. `scenario.canary` — literal substring fallback so the helper\n * works on existing scenario fixtures.\n *\n * Returns `null` when nothing forbidden was found OR the scenario\n * declared no pattern.\n */\nexport function checkBehavioralCanary(\n output: string,\n scenario: DatasetScenario,\n): CanaryLeak | null {\n const pattern = scenario.forbiddenPattern ?? scenario.canary\n if (!pattern) return null\n const hit = matchForbidden(output, pattern)\n if (!hit) return null\n return {\n scenarioId: scenario.id,\n canary: pattern,\n evidence: excerpt(output, hit),\n }\n}\n\n/**\n * Behavioral canary over many (scenario, output) pairs. Sibling to\n * {@link import('./canary').runCanaries | runCanaries} — same idea\n * (run-many → report) but the question being answered is \"did the\n * AGENT misbehave?\" rather than \"did the EVAL grep fire?\".\n *\n * Returns one `CanaryLeak` per pair where the agent's output\n * contained its scenario's `forbiddenPattern` (or `canary` fallback).\n */\nexport function runBehavioralCanaries(\n cases: Array<{ scenario: DatasetScenario; output: string; runId?: string }>,\n): CanaryLeak[] {\n const leaks: CanaryLeak[] = []\n for (const c of cases) {\n const leak = checkBehavioralCanary(c.output, c.scenario)\n if (leak) leaks.push({ ...leak, runId: c.runId ?? leak.runId })\n }\n return leaks\n}\n\n/**\n * Resolve a forbidden-pattern string to the matched substring inside\n * `output`. `/body/flags` notation is interpreted as a regex; anything\n * else is a literal substring.\n */\nfunction matchForbidden(output: string, pattern: string): string | null {\n const re = tryParseRegex(pattern)\n if (re) {\n const m = output.match(re)\n return m && m[0].length > 0 ? m[0] : null\n }\n return output.includes(pattern) ? pattern : null\n}\n\nfunction tryParseRegex(pattern: string): RegExp | null {\n if (pattern.length < 2 || pattern[0] !== '/') return null\n const last = pattern.lastIndexOf('/')\n if (last <= 0) return null\n const body = pattern.slice(1, last)\n const flags = pattern.slice(last + 1)\n if (!/^[gimsuy]*$/.test(flags)) return null\n try {\n return new RegExp(body, flags)\n } catch {\n return null\n }\n}\n\n/**\n * Scan the LLM-output history in a corpus; returns every case where a\n * canary from a known scenario appeared in agent output. Pass the full\n * set of scenarios whose canaries you care about (typically the whole\n * held-out slice).\n */\nexport async function canaryLeakView(\n store: TraceStore,\n scenarios: DatasetScenario[],\n): Promise<CanaryLeak[]> {\n const targets = scenarios.filter((s) => !!s.canary)\n if (targets.length === 0) return []\n const spans = await llmSpans(store)\n const leaks: CanaryLeak[] = []\n for (const span of spans) {\n const output = span.output ?? ''\n for (const s of targets) {\n if (s.canary && output.includes(s.canary)) {\n leaks.push({\n scenarioId: s.id,\n canary: s.canary,\n runId: span.runId,\n evidence: excerpt(output, s.canary),\n })\n }\n }\n }\n return leaks\n}\n\nexport class HoldoutAuditor {\n private scenarios: DatasetScenario[]\n private accessLog: Array<{ scenarioId: string; purpose: string; at: number }> = []\n\n constructor(scenarios: DatasetScenario[]) {\n this.scenarios = scenarios\n }\n\n /** Retrieve a holdout scenario for a declared purpose. Non-'evaluation' throws. */\n get(scenarioId: string, purpose: 'evaluation' | 'debugging'): DatasetScenario {\n if (purpose !== 'evaluation' && purpose !== 'debugging') {\n throw new Error(\n `HoldoutAuditor.get: purpose must be 'evaluation' or 'debugging', got ${purpose}`,\n )\n }\n const s = this.scenarios.find((x) => x.id === scenarioId)\n if (!s) throw new Error(`holdout scenario \"${scenarioId}\" not found`)\n this.accessLog.push({ scenarioId, purpose, at: Date.now() })\n return s\n }\n\n getAccessLog(): ReadonlyArray<{ scenarioId: string; purpose: string; at: number }> {\n return this.accessLog\n }\n}\n\nfunction excerpt(source: string, needle: string): string {\n const at = source.indexOf(needle)\n if (at < 0) return ''\n const start = Math.max(0, at - 30)\n const end = Math.min(source.length, at + needle.length + 30)\n return (start > 0 ? '…' : '') + source.slice(start, end) + (end < source.length ? '…' : '')\n}\n","/**\n * # `analyzeRuns()` — turn a set of agent runs into an actionable decision packet.\n *\n * Wires the substrate's statistical, calibration, clustering, Pareto, and\n * release-confidence primitives into one `InsightReport`. Two top-level\n * entry points use this function:\n *\n * - `selfImprove()` calls it on the campaign output to attach a packet\n * to every run.\n * - Consumers with observed `RunRecord[]` (production traces, gold\n * corpora, approve/reject tables) call it directly via `analyzeRuns()`\n * for analysis without a closed loop.\n *\n * Every section is opt-in based on what the input data supports — the\n * function never invents signal. If runs carry no judge scores, `judges`\n * is empty. If there's no baseline/candidate split, `lift` is undefined.\n * If no `analyst` is wired, `failureClusters` is undefined.\n *\n * The `recommendations` array is the human-readable layer; everything\n * else is the evidence backing each recommendation.\n */\n\nimport type { AnalystRegistry } from '../analyst/registry'\nimport type { AnalystFinding } from '../analyst/types'\nimport { checkCanaries } from '../contamination-guard'\nimport type { DatasetScenario } from '../dataset'\nimport { summarizeBackendIntegrity } from '../integrity/backend-integrity'\nimport type { RunRecord } from '../run-record'\nimport {\n cohensD,\n pairedBootstrap,\n pairedMde,\n pairedTTest,\n pearsonR,\n requiredSampleSize,\n spearmanR,\n} from '../statistics'\nimport { type ParetoFigureSpec, paretoChart } from '../summary-report'\n\nimport type {\n FailureClusterInsight,\n FailureModeTally,\n InsightReport,\n InterRaterInsight,\n JudgeInsight,\n LiftInsight,\n MetricDelta,\n OutcomeCorrelationInsight,\n PriorPeriodComparison,\n Recommendation,\n ScalarDistribution,\n} from './insight-report'\n\n// ── Public API ───────────────────────────────────────────────────────\n\nexport interface AnalyzeRunsOptions {\n /** The runs to analyze. */\n runs: RunRecord[]\n /** Which split to score against when reading composite from RunOutcome.\n * Default: holdout when ANY run has a `holdoutScore`, else search. */\n split?: 'search' | 'holdout' | 'auto'\n /** Pairwise analysis configuration. When both `baselineCandidateId` and\n * `candidateCandidateId` are present, lift is computed on paired\n * (experimentId, seed) tuples shared between the two sides. */\n baselineCandidateId?: string\n candidateCandidateId?: string\n /** Canary scenarios — checked against every run's raw output for\n * holdout contamination. */\n canaryScenarios?: DatasetScenario[]\n /** Analyst registry for failure clustering. When omitted, the\n * `failureClusters` section is left undefined. */\n analyst?: AnalystRegistry\n /** Downstream outcome metric per run (e.g. engagement rate, approval\n * rate, downstream pass rate). When present, the report includes\n * `outcomeCorrelation` + a simple linear reward model fit. */\n outcomeSignal?: {\n metric: string\n valueByRunId: Record<string, number>\n }\n /** Multi-rater feedback for inter-rater agreement. Each entry is one\n * rater's score for one run. Two or more raters → kappa + disagreement\n * triage list. */\n raterScores?: Array<{ runId: string; rater: string; score: number }>\n /** Number of histogram bins for distributional summaries. Default 12. */\n histogramBins?: number\n /** Decision threshold — the smallest composite lift the caller cares\n * about. Used by the recommendations engine to call ship vs hold.\n * Default 0.02. */\n decisionThreshold?: number\n /** Optional prior-period runs. When set, the report includes\n * `priorPeriodComparison` with per-metric Welch-CI deltas and\n * recommendations fire on statistically significant regressions.\n * The two windows do NOT have to share scenarios — the comparison\n * is two-sample unpaired (the substrate's `lift` field uses paired\n * bootstrap on shared (experimentId, seed) tuples; this is the\n * shape for \"this week vs last week\" rather than \"candidate vs\n * baseline within a campaign\"). */\n baselineRuns?: RunRecord[]\n /** Human-readable label for the baseline window, e.g. \"vs prior 7\n * days\", \"vs v3.1 release\". Surfaces in recommendations + UI. */\n baselineLabel?: string\n}\n\nexport async function analyzeRuns(opts: AnalyzeRunsOptions): Promise<InsightReport> {\n const runs = opts.runs\n const bins = opts.histogramBins ?? 12\n const threshold = opts.decisionThreshold ?? 0.02\n const split = resolveSplit(runs, opts.split ?? 'auto')\n\n const compositeWithIds = runs\n .map((r) => ({ runId: r.runId, score: compositeOf(r, split) }))\n .filter((p) => Number.isFinite(p.score))\n const composite = distributionOf(\n compositeWithIds.map((p) => p.score),\n bins,\n compositeWithIds,\n )\n\n const perDimension = computePerDimension(runs, bins)\n\n const costs = runs.map((r) => r.costUsd).filter(Number.isFinite)\n const costDist = distributionOf(costs, bins)\n const pareto = paretoChart(runs, { split })\n const degraded: { cost?: string; pareto?: string } = {}\n if (costs.length === 0 || costs.every((c) => c === 0)) {\n degraded.cost = diagnoseZeroCost(runs)\n }\n if (pareto.points.length < 2) {\n degraded.pareto =\n pareto.points.length === 0\n ? 'no candidates — Pareto unavailable'\n : 'single candidate — Pareto is a single point, not a frontier'\n }\n const costQuality = {\n cost: costDist,\n pareto,\n ...(degraded.cost || degraded.pareto ? { degraded } : {}),\n }\n\n const judges = computeJudgeInsights(runs)\n\n const interRater = opts.raterScores ? computeInterRater(opts.raterScores) : undefined\n\n const lift = computeLift(runs, opts.baselineCandidateId, opts.candidateCandidateId, split)\n\n const failureClusters = opts.analyst\n ? await computeFailureClusters(runs, opts.analyst, split)\n : undefined\n\n const failureModes = computeFailureModes(runs)\n\n const contamination = opts.canaryScenarios\n ? computeContamination(runs, opts.canaryScenarios)\n : undefined\n\n const outcomeCorrelation = opts.outcomeSignal\n ? computeOutcomeCorrelation(runs, opts.outcomeSignal, split)\n : undefined\n\n const release = buildReleaseScorecard(composite, lift, contamination)\n\n const priorPeriodComparison = opts.baselineRuns\n ? computePriorPeriodComparison(runs, opts.baselineRuns, split, opts.baselineLabel)\n : undefined\n\n const recommendations = buildRecommendations({\n composite,\n judges,\n interRater,\n lift,\n failureClusters,\n failureModes,\n contamination,\n outcomeCorrelation,\n priorPeriodComparison,\n threshold,\n })\n\n return {\n n: runs.length,\n composite,\n perDimension,\n costQuality,\n judges,\n interRater,\n lift,\n failureClusters,\n contamination,\n outcomeCorrelation,\n release,\n ...(failureModes ? { failureModes } : {}),\n ...(priorPeriodComparison ? { priorPeriodComparison } : {}),\n recommendations,\n }\n}\n\n/** Model-free failure tally. Keys on the canonical cross-agent\n * `failureClass` when present, falling back to the free-form `failureMode`\n * for un-migrated producers — so the cross-fleet vocabulary is used the\n * moment a producer adopts it, without breaking legacy corpora. Returns\n * undefined when no run carries either tag. */\n/** Explain a zero-valued cost axis by its root cause, not just \"no signal\".\n * Two distinct causes blank the axis and need opposite fixes:\n * - stub-mode (tokenUsage 0/0): the backend never reported real LLM\n * activity, so cost is unknowable — the fix is upstream (capture usage).\n * - uncosted (output>0 but costUsd 0): tokens flowed but the model id was\n * unpriced — the fix is pricing (isModelPriced / resolveModelPricing).\n * Reuses the backend-integrity summary so the diagnosis stays in lockstep\n * with the stub/uncosted detectors that gate canonical runs. */\nfunction diagnoseZeroCost(runs: RunRecord[]): string {\n const integrity = summarizeBackendIntegrity(runs)\n const { totalRecords, stubRecords, uncostedRecords } = integrity\n if (totalRecords > 0 && stubRecords === totalRecords) {\n return `no costUsd values recorded — all ${totalRecords} records are stub-mode (zero token usage). The backend never reported real LLM activity, so cost cannot be computed; verify the backend actually ran before trusting this corpus.`\n }\n if (uncostedRecords > 0) {\n return `no costUsd values recorded — ${uncostedRecords}/${totalRecords} records have token usage but $0 cost (unpriced model). Check isModelPriced(model) for the run's model id and add it to FAMILY_PRICING.`\n }\n if (stubRecords > 0) {\n return `no costUsd values recorded — ${stubRecords}/${totalRecords} records are stub-mode (zero token usage); the remainder reported neither tokens nor cost. Cost axis carries no signal.`\n }\n return 'no costUsd values recorded — cost axis carries no signal'\n}\n\nfunction computeFailureModes(runs: RunRecord[]): FailureModeTally[] | undefined {\n const counts = new Map<string, number>()\n for (const r of runs) {\n const key = r.failureClass ?? r.failureMode\n if (key) counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n if (counts.size === 0) return undefined\n const n = runs.length\n return [...counts.entries()]\n .map(([mode, count]) => ({ mode, count, share: n > 0 ? count / n : 0 }))\n .sort((a, b) => b.count - a.count || a.mode.localeCompare(b.mode))\n}\n\n// ── Prior-period comparison ─────────────────────────────────────────\n\n/** Direction of the metric — does \"higher current\" mean better or worse?\n * Composite + judge dimensions: higher is better. Cost + duration: lower\n * is better. The recommendations engine flips the sign before judging\n * regressed vs improved. */\ntype MetricDirection = 'higher-is-better' | 'lower-is-better'\n\nfunction computePriorPeriodComparison(\n current: RunRecord[],\n baseline: RunRecord[],\n split: 'search' | 'holdout',\n windowLabel: string | undefined,\n): PriorPeriodComparison | undefined {\n if (current.length === 0 || baseline.length === 0) return undefined\n\n const metrics: Record<string, MetricDelta> = {}\n const directions: Record<string, MetricDirection> = {}\n\n const compositeCurrent = current\n .map((r) => compositeOf(r, split))\n .filter(Number.isFinite) as number[]\n const compositeBaseline = baseline\n .map((r) => compositeOf(r, split))\n .filter(Number.isFinite) as number[]\n if (compositeCurrent.length > 0 && compositeBaseline.length > 0) {\n metrics.composite = welchCompare(compositeBaseline, compositeCurrent)\n directions.composite = 'higher-is-better'\n }\n\n const costCurrent = current.map((r) => r.costUsd).filter(Number.isFinite)\n const costBaseline = baseline.map((r) => r.costUsd).filter(Number.isFinite)\n if (costCurrent.length > 0 && costBaseline.length > 0) {\n metrics.cost = welchCompare(costBaseline, costCurrent)\n directions.cost = 'lower-is-better'\n }\n\n const durCurrent = current.map((r) => r.wallMs).filter(Number.isFinite)\n const durBaseline = baseline.map((r) => r.wallMs).filter(Number.isFinite)\n if (durCurrent.length > 0 && durBaseline.length > 0) {\n metrics.duration = welchCompare(durBaseline, durCurrent)\n directions.duration = 'lower-is-better'\n }\n\n const tokCurrent = current\n .map((r) => (r.tokenUsage.input ?? 0) + (r.tokenUsage.output ?? 0))\n .filter(Number.isFinite)\n const tokBaseline = baseline\n .map((r) => (r.tokenUsage.input ?? 0) + (r.tokenUsage.output ?? 0))\n .filter(Number.isFinite)\n if (tokCurrent.length > 0 && tokBaseline.length > 0) {\n metrics.tokenUsage = welchCompare(tokBaseline, tokCurrent)\n directions.tokenUsage = 'lower-is-better'\n }\n\n // Per-dimension judge comparisons — only for dimensions present in BOTH\n // windows. We use perDimMean since per-judge nesting is finicky for\n // two-sample comparisons across different judge configurations.\n const dimsCurrent = collectPerDimension(current)\n const dimsBaseline = collectPerDimension(baseline)\n for (const dim of Object.keys(dimsCurrent)) {\n const b = dimsBaseline[dim]\n const c = dimsCurrent[dim]\n if (!b || b.length === 0 || !c || c.length === 0) continue\n metrics[`dim.${dim}`] = welchCompare(b, c)\n directions[`dim.${dim}`] = 'higher-is-better'\n }\n\n const regressedMetrics: string[] = []\n const improvedMetrics: string[] = []\n for (const [name, delta] of Object.entries(metrics)) {\n if (!delta.significant) continue\n const dir = directions[name] ?? 'higher-is-better'\n const better = dir === 'higher-is-better' ? delta.delta > 0 : delta.delta < 0\n if (better) improvedMetrics.push(name)\n else regressedMetrics.push(name)\n }\n\n return {\n baselineN: baseline.length,\n currentN: current.length,\n ...(windowLabel ? { windowLabel } : {}),\n metrics,\n regressedMetrics,\n improvedMetrics,\n }\n}\n\n/** Collect per-dimension values across runs (from outcome.judgeScores.perDimMean). */\nfunction collectPerDimension(runs: RunRecord[]): Record<string, number[]> {\n const out: Record<string, number[]> = {}\n for (const r of runs) {\n const perDim = r.outcome.judgeScores?.perDimMean\n if (!perDim) continue\n for (const [dim, value] of Object.entries(perDim)) {\n if (!Number.isFinite(value)) continue\n if (!out[dim]) out[dim] = []\n out[dim].push(value as number)\n }\n }\n return out\n}\n\n/** Two-sample Welch comparison: unequal-variance t-test + CI on the delta\n * + Cohen's d (pooled stddev). Significance = p < 0.05 AND |d| >= 0.2. */\nfunction welchCompare(baseline: number[], current: number[]): MetricDelta {\n const baselineMean = mean(baseline)\n const currentMean = mean(current)\n const baselineVar = sampleVariance(baseline, baselineMean)\n const currentVar = sampleVariance(current, currentMean)\n const baselineN = baseline.length\n const currentN = current.length\n const delta = currentMean - baselineMean\n\n // Welch standard error\n const se = Math.sqrt(baselineVar / baselineN + currentVar / currentN)\n // For 95% CI we use z=1.96 (large-n approximation). Customers running\n // analyzeRuns will typically have n >= 30; the t-correction is\n // negligible vs the practical noise floor.\n const halfWidth = 1.96 * (se > 0 ? se : 0)\n const ci95: [number, number] = [delta - halfWidth, delta + halfWidth]\n\n // p-value via normal approximation to the t-statistic.\n const t = se > 0 ? delta / se : 0\n const pValue = se > 0 ? 2 * (1 - standardNormalCdf(Math.abs(t))) : 1\n\n // Cohen's d — pooled stddev.\n const pooledStddev = Math.sqrt(\n ((baselineN - 1) * baselineVar + (currentN - 1) * currentVar) /\n Math.max(1, baselineN + currentN - 2),\n )\n const cohensD = pooledStddev > 0 ? delta / pooledStddev : 0\n\n // Significance: BOTH p < 0.05 AND |d| >= 0.2 (small-effect threshold).\n const significant = pValue < 0.05 && Math.abs(cohensD) >= 0.2\n\n return {\n current: currentMean,\n baseline: baselineMean,\n delta,\n ci95,\n pValue,\n cohensD,\n baselineN,\n currentN,\n significant,\n }\n}\n\nfunction sampleVariance(xs: number[], xsMean: number): number {\n if (xs.length < 2) return 0\n let s = 0\n for (const x of xs) s += (x - xsMean) ** 2\n return s / (xs.length - 1)\n}\n\n/** Abramowitz & Stegun approximation to Φ(z). Maximum error ~7.5e-8. */\nfunction standardNormalCdf(z: number): number {\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n const sign = z < 0 ? -1 : 1\n const x = Math.abs(z) / Math.SQRT2\n const t = 1 / (1 + p * x)\n const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x)\n return 0.5 * (1 + sign * y)\n}\n\n// ── Composite + split selection ─────────────────────────────────────\n\nfunction resolveSplit(\n runs: RunRecord[],\n pref: 'search' | 'holdout' | 'auto',\n): 'search' | 'holdout' {\n if (pref !== 'auto') return pref\n const hasHoldout = runs.some((r) => Number.isFinite(r.outcome.holdoutScore))\n return hasHoldout ? 'holdout' : 'search'\n}\n\nfunction compositeOf(run: RunRecord, split: 'search' | 'holdout'): number {\n const primary = split === 'holdout' ? run.outcome.holdoutScore : run.outcome.searchScore\n if (Number.isFinite(primary)) return primary as number\n // Fall through to the other split if the preferred one is missing —\n // analyzeRuns shouldn't refuse to summarise a run just because the\n // caller asked for the split that wasn't recorded.\n const alt = split === 'holdout' ? run.outcome.searchScore : run.outcome.holdoutScore\n return Number.isFinite(alt) ? (alt as number) : Number.NaN\n}\n\n// ── Distribution helpers ────────────────────────────────────────────\n\nfunction distributionOf(\n values: number[],\n bins: number,\n withIds?: Array<{ runId: string; score: number }>,\n): ScalarDistribution {\n if (values.length === 0) {\n return {\n n: 0,\n mean: 0,\n p50: 0,\n p95: 0,\n stddev: 0,\n min: 0,\n max: 0,\n histogram: [],\n }\n }\n const sorted = [...values].sort((a, b) => a - b)\n const n = sorted.length\n const mean = sorted.reduce((s, v) => s + v, 0) / n\n const variance = sorted.reduce((s, v) => s + (v - mean) ** 2, 0) / n\n const stddev = Math.sqrt(variance)\n const tailRuns = withIds\n ? [...withIds].sort((a, b) => a.score - b.score).slice(0, Math.min(5, withIds.length))\n : undefined\n return {\n n,\n mean,\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n stddev,\n min: sorted[0]!,\n max: sorted[n - 1]!,\n histogram: histogram(sorted, bins),\n ...(tailRuns ? { tailRuns } : {}),\n }\n}\n\nfunction percentile(sorted: number[], q: number): number {\n if (sorted.length === 0) return 0\n if (sorted.length === 1) return sorted[0]!\n const idx = (sorted.length - 1) * q\n const lo = Math.floor(idx)\n const hi = Math.ceil(idx)\n if (lo === hi) return sorted[lo]!\n const w = idx - lo\n return sorted[lo]! * (1 - w) + sorted[hi]! * w\n}\n\n/** Even-width histogram over the value range. Returns inclusive-lo /\n * exclusive-hi bins (closed on right for the last bin) compatible with\n * the substrate's `GainDistributionBin` shape. */\nfunction histogram(sorted: number[], bins: number): ScalarDistribution['histogram'] {\n if (sorted.length === 0 || bins < 1) return []\n const min = sorted[0]!\n const max = sorted[sorted.length - 1]!\n if (min === max) return [{ lo: min, hi: max, count: sorted.length }]\n const width = (max - min) / bins\n const out: ScalarDistribution['histogram'] = []\n for (let i = 0; i < bins; i++) {\n const lo = min + i * width\n const hi = i === bins - 1 ? max : lo + width\n out.push({ lo, hi, count: 0 })\n }\n for (const v of sorted) {\n const idx = Math.min(bins - 1, Math.floor((v - min) / width))\n out[idx]!.count++\n }\n return out\n}\n\nfunction computePerDimension(runs: RunRecord[], bins: number): Record<string, ScalarDistribution> {\n // JudgeScoresRecord pre-aggregates `perDimMean` (mean across judges per\n // dimension). We collect those means across runs to produce a per-dim\n // distribution at the corpus level. Consumers who want per-judge\n // dimension values reach into `perJudge[judgeId][dim]` themselves.\n const byDim = new Map<string, number[]>()\n for (const run of runs) {\n const scores = run.outcome.judgeScores\n if (!scores) continue\n for (const [dim, value] of Object.entries(scores.perDimMean ?? {})) {\n if (!Number.isFinite(value)) continue\n const arr = byDim.get(dim) ?? []\n arr.push(value)\n byDim.set(dim, arr)\n }\n }\n const out: Record<string, ScalarDistribution> = {}\n for (const [dim, values] of byDim) out[dim] = distributionOf(values, bins)\n return out\n}\n\n// ── Judge insights ──────────────────────────────────────────────────\n\nfunction computeJudgeInsights(runs: RunRecord[]): Record<string, JudgeInsight> {\n // Each judge's per-run mean is the average of its per-dimension scores\n // for that run. We aggregate those means across all runs each judge\n // scored — giving consumers a \"this judge's typical verdict\" reading.\n const out: Record<string, JudgeInsight> = {}\n const byJudge = new Map<string, number[]>()\n for (const run of runs) {\n const scores = run.outcome.judgeScores\n if (!scores?.perJudge) continue\n for (const [judgeId, dims] of Object.entries(scores.perJudge)) {\n const dimValues = Object.values(dims).filter(Number.isFinite) as number[]\n if (dimValues.length === 0) continue\n const judgeMean = dimValues.reduce((s, v) => s + v, 0) / dimValues.length\n const arr = byJudge.get(judgeId) ?? []\n arr.push(judgeMean)\n byJudge.set(judgeId, arr)\n }\n }\n for (const [judgeId, values] of byJudge) {\n out[judgeId] = {\n n: values.length,\n meanScore: values.reduce((s, v) => s + v, 0) / values.length,\n }\n }\n return out\n}\n\n// ── Inter-rater agreement ───────────────────────────────────────────\n\nfunction computeInterRater(\n ratings: Array<{ runId: string; rater: string; score: number }>,\n): InterRaterInsight | undefined {\n const byRun = new Map<string, Array<{ rater: string; score: number }>>()\n for (const r of ratings) {\n if (!Number.isFinite(r.score)) continue\n const list = byRun.get(r.runId) ?? []\n list.push({ rater: r.rater, score: r.score })\n byRun.set(r.runId, list)\n }\n const raters = new Set(ratings.map((r) => r.rater))\n const jointlyRated: string[] = []\n for (const [runId, ratersForRun] of byRun) {\n const seen = new Set(ratersForRun.map((r) => r.rater))\n let all = true\n for (const r of raters) if (!seen.has(r)) all = false\n if (all) jointlyRated.push(runId)\n }\n if (raters.size < 2 || jointlyRated.length === 0) return undefined\n\n const raterList = [...raters].sort()\n const perPair: Record<string, number> = {}\n for (let i = 0; i < raterList.length; i++) {\n for (let j = i + 1; j < raterList.length; j++) {\n const a = raterList[i]!\n const b = raterList[j]!\n const aScores: number[] = []\n const bScores: number[] = []\n for (const runId of jointlyRated) {\n const ratersForRun = byRun.get(runId)!\n const sa = ratersForRun.find((r) => r.rater === a)?.score\n const sb = ratersForRun.find((r) => r.rater === b)?.score\n if (sa !== undefined && sb !== undefined) {\n aScores.push(sa)\n bScores.push(sb)\n }\n }\n perPair[`${a}::${b}`] = pearsonR(aScores, bScores)\n }\n }\n // Average only the finite pair correlations — a degenerate pair (a single\n // jointly-rated run, or a rater whose scores are constant) yields NaN and\n // carries no agreement signal, so it must not drag the mean toward 0.\n const pairKappas = Object.values(perPair).filter((v) => Number.isFinite(v))\n const kappa =\n pairKappas.length === 0 ? 0 : pairKappas.reduce((s, v) => s + v, 0) / pairKappas.length\n\n const disagreementCases = jointlyRated\n .map((runId) => {\n const ratersForRun = byRun.get(runId)!\n const scores = ratersForRun.map((r) => r.score)\n const range = Math.max(...scores) - Math.min(...scores)\n return { runId, ratings: ratersForRun, range }\n })\n .sort((a, b) => b.range - a.range)\n .slice(0, 20)\n\n return {\n raters: raters.size,\n jointlyRated: jointlyRated.length,\n kappa,\n perPair,\n disagreementCases,\n }\n}\n\n// ── Lift ────────────────────────────────────────────────────────────\n\nfunction computeLift(\n runs: RunRecord[],\n baselineId: string | undefined,\n candidateId: string | undefined,\n split: 'search' | 'holdout',\n): LiftInsight | undefined {\n let bId = baselineId\n let cId = candidateId\n if (!bId || !cId) {\n // Auto-detect: when exactly two distinct candidateIds appear, treat the\n // lower-mean side as baseline.\n const ids = [...new Set(runs.map((r) => r.candidateId))]\n if (ids.length !== 2) return undefined\n const [idA, idB] = ids as [string, string]\n const meanA = mean(runs.filter((r) => r.candidateId === idA).map((r) => compositeOf(r, split)))\n const meanB = mean(runs.filter((r) => r.candidateId === idB).map((r) => compositeOf(r, split)))\n bId = meanA <= meanB ? idA : idB\n cId = meanA <= meanB ? idB : idA\n }\n\n const baseline = runs.filter((r) => r.candidateId === bId)\n const candidate = runs.filter((r) => r.candidateId === cId)\n if (baseline.length === 0 || candidate.length === 0) return undefined\n\n // Pair on (experimentId, seed). When that key doesn't match, fall back\n // to ordinal pairing — common for fresh runs from the same scenario list.\n const baselineByKey = new Map(baseline.map((r) => [pairingKey(r), r]))\n const pairedBaseline: number[] = []\n const pairedCandidate: number[] = []\n let usedKeyPairing = false\n for (const cand of candidate) {\n const b = baselineByKey.get(pairingKey(cand))\n if (b) {\n const bC = compositeOf(b, split)\n const cC = compositeOf(cand, split)\n if (Number.isFinite(bC) && Number.isFinite(cC)) {\n pairedBaseline.push(bC)\n pairedCandidate.push(cC)\n usedKeyPairing = true\n }\n }\n }\n if (!usedKeyPairing) {\n const n = Math.min(baseline.length, candidate.length)\n for (let i = 0; i < n; i++) {\n const bC = compositeOf(baseline[i]!, split)\n const cC = compositeOf(candidate[i]!, split)\n if (Number.isFinite(bC) && Number.isFinite(cC)) {\n pairedBaseline.push(bC)\n pairedCandidate.push(cC)\n }\n }\n }\n if (pairedBaseline.length === 0) return undefined\n\n const baselineMean = mean(pairedBaseline)\n const candidateMean = mean(pairedCandidate)\n const delta = candidateMean - baselineMean\n\n const bootstrap = pairedBootstrap(pairedBaseline, pairedCandidate, {\n confidence: 0.95,\n resamples: 2000,\n statistic: 'mean',\n })\n const tTest = pairedTTest(pairedBaseline, pairedCandidate)\n const d = cohensD(pairedBaseline, pairedCandidate)\n const mde = pairedMde({ nPaired: pairedBaseline.length, power: 0.8, alpha: 0.05 })\n const requiredN = requiredSampleSize({\n effect: Math.max(Math.abs(delta), 1e-6),\n power: 0.8,\n alpha: 0.05,\n })\n\n return {\n baselineMean,\n candidateMean,\n delta,\n ci95: [bootstrap.low, bootstrap.high],\n pValue: tTest.p,\n n: pairedBaseline.length,\n cohensD: d,\n mde,\n requiredN,\n }\n}\n\nfunction pairingKey(r: RunRecord): string {\n return `${r.experimentId}::${r.seed}`\n}\n\nfunction mean(arr: number[]): number {\n return arr.length === 0 ? 0 : arr.reduce((s, v) => s + v, 0) / arr.length\n}\n\n// ── Failure clustering ──────────────────────────────────────────────\n\nasync function computeFailureClusters(\n runs: RunRecord[],\n analyst: AnalystRegistry,\n split: 'search' | 'holdout',\n): Promise<FailureClusterInsight | undefined> {\n const failed = runs.filter((r) => compositeOf(r, split) < 0.5 || r.failureMode !== undefined)\n if (failed.length === 0) return { clusters: [], totalFailures: 0 }\n\n const clusters = new Map<string, { exemplars: string[]; share: number }>()\n for (const run of failed) {\n try {\n // AnalystRunInputs routes by field name: run-record analysts read\n // `runRecord`. Any other shape makes every analyst skip with\n // \"missing input\" and the clusters come back silently empty.\n const result = await analyst.run(run.runId, { runRecord: run })\n for (const finding of result.findings as AnalystFinding[]) {\n const key = finding.area || finding.analyst_id || 'unclassified'\n const c = clusters.get(key) ?? { exemplars: [], share: 0 }\n if (c.exemplars.length < 5) c.exemplars.push(run.runId)\n clusters.set(key, c)\n }\n } catch {\n const c = clusters.get('analyst-error') ?? { exemplars: [], share: 0 }\n if (c.exemplars.length < 5) c.exemplars.push(run.runId)\n clusters.set('analyst-error', c)\n }\n }\n const clusterList = [...clusters.entries()].map(([id, c]) => ({\n id,\n name: id,\n share: c.exemplars.length / failed.length,\n exemplars: c.exemplars,\n }))\n clusterList.sort((a, b) => b.share - a.share)\n return { clusters: clusterList, totalFailures: failed.length }\n}\n\n// ── Contamination ──────────────────────────────────────────────────\n\nfunction computeContamination(\n runs: RunRecord[],\n canaries: DatasetScenario[],\n): InsightReport['contamination'] {\n let leaks = 0\n const details: Array<{ runId: string; canary: string; matched: string }> = []\n for (const run of runs) {\n const output = stringifyOutput(run)\n if (!output) continue\n const leaksHere = checkCanaries(output, canaries)\n for (const leak of leaksHere) {\n leaks++\n details.push({ runId: run.runId, canary: leak.canary, matched: leak.evidence })\n }\n }\n return { leaks, holdoutAuditPassed: leaks === 0, details }\n}\n\nfunction stringifyOutput(run: RunRecord): string | undefined {\n // RunRecord doesn't fix where \"the agent's output\" lives — different\n // consumers stash it differently. We probe the common shapes: the\n // outcome.raw map (numeric only by design — unlikely to contain text),\n // and any string-valued fields tucked under metadata via type casting.\n // Consumers with bespoke shapes pass canaryScenarios only when they\n // know their runs carry a stringifiable surface.\n const metadata = (run as unknown as { metadata?: Record<string, unknown> }).metadata\n if (typeof metadata?.output === 'string') return metadata.output\n if (typeof metadata?.text === 'string') return metadata.text\n return undefined\n}\n\n// ── Outcome correlation + linear reward model ──────────────────────\n\nfunction computeOutcomeCorrelation(\n runs: RunRecord[],\n outcome: { metric: string; valueByRunId: Record<string, number> },\n split: 'search' | 'holdout',\n): OutcomeCorrelationInsight | undefined {\n const xs: number[] = []\n const ys: number[] = []\n for (const run of runs) {\n const y = outcome.valueByRunId[run.runId]\n if (y === undefined || !Number.isFinite(y)) continue\n const x = compositeOf(run, split)\n if (!Number.isFinite(x)) continue\n xs.push(x)\n ys.push(y)\n }\n if (xs.length < 3) return undefined\n\n const p = pearsonR(xs, ys)\n const s = spearmanR(xs, ys)\n const meanX = mean(xs)\n const meanY = mean(ys)\n let num = 0\n let denom = 0\n for (let i = 0; i < xs.length; i++) {\n num += (xs[i]! - meanX) * (ys[i]! - meanY)\n denom += (xs[i]! - meanX) ** 2\n }\n const slope = denom === 0 ? 0 : num / denom\n const intercept = meanY - slope * meanX\n const ssTot = ys.reduce((a, y) => a + (y - meanY) ** 2, 0)\n const ssRes = ys.reduce((a, y, i) => a + (y - (intercept + slope * xs[i]!)) ** 2, 0)\n const r2 = ssTot === 0 ? 0 : 1 - ssRes / ssTot\n\n return {\n metric: outcome.metric,\n n: xs.length,\n pearson: p,\n spearman: s,\n rewardModel: { intercept, slope, r2 },\n }\n}\n\n// ── Release confidence scorecard ───────────────────────────────────\n\nfunction buildReleaseScorecard(\n composite: ScalarDistribution,\n lift: LiftInsight | undefined,\n contamination: InsightReport['contamination'],\n): InsightReport['release'] {\n // Synthesise a minimal scorecard from the rolled-up signal. The\n // substrate's `evaluateReleaseConfidence` primitive consumes a richer\n // input shape that callers can produce by wiring SLO definitions; the\n // shape here is the contract `selfImprove`/`analyzeRuns` consumers\n // receive automatically. They can call `evaluateReleaseConfidence`\n // directly when they want SLO-based axis evaluation.\n const axes: InsightReport['release']['axes'] = []\n const liftPass =\n lift === undefined || lift.ci95[0] > 0\n ? ('pass' as const)\n : lift.delta > 0\n ? ('warn' as const)\n : ('fail' as const)\n axes.push({\n name: 'quality-lift',\n status: liftPass,\n detail: lift\n ? `delta=${lift.delta.toFixed(3)}, CI95=[${lift.ci95[0].toFixed(3)}, ${lift.ci95[1].toFixed(3)}], n=${lift.n}`\n : 'no baseline/candidate pair available',\n })\n const contamPass =\n contamination === undefined || contamination.leaks === 0 ? ('pass' as const) : ('fail' as const)\n axes.push({\n name: 'contamination',\n status: contamPass,\n detail: contamination ? `${contamination.leaks} canary leak(s)` : 'no canaries supplied',\n })\n axes.push({\n name: 'composite-distribution',\n status: composite.mean >= 0.5 ? 'pass' : composite.mean >= 0.3 ? 'warn' : 'fail',\n detail: `mean=${composite.mean.toFixed(3)}, p50=${composite.p50.toFixed(3)}, p95=${composite.p95.toFixed(3)} over n=${composite.n}`,\n })\n const status = axes.some((a) => a.status === 'fail')\n ? 'fail'\n : axes.some((a) => a.status === 'warn')\n ? 'warn'\n : 'pass'\n return {\n status,\n axes,\n issues: [],\n }\n}\n\n// ── Recommendations engine ─────────────────────────────────────────\n\ninterface RecommendationContext {\n composite: ScalarDistribution\n judges: Record<string, JudgeInsight>\n interRater?: InterRaterInsight\n lift?: LiftInsight\n failureClusters?: FailureClusterInsight\n failureModes?: FailureModeTally[]\n contamination?: InsightReport['contamination']\n outcomeCorrelation?: OutcomeCorrelationInsight\n priorPeriodComparison?: PriorPeriodComparison\n threshold: number\n}\n\nfunction buildRecommendations(ctx: RecommendationContext): Recommendation[] {\n const out: Recommendation[] = []\n\n // Prior-period regressions — highest customer-impact signal when present.\n // \"Did my last change help?\" with a falsifiable answer.\n if (ctx.priorPeriodComparison) {\n const ppc = ctx.priorPeriodComparison\n const label = ppc.windowLabel ?? 'baseline period'\n for (const name of ppc.regressedMetrics) {\n const d = ppc.metrics[name]\n if (!d) continue\n out.push({\n priority: 'critical',\n kind: 'investigate',\n title: `${name} regressed from ${d.baseline.toFixed(3)} → ${d.current.toFixed(3)} vs ${label}`,\n detail: `Welch CI95 = [${d.ci95[0].toFixed(3)}, ${d.ci95[1].toFixed(3)}], p=${d.pValue.toFixed(4)}, Cohen's d=${d.cohensD.toFixed(2)} (n_current=${d.currentN}, n_baseline=${d.baselineN}). The regression is statistically significant at p<0.05 with at-least-small effect size.`,\n evidencePath: `priorPeriodComparison.metrics.${name}`,\n })\n }\n for (const name of ppc.improvedMetrics) {\n const d = ppc.metrics[name]\n if (!d) continue\n out.push({\n priority: 'low',\n kind: 'ship',\n title: `${name} improved from ${d.baseline.toFixed(3)} → ${d.current.toFixed(3)} vs ${label}`,\n detail: `Welch CI95 = [${d.ci95[0].toFixed(3)}, ${d.ci95[1].toFixed(3)}], p=${d.pValue.toFixed(4)}, Cohen's d=${d.cohensD.toFixed(2)} (n_current=${d.currentN}, n_baseline=${d.baselineN}). Statistically significant improvement worth flagging.`,\n evidencePath: `priorPeriodComparison.metrics.${name}`,\n })\n }\n }\n\n // Composite-distribution branch. Fires when the overall quality signal is\n // poor regardless of lift / contamination / clusters — the customer needs\n // to know they have a problem AND which specific runs to inspect.\n if (ctx.composite.n > 0) {\n if (ctx.composite.mean < 0.3) {\n const tail = ctx.composite.tailRuns ?? []\n const names = tail\n .slice(0, 5)\n .map((t) => `${t.runId}=${t.score.toFixed(3)}`)\n .join(', ')\n out.push({\n priority: 'critical',\n kind: 'investigate',\n title: `Composite mean ${ctx.composite.mean.toFixed(3)} is below the 0.3 floor — the agent is broken on this corpus`,\n detail:\n tail.length > 0\n ? `Worst ${tail.length} run${tail.length === 1 ? '' : 's'} to inspect first: ${names}. Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`\n : `Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`,\n evidencePath: 'composite.tailRuns',\n })\n } else if (ctx.composite.mean < 0.5) {\n const tail = ctx.composite.tailRuns ?? []\n const names = tail\n .slice(0, 3)\n .map((t) => `${t.runId}=${t.score.toFixed(3)}`)\n .join(', ')\n out.push({\n priority: 'high',\n kind: 'investigate',\n title: `Composite mean ${ctx.composite.mean.toFixed(3)} is below 0.5 — investigate the lower tail before claiming the agent is healthy`,\n detail:\n tail.length > 0\n ? `Worst ${tail.length} run${tail.length === 1 ? '' : 's'}: ${names}. Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`\n : `Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`,\n evidencePath: 'composite.tailRuns',\n })\n }\n }\n\n // Dominant-failure-mode branch (model-free). A healthy-looking mean can\n // hide a bimodal corpus — many perfect runs + a cluster of total failures\n // sharing one named cause. Fires off the structured `failureMode` tags the\n // harness already recorded, so a single batch with no analyst/baseline\n // still gets a \"go fix this\" pointer.\n if (ctx.failureModes && ctx.failureModes.length > 0) {\n const top = ctx.failureModes[0]!\n if (top.count >= 3 && top.share >= 0.15) {\n out.push({\n priority: top.share >= 0.25 ? 'high' : 'medium',\n kind: 'investigate',\n title: `'${top.mode}' is the dominant failure mode — ${top.count} runs (${(top.share * 100).toFixed(0)}% of the corpus)`,\n detail: `The mean composite can look acceptable while one named failure dominates the lower tail. ${top.count} of ${ctx.composite.n} runs failed with '${top.mode}'${ctx.failureModes.length > 1 ? ` (next: '${ctx.failureModes[1]!.mode}' ×${ctx.failureModes[1]!.count})` : ''}. Fix this cause first.`,\n evidencePath: 'failureModes',\n })\n }\n }\n\n // Missing-judges branch. The report can't surface per-dimension or\n // calibration signal when `outcome.judgeScores` is empty across the\n // corpus. Tell the customer how to enrich.\n if (Object.keys(ctx.judges).length === 0 && ctx.composite.n > 0) {\n out.push({\n priority: 'medium',\n kind: 'expand-corpus',\n title: 'No judge scores recorded — per-dimension + calibration insights unavailable',\n detail:\n 'Records have no `outcome.judgeScores`. To unlock perDimension, judges, and calibration, attach a Judge run during your eval pass and populate `outcome.judgeScores.perJudge[judgeName][dimension] = score`. See `docs/insight-report.md` for the expected shape.',\n evidencePath: 'judges',\n })\n }\n\n if (ctx.lift) {\n const decisive = ctx.lift.ci95[0] > ctx.threshold\n const inconclusive = ctx.lift.ci95[0] <= ctx.threshold && ctx.lift.ci95[1] > ctx.threshold\n if (decisive) {\n out.push({\n priority: 'critical',\n kind: 'ship',\n title: `Ship — lift ${ctx.lift.delta.toFixed(3)} (95% CI ${ctx.lift.ci95[0].toFixed(3)}..${ctx.lift.ci95[1].toFixed(3)})`,\n detail: `Holdout lift exceeds threshold ${ctx.threshold} with 95% bootstrap confidence (n=${ctx.lift.n}, p=${ctx.lift.pValue.toFixed(4)}, d=${ctx.lift.cohensD.toFixed(2)}).`,\n evidencePath: 'lift',\n })\n } else if (inconclusive) {\n out.push({\n priority: 'high',\n kind: 'expand-corpus',\n title: `Inconclusive — need ~${ctx.lift.requiredN} paired runs (have ${ctx.lift.n}) at current effect size`,\n detail: `CI straddles threshold. Current MDE at 80% power is ${ctx.lift.mde.toFixed(3)}; observed delta is ${ctx.lift.delta.toFixed(3)}.`,\n evidencePath: 'lift',\n })\n } else {\n out.push({\n priority: 'critical',\n kind: 'hold',\n title: `Hold — lift CI lower bound ${ctx.lift.ci95[0].toFixed(3)} is at or below threshold ${ctx.threshold}`,\n detail: `Bootstrap CI provides no statistical evidence the candidate is better. Consider tightening the mutation or expanding the holdout.`,\n evidencePath: 'lift',\n })\n }\n }\n\n if (ctx.contamination && ctx.contamination.leaks > 0) {\n out.push({\n priority: 'critical',\n kind: 'fix',\n title: `${ctx.contamination.leaks} canary leak${ctx.contamination.leaks === 1 ? '' : 's'} detected`,\n detail: `Holdout integrity is compromised. The lift number is unreliable until you investigate.`,\n evidencePath: 'contamination',\n })\n }\n\n if (ctx.interRater && ctx.interRater.kappa < 0.5) {\n out.push({\n priority: 'high',\n kind: 'recalibrate',\n title: `Inter-rater agreement κ=${ctx.interRater.kappa.toFixed(2)} is below 0.5`,\n detail: `Raters disagree on what 'good' looks like. Top disagreement cases listed in interRater.disagreementCases — consider a triage meeting or refining the rubric.`,\n evidencePath: 'interRater',\n })\n }\n\n if (ctx.failureClusters && ctx.failureClusters.clusters.length > 0) {\n const top = ctx.failureClusters.clusters[0]!\n out.push({\n priority: 'high',\n kind: 'investigate',\n title: `Top failure cluster: ${top.name} (${(top.share * 100).toFixed(0)}% of failures)`,\n detail: `${ctx.failureClusters.totalFailures} runs failed. The largest cluster groups ${top.exemplars.length} exemplars under '${top.name}'.`,\n evidencePath: 'failureClusters.clusters[0]',\n })\n }\n\n if (ctx.outcomeCorrelation && Math.abs(ctx.outcomeCorrelation.spearman) < 0.3) {\n out.push({\n priority: 'medium',\n kind: 'recalibrate',\n title: `Judge scores decoupled from ${ctx.outcomeCorrelation.metric} (Spearman ρ=${ctx.outcomeCorrelation.spearman.toFixed(2)})`,\n detail: `Your judges score what they were trained to score, but it isn't predicting downstream ${ctx.outcomeCorrelation.metric}. Consider retraining the judge against ${ctx.outcomeCorrelation.metric} as the gold signal.`,\n evidencePath: 'outcomeCorrelation',\n })\n }\n\n return out\n}\n\n// ── Re-export pareto figure spec for hosted-side rendering ─────────\n\nexport type { ParetoFigureSpec }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BO,SAAS,cAAc,QAAgB,WAA4C;AACxF,QAAM,QAAsB,CAAC;AAC7B,aAAW,KAAK,WAAW;AACzB,QAAI,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wB,IAAI,IAAI,MAAM,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;AAAA,MACxE,QAAQ,GAAG,IAAI,gBAAgB,aAAa,4CAA4C,IAAI,UAAU,MAAM,qBAAqB,IAAI,IAAI;AAAA,MACzI,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AAEA,MAAI,IAAI,sBAAsB,KAAK,IAAI,IAAI,mBAAmB,QAAQ,IAAI,KAAK;AAC7E,QAAI,KAAK;AAAA,MACP,UAAU;AAAA,MACV,MAAM;AAAA,MACN,OAAO,+BAA+B,IAAI,mBAAmB,MAAM,qBAAgB,IAAI,mBAAmB,SAAS,QAAQ,CAAC,CAAC;AAAA,MAC7H,QAAQ,yFAAyF,IAAI,mBAAmB,MAAM,2CAA2C,IAAI,mBAAmB,MAAM;AAAA,MACtM,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["cohensD","mean"]}
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  runCanaries,
3
3
  scoreRedTeamOutput
4
- } from "./chunk-7QTQKIDD.js";
4
+ } from "./chunk-JMIUM2HE.js";
5
5
  import {
6
6
  runCampaign
7
- } from "./chunk-2T4EZACH.js";
7
+ } from "./chunk-HRGTA6U5.js";
8
8
  import {
9
9
  detectRewardHacking
10
- } from "./chunk-5HRORJQY.js";
10
+ } from "./chunk-AIGWQEME.js";
11
11
  import {
12
12
  pairedBootstrap
13
- } from "./chunk-56GC6VYO.js";
13
+ } from "./chunk-HRGUJTER.js";
14
14
 
15
15
  // src/campaign/gates/compose.ts
16
16
  function composeGate(...gates) {
@@ -432,4 +432,4 @@ export {
432
432
  runEval,
433
433
  evolutionaryProposer
434
434
  };
435
- //# sourceMappingURL=chunk-KKWJD5E6.js.map
435
+ //# sourceMappingURL=chunk-RPZMBW27.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  summaryTable
3
- } from "./chunk-URWVKRCS.js";
3
+ } from "./chunk-6GT4NI4V.js";
4
4
  import {
5
5
  VerificationError
6
6
  } from "./chunk-3BFEG2F6.js";
@@ -574,4 +574,4 @@ export {
574
574
  judgeReplayGate,
575
575
  renderReleaseReport
576
576
  };
577
- //# sourceMappingURL=chunk-QTMYW64F.js.map
577
+ //# sourceMappingURL=chunk-VDGPPGE3.js.map
@@ -1,9 +1,9 @@
1
- import { S as Scenario, M as MutableSurface, b as DispatchContext, a as JudgeConfig, c as SurfaceProposer, G as Gate, L as LabeledScenarioStore, C as CampaignResult, d as GateDecision } from '../types-DQRY8ZT-.js';
2
- export { e as CampaignAggregates, f as CampaignArtifactWriter, g as CampaignCellResult, h as CampaignCostMeter, i as CampaignTraceWriter, j as CodeSurface, D as Dispatch, k as GateContext, l as GateResult, m as GenerationCandidate, n as GenerationRecord, o as JudgeDimension, J as JudgeScore, p as Mutator, O as OptimizationProposer, q as OptimizerConfig, r as SessionScript } from '../types-DQRY8ZT-.js';
3
- import { L as LoopProvenanceRecord, R as RunEvalOptions } from '../provenance-CncDq9qE.js';
4
- export { A as AxisEvidence, a as AxisVerdict, B as BuildEvidenceVectorOptions, D as DefaultProductionGateOptions, E as EvidenceVector, b as EvolutionaryProposerOptions, H as HeldOutGateOptions, O as ObjectiveSource, P as ParetoSignificanceGateOptions, c as PromotionObjective, d as PromotionPolicy, e as buildEvidenceVector, f as composeGate, g as defaultProductionGate, h as evolutionaryProposer, i as heldOutGate, p as paretoPolicy, j as paretoSignificanceGate, r as runEval } from '../provenance-CncDq9qE.js';
5
- import { C as CampaignStorage, R as RunOptimizationOptions, a as RunImprovementLoopResult } from '../gepa-C1NCIZ9o.js';
6
- export { G as GepaProposerOptions, b as RunCampaignOptions, c as RunImprovementLoopOptions, f as fsCampaignStorage, g as gepaProposer, i as inMemoryCampaignStorage, r as runCampaign, d as runImprovementLoop } from '../gepa-C1NCIZ9o.js';
1
+ import { S as Scenario, M as MutableSurface, b as DispatchContext, a as JudgeConfig, e as SurfaceProposer, f as Gate, L as LabeledScenarioStore, C as CampaignResult, i as GateDecision } from '../types-BMahhhio.js';
2
+ export { j as CampaignAggregates, k as CampaignArtifactWriter, l as CampaignCellResult, m as CampaignCostMeter, c as CampaignTraceWriter, n as CodeSurface, D as Dispatch, g as GateContext, G as GateResult, o as GenerationCandidate, d as GenerationRecord, p as JudgeDimension, J as JudgeScore, h as Mutator, O as OptimizationProposer, q as OptimizerConfig, r as SessionScript } from '../types-BMahhhio.js';
3
+ import { L as LoopProvenanceRecord, R as RunEvalOptions } from '../provenance-DJ--Jcbg.js';
4
+ export { A as AxisEvidence, a as AxisVerdict, B as BuildEvidenceVectorOptions, D as DefaultProductionGateOptions, E as EvidenceVector, b as EvolutionaryProposerOptions, H as HeldOutGateOptions, O as ObjectiveSource, P as ParetoSignificanceGateOptions, c as PromotionObjective, d as PromotionPolicy, e as buildEvidenceVector, f as composeGate, g as defaultProductionGate, h as evolutionaryProposer, i as heldOutGate, p as paretoPolicy, j as paretoSignificanceGate, r as runEval } from '../provenance-DJ--Jcbg.js';
5
+ import { C as CampaignStorage, a as RunOptimizationOptions, b as RunImprovementLoopResult } from '../gepa-Dprxvz8r.js';
6
+ export { G as GepaProposerOptions, R as RunCampaignOptions, c as RunImprovementLoopOptions, f as fsCampaignStorage, g as gepaProposer, i as inMemoryCampaignStorage, r as runCampaign, d as runImprovementLoop } from '../gepa-Dprxvz8r.js';
7
7
  export { D as DeploymentOutcome, F as FileSystemOutcomeStore, a as FileSystemOutcomeStoreOptions, I as InMemoryOutcomeStore, b as OutcomeStore } from '../outcome-store-rnXLEqSn.js';
8
8
  import { HostedTenant, EvalRunCellScore, EvalRunGenerationSnapshot, EvalRunEvent, TraceSpanEvent } from '../hosted/index.js';
9
9
  import { R as RunRecord, a as RunSplitTag } from '../run-record-CP2ObebC.js';
@@ -11,7 +11,8 @@ import { I as InsightReport } from '../insight-report-BnRjTibG.js';
11
11
  export { F as FailureClusterInsight, a as InterRaterInsight, J as JudgeInsight, L as LiftInsight, O as OutcomeCorrelationInsight, R as Recommendation, b as ReleaseSummary, S as ScalarDistribution } from '../insight-report-BnRjTibG.js';
12
12
  export { D as DefaultAnalystRegistryOptions, c as buildDefaultAnalystRegistry } from '../default-registry-GyE8X5SP.js';
13
13
  export { c as AnalystFinding } from '../types-B5x54y6n.js';
14
- export { A as AnalyzeRunsOptions, a as analyzeRuns } from '../analyze-runs-DtT6F_6T.js';
14
+ import { A as AnalyzeRunsOptions } from '../analyze-runs-DtT6F_6T.js';
15
+ export { a as analyzeRuns } from '../analyze-runs-DtT6F_6T.js';
15
16
  export { C as CodeAgentSessionDiagnostic, a as CodeAgentSessionIntakeOptions, b as CodeAgentSessionIntakeResult, c as CodeAgentSessionMetrics, d as CodeAgentSessionSource, P as ParsedCodeAgentJsonl, f as fromClaudeCodeSession, e as fromCodexSession, g as fromKimiCodeSession, h as fromOpenCodeSession, i as fromPiSession, j as fromPigraphSession, p as parseCodeAgentJsonl } from '../code-agent-session-CPHRCb4-.js';
16
17
  import '../red-team-BWdoyleI.js';
17
18
  import '../dataset-BbGkaN2I.js';
@@ -19,7 +20,7 @@ import '../errors-CzMUYo7b.js';
19
20
  import '../store-BcFXE6LG.js';
20
21
  import '../schema-m0gsnbt3.js';
21
22
  import '../pareto-E-pembql.js';
22
- import '../statistics-CCJpTGOS.js';
23
+ import '../statistics-xP-cWc5k.js';
23
24
  import '../judge-calibration-0p2QcWNE.js';
24
25
  import '../types-C7DGg5ex.js';
25
26
  import '@tangle-network/tcloud';
@@ -358,6 +359,140 @@ interface DefinedAgentEval<TScenario extends Scenario, TArtifact> {
358
359
  */
359
360
  declare function defineAgentEval<TScenario extends Scenario, TArtifact>(defaults: DefineAgentEvalOptions<TScenario, TArtifact>): DefinedAgentEval<TScenario, TArtifact>;
360
361
 
362
+ /**
363
+ * # `intake/run-record-dir` — load a directory or file of `RunRecord`s.
364
+ *
365
+ * The on-disk counterpart to the in-memory intake adapters: point it at a
366
+ * single `.json` (array) / `.jsonl` (one record per line) file or at a
367
+ * directory of such files, and it returns the substrate-canonical
368
+ * `RunRecord[]` ready for `analyzeRuns({ runs })`.
369
+ *
370
+ * Validation is at the boundary: each parsed object goes through
371
+ * `parseRunRecordSafe`. By default an invalid record fails loud with its
372
+ * file + index; pass `onInvalid: 'collect'` to keep the valid records and
373
+ * receive the rejects as structured diagnostics instead.
374
+ */
375
+
376
+ /** A record that failed boundary validation, with enough context to fix it. */
377
+ interface RunRecordRejection {
378
+ /** Absolute or caller-relative path to the file the record came from. */
379
+ file: string;
380
+ /** Zero-based position within the file (array index or JSONL line number). */
381
+ index: number;
382
+ /** The validator's message. */
383
+ reason: string;
384
+ }
385
+ interface FromRunRecordDirOptions {
386
+ /**
387
+ * How to treat a record that fails `parseRunRecordSafe`:
388
+ * - `'throw'` (default) — fail loud on the first invalid record.
389
+ * - `'collect'` — drop it, keep the rest, and return it under `rejected`.
390
+ */
391
+ onInvalid?: 'throw' | 'collect';
392
+ /**
393
+ * When the input is a directory, only files matching this predicate are
394
+ * read. Default: any file ending in `.json` or `.jsonl`. The `analysis.json`
395
+ * artifact `evalReportingSuite` writes is always skipped so a re-run never
396
+ * ingests its own output.
397
+ */
398
+ include?: (fileName: string) => boolean;
399
+ /**
400
+ * Recurse into subdirectories when the input is a directory. Default false —
401
+ * a flat run directory is the common case and recursion can silently pull in
402
+ * unrelated corpora.
403
+ */
404
+ recursive?: boolean;
405
+ }
406
+ interface FromRunRecordDirResult {
407
+ /** Records that passed boundary validation, in file-then-index order. */
408
+ runs: RunRecord[];
409
+ /** Records that failed validation. Empty unless `onInvalid: 'collect'`. */
410
+ rejected: RunRecordRejection[];
411
+ /** The files that were read, in the order they were processed. */
412
+ files: string[];
413
+ }
414
+ /**
415
+ * Resolve a file or directory path into validated `RunRecord[]`.
416
+ *
417
+ * A `.json` file must parse to a top-level array; a `.jsonl` file is one
418
+ * record per non-empty line. Directories are read shallowly by default
419
+ * (set `recursive` to descend); the `analysis.json` output artifact is
420
+ * always excluded.
421
+ */
422
+ declare function fromRunRecordDir(path: string, options?: FromRunRecordDirOptions): Promise<FromRunRecordDirResult>;
423
+
424
+ /**
425
+ * # `evalReportingSuite` — one call from runs (or a run dir) to `analysis.json`.
426
+ *
427
+ * A thin wrapper over the analysis primitive (`analyzeRuns`) and the on-disk
428
+ * intake adapter (`fromRunRecordDir`). It does NOT reimplement any statistics,
429
+ * distributions, or clustering — it resolves the input into validated
430
+ * `RunRecord[]`, calls `analyzeRuns` with the options you'd pass it directly,
431
+ * wraps the result in a small provenance envelope, and (optionally) writes a
432
+ * single `analysis.json` artifact.
433
+ *
434
+ * ```ts
435
+ * // From a directory of run files, write ./runs/analysis.json:
436
+ * const suite = await evalReportingSuite('./runs', { write: true })
437
+ * // From records already in memory, no write:
438
+ * const suite = await evalReportingSuite(records, { analyze: { decisionThreshold: 0.03 } })
439
+ * suite.report // the InsightReport — distributions, paired lift, findings rollup
440
+ * ```
441
+ */
442
+
443
+ /** Either records in hand or a path to a `.json` / `.jsonl` file or a
444
+ * directory of them. */
445
+ type EvalReportingSuiteInput = RunRecord[] | string;
446
+ interface EvalReportingSuiteOptions {
447
+ /** Forwarded verbatim to `analyzeRuns` (everything except `runs`, which the
448
+ * suite supplies from the resolved input). Use this for split selection,
449
+ * baseline/candidate ids, canaries, prior-period runs, the analyst registry,
450
+ * etc. */
451
+ analyze?: Omit<AnalyzeRunsOptions, 'runs'>;
452
+ /** Loader options used only when the input is a path. */
453
+ load?: FromRunRecordDirOptions;
454
+ /**
455
+ * Write the suite result as a single `analysis.json`.
456
+ * - `true` — write to `<dir>/analysis.json` when the input is a directory,
457
+ * or alongside the input file; throws if the input is in-memory records
458
+ * (no directory to anchor to — pass an explicit path instead).
459
+ * - a string — write to exactly this path (a directory path gets
460
+ * `analysis.json` appended; any other path is used verbatim).
461
+ * - omitted / false — do not write.
462
+ */
463
+ write?: boolean | string;
464
+ }
465
+ /** The suite artifact — the `analyzeRuns` report plus provenance. This is the
466
+ * exact shape serialized to `analysis.json`. */
467
+ interface EvalReportingSuiteResult {
468
+ /** The analysis itself — distributions, paired stats/lift, failure rollup,
469
+ * recommendations. Produced by `analyzeRuns`. */
470
+ report: InsightReport;
471
+ /** How the suite was run, so a reader can verify provenance. */
472
+ provenance: {
473
+ /** ISO timestamp the suite ran. */
474
+ generatedAt: string;
475
+ /** Number of records analyzed (mirrors `report.n`). */
476
+ runCount: number;
477
+ /** The source path when the input was a directory/file; null for
478
+ * in-memory records. */
479
+ sourcePath: string | null;
480
+ /** Files read when loading from disk; empty for in-memory input. */
481
+ files: string[];
482
+ /** Records dropped at the validation boundary. Always empty unless
483
+ * `load.onInvalid` was set to `'collect'`. */
484
+ rejected: FromRunRecordDirResult['rejected'];
485
+ };
486
+ /** The path `analysis.json` was written to, or null when `write` was unset. */
487
+ writtenTo: string | null;
488
+ }
489
+ /**
490
+ * Resolve runs (or a run dir/file), run `analyzeRuns`, and optionally persist a
491
+ * single `analysis.json`. The only analysis logic lives in `analyzeRuns`; this
492
+ * function is composition + I/O.
493
+ */
494
+ declare function evalReportingSuite(input: EvalReportingSuiteInput, options?: EvalReportingSuiteOptions): Promise<EvalReportingSuiteResult>;
495
+
361
496
  /**
362
497
  * # `@tangle-network/agent-eval/contract` — eval-run diff primitive.
363
498
  *
@@ -687,4 +822,4 @@ interface FromOtelSpansOptions {
687
822
  }
688
823
  declare function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[];
689
824
 
690
- export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AuthoringProvenance, CampaignResult, CampaignStorage, type DefineAgentEvalOptions, type DefinedAgentEval, DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalRunDiff, type FeedbackTableMeta, type FeedbackTableRow, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, Gate, GateDecision, HostedTenant, InsightReport, JudgeConfig, MutableSurface, type PartitionByAuthoringModelResult, RunEvalOptions, RunImprovementLoopResult, Scenario, type SelfImproveBudget, type SelfImproveLlm, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SurfaceProposer, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, fromFeedbackTable, fromOtelSpans, parseAgentTrace, partitionRunsByAuthoringModel, selfImprove };
825
+ export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, AnalyzeRunsOptions, type AuthoringProvenance, CampaignResult, CampaignStorage, type DefineAgentEvalOptions, type DefinedAgentEval, DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalReportingSuiteInput, type EvalReportingSuiteOptions, type EvalReportingSuiteResult, type EvalRunDiff, type FeedbackTableMeta, type FeedbackTableRow, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, type FromRunRecordDirOptions, type FromRunRecordDirResult, Gate, GateDecision, HostedTenant, InsightReport, JudgeConfig, MutableSurface, type PartitionByAuthoringModelResult, RunEvalOptions, RunImprovementLoopResult, type RunRecordRejection, Scenario, type SelfImproveBudget, type SelfImproveLlm, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SurfaceProposer, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, fromFeedbackTable, fromOtelSpans, fromRunRecordDir, parseAgentTrace, partitionRunsByAuthoringModel, selfImprove };
@@ -18,36 +18,36 @@ import {
18
18
  paretoPolicy,
19
19
  paretoSignificanceGate,
20
20
  runEval
21
- } from "../chunk-KKWJD5E6.js";
21
+ } from "../chunk-RPZMBW27.js";
22
22
  import {
23
23
  analyzeRuns
24
- } from "../chunk-Z6L6YSU6.js";
24
+ } from "../chunk-QZYXA7ZO.js";
25
25
  import {
26
26
  emitLoopProvenance,
27
27
  gepaProposer,
28
28
  heldOutGate,
29
29
  runImprovementLoop,
30
30
  surfaceContentHash
31
- } from "../chunk-7QTQKIDD.js";
31
+ } from "../chunk-JMIUM2HE.js";
32
32
  import {
33
33
  fsCampaignStorage,
34
34
  inMemoryCampaignStorage,
35
35
  runCampaign
36
- } from "../chunk-2T4EZACH.js";
36
+ } from "../chunk-HRGTA6U5.js";
37
37
  import "../chunk-VI2UW6B6.js";
38
38
  import {
39
39
  buildDefaultAnalystRegistry
40
- } from "../chunk-AQ5WQAIV.js";
40
+ } from "../chunk-3NHEO6ZC.js";
41
41
  import "../chunk-S4SYLDFX.js";
42
- import "../chunk-5HRORJQY.js";
42
+ import "../chunk-AIGWQEME.js";
43
43
  import {
44
44
  FileSystemOutcomeStore,
45
45
  InMemoryOutcomeStore
46
46
  } from "../chunk-3RF76KTD.js";
47
47
  import "../chunk-CWNP4DV4.js";
48
- import "../chunk-URWVKRCS.js";
48
+ import "../chunk-6GT4NI4V.js";
49
49
  import "../chunk-45EEMHTC.js";
50
- import "../chunk-56GC6VYO.js";
50
+ import "../chunk-HRGUJTER.js";
51
51
  import "../chunk-GGE4NNQT.js";
52
52
  import "../chunk-UFSG7ACU.js";
53
53
  import "../chunk-5BKGXME7.js";
@@ -57,6 +57,9 @@ import {
57
57
  LLM_OUTPUT_TOKEN_ATTR_KEYS
58
58
  } from "../chunk-YBIGNSCZ.js";
59
59
  import "../chunk-PC4UYEBM.js";
60
+ import {
61
+ parseRunRecordSafe
62
+ } from "../chunk-LO6IOIJ2.js";
60
63
  import "../chunk-VSMTAMNK.js";
61
64
  import "../chunk-3BFEG2F6.js";
62
65
  import "../chunk-PZ5AY32C.js";
@@ -474,6 +477,145 @@ function requirePositiveInteger(value, field) {
474
477
  return value;
475
478
  }
476
479
 
480
+ // src/contract/eval-reporting-suite.ts
481
+ import { mkdir, writeFile } from "fs/promises";
482
+ import { dirname, join as join2 } from "path";
483
+
484
+ // src/contract/intake/run-record-dir.ts
485
+ import { readdir, readFile, stat } from "fs/promises";
486
+ import { join } from "path";
487
+ var ANALYSIS_ARTIFACT = "analysis.json";
488
+ function defaultInclude(fileName) {
489
+ if (fileName === ANALYSIS_ARTIFACT) return false;
490
+ return fileName.endsWith(".json") || fileName.endsWith(".jsonl");
491
+ }
492
+ async function fromRunRecordDir(path, options = {}) {
493
+ const onInvalid = options.onInvalid ?? "throw";
494
+ const include = options.include ?? defaultInclude;
495
+ const stats = await stat(path);
496
+ const filePaths = stats.isDirectory() ? await collectFiles(path, include, options.recursive ?? false) : [path];
497
+ const runs = [];
498
+ const rejected = [];
499
+ for (const file of filePaths) {
500
+ const raw = await parseRecordFile(file);
501
+ for (const { index, value } of raw) {
502
+ const parsed = parseRunRecordSafe(value);
503
+ if (parsed.ok) {
504
+ runs.push(parsed.value);
505
+ continue;
506
+ }
507
+ const rejection = { file, index, reason: parsed.error.message };
508
+ if (onInvalid === "throw") {
509
+ throw new Error(
510
+ `fromRunRecordDir: invalid RunRecord in '${file}' at index ${index}: ${parsed.error.message}`
511
+ );
512
+ }
513
+ rejected.push(rejection);
514
+ }
515
+ }
516
+ return { runs, rejected, files: filePaths };
517
+ }
518
+ async function parseRecordFile(file) {
519
+ const text = await readFile(file, "utf8");
520
+ const trimmed = text.trim();
521
+ if (trimmed.length === 0) return [];
522
+ if (trimmed.startsWith("[")) {
523
+ const parsed = JSON.parse(trimmed);
524
+ if (!Array.isArray(parsed)) {
525
+ throw new Error(`fromRunRecordDir: file '${file}' did not parse to an array`);
526
+ }
527
+ return parsed.map((value, index) => ({ index, value }));
528
+ }
529
+ const out = [];
530
+ const lines = trimmed.split("\n");
531
+ for (let i = 0; i < lines.length; i++) {
532
+ const line = lines[i].trim();
533
+ if (line.length === 0) continue;
534
+ try {
535
+ out.push({ index: i, value: JSON.parse(line) });
536
+ } catch (err) {
537
+ throw new Error(
538
+ `fromRunRecordDir: file '${file}' line ${i + 1} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`
539
+ );
540
+ }
541
+ }
542
+ return out;
543
+ }
544
+ async function collectFiles(dir, include, recursive) {
545
+ const entries = await readdir(dir, { withFileTypes: true });
546
+ const files = [];
547
+ const subdirs = [];
548
+ for (const entry of entries) {
549
+ if (entry.isDirectory()) {
550
+ if (recursive) subdirs.push(join(dir, entry.name));
551
+ continue;
552
+ }
553
+ if (include(entry.name)) files.push(join(dir, entry.name));
554
+ }
555
+ files.sort();
556
+ subdirs.sort();
557
+ for (const sub of subdirs) {
558
+ files.push(...await collectFiles(sub, include, recursive));
559
+ }
560
+ return files;
561
+ }
562
+
563
+ // src/contract/eval-reporting-suite.ts
564
+ var ANALYSIS_ARTIFACT2 = "analysis.json";
565
+ async function evalReportingSuite(input, options = {}) {
566
+ const fromPath = typeof input === "string";
567
+ let runs;
568
+ let files = [];
569
+ let rejected = [];
570
+ if (fromPath) {
571
+ const loaded = await fromRunRecordDir(input, options.load);
572
+ runs = loaded.runs;
573
+ files = loaded.files;
574
+ rejected = loaded.rejected;
575
+ } else {
576
+ runs = input;
577
+ }
578
+ if (runs.length === 0) {
579
+ throw new Error(
580
+ fromPath ? `evalReportingSuite: no RunRecords found at '${input}'` : "evalReportingSuite: no RunRecords to analyze"
581
+ );
582
+ }
583
+ const report = await analyzeRuns({ ...options.analyze, runs });
584
+ const result = {
585
+ report,
586
+ provenance: {
587
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
588
+ runCount: runs.length,
589
+ sourcePath: fromPath ? input : null,
590
+ files,
591
+ rejected
592
+ },
593
+ writtenTo: null
594
+ };
595
+ const target = resolveWriteTarget(options.write, fromPath ? input : null);
596
+ if (target) {
597
+ await mkdir(dirname(target), { recursive: true });
598
+ await writeFile(target, `${JSON.stringify(result, null, 2)}
599
+ `, "utf8");
600
+ result.writtenTo = target;
601
+ }
602
+ return result;
603
+ }
604
+ function resolveWriteTarget(write, sourcePath) {
605
+ if (!write) return null;
606
+ if (typeof write === "string") {
607
+ const looksLikeDir = write.endsWith("/") || !write.endsWith(".json") && !write.endsWith(".jsonl");
608
+ return looksLikeDir ? join2(write, ANALYSIS_ARTIFACT2) : write;
609
+ }
610
+ if (sourcePath === null) {
611
+ throw new Error(
612
+ "evalReportingSuite: write:true needs a source path to anchor analysis.json \u2014 pass an explicit output path when analyzing in-memory records"
613
+ );
614
+ }
615
+ const isFile = sourcePath.endsWith(".json") || sourcePath.endsWith(".jsonl");
616
+ return isFile ? join2(dirname(sourcePath), ANALYSIS_ARTIFACT2) : join2(sourcePath, ANALYSIS_ARTIFACT2);
617
+ }
618
+
477
619
  // src/contract/diff.ts
478
620
  function keyForCell(cell) {
479
621
  return JSON.stringify([cell.scenarioId, cell.rep]);
@@ -833,6 +975,7 @@ export {
833
975
  diffGenerations,
834
976
  diffRunBaselineToWinner,
835
977
  diffRuns,
978
+ evalReportingSuite,
836
979
  evolutionaryProposer,
837
980
  fromClaudeCodeSession,
838
981
  fromCodexSession,
@@ -842,6 +985,7 @@ export {
842
985
  fromOtelSpans,
843
986
  fromPiSession,
844
987
  fromPigraphSession,
988
+ fromRunRecordDir,
845
989
  fsCampaignStorage,
846
990
  gepaProposer,
847
991
  heldOutGate,