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-D9tuReDv.js';
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-D9tuReDv.js';
import { L as LoopProvenanceRecord, R as RunEvalOptions } from '../provenance-C5KAhiom.js';
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-C5KAhiom.js';
import { C as CampaignStorage, a as RunOptimizationOptions, b as RunImprovementLoopResult } from '../gepa-3TG16SYf.js';
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-3TG16SYf.js';
export { D as DeploymentOutcome, F as FileSystemOutcomeStore, a as FileSystemOutcomeStoreOptions, I as InMemoryOutcomeStore, b as OutcomeStore } from '../outcome-store-rnXLEqSn.js';
import { HostedTenant, EvalRunCellScore, EvalRunGenerationSnapshot, EvalRunEvent, TraceSpanEvent } from '../hosted/index.js';
import { R as RunRecord, a as RunSplitTag } from '../run-record-CP2ObebC.js';
import { I as InsightReport } from '../insight-report-BnRjTibG.js';
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';
export { D as DefaultAnalystRegistryOptions, c as buildDefaultAnalystRegistry } from '../default-registry-GyE8X5SP.js';
export { c as AnalystFinding } from '../types-B5x54y6n.js';
import { A as AnalyzeRunsOptions } from '../analyze-runs-DtT6F_6T.js';
export { a as analyzeRuns } from '../analyze-runs-DtT6F_6T.js';
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';
import '../red-team-BWdoyleI.js';
import '../dataset-BbGkaN2I.js';
import '../errors-CzMUYo7b.js';
import '../store-BcFXE6LG.js';
import '../schema-m0gsnbt3.js';
import '../pareto-E-pembql.js';
import '../statistics-xP-cWc5k.js';
import '../judge-calibration-0p2QcWNE.js';
import '../types-C7DGg5ex.js';
import '@tangle-network/tcloud';
import '../llm-client-Bj7g0rqu.js';
import '../raw-provider-sink-C46HDghv.js';
import '@tangle-network/agent-interface';
import '../summary-report-CInXwsza.js';
import '../failure-cluster-DH9Flgcf.js';
import '@ax-llm/ax';
import '../kind-factory-X3eDYbKn.js';
import '../store-C1YxJDEK.js';
import 'zod';

/**
 * # `selfImprove()` - the one-call improvement loop.
 *
 * The cheapest possible call site to run a real closed-loop self-
 * improvement over your agent. Wraps `runImprovementLoop` with smart
 * defaults and a budget-shaped options API; every escape hatch the
 * substrate exposes is reachable from here without losing the
 * one-function feel.
 *
 * Defaults:
 *   - In-memory storage (no filesystem touch).
 *   - `gepaProposer` reflective mutation with copywriting-flavored primitives
 *     (override `proposer` or `mutationPrimitives` for any domain).
 *   - `defaultProductionGate` with `deltaThreshold: 0.05`.
 *   - Held-out split = 25% of scenarios, deterministic by id hash.
 *   - 3 generations × population 2 (raise via `budget` for more search).
 *   - `autoOnPromote: 'none'` (we don't open PRs unless you ask).
 *
 * Want one-click? Provide `agent` + `scenarios` + `judge`. Done.
 * Want distributed? Pass `cellPlacement` + an `httpDispatch`-backed
 * agent. Want a code-tier surface? Pass a `MutableSurface` + your own
 * `proposer`. Same function.
 */

interface SelfImproveBudget {
    /** Hard $ ceiling across all cells in baseline + every generation. Cells
     *  beyond the ceiling are skipped (cost-aware, not aborted). */
    dollars?: number;
    /** How many improvement generations to explore. Default 3. Set 0 to
     *  skip improvement entirely (selfImprove becomes a baseline-only run). */
    generations?: number;
    /** Candidates the proposer emits per generation. Default 2. */
    populationSize?: number;
    /** Max concurrent cells across the loop. Default 2. */
    maxConcurrency?: number;
    /** Fraction of `scenarios` held out from training, used for the gate.
     *  Default 0.25. Ignored when `holdoutScenarios` is set explicitly. */
    holdoutFraction?: number;
    /** Explicit held-out scenarios; overrides `holdoutFraction`. */
    holdoutScenarios?: Scenario[];
    /** Per-scenario replicates per cell — raises bootstrap-CI tightness. Default 1. */
    reps?: number;
    /** Top-scoring candidates carried into the next generation. Default 2. */
    promoteTopK?: number;
}
interface SelfImproveLlm {
    /** Endpoint base URL. Default Tangle Router. */
    baseUrl?: string;
    /** Bearer token. Default `process.env.OPENAI_API_KEY`. */
    apiKey?: string;
    /** Model id used by `gepaProposer` reflection. Default
     *  `anthropic/claude-sonnet-4.6`. */
    model?: string;
}
type SelfImproveProgressEvent = {
    kind: 'baseline.started';
    scenarios: number;
} | {
    kind: 'baseline.completed';
    compositeMean: number;
    durationMs: number;
} | {
    kind: 'generation.started';
    index: number;
    populationSize: number;
} | {
    kind: 'generation.completed';
    index: number;
    bestComposite: number;
    durationMs: number;
} | {
    kind: 'gate.decided';
    decision: string;
    lift: number;
};
interface SelfImproveOptions<TScenario extends Scenario, TArtifact> {
    /**
     * Your agent — a function that takes the current `MutableSurface`
     * (typically a system prompt the loop is optimizing) plus the
     * scenario + cell ctx, and returns the artifact your judge scores.
     *
     * Same shape as `RunOptimizationOptions.dispatchWithSurface`. Wrap a
     * plain `Dispatch` if you don't have a surface seam:
     *
     *   agent: (_surface, scenario, ctx) => yourPlainDispatch(scenario, ctx)
     *
     * That mode evaluates without mutating any surface — useful as a
     * baseline-only run (set `budget.generations = 0`).
     */
    agent: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
    /** Scenarios to evaluate against. Train/holdout split is computed from
     *  these unless `budget.holdoutScenarios` is set explicitly. */
    scenarios: TScenario[];
    /** Judge that scores artifacts. Bring your own; use `langchainJudge`
     *  from `/adapters/langchain` for a Runnable-shaped one. */
    judge: JudgeConfig<TArtifact, TScenario>;
    /** Starting surface — system prompt, JSON config, anything `MutableSurface`
     *  accepts. The proposer mutates this each generation. */
    baselineSurface: MutableSurface;
    /** Budget + loop shape. All fields optional. */
    budget?: SelfImproveBudget;
    /** Custom surface proposer. Default is `gepaProposer` configured from `llm` +
     *  `mutationPrimitives`. */
    proposer?: SurfaceProposer;
    /** Default-proposer overrides — used when `proposer` is unset. */
    mutationPrimitives?: string[];
    proposerTarget?: string;
    /** Custom gate. Default is `defaultProductionGate` with
     *  `deltaThreshold: 0.05` on the held-out split. */
    gate?: Gate<TArtifact, TScenario>;
    /** LLM config consumed by the default `gepaProposer`. Ignored if you pass
     *  your own `proposer`. */
    llm?: SelfImproveLlm;
    /** Storage backend. Default is DURABLE: when a real (non-`mem://`) `runDir`
     *  is available, the substrate defaults to `fsCampaignStorage()` so the
     *  provenance record + OTel spans survive the call. Pass
     *  `inMemoryCampaignStorage()` explicitly to opt OUT (tests, edge runtimes).
     *  Default when `runDir` is `mem://...` (or unset): in-memory. */
    storage?: CampaignStorage;
    /** Run directory (logical for in-memory storage, real path for fs).
     *  Default `mem://selfImprove-<timestamp>` (in-memory, non-durable). Pass a
     *  real path to persist the provenance record + spans. */
    runDir?: string;
    /**
     * Worker call records for backend provenance. The agent is opaque to the
     * substrate (it returns an artifact, not token usage), so to capture an
     * `assertRealBackend`-grade verdict + worker call count + model in the
     * provenance record, the agent reports its per-call `RunRecord`s here.
     * Called once after the loop; return the records the agent accumulated.
     * When unset, backend provenance is derived from campaign cells (cost only;
     * verdict will read `stub` without token usage — the honest signal that no
     * token channel was wired).
     */
    collectWorkerRecords?: () => RunRecord[];
    /** Fires once the durable provenance record + OTel spans are emitted.
     *  Receives the structured record for inline assertions / custom routing. */
    onProvenance?: (record: LoopProvenanceRecord) => void;
    /** Distributed execution seam — same as `RunCampaignOptions.cellPlacement`.
     *  Returns an opaque placement key the substrate forwards to your agent
     *  as `ctx.placement`. Combined with `httpDispatch` from
     *  `/adapters/http`, fans cells across regions. */
    cellPlacement?: (input: {
        scenario: TScenario;
        rep: number;
        generation?: number;
    }) => string | undefined;
    /** Streaming hook — fires on baseline + each generation + gate decision.
     *  Consumer routes events wherever (UI, dashboard, logs). */
    onProgress?: (event: SelfImproveProgressEvent) => void;
    /** Auto-promotion behavior on a ship decision. Default `'none'` — we
     *  return the winner; you ship it however you ship. `'pr'` opens a
     *  GitHub PR via `openAutoPr`; requires `ghOwner` + `ghRepo`. */
    autoOnPromote?: 'pr' | 'none';
    ghOwner?: string;
    ghRepo?: string;
    /**
     * Opt-in: ship eval-run events to a hosted orchestrator (ours, your
     * self-hosted one, or any compatible implementation of the
     * `docs/hosted-ingest-spec.md` wire format). When set, the substrate
     * POSTs the final `EvalRunEvent` to `${endpoint}/v1/ingest/eval-runs`
     * after the loop completes. Failures are logged but do not fail the
     * loop — local result is always returned.
     *
     * For our orchestrator: `{ endpoint: 'https://orchestrator.tangle.tools/v1', apiKey, tenantId }`.
     *
     * For your self-hosted: any URL serving the wire format. See
     * `examples/hosted-ingest-server/` for the reference receiver.
     */
    hostedTenant?: HostedTenant;
    /** Free-form labels attached to the hosted event (env, branch, model id,
     *  etc.). Ignored when `hostedTenant` is unset. */
    hostedLabels?: Record<string, string>;
    /** Capture every artifact + judge score to this store (labeled-example
     *  corpus the proposer may read for few-shot, and the dataset you ship). Pass
     *  `'off'` to disable. Default: off. */
    labeledStore?: LabeledScenarioStore | 'off';
    /** Capture-source tag for `labeledStore`. Default `'eval-run'`. */
    captureSource?: 'production-trace' | 'eval-run' | 'manual' | 'red-team' | 'synthetic';
    /**
     * Per-cell backend-integrity expectation — the fail-loud guard. A cell that
     * produced an artifact but reported `costUsd === 0` AND zero tokens is a
     * stub. Modes: `'assert'` throws on the first such cell, `'warn'` logs it,
     * `'off'` skips the check (offline/replay). Default `'assert'` — `selfImprove`
     * is the real-run path, so a stub fails loud rather than scoring a clean 0.
     */
    expectUsage?: 'assert' | 'warn' | 'off';
    /**
     * Per-generation findings producer. After each
     * generation is scored, this is called; whatever it returns REPLACES the
     * proposer's `findings` for the next generation's `propose()`. Plug a
     * trace-analyst registry / HALO here. When absent, findings stay
     * `opts.findings`.
     */
    analyzeGeneration?: RunOptimizationOptions<TScenario, TArtifact>['analyzeGeneration'];
    /** Static findings forwarded to the proposer's `propose()` as `ctx.findings`
     *  (a findings-grounded proposer consumes them). Default: none. */
    findings?: unknown[];
}
interface SelfImproveResult<TScenario extends Scenario, TArtifact> {
    /** Composite mean across all scenarios, baseline run. */
    baseline: {
        compositeMean: number;
        perScenario: Record<string, number>;
    };
    /** Composite mean on the held-out set, winner run. */
    winner: {
        compositeMean: number;
        perScenario: Record<string, number>;
        surface: MutableSurface;
        /** Proposer label for the promoted change. Absent ⇒ winner == baseline or
         *  a bare-surface mutator. */
        label?: string;
        /** Proposer rationale — the "because Z" that motivated the promoted change.
         *  Threaded from the proposer's `ProposedCandidate` through the loop.
         *  Absent ⇒ winner == baseline. */
        rationale?: string;
    };
    /** `winner.compositeMean - baselineOnHoldout.compositeMean`. Positive
     *  means the gate observed improvement. */
    lift: number;
    /** The explicit baseline→winner unified diff. Always present (empty string
     *  when winner == baseline). */
    diff: string;
    /** Durable, queryable provenance record: candidate→cell→gate→promote chain +
     *  rationale + diff + backend provenance. The artifact the hosted ingest
     *  path stores; the +lift RECOMPUTES from `record.heldOutLift`. */
    provenance: LoopProvenanceRecord;
    /** `defaultProductionGate.decide()` result. */
    gateDecision: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling';
    /** Number of generations actually explored (may be less than the
     *  budget if the proposer gave up early). */
    generationsExplored: number;
    /** Wall-clock total. */
    durationMs: number;
    /** Total cost across baseline + every generation. */
    totalCostUsd: number;
    /**
     * Rigor packet: distributional summary, paired-bootstrap lift CI,
     * judge stats, contamination check, recommendations. Wired through
     * `analyzeRuns()` on the baseline + winner cells of the campaign.
     * Hosted-tier dashboards render this as the v3-vs-v4 decision view.
     */
    insight: InsightReport;
    /**
     * Raw substrate result for advanced inspection — full per-generation
     * candidates, full campaign artifacts, all judge scores. Useful for
     * debugging or reporting beyond the summary.
     */
    raw: RunImprovementLoopResult<TArtifact, TScenario>;
}
/**
 * One-shot self-improvement loop. See module docstring for defaults +
 * extension points.
 *
 * @example Minimum:
 *
 *   const result = await selfImprove({
 *     agent: (surface, scenario, ctx) => myAgent(surface, scenario, ctx.signal),
 *     scenarios,
 *     judge,
 *     baselineSurface: DEFAULT_PROMPT,
 *   })
 *   console.log(`lift: ${result.lift.toFixed(3)} (${result.gateDecision})`)
 *
 * @example Distributed (workers in three regions):
 *
 *   await selfImprove({
 *     agent: httpDispatch({ resolveUrl: ({ placement }) => REGION_URLS[placement!] }),
 *     scenarios,
 *     judge,
 *     baselineSurface: DEFAULT_PROMPT,
 *     cellPlacement: ({ scenario }) => scenario.region,
 *     budget: { maxConcurrency: 12 },
 *   })
 */
declare function selfImprove<TScenario extends Scenario, TArtifact>(opts: SelfImproveOptions<TScenario, TArtifact>): Promise<SelfImproveResult<TScenario, TArtifact>>;

type AgentEvalAgent<TScenario extends Scenario, TArtifact> = (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
type DefineAgentEvalOptions<TScenario extends Scenario, TArtifact> = SelfImproveOptions<TScenario, TArtifact>;
interface AgentEvalEvaluateOptions<TScenario extends Scenario, TArtifact> extends Omit<RunEvalOptions<TScenario, TArtifact>, 'dispatch' | 'judges' | 'runDir' | 'scenarios'> {
    /** Scenario set to evaluate. Defaults to the scenarios passed to `defineAgentEval`. */
    scenarios?: TScenario[];
    /** Surface to evaluate. Defaults to the baseline surface passed to `defineAgentEval`. */
    surface?: MutableSurface;
    /** Agent to evaluate. Defaults to the agent passed to `defineAgentEval`. */
    agent?: AgentEvalAgent<TScenario, TArtifact>;
    /** Single judge override. Ignored when `judges` is set. */
    judge?: JudgeConfig<TArtifact, TScenario>;
    /** Full judge list override. Defaults to the single judge passed to `defineAgentEval`. */
    judges?: JudgeConfig<TArtifact, TScenario>[];
    /** Logical or filesystem run directory. Defaults to an in-memory run. */
    runDir?: string;
}
type AgentEvalImproveOptions<TScenario extends Scenario, TArtifact> = Omit<Partial<SelfImproveOptions<TScenario, TArtifact>>, 'budget' | 'hostedTenant' | 'llm'> & {
    budget?: Partial<SelfImproveBudget>;
    hostedTenant?: Partial<HostedTenant>;
    llm?: Partial<SelfImproveLlm>;
};
interface DefinedAgentEval<TScenario extends Scenario, TArtifact> {
    /** The default scenarios used by `evaluate()` and `improve()`. */
    readonly scenarios: readonly TScenario[];
    /** The default baseline surface used by `evaluate()` and `improve()`. */
    readonly baselineSurface: MutableSurface;
    /**
     * Run one scored evaluation. Use this for a baseline score or to score one
     * candidate surface without running an improvement loop.
     */
    evaluate(opts?: AgentEvalEvaluateOptions<TScenario, TArtifact>): Promise<CampaignResult<TArtifact, TScenario>>;
    /**
     * Run the closed improvement loop. Per-call overrides replace the definition
     * except for nested config objects (`budget`, `llm`, `hostedTenant`), which
     * are merged field-by-field so callers can override one knob without
     * repeating secrets or budget defaults.
     */
    improve(opts?: AgentEvalImproveOptions<TScenario, TArtifact>): Promise<SelfImproveResult<TScenario, TArtifact>>;
}
/**
 * Define an agent eval once, then either score a surface with `evaluate()` or
 * run the closed loop with `improve()`.
 *
 * This is a DX wrapper only: it delegates to `runEval()` and `selfImprove()` and
 * returns their native result shapes.
 */
declare function defineAgentEval<TScenario extends Scenario, TArtifact>(defaults: DefineAgentEvalOptions<TScenario, TArtifact>): DefinedAgentEval<TScenario, TArtifact>;

/**
 * # `intake/run-record-dir` — load a directory or file of `RunRecord`s.
 *
 * The on-disk counterpart to the in-memory intake adapters: point it at a
 * single `.json` (array) / `.jsonl` (one record per line) file or at a
 * directory of such files, and it returns the substrate-canonical
 * `RunRecord[]` ready for `analyzeRuns({ runs })`.
 *
 * Validation is at the boundary: each parsed object goes through
 * `parseRunRecordSafe`. By default an invalid record fails loud with its
 * file + index; pass `onInvalid: 'collect'` to keep the valid records and
 * receive the rejects as structured diagnostics instead.
 */

/** A record that failed boundary validation, with enough context to fix it. */
interface RunRecordRejection {
    /** Absolute or caller-relative path to the file the record came from. */
    file: string;
    /** Zero-based position within the file (array index or JSONL line number). */
    index: number;
    /** The validator's message. */
    reason: string;
}
interface FromRunRecordDirOptions {
    /**
     * How to treat a record that fails `parseRunRecordSafe`:
     *   - `'throw'` (default) — fail loud on the first invalid record.
     *   - `'collect'` — drop it, keep the rest, and return it under `rejected`.
     */
    onInvalid?: 'throw' | 'collect';
    /**
     * When the input is a directory, only files matching this predicate are
     * read. Default: any file ending in `.json` or `.jsonl`. The `analysis.json`
     * artifact `evalReportingSuite` writes is always skipped so a re-run never
     * ingests its own output.
     */
    include?: (fileName: string) => boolean;
    /**
     * Recurse into subdirectories when the input is a directory. Default false —
     * a flat run directory is the common case and recursion can silently pull in
     * unrelated corpora.
     */
    recursive?: boolean;
}
interface FromRunRecordDirResult {
    /** Records that passed boundary validation, in file-then-index order. */
    runs: RunRecord[];
    /** Records that failed validation. Empty unless `onInvalid: 'collect'`. */
    rejected: RunRecordRejection[];
    /** The files that were read, in the order they were processed. */
    files: string[];
}
/**
 * Resolve a file or directory path into validated `RunRecord[]`.
 *
 * A `.json` file must parse to a top-level array; a `.jsonl` file is one
 * record per non-empty line. Directories are read shallowly by default
 * (set `recursive` to descend); the `analysis.json` output artifact is
 * always excluded.
 */
declare function fromRunRecordDir(path: string, options?: FromRunRecordDirOptions): Promise<FromRunRecordDirResult>;

/**
 * # `evalReportingSuite` — one call from runs (or a run dir) to `analysis.json`.
 *
 * A thin wrapper over the analysis primitive (`analyzeRuns`) and the on-disk
 * intake adapter (`fromRunRecordDir`). It does NOT reimplement any statistics,
 * distributions, or clustering — it resolves the input into validated
 * `RunRecord[]`, calls `analyzeRuns` with the options you'd pass it directly,
 * wraps the result in a small provenance envelope, and (optionally) writes a
 * single `analysis.json` artifact.
 *
 * ```ts
 * // From a directory of run files, write ./runs/analysis.json:
 * const suite = await evalReportingSuite('./runs', { write: true })
 * // From records already in memory, no write:
 * const suite = await evalReportingSuite(records, { analyze: { decisionThreshold: 0.03 } })
 * suite.report // the InsightReport — distributions, paired lift, findings rollup
 * ```
 */

/** Either records in hand or a path to a `.json` / `.jsonl` file or a
 *  directory of them. */
type EvalReportingSuiteInput = RunRecord[] | string;
interface EvalReportingSuiteOptions {
    /** Forwarded verbatim to `analyzeRuns` (everything except `runs`, which the
     *  suite supplies from the resolved input). Use this for split selection,
     *  baseline/candidate ids, canaries, prior-period runs, the analyst registry,
     *  etc. */
    analyze?: Omit<AnalyzeRunsOptions, 'runs'>;
    /** Loader options used only when the input is a path. */
    load?: FromRunRecordDirOptions;
    /**
     * Write the suite result as a single `analysis.json`.
     *   - `true` — write to `<dir>/analysis.json` when the input is a directory,
     *     or alongside the input file; throws if the input is in-memory records
     *     (no directory to anchor to — pass an explicit path instead).
     *   - a string — write to exactly this path (a directory path gets
     *     `analysis.json` appended; any other path is used verbatim).
     *   - omitted / false — do not write.
     */
    write?: boolean | string;
}
/** The suite artifact — the `analyzeRuns` report plus provenance. This is the
 *  exact shape serialized to `analysis.json`. */
interface EvalReportingSuiteResult {
    /** The analysis itself — distributions, paired stats/lift, failure rollup,
     *  recommendations. Produced by `analyzeRuns`. */
    report: InsightReport;
    /** How the suite was run, so a reader can verify provenance. */
    provenance: {
        /** ISO timestamp the suite ran. */
        generatedAt: string;
        /** Number of records analyzed (mirrors `report.n`). */
        runCount: number;
        /** The source path when the input was a directory/file; null for
         *  in-memory records. */
        sourcePath: string | null;
        /** Files read when loading from disk; empty for in-memory input. */
        files: string[];
        /** Records dropped at the validation boundary. Always empty unless
         *  `load.onInvalid` was set to `'collect'`. */
        rejected: FromRunRecordDirResult['rejected'];
    };
    /** The path `analysis.json` was written to, or null when `write` was unset. */
    writtenTo: string | null;
}
/**
 * Resolve runs (or a run dir/file), run `analyzeRuns`, and optionally persist a
 * single `analysis.json`. The only analysis logic lives in `analyzeRuns`; this
 * function is composition + I/O.
 */
declare function evalReportingSuite(input: EvalReportingSuiteInput, options?: EvalReportingSuiteOptions): Promise<EvalReportingSuiteResult>;

/**
 * # `@tangle-network/agent-eval/contract` — eval-run diff primitive.
 *
 * The substrate side of the v-N-versus-v-N+1 dashboard view. Given two
 * `EvalRunEvent`s (or two `EvalRunGenerationSnapshot`s from one run), this
 * returns a normalised diff: per-cell composite + per-judge/per-dimension
 * deltas, surface-hash change, aggregate cost + duration shifts.
 *
 * Consumed by:
 *   - The hosted-tier dashboard (intelligence-web) — renders v3 vs v4
 *     comparisons of cells × judges × dimensions.
 *   - CI reporting — emits a "shipped: composite +0.07, cost +$1.20" line
 *     in PR review for autonomous-improvement runs.
 *   - Any downstream consumer that needs "what actually changed" without
 *     reimplementing the matching + arithmetic.
 *
 * Cells are matched on the natural composite key `(scenarioId, rep)`.
 * Unmatched cells surface as `removed` / `added` so callers can tell
 * "this cell got worse" from "this cell wasn't run."
 */

/** Per-dimension delta. `before` / `after` are null when the judge did not
 *  emit a value for that side. `delta` is `after - before`; null when
 *  either side is null. */
interface EvalDimensionDelta {
    before: number | null;
    after: number | null;
    delta: number | null;
}
/** Per-cell delta, keyed on `(scenarioId, rep)`. */
interface EvalCellScoreDelta {
    scenarioId: string;
    rep: number;
    compositeBefore: number;
    compositeAfter: number;
    compositeDelta: number;
    /** Per-judge → per-dimension deltas. Outer key = judge name from
     *  `EvalRunCellScore.dimensions`; inner key = dimension name. */
    dimensions: Record<string, Record<string, EvalDimensionDelta>>;
}
/** Diff between two generation snapshots — the unit the dashboard renders
 *  for a single "v3 vs v4" comparison. */
interface EvalGenerationDiff {
    beforeIndex: number;
    afterIndex: number;
    beforeSurfaceHash: string;
    afterSurfaceHash: string;
    surfaceChanged: boolean;
    /** Cells present in both snapshots, matched on `(scenarioId, rep)`. */
    matched: EvalCellScoreDelta[];
    /** Cells present in `before` but missing from `after`. */
    removed: EvalRunCellScore[];
    /** Cells present in `after` but missing from `before`. */
    added: EvalRunCellScore[];
    /** Aggregate composite mean across all cells in the snapshot. */
    compositeBefore: number;
    compositeAfter: number;
    compositeDelta: number;
    costUsdBefore: number;
    costUsdAfter: number;
    costUsdDelta: number;
    durationMsBefore: number;
    durationMsAfter: number;
    durationMsDelta: number;
}
/** Diff between two full eval-runs. Includes both baseline-vs-baseline and
 *  winner-vs-winner generation diffs when both sides expose them, plus
 *  run-level metadata. */
interface EvalRunDiff {
    beforeRunId: string;
    afterRunId: string;
    beforeTimestamp: string;
    afterTimestamp: string;
    beforeGateDecision: GateDecision | null;
    afterGateDecision: GateDecision | null;
    beforeHoldoutLift: number | null;
    afterHoldoutLift: number | null;
    holdoutLiftDelta: number | null;
    beforeTotalCostUsd: number;
    afterTotalCostUsd: number;
    totalCostUsdDelta: number;
    beforeTotalDurationMs: number;
    afterTotalDurationMs: number;
    totalDurationMsDelta: number;
    /** Baseline-vs-baseline diff. Null when either run has no baseline. */
    baselineDiff: EvalGenerationDiff | null;
    /** Highest-index-generation comparison. Null when either run has no
     *  recorded generations (e.g. baseline-only or errored before any
     *  generation completed). */
    winnersDiff: EvalGenerationDiff | null;
}
/**
 * Diff two generation snapshots. Cells are matched on `(scenarioId, rep)`;
 * unmatched cells surface in `added` / `removed`. Aggregate fields are
 * recomputed from the snapshot's stored fields, not re-derived from cells —
 * this keeps the diff consistent with whatever aggregation the substrate
 * actually reported.
 */
declare function diffGenerations(before: EvalRunGenerationSnapshot, after: EvalRunGenerationSnapshot): EvalGenerationDiff;
/**
 * Diff two full eval-runs. Produces baseline-vs-baseline and
 * winner-vs-winner generation diffs when both sides expose them, plus
 * run-level cost / lift / gate-decision deltas.
 */
declare function diffRuns(before: EvalRunEvent, after: EvalRunEvent): EvalRunDiff;
/**
 * Within-run baseline → winning-generation diff. The natural "what did the
 * improvement loop produce" view for a single run. Returns null when the
 * run never reached a generation past baseline (errored early, or the gate
 * shipped the baseline as-is).
 */
declare function diffRunBaselineToWinner(run: EvalRunEvent): EvalGenerationDiff | null;

/**
 * `fromAgentTrace` — provenance correlation from Cursor's Agent Trace spec
 * (https://github.com/cursor/agent-trace, RFC v0.1.0).
 *
 * Agent Trace is NOT a run/quality trace — it carries no outcome, score, or
 * cost. It records *code authorship*: for a VCS revision, which AI model /
 * conversation authored which file ranges. It explicitly disclaims quality
 * assessment — which is exactly what `analyzeRuns` adds.
 *
 * The two layers join on a key the substrate already has: a `RunRecord`
 * carries `commitSha`, and an Agent Trace record is keyed by
 * `vcs.revision`. So this adapter does not produce `RunRecord`s — it builds a
 * provenance index by commit and partitions existing runs by their authoring
 * model. Feed each cohort to `analyzeRuns` (or pass one as `baselineRuns`) to
 * answer the question no run-only trace can: *which authoring agent's code
 * fails / regresses / costs more.*
 *
 * Granularity is commit-level (the SHA join). Per-file/per-line correlation
 * would require runs to record which files they exercised — out of scope.
 */

type AgentTraceContributorType = 'human' | 'ai' | 'mixed' | 'unknown';
interface AgentTraceContributor {
    type: AgentTraceContributorType;
    /** models.dev id, e.g. `anthropic/claude-opus-4-5-20251101`. */
    model_id?: string;
}
interface AgentTraceRange {
    start_line: number;
    end_line: number;
    content_hash?: string;
    /** Per-range contributor override (agent handoffs). Wins over the
     *  conversation-level contributor for these lines. */
    contributor?: AgentTraceContributor;
}
interface AgentTraceConversation {
    url?: string;
    contributor?: AgentTraceContributor;
    ranges: AgentTraceRange[];
}
interface AgentTraceFile {
    path: string;
    conversations: AgentTraceConversation[];
}
interface AgentTraceRecord {
    version: string;
    id: string;
    timestamp: string;
    vcs?: {
        type: string;
        revision: string;
    };
    tool?: {
        name?: string;
        version?: string;
    };
    files: AgentTraceFile[];
}
/** Authorship provenance for one VCS revision, aggregated across the record's
 *  files/conversations/ranges. */
interface AuthoringProvenance {
    commitSha: string;
    /** Unique AI model ids that authored code in this commit (type ai|mixed). */
    aiModels: string[];
    /** Tools that produced the records (e.g. `cursor`). */
    tools: string[];
    conversationCount: number;
    fileCount: number;
    /** Total attributed lines (sum of range spans). */
    lineCount: number;
    /** True if any range was authored (in whole or part) by a human. */
    humanInvolved: boolean;
}
type AgentTraceIndex = Map<string, AuthoringProvenance>;
/**
 * Build a commit → provenance index from Agent Trace records. Multiple records
 * for the same revision are merged. Records without `vcs.revision` are skipped
 * (the SHA is the join key — without it there is nothing to correlate against).
 */
declare function parseAgentTrace(records: AgentTraceRecord[]): AgentTraceIndex;
interface PartitionByAuthoringModelResult {
    /** Runs grouped by each AI model that authored code in the run's commit. A
     *  run whose commit had multiple authoring models appears under EACH — the
     *  cohorts overlap by construction at commit granularity. */
    byModel: Map<string, RunRecord[]>;
    /** Runs whose `commitSha` had no Agent Trace provenance (no record, or no
     *  AI authorship). Kept separate — never silently folded into a cohort. */
    unattributed: RunRecord[];
}
/**
 * Partition runs by the AI model(s) that authored the code at each run's
 * `commitSha`. Feed `byModel.get(modelId)` to `analyzeRuns`, or compare two
 * model cohorts via `analyzeRuns({ runs: a, baselineRuns: b })` for a lift CI
 * on "model A's code vs model B's code".
 */
declare function partitionRunsByAuthoringModel(runs: RunRecord[], index: AgentTraceIndex): PartitionByAuthoringModelResult;

/**
 * # `intake/feedback-table` — multi-rater approve/reject corpus → `RunRecord[]`.
 *
 * The generic shape behind Obsidian's `#approved` / `#rejected` tags, a
 * Google Sheet, a Postgres `feedback` table, or any CSV with ratings.
 *
 * Caller supplies one row per (run, rater) tuple plus per-run metadata; the
 * adapter rolls them up into the substrate-canonical `RunRecord` shape so
 * `analyzeRuns({ runs, raterScores })` can produce inter-rater agreement,
 * disagreement triage, and downstream recommendations.
 *
 * Per-run `RunRecord.outcome.searchScore` is the rater-mean rating
 * (normalised to 0..1 when scale is supplied); `outcome.raw` carries the
 * per-rater scores keyed by rater id for downstream attribution.
 */

interface FeedbackTableRow {
    /** Stable id for this run — the unit a rater scored. Drives pairing
     *  across analysis primitives. */
    runId: string;
    /** Identifier of the rater that produced this rating. */
    rater: string;
    /** The rating itself. Accepts boolean (approve/reject), 0..1 scalar,
     *  or any numeric scale — see `scale`. */
    rating: number | boolean;
    /** Optional metadata carried through to `RunRecord.outcome.raw` and the
     *  custom-shape metadata bag. */
    metadata?: Record<string, unknown>;
}
interface FeedbackTableMeta {
    runId: string;
    /** When omitted, defaults to `'feedback-corpus'`. Used to group related
     *  runs in `analyzeRuns()` lift analysis. */
    experimentId?: string;
    /** When omitted, defaults to `runId` — each run is its own candidate. */
    candidateId?: string;
    /** Cost in USD, when available. Set to 0 when unknown — the consumer's
     *  cost analysis sections will collapse gracefully. */
    costUsd?: number;
    /** Wall-clock ms, when available. Defaults to 0. */
    wallMs?: number;
    /** Model identifier including snapshot. Default `unknown@unknown`. */
    model?: string;
    /** Optional sha256 of the prompt; default `'sha256:unknown'`. */
    promptHash?: string;
    /** Default `'sha256:unknown'`. */
    configHash?: string;
    /** Default `'unknown'`. */
    commitSha?: string;
    /** Default `'holdout'` — feedback corpora are by nature the holdout
     *  signal a closed-loop improvement aims at. */
    splitTag?: RunSplitTag;
    /** Free-form metadata available to consumers via the cast-out path on
     *  the resulting RunRecord. */
    extras?: Record<string, unknown>;
}
interface FromFeedbackTableOptions {
    /** Per-(run, rater) ratings. */
    ratings: FeedbackTableRow[];
    /** Per-run metadata. When a runId appears in `ratings` but not here, the
     *  adapter synthesises minimal metadata with defaults documented above. */
    meta?: FeedbackTableMeta[];
    /** Rating scale. Provide `{ min, max }` for non-0..1 numeric scales.
     *  Booleans are normalised: true → 1, false → 0. Default: assumes
     *  ratings are already 0..1. */
    scale?: {
        min: number;
        max: number;
    };
    /** When true, the rater scores are emitted into `raterScores` (a sibling
     *  array `analyzeRuns()` accepts) instead of being averaged into the
     *  run's `outcome.searchScore`. Default `true` — preserves rater-level
     *  signal for inter-rater analysis. */
    emitRaterScores?: boolean;
}
interface FromFeedbackTableResult {
    runs: RunRecord[];
    /** Rater-level scores ready to pass into `analyzeRuns({ raterScores })`
     *  for inter-rater agreement + disagreement triage. */
    raterScores: Array<{
        runId: string;
        rater: string;
        score: number;
    }>;
}
declare function fromFeedbackTable(opts: FromFeedbackTableOptions): FromFeedbackTableResult;

/**
 * # `intake/otel-spans` — OTel `TraceSpanEvent[]` → `RunRecord[]`.
 *
 * Turns an existing observability stream into the substrate-canonical
 * `RunRecord` shape so consumers with logs but no eval discipline can
 * call `analyzeRuns()` against their production traffic immediately.
 *
 * Pivot rule: spans are grouped by `tangle.runId` (the same attribute the
 * hosted-tier wire format uses) or, when absent, by `traceId`. One group
 * becomes one `RunRecord`. The root span (no `parentSpanId`) supplies:
 *
 *   - `runId` (the group key)
 *   - `wallMs` from `endTimeUnixNano - startTimeUnixNano`
 *   - `model` from `gen_ai.request.model` / `llm.model` / `tangle.model`
 *   - cost from `cost.usd` / `gen_ai.usage.cost_usd` / `tangle.cost.usd`
 *   - token usage from `gen_ai.usage.{input,output}_tokens`
 *   - `outcome.searchScore` from `tangle.score` / `eval.score` when
 *     present; `outcome.raw` collects every numeric attribute.
 *
 * Spans that ERRORed (`status.code === 'ERROR'`) populate `failureMode`
 * with their `name` so `analyzeRuns()`'s failure clustering sees them.
 */

interface FromOtelSpansOptions {
    spans: TraceSpanEvent[];
    /** Default split tag for synthesized records. Defaults to `'holdout'`. */
    defaultSplit?: RunSplitTag;
    /** Default `experimentId` when not present on any span. */
    experimentId?: string;
}
declare function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[];

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 };
