import {
  fromClaudeCodeSession,
  fromCodexSession,
  fromKimiCodeSession,
  fromOpenCodeSession,
  fromPiSession,
  fromPigraphSession,
  parseCodeAgentJsonl
} from "../chunk-S42AWHMP.js";
import {
  createHostedClient
} from "../chunk-ZZUXHH3R.js";
import {
  buildEvidenceVector,
  composeGate,
  defaultProductionGate,
  evolutionaryProposer,
  paretoPolicy,
  paretoSignificanceGate,
  runEval
} from "../chunk-KKWJD5E6.js";
import {
  analyzeRuns
} from "../chunk-Z6L6YSU6.js";
import {
  emitLoopProvenance,
  gepaProposer,
  heldOutGate,
  runImprovementLoop,
  surfaceContentHash
} from "../chunk-7QTQKIDD.js";
import {
  fsCampaignStorage,
  inMemoryCampaignStorage,
  runCampaign
} from "../chunk-2T4EZACH.js";
import "../chunk-VI2UW6B6.js";
import {
  buildDefaultAnalystRegistry
} from "../chunk-AQ5WQAIV.js";
import "../chunk-S4SYLDFX.js";
import "../chunk-5HRORJQY.js";
import {
  FileSystemOutcomeStore,
  InMemoryOutcomeStore
} from "../chunk-3RF76KTD.js";
import "../chunk-CWNP4DV4.js";
import "../chunk-URWVKRCS.js";
import "../chunk-45EEMHTC.js";
import "../chunk-56GC6VYO.js";
import "../chunk-GGE4NNQT.js";
import "../chunk-UFSG7ACU.js";
import "../chunk-5BKGXME7.js";
import {
  LLM_INPUT_TOKEN_ATTR_KEYS,
  LLM_MODEL_ATTR_KEYS,
  LLM_OUTPUT_TOKEN_ATTR_KEYS
} from "../chunk-YBIGNSCZ.js";
import "../chunk-PC4UYEBM.js";
import "../chunk-VSMTAMNK.js";
import "../chunk-3BFEG2F6.js";
import "../chunk-PZ5AY32C.js";

// src/contract/self-improve.ts
import { createHash } from "crypto";
function splitTrainHoldout(scenarios, fraction) {
  function hash(s) {
    let h = 2166136261 >>> 0;
    for (let i = 0; i < s.length; i++) {
      h ^= s.charCodeAt(i);
      h = Math.imul(h, 16777619) >>> 0;
    }
    return h;
  }
  const sorted = [...scenarios].sort((a, b) => hash(a.id) - hash(b.id));
  const nHoldout = Math.max(1, Math.min(sorted.length - 1, Math.round(sorted.length * fraction)));
  return {
    holdout: sorted.slice(0, nHoldout),
    train: sorted.slice(nHoldout)
  };
}
function meanComposite(byScenario) {
  const perScenario = {};
  const values = [];
  for (const [id, agg] of Object.entries(byScenario)) {
    perScenario[id] = agg.meanComposite;
    values.push(agg.meanComposite);
  }
  return {
    compositeMean: values.length === 0 ? 0 : values.reduce((s, v) => s + v, 0) / values.length,
    perScenario
  };
}
var DEFAULT_MUTATION_PRIMITIVES = [
  "Tighten the hook: lead with the specific user outcome.",
  "Replace generic adjectives with specific verbs or proof numbers.",
  "Anchor every claim in something the scenario's brief literally supports.",
  "Honor the surface-shape constraint (length, register, audience vocabulary)."
];
async function selfImprove(opts) {
  const startedAt = Date.now();
  const budget = opts.budget ?? {};
  const generations = budget.generations ?? 3;
  const populationSize = budget.populationSize ?? 2;
  const maxConcurrency = budget.maxConcurrency ?? 2;
  const holdoutFraction = budget.holdoutFraction ?? 0.25;
  const costCeiling = budget.dollars;
  const expectUsage = opts.expectUsage ?? "assert";
  const explicitHoldout = budget.holdoutScenarios;
  const { train, holdout } = explicitHoldout ? {
    train: opts.scenarios.filter((s) => !explicitHoldout.some((h) => h.id === s.id)),
    holdout: explicitHoldout
  } : splitTrainHoldout(opts.scenarios, holdoutFraction);
  if (train.length === 0) {
    throw new Error(
      "selfImprove: train split is empty. Reduce holdoutFraction or pass more scenarios."
    );
  }
  if (holdout.length === 0) {
    throw new Error("selfImprove: holdout split is empty. Pass more scenarios.");
  }
  const proposer = opts.proposer ?? gepaProposer({
    llm: {
      baseUrl: opts.llm?.baseUrl ?? "https://router.tangle.tools/v1",
      apiKey: opts.llm?.apiKey ?? process.env.OPENAI_API_KEY ?? ""
    },
    model: opts.llm?.model ?? "anthropic/claude-sonnet-4.6",
    target: opts.proposerTarget ?? "agent surface (system prompt or config) being optimized by selfImprove",
    mutationPrimitives: opts.mutationPrimitives ?? DEFAULT_MUTATION_PRIMITIVES
  });
  const gate = opts.gate ?? defaultProductionGate({
    holdoutScenarios: holdout,
    deltaThreshold: 0.05
  });
  const runDir = opts.runDir ?? `mem://selfImprove-${startedAt}`;
  const isMemRunDir = runDir.startsWith("mem://");
  const storage = opts.storage ?? (isMemRunDir ? inMemoryCampaignStorage() : fsCampaignStorage());
  if (opts.onProgress) {
    opts.onProgress({ kind: "baseline.started", scenarios: opts.scenarios.length });
  }
  const result = await runImprovementLoop({
    scenarios: train,
    baselineSurface: opts.baselineSurface,
    dispatchWithSurface: opts.agent,
    proposer,
    judges: [opts.judge],
    populationSize,
    maxGenerations: generations,
    promoteTopK: budget.promoteTopK,
    reps: budget.reps,
    holdoutScenarios: holdout,
    gate,
    autoOnPromote: opts.autoOnPromote ?? "none",
    ghOwner: opts.ghOwner,
    ghRepo: opts.ghRepo,
    storage,
    runDir,
    maxConcurrency,
    cellPlacement: opts.cellPlacement,
    costCeiling,
    expectUsage,
    labeledStore: opts.labeledStore,
    captureSource: opts.captureSource,
    analyzeGeneration: opts.analyzeGeneration,
    findings: opts.findings
  });
  const baseline = meanComposite(result.baselineOnHoldout.aggregates.byScenario);
  const winnerStats = meanComposite(result.winnerOnHoldout.aggregates.byScenario);
  if (opts.onProgress) {
    opts.onProgress({
      kind: "baseline.completed",
      compositeMean: baseline.compositeMean,
      durationMs: Date.now() - startedAt
    });
    opts.onProgress({
      kind: "gate.decided",
      decision: result.gateResult.decision,
      lift: winnerStats.compositeMean - baseline.compositeMean
    });
  }
  const totalCost = result.baselineCampaign.aggregates.totalCostUsd + result.generations.reduce(
    (sum, gen) => sum + gen.surfaces.reduce((s, sf) => s + sf.campaign.aggregates.totalCostUsd, 0),
    0
  );
  const insight = await analyzeRuns({
    runs: [
      ...cellsToRunRecords(result.baselineCampaign.cells, "baseline", runDir, opts.baselineSurface),
      ...cellsToRunRecords(result.winnerOnHoldout.cells, "winner", runDir, result.winnerSurface)
    ],
    baselineCandidateId: "baseline",
    candidateCandidateId: "winner"
  });
  const durationMs = Date.now() - startedAt;
  const workerRecords = opts.collectWorkerRecords?.() ?? cellsToRunRecords(result.winnerOnHoldout.cells, "winner", runDir, result.winnerSurface);
  const { record: provenance } = await emitLoopProvenance({
    runId: `${runDir}#${startedAt}`,
    runDir,
    timestamp: new Date(startedAt).toISOString(),
    baselineSurface: opts.baselineSurface,
    winnerSurface: result.winnerSurface,
    winnerLabel: result.winnerLabel,
    winnerRationale: result.winnerRationale,
    diff: result.promotedDiff,
    generations: result.generations.map((g) => ({
      generationIndex: g.record.generationIndex,
      candidates: g.record.candidates,
      promoted: g.record.promoted,
      surfaces: g.surfaces.map((s) => ({ surfaceHash: s.surfaceHash, surface: s.surface }))
    })),
    gate: result.gateResult,
    baselineOnHoldout: result.baselineOnHoldout,
    winnerOnHoldout: result.winnerOnHoldout,
    workerRecords,
    totalCostUsd: totalCost,
    totalDurationMs: durationMs,
    storage,
    hostedClient: opts.hostedTenant ? createHostedClient(opts.hostedTenant) : void 0
  });
  if (opts.onProvenance) opts.onProvenance(provenance);
  const summary = {
    baseline,
    winner: {
      ...winnerStats,
      surface: result.winnerSurface,
      ...result.winnerLabel ? { label: result.winnerLabel } : {},
      ...result.winnerRationale ? { rationale: result.winnerRationale } : {}
    },
    lift: winnerStats.compositeMean - baseline.compositeMean,
    diff: result.promotedDiff,
    provenance,
    gateDecision: result.gateResult.decision,
    generationsExplored: result.generations.length,
    durationMs,
    totalCostUsd: totalCost,
    insight,
    raw: result
  };
  if (opts.hostedTenant) {
    try {
      await shipEvalRunToHosted(opts.hostedTenant, opts, summary, result, runDir);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.warn(`[agent-eval] hosted ingest failed (continuing): ${msg}`);
    }
  }
  return summary;
}
async function shipEvalRunToHosted(tenant, opts, summary, raw, runDir) {
  const client = createHostedClient(tenant);
  function snapshotFromCampaign(index, surface, campaign, durationMs) {
    const cells = campaign.cells.map((cell) => {
      const judgeScores = Object.values(cell.judgeScores);
      const composite = judgeScores.length === 0 ? 0 : judgeScores.reduce((s, j) => s + j.composite, 0) / judgeScores.length;
      return {
        scenarioId: cell.scenarioId,
        rep: cell.rep,
        compositeMean: composite,
        dimensions: Object.fromEntries(
          Object.entries(cell.judgeScores).map(([name, score]) => [name, score.dimensions])
        ),
        errorMessage: cell.error ?? void 0
      };
    });
    const compositeMean = cells.length === 0 ? 0 : cells.reduce((s, c) => s + c.compositeMean, 0) / cells.length;
    return {
      index,
      surfaceHash: typeof surface === "string" ? hashString(surface) : hashString(JSON.stringify(surface ?? "")),
      surface,
      cells,
      compositeMean,
      costUsd: campaign.aggregates.totalCostUsd,
      durationMs
    };
  }
  const generations = [];
  generations.push(snapshotFromCampaign(0, opts.baselineSurface, raw.baselineCampaign, 0));
  for (const gen of raw.generations) {
    const winner = gen.surfaces.reduce(
      (best, s) => s.campaign.aggregates.cellsExecuted > 0 && (best === void 0 || averageComposite(s.campaign) > averageComposite(best.campaign)) ? s : best,
      gen.surfaces[0]
    );
    if (!winner) continue;
    generations.push(
      snapshotFromCampaign(gen.record.generationIndex + 1, winner.surface, winner.campaign, 0)
    );
  }
  const event = {
    runId: `${runDir}#${Date.now()}`,
    runDir,
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    status: "finished",
    labels: opts.hostedLabels ?? {},
    baseline: generations[0],
    generations,
    gateDecision: summary.gateDecision,
    holdoutLift: summary.lift,
    totalCostUsd: summary.totalCostUsd,
    totalDurationMs: summary.durationMs,
    insightReport: summary.insight
  };
  await client.ingestEvalRun(event);
}
function averageComposite(campaign) {
  const aggs = Object.values(campaign.aggregates.byScenario);
  return aggs.length === 0 ? 0 : aggs.reduce((s, a) => s + a.meanComposite, 0) / aggs.length;
}
function hashString(s) {
  let h = 2166136261 >>> 0;
  for (let i = 0; i < s.length; i++) {
    h ^= s.charCodeAt(i);
    h = Math.imul(h, 16777619) >>> 0;
  }
  return h.toString(16).padStart(8, "0");
}
function cellsToRunRecords(cells, candidateId, runId, surface) {
  const promptHash = surfaceContentHash(surface);
  const configHash = `sha256:${createHash("sha256").update(candidateId).digest("hex")}`;
  return cells.map((cell) => {
    const perJudge = {};
    const perDimMeanAccum = {};
    let compositeSum = 0;
    let compositeCount = 0;
    for (const [judgeId, score] of Object.entries(cell.judgeScores)) {
      perJudge[judgeId] = { ...score.dimensions };
      for (const [dim, value] of Object.entries(score.dimensions)) {
        if (!Number.isFinite(value)) continue;
        const accum = perDimMeanAccum[dim] ?? { sum: 0, n: 0 };
        accum.sum += value;
        accum.n += 1;
        perDimMeanAccum[dim] = accum;
      }
      if (Number.isFinite(score.composite)) {
        compositeSum += score.composite;
        compositeCount += 1;
      }
    }
    const perDimMean = {};
    for (const [dim, { sum, n }] of Object.entries(perDimMeanAccum)) {
      perDimMean[dim] = n === 0 ? 0 : sum / n;
    }
    const composite = compositeCount === 0 ? 0 : compositeSum / compositeCount;
    const judgeScores = {
      perJudge,
      perDimMean,
      composite
    };
    return {
      runId: `${runId}::${candidateId}::${cell.cellId}`,
      experimentId: runId,
      candidateId,
      // Pair on (scenarioId, rep) — analyzeRuns pairs on (experimentId, seed).
      // Synthesize a stable seed for that pairing.
      seed: cell.rep * 1e6 + hashString(cell.scenarioId).slice(0, 6).split("").reduce((a, c) => a * 31 + c.charCodeAt(0) >>> 0, 0),
      model: "campaign-cell",
      promptHash,
      configHash,
      commitSha: "cell",
      wallMs: cell.durationMs,
      costUsd: cell.costUsd,
      tokenUsage: { input: 0, output: 0 },
      outcome: {
        holdoutScore: composite,
        raw: {},
        judgeScores
      },
      splitTag: "holdout",
      ...cell.error ? { failureMode: cell.error } : {}
    };
  });
}

// src/contract/define-agent-eval.ts
function defineAgentEval(defaults) {
  const defaultEvaluateOptions = evaluateDefaults(defaults);
  return {
    scenarios: defaults.scenarios,
    baselineSurface: defaults.baselineSurface,
    async evaluate(opts = {}) {
      const { agent, judge, judges, runDir, scenarios, surface, ...campaignOpts } = opts;
      const selectedAgent = agent ?? defaults.agent;
      const selectedSurface = surface ?? defaults.baselineSurface;
      const selectedRunDir = runDir ?? defaults.runDir ?? `mem://defineAgentEval-${Date.now()}`;
      const selectedStorage = campaignOpts.storage ?? defaultEvaluateOptions.storage ?? (selectedRunDir.startsWith("mem://") ? inMemoryCampaignStorage() : void 0);
      const evalOptions = {
        ...defaultEvaluateOptions,
        ...campaignOpts,
        ...selectedStorage ? { storage: selectedStorage } : {},
        runDir: selectedRunDir,
        scenarios: scenarios ?? defaults.scenarios,
        dispatch: (scenario, ctx) => selectedAgent(selectedSurface, scenario, ctx),
        judges: evaluateJudges(judges, judge ?? defaults.judge)
      };
      if (evalOptions.reps !== void 0)
        evalOptions.reps = requirePositiveInteger(evalOptions.reps, "reps");
      return runEval(evalOptions);
    },
    async improve(opts = {}) {
      const {
        budget: budgetOverride,
        hostedTenant: hostedTenantOverride,
        llm: llmOverride,
        ...topLevelOverrides
      } = opts;
      const merged = mergeDefined(defaults, topLevelOverrides);
      const budget = mergeBudget(defaults.budget, budgetOverride);
      const llm = mergeLlm(defaults.llm, llmOverride);
      const hostedTenant = mergeHostedTenant(defaults.hostedTenant, hostedTenantOverride);
      return selfImprove({
        ...merged,
        ...budget ? { budget } : {},
        ...llm ? { llm } : {},
        ...hostedTenant ? { hostedTenant } : {}
      });
    }
  };
}
function evaluateDefaults(defaults) {
  const out = {};
  if (defaults.storage) out.storage = defaults.storage;
  if (defaults.labeledStore) out.labeledStore = defaults.labeledStore;
  if (defaults.captureSource) out.captureSource = defaults.captureSource;
  if (defaults.cellPlacement) out.cellPlacement = defaults.cellPlacement;
  if (defaults.expectUsage) out.expectUsage = defaults.expectUsage;
  if (defaults.budget?.dollars !== void 0) out.costCeiling = defaults.budget.dollars;
  if (defaults.budget?.maxConcurrency !== void 0)
    out.maxConcurrency = defaults.budget.maxConcurrency;
  if (defaults.budget?.reps !== void 0)
    out.reps = requirePositiveInteger(defaults.budget.reps, "budget.reps");
  return out;
}
function mergeBudget(defaults, overrides) {
  const merged = mergeOptionalObject(defaults, overrides);
  if (merged?.reps !== void 0) merged.reps = requirePositiveInteger(merged.reps, "budget.reps");
  return merged;
}
function mergeLlm(defaults, overrides) {
  return mergeOptionalObject(defaults, overrides);
}
function mergeHostedTenant(defaults, overrides) {
  const merged = mergeOptionalObject(defaults, overrides);
  if (!merged) return void 0;
  if (!merged.endpoint?.trim() || !merged.apiKey?.trim() || !merged.tenantId?.trim()) {
    throw new Error(
      "defineAgentEval.improve: hostedTenant requires endpoint, apiKey, and tenantId after merging defaults and overrides"
    );
  }
  return merged;
}
function mergeDefined(defaults, overrides) {
  if (!overrides) return defaults;
  const merged = { ...defaults };
  for (const [key, value] of Object.entries(overrides)) {
    if (value !== void 0) merged[key] = value;
  }
  return merged;
}
function mergeOptionalObject(defaults, overrides) {
  if (!defaults && !overrides) return void 0;
  return mergeDefined(defaults ?? {}, overrides);
}
function evaluateJudges(judges, defaultJudge) {
  if (judges !== void 0) {
    if (judges.length === 0) {
      throw new Error("defineAgentEval.evaluate: judges must not be empty");
    }
    return judges;
  }
  return [defaultJudge];
}
function requirePositiveInteger(value, field) {
  if (!Number.isInteger(value) || value < 1) {
    throw new Error(`defineAgentEval: ${field} must be a positive integer`);
  }
  return value;
}

// src/contract/diff.ts
function keyForCell(cell) {
  return JSON.stringify([cell.scenarioId, cell.rep]);
}
function diffDimensions(before, after) {
  const out = {};
  const judges = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
  for (const judge of judges) {
    const beforeDims = before[judge] ?? {};
    const afterDims = after[judge] ?? {};
    const dims = /* @__PURE__ */ new Set([...Object.keys(beforeDims), ...Object.keys(afterDims)]);
    const judgeOut = {};
    for (const dim of dims) {
      const rawBefore = beforeDims[dim];
      const rawAfter = afterDims[dim];
      const b = typeof rawBefore === "number" && Number.isFinite(rawBefore) ? rawBefore : null;
      const a = typeof rawAfter === "number" && Number.isFinite(rawAfter) ? rawAfter : null;
      judgeOut[dim] = {
        before: b,
        after: a,
        delta: b !== null && a !== null ? a - b : null
      };
    }
    out[judge] = judgeOut;
  }
  return out;
}
function diffGenerations(before, after) {
  const beforeMap = new Map(before.cells.map((c) => [keyForCell(c), c]));
  const afterMap = new Map(after.cells.map((c) => [keyForCell(c), c]));
  const matched = [];
  const removed = [];
  const added = [];
  for (const [key, beforeCell] of beforeMap) {
    const afterCell = afterMap.get(key);
    if (!afterCell) {
      removed.push(beforeCell);
      continue;
    }
    matched.push({
      scenarioId: beforeCell.scenarioId,
      rep: beforeCell.rep,
      compositeBefore: beforeCell.compositeMean,
      compositeAfter: afterCell.compositeMean,
      compositeDelta: afterCell.compositeMean - beforeCell.compositeMean,
      dimensions: diffDimensions(beforeCell.dimensions, afterCell.dimensions)
    });
  }
  for (const [key, afterCell] of afterMap) {
    if (!beforeMap.has(key)) added.push(afterCell);
  }
  return {
    beforeIndex: before.index,
    afterIndex: after.index,
    beforeSurfaceHash: before.surfaceHash,
    afterSurfaceHash: after.surfaceHash,
    surfaceChanged: before.surfaceHash !== after.surfaceHash,
    matched,
    removed,
    added,
    compositeBefore: before.compositeMean,
    compositeAfter: after.compositeMean,
    compositeDelta: after.compositeMean - before.compositeMean,
    costUsdBefore: before.costUsd,
    costUsdAfter: after.costUsd,
    costUsdDelta: after.costUsd - before.costUsd,
    durationMsBefore: before.durationMs,
    durationMsAfter: after.durationMs,
    durationMsDelta: after.durationMs - before.durationMs
  };
}
function winnerOf(run) {
  if (run.generations.length === 0) return null;
  let winner = run.generations[0];
  for (const gen of run.generations) {
    if (gen.index > winner.index) winner = gen;
  }
  return winner;
}
function diffRuns(before, after) {
  const beforeWinner = winnerOf(before);
  const afterWinner = winnerOf(after);
  const baselineDiff = before.baseline && after.baseline ? diffGenerations(before.baseline, after.baseline) : null;
  const winnersDiff = beforeWinner && afterWinner ? diffGenerations(beforeWinner, afterWinner) : null;
  const beforeLift = before.holdoutLift ?? null;
  const afterLift = after.holdoutLift ?? null;
  return {
    beforeRunId: before.runId,
    afterRunId: after.runId,
    beforeTimestamp: before.timestamp,
    afterTimestamp: after.timestamp,
    beforeGateDecision: before.gateDecision ?? null,
    afterGateDecision: after.gateDecision ?? null,
    beforeHoldoutLift: beforeLift,
    afterHoldoutLift: afterLift,
    holdoutLiftDelta: beforeLift !== null && afterLift !== null ? afterLift - beforeLift : null,
    beforeTotalCostUsd: before.totalCostUsd,
    afterTotalCostUsd: after.totalCostUsd,
    totalCostUsdDelta: after.totalCostUsd - before.totalCostUsd,
    beforeTotalDurationMs: before.totalDurationMs,
    afterTotalDurationMs: after.totalDurationMs,
    totalDurationMsDelta: after.totalDurationMs - before.totalDurationMs,
    baselineDiff,
    winnersDiff
  };
}
function diffRunBaselineToWinner(run) {
  if (!run.baseline) return null;
  const winner = winnerOf(run);
  if (!winner || winner.index === run.baseline.index) return null;
  return diffGenerations(run.baseline, winner);
}

// src/contract/intake/agent-trace.ts
function rangeLines(r) {
  return Math.max(0, r.end_line - r.start_line + 1);
}
function parseAgentTrace(records) {
  const acc = /* @__PURE__ */ new Map();
  for (const record of records) {
    const sha = record.vcs?.revision;
    if (!sha) continue;
    let a = acc.get(sha);
    if (!a) {
      a = {
        models: /* @__PURE__ */ new Set(),
        tools: /* @__PURE__ */ new Set(),
        files: /* @__PURE__ */ new Set(),
        conversationCount: 0,
        lineCount: 0,
        humanInvolved: false
      };
      acc.set(sha, a);
    }
    if (record.tool?.name) a.tools.add(record.tool.name);
    for (const file of record.files ?? []) {
      a.files.add(file.path);
      for (const conv of file.conversations ?? []) {
        a.conversationCount += 1;
        for (const range of conv.ranges ?? []) {
          const contributor = range.contributor ?? conv.contributor;
          a.lineCount += rangeLines(range);
          if (!contributor) continue;
          if (contributor.type === "human" || contributor.type === "mixed") {
            a.humanInvolved = true;
          }
          if ((contributor.type === "ai" || contributor.type === "mixed") && contributor.model_id) {
            a.models.add(contributor.model_id);
          }
        }
      }
    }
  }
  const index = /* @__PURE__ */ new Map();
  for (const [sha, a] of acc) {
    index.set(sha, {
      commitSha: sha,
      aiModels: [...a.models].sort(),
      tools: [...a.tools].sort(),
      conversationCount: a.conversationCount,
      fileCount: a.files.size,
      lineCount: a.lineCount,
      humanInvolved: a.humanInvolved
    });
  }
  return index;
}
function partitionRunsByAuthoringModel(runs, index) {
  const byModel = /* @__PURE__ */ new Map();
  const unattributed = [];
  for (const run of runs) {
    const provenance = index.get(run.commitSha);
    if (!provenance || provenance.aiModels.length === 0) {
      unattributed.push(run);
      continue;
    }
    for (const model of provenance.aiModels) {
      const cohort = byModel.get(model) ?? [];
      cohort.push(run);
      byModel.set(model, cohort);
    }
  }
  return { byModel, unattributed };
}

// src/contract/intake/feedback-table.ts
function fromFeedbackTable(opts) {
  const { ratings, meta = [], scale, emitRaterScores = true } = opts;
  const metaByRun = new Map(meta.map((m) => [m.runId, m]));
  const normalise = (rating) => {
    if (typeof rating === "boolean") return rating ? 1 : 0;
    if (!Number.isFinite(rating)) return Number.NaN;
    if (!scale) return rating;
    const { min, max } = scale;
    if (max === min) return rating;
    return (rating - min) / (max - min);
  };
  const byRun = /* @__PURE__ */ new Map();
  for (const row of ratings) {
    const list = byRun.get(row.runId) ?? [];
    list.push(row);
    byRun.set(row.runId, list);
  }
  const runs = [];
  const raterScores = [];
  for (const [runId, rowsForRun] of byRun) {
    const normalised = rowsForRun.map((r) => ({ rater: r.rater, score: normalise(r.rating) })).filter((r) => Number.isFinite(r.score));
    if (normalised.length === 0) continue;
    const meanScore = normalised.reduce((s, r) => s + r.score, 0) / normalised.length;
    const runMeta = metaByRun.get(runId) ?? { runId };
    const judgeScores = {
      perJudge: Object.fromEntries(normalised.map((r) => [r.rater, { rating: r.score }])),
      perDimMean: { rating: meanScore },
      composite: meanScore
    };
    const outcome = {
      // Feedback corpora ARE the holdout signal — score lands on
      // `holdoutScore` so downstream substrate primitives (`paretoChart`,
      // promotion gates) read it correctly by default.
      holdoutScore: meanScore,
      raw: Object.fromEntries(normalised.map((r) => [`rater:${r.rater}`, r.score])),
      judgeScores
    };
    runs.push({
      runId,
      experimentId: runMeta.experimentId ?? "feedback-corpus",
      candidateId: runMeta.candidateId ?? runId,
      seed: 0,
      model: runMeta.model ?? "unknown@unknown",
      promptHash: runMeta.promptHash ?? "sha256:unknown",
      configHash: runMeta.configHash ?? "sha256:unknown",
      commitSha: runMeta.commitSha ?? "unknown",
      wallMs: runMeta.wallMs ?? 0,
      costUsd: runMeta.costUsd ?? 0,
      tokenUsage: { input: 0, output: 0 },
      outcome,
      splitTag: runMeta.splitTag ?? "holdout"
    });
    if (emitRaterScores) {
      for (const r of normalised) raterScores.push({ runId, rater: r.rater, score: r.score });
    }
  }
  return { runs, raterScores };
}

// src/contract/intake/otel-spans.ts
var SCORE_KEYS = ["tangle.score", "eval.score", "score"];
var MODEL_KEYS = ["tangle.model", ...LLM_MODEL_ATTR_KEYS, "model"];
var COST_KEYS = ["tangle.cost.usd", "gen_ai.usage.cost_usd", "cost.usd", "cost"];
var INPUT_TOKEN_KEYS = [...LLM_INPUT_TOKEN_ATTR_KEYS, "tangle.tokens.in", "tokens.in"];
var OUTPUT_TOKEN_KEYS = [...LLM_OUTPUT_TOKEN_ATTR_KEYS, "tangle.tokens.out", "tokens.out"];
var PROMPT_HASH_KEYS = ["tangle.prompt_hash", "prompt.hash"];
var CONFIG_HASH_KEYS = ["tangle.config_hash", "config.hash"];
function fromOtelSpans(opts) {
  const { spans, defaultSplit = "holdout", experimentId = "otel-corpus" } = opts;
  const grouped = groupSpans(spans);
  const runs = [];
  for (const [groupKey, groupSpans2] of grouped) {
    const root = findRoot(groupSpans2);
    if (!root) continue;
    const wallMs = Math.max(0, (root.endTimeUnixNano - root.startTimeUnixNano) / 1e6);
    const model = readAttrString(groupSpans2, MODEL_KEYS) ?? "unknown@unknown";
    const costUsd = readAttrNumber(groupSpans2, COST_KEYS) ?? 0;
    const inputTokens = readAttrNumber(groupSpans2, INPUT_TOKEN_KEYS) ?? 0;
    const outputTokens = readAttrNumber(groupSpans2, OUTPUT_TOKEN_KEYS) ?? 0;
    const promptHash = readAttrString(groupSpans2, PROMPT_HASH_KEYS) ?? "sha256:unknown";
    const configHash = readAttrString(groupSpans2, CONFIG_HASH_KEYS) ?? "sha256:unknown";
    const score = readAttrNumber(groupSpans2, SCORE_KEYS);
    const rawNumeric = collectNumericAttrs(groupSpans2);
    const tokenUsage = {
      input: inputTokens,
      output: outputTokens
    };
    const judgeScores = score !== void 0 ? {
      perJudge: { "otel-derived": { score } },
      perDimMean: { score },
      composite: score
    } : void 0;
    const errorSpan = groupSpans2.find((s) => s.status?.code === "ERROR");
    const outcome = {
      ...opts.defaultSplit === "search" ? { searchScore: score } : { holdoutScore: score },
      raw: rawNumeric,
      ...judgeScores ? { judgeScores } : {}
    };
    runs.push({
      runId: groupKey,
      experimentId,
      candidateId: root.attributes["tangle.candidateId"] ?? "otel-default",
      seed: 0,
      model,
      promptHash,
      configHash,
      commitSha: root.attributes["tangle.commit_sha"] ?? "unknown",
      wallMs,
      costUsd,
      tokenUsage,
      outcome,
      splitTag: defaultSplit,
      ...errorSpan ? { failureMode: errorSpan.name } : {}
    });
  }
  return runs;
}
function groupSpans(spans) {
  const m = /* @__PURE__ */ new Map();
  for (const span of spans) {
    const key = span["tangle.runId"] ?? span.traceId;
    const list = m.get(key) ?? [];
    list.push(span);
    m.set(key, list);
  }
  return m;
}
function findRoot(group) {
  return group.find((s) => !s.parentSpanId) ?? group[0];
}
function readAttrString(spans, keys) {
  for (const span of spans) {
    for (const key of keys) {
      const v = span.attributes[key];
      if (typeof v === "string" && v.length > 0) return v;
    }
  }
  return void 0;
}
function readAttrNumber(spans, keys) {
  for (const span of spans) {
    for (const key of keys) {
      const v = span.attributes[key];
      if (typeof v === "number" && Number.isFinite(v)) return v;
      if (typeof v === "string") {
        const parsed = Number(v);
        if (Number.isFinite(parsed)) return parsed;
      }
    }
  }
  return void 0;
}
function collectNumericAttrs(spans) {
  const raw = {};
  for (const span of spans) {
    for (const [k, v] of Object.entries(span.attributes)) {
      if (typeof v === "number" && Number.isFinite(v)) raw[k] = v;
    }
  }
  return raw;
}
export {
  FileSystemOutcomeStore,
  InMemoryOutcomeStore,
  analyzeRuns,
  buildDefaultAnalystRegistry,
  buildEvidenceVector,
  composeGate,
  defaultProductionGate,
  defineAgentEval,
  diffGenerations,
  diffRunBaselineToWinner,
  diffRuns,
  evolutionaryProposer,
  fromClaudeCodeSession,
  fromCodexSession,
  fromFeedbackTable,
  fromKimiCodeSession,
  fromOpenCodeSession,
  fromOtelSpans,
  fromPiSession,
  fromPigraphSession,
  fsCampaignStorage,
  gepaProposer,
  heldOutGate,
  inMemoryCampaignStorage,
  paretoPolicy,
  paretoSignificanceGate,
  parseAgentTrace,
  parseCodeAgentJsonl,
  partitionRunsByAuthoringModel,
  runCampaign,
  runEval,
  runImprovementLoop,
  selfImprove
};
//# sourceMappingURL=index.js.map