import { C as CampaignStorage } from '../provenance-D0WeCXt1.js';
export { B as BuildLoopProvenanceArgs, D as DefaultProductionGateOptions, E as EmitLoopProvenanceArgs, a as EmitLoopProvenanceResult, b as EvolutionaryDriverOptions, G as GepaDriverConstraints, c as GepaDriverOptions, H as HeldOutGateOptions, L as LoopProvenanceBackend, d as LoopProvenanceCandidate, e as LoopProvenanceRecord, O as OpenAutoPrOptions, f as OpenAutoPrResult, R as RunCampaignOptions, g as RunEvalOptions, h as RunImprovementLoopOptions, i as RunImprovementLoopResult, j as RunOptimizationOptions, k as RunOptimizationResult, l as buildLoopProvenanceRecord, m as composeGate, n as countSentenceEdits, o as defaultProductionGate, p as defaultRenderDiff, q as emitLoopProvenance, r as evolutionaryDriver, s as extractH2Sections, t as fsCampaignStorage, u as gepaDriver, v as heldOutGate, w as inMemoryCampaignStorage, x as loopProvenanceSpans, y as openAutoPr, z as provenanceRecordPath, A as provenanceSpansPath, F as runCampaign, I as runEval, J as runImprovementLoop, K as runOptimization, M as surfaceContentHash, N as surfaceHash } from '../provenance-D0WeCXt1.js';
import { L as LabeledScenarioStore, c as LabeledScenarioWrite, d as LabeledScenarioSampleArgs, e as LabeledScenarioRecord, f as LabelTrust, S as Scenario, b as DispatchContext, a as JudgeConfig, g as LabeledScenarioSource, C as CampaignResult, h as CodeSurface } from '../types-Beb6KPqZ.js';
export { i as CampaignAggregates, j as CampaignArtifactWriter, k as CampaignCellResult, l as CampaignCostMeter, m as CampaignTokenUsage, n as CampaignTraceWriter, D as DispatchFn, G as Gate, o as GateContext, p as GateDecision, q as GateResult, r as GenerationCandidate, s as GenerationRecord, I as ImprovementDriver, t as JudgeAggregate, u as JudgeDimension, J as JudgeScore, M as MutableSurface, v as Mutator, O as OptimizerConfig, P as ProposeContext, w as ProposedCandidate, R as RedactionStatus, x as ScenarioAggregate, y as SessionScript, T as TraceSpan, z as isProposedCandidate, A as labelTrustRank } from '../types-Beb6KPqZ.js';
import { A as AgentProfile, B as BackendIntegrityReport } from '../agent-profile-9J9hxdm2.js';
import { A as AgentEvalError } from '../errors-Dwqw-T_m.js';
import { a as RunSplitTag, R as RunRecord } from '../run-record-DgUVo5pw.js';
import '../llm-client-DbjLfz-K.js';
import '../raw-provider-sink-C46HDghv.js';
import '../red-team-DW9Ca_tj.js';
import '../dataset-B2kL-fSM.js';
import '../store-CKUAgsJz.js';
import '../schema-m0gsnbt3.js';
import '../index-D9dwa00f.js';
import '../summary-report-BQvXpvaR.js';
import '../failure-cluster-CL7IVgkJ.js';
import '../judge-calibration-DilmB3Ml.js';

/**
 * @experimental
 *
 * Filesystem `LabeledScenarioStore` adapter. The default capture sink for
 * traces + eval artifacts. Production deployments typically swap for a
 * Turso/SQLite adapter (same interface).
 *
 * Records land as one JSONL file per source under `<root>/<source>.jsonl`.
 * Each line is a `LabeledScenarioRecord`. Append-only — no in-place edits.
 *
 * Safety properties enforced at write-time:
 *
 *   - **Provenance required**: writes without `source`, `sourceVersionHash`,
 *     `capturedAt`, `redactionStatus` are rejected. Closes the alignment
 *     reviewer's data-poisoning gap.
 *   - **Per-source rate limits**: optional `rateLimitBucket` + `maxWritesPerMinute`
 *     stops a single tenant/source from flooding the store.
 *
 * Safety properties enforced at sample-time:
 *
 *   - **Required split + capturedBefore**: substrate refuses to sample without
 *     an explicit `split` ('train' | 'test') AND a temporal cutoff. Eliminates
 *     accidental train/test contamination.
 *   - **Default training-source filter**: when the store is sampled with
 *     `split: 'train'`, production-trace records are EXCLUDED unless the
 *     caller passes `filter.source: 'production-trace'` explicitly. Closes
 *     the contamination-by-default gap flagged by the senior eval engineer.
 */

interface FsLabeledScenarioStoreOptions {
    /** Root directory for JSONL files. Created if missing. */
    root: string;
    /** Per-source rate limit. When set, writes exceeding the cap are rejected
     *  with a typed error. Default: no limit. */
    maxWritesPerMinutePerBucket?: number;
    /** Test seam — override `Date.now()` for deterministic tests. */
    now?: () => number;
}
declare class LabeledScenarioStoreError extends Error {
    readonly code: string;
    constructor(code: string, message: string);
}
declare class FsLabeledScenarioStore implements LabeledScenarioStore {
    private readonly options;
    private readonly now;
    private readonly rateLimits;
    constructor(options: FsLabeledScenarioStoreOptions);
    observe(write: LabeledScenarioWrite): Promise<void>;
    sample(args: LabeledScenarioSampleArgs): Promise<LabeledScenarioRecord[]>;
    size(): Promise<{
        train: number;
        test: number;
        bySource: Record<string, number>;
        byTrust: Record<LabelTrust, number>;
    }>;
    private assertProvenance;
    private assertRateLimit;
    private toRecord;
    private pathForSource;
}

/**
 * @experimental
 *
 * `runProfileMatrix` — the missing keystone between `runAgentMatrix` and the
 * backend-integrity guard.
 *
 * The gap it closes: `runAgentMatrix` is a topology-opaque scheduler whose
 * cells return a bare `{ output, verdict, costUsd }` — no `tokenUsage`, not a
 * `RunRecord`. `assertRealBackend` / `summarizeBackendIntegrity` key on
 * `RunRecord.tokenUsage`, so they cannot run on a raw matrix result. Every
 * consumer therefore hand-writes the same bridge: fan a profile × scenario
 * cartesian, call dispatch, fabricate a `RunRecord` with token usage, thread it
 * back, run the integrity guard. That hand-rolled bridge is exactly the pile of
 * bespoke `eval:*` scripts the adoption skills keep trying (and failing) to
 * forbid.
 *
 * `runProfileMatrix` IS that bridge, once:
 *
 *   - axis 3 (PROFILE) = `profiles: AgentProfile[]`
 *   - axis 1 (PERSONA/SCENARIO) = `scenarios: Scenario[]` (each scenario carries
 *     its persona; `personaOf` groups them for the `byPersona` pivot)
 *   - the scoring axis = `judges`
 *
 * It runs `runCampaign` once per profile (reusing its seeds, reps, bootstrap
 * CIs, resumability, and the `LabeledScenarioStore` capture flywheel), maps
 * every cell to a validated `RunRecord` carrying the real `tokenUsage` the
 * dispatch reported via `ctx.cost.observeTokens`, and runs `assertRealBackend`
 * BY CONSTRUCTION before returning — so a stub-backend run fails loudly instead
 * of reporting a clean 0/N leaderboard.
 *
 * Dispatch contract: a dispatch that calls an LLM MUST report usage via
 * `ctx.cost.observeTokens({ input, output })` (and cost via `ctx.cost.observe`).
 * A dispatch that reports zero tokens is indistinguishable from a stub and the
 * integrity guard treats it as one.
 */

/** Thrown when the matrix is misconfigured (no profiles, a profile whose model
 *  lacks a snapshot version, etc.). Distinct from `BackendIntegrityError`,
 *  which signals a stub backend at run time. */
declare class ProfileMatrixError extends AgentEvalError {
    constructor(message: string);
}
/** Dispatch for one cell: render `profile` against `scenario`, returning the
 *  artifact the judges score. Report LLM usage via `ctx.cost.observeTokens`
 *  and `ctx.cost.observe` — the integrity guard depends on it. */
type ProfileDispatchFn<TScenario extends Scenario, TArtifact> = (profile: AgentProfile, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
interface RunProfileMatrixOptions<TScenario extends Scenario, TArtifact> {
    /** Axis 3 — the agent-under-test configurations. Each is one column. */
    profiles: AgentProfile[];
    /** Axis 1 — the persona/scenario corpus, run against every profile. */
    scenarios: TScenario[];
    /** Renders one (profile, scenario) cell. */
    dispatch: ProfileDispatchFn<TScenario, TArtifact>;
    /** The scoring axis. */
    judges?: JudgeConfig<TArtifact, TScenario>[];
    /** Where each profile's campaign writes artifacts/traces. One subdir per
     *  profile. */
    runDir: string;
    /** Git SHA the harness ran from — stamped onto every RunRecord (mandatory
     *  for paper-grade records). */
    commitSha: string;
    /** Logical experiment id shared across the whole matrix so the promotion
     *  gate can pair profiles on matched scenarios. Default: a hash of the
     *  profile + scenario ids. */
    experimentId?: string;
    /** Which split these runs belong to. Default `'search'`. */
    splitTag?: RunSplitTag;
    /** Replicates per (profile, scenario) cell for CI bands. Default 1. */
    reps?: number;
    /** Campaign seed (per profile). Default 42. */
    seed?: number;
    /**
     * Backend-integrity posture, enforced AFTER the matrix completes:
     *   - `'assert'` (default) — throw `BackendIntegrityError` if the run was a
     *     stub (and, with `allowMixed:false`, if it was mixed).
     *   - `'warn'` — log the verdict but never throw.
     *   - `'off'` — skip the guard entirely (only for offline/replay analysis).
     */
    integrity?: 'assert' | 'warn' | 'off';
    /** Forwarded to `assertRealBackend`. Default true (tolerate partial 429
     *  cascades); set false for strict CI gates. */
    allowMixed?: boolean;
    /** Max concurrent cells WITHIN each profile's campaign. Default 2.
     *  Profiles run sequentially so the cost ceiling is honored deterministically. */
    maxConcurrency?: number;
    /** Cumulative USD cap per profile campaign. */
    costCeiling?: number;
    /** Capture flywheel — forwarded to each campaign. */
    labeledStore?: LabeledScenarioStore | 'off';
    captureSource?: LabeledScenarioSource;
    /** Storage backend. Default `fsCampaignStorage`. Pass
     *  `inMemoryCampaignStorage()` for edge/CF-Worker/test runs. */
    storage?: CampaignStorage;
    /** Test seam — override the wall clock. */
    now?: () => Date;
    /** Optional persona key per scenario — drives the `byPersona` pivot. When
     *  unset, `byPersona` is omitted. */
    personaOf?: (scenario: TScenario) => string;
    /** Validate every produced RunRecord with `validateRunRecord` (fail-loud).
     *  Default true — catches bad model snapshots and non-finite judge dims at
     *  the boundary instead of letting them poison downstream analysis. */
    validate?: boolean;
}
interface ProfileSummary {
    profileId: string;
    profileHash: string;
    model: string;
    /** RunRecords produced for this profile (= scenarios × reps). */
    records: number;
    /** Mean composite across this profile's records. */
    meanComposite: number;
    totalCostUsd: number;
    /** Per-profile integrity verdict — surfaces a single profile that ran stub
     *  even when the matrix as a whole looks real. */
    integrity: BackendIntegrityReport;
}
interface ScenarioRollup {
    meanComposite: number;
    n: number;
}
interface RunProfileMatrixResult<TArtifact, TScenario extends Scenario> {
    matrixId: string;
    experimentId: string;
    /** One RunRecord per (profile, scenario, rep) cell — the integrity-checked,
     *  paper-grade output. Feed straight into `analyzeRuns`, `HeldOutGate`,
     *  scorecards, the hosted wire format. */
    records: RunRecord[];
    byProfile: Record<string, ProfileSummary>;
    byScenario: Record<string, ScenarioRollup>;
    /** Present only when `personaOf` was supplied. */
    byPersona?: Record<string, ScenarioRollup>;
    /** Whole-matrix integrity report (the one `integrity:'assert'` enforces). */
    integrity: BackendIntegrityReport;
    /** The raw per-profile campaign results, keyed by profile id. */
    campaigns: Record<string, CampaignResult<TArtifact, TScenario>>;
}
declare function runProfileMatrix<TScenario extends Scenario, TArtifact>(opts: RunProfileMatrixOptions<TScenario, TArtifact>): Promise<RunProfileMatrixResult<TArtifact, TScenario>>;

/**
 * @experimental
 *
 * VCS-pluggable worktree adapter. One improvement = one worktree, PR-like
 * (multiple commits allowed). A code-tier driver's `propose()` creates a
 * worktree, an agent commits the change into it, and `finalize()` returns a
 * `CodeSurface{ worktreeRef }` the measurement checks out to run the worker
 * against the changed code. On promotion the worktree becomes the PR branch.
 *
 * The interface is VCS-agnostic so a future `jj` ([jj-vcs](https://github.com/jj-vcs/jj))
 * adapter can slot in without touching driver code. Only the git adapter
 * ships today. See `docs/design/self-improvement-engine.md`.
 */

interface Worktree {
    /** Absolute path to the checked-out worktree directory. */
    path: string;
    /** The branch the worktree is on (becomes the PR branch on promotion). */
    branch: string;
    /** The ref the worktree was forked from. */
    baseRef: string;
}
interface WorktreeAdapter {
    /** Create an isolated worktree on a fresh branch off `baseRef`. */
    create(opts: {
        baseRef: string;
        label: string;
    }): Promise<Worktree>;
    /** Commit any pending changes in the worktree, then return a CodeSurface
     *  pointing at it. The agent has already written its change into
     *  `worktree.path` by the time this is called. */
    finalize(worktree: Worktree, summary: string): Promise<CodeSurface>;
    /** Remove the worktree (and its branch) — called for losing candidates. */
    discard(worktree: Worktree): Promise<void>;
}
declare class WorktreeAdapterError extends Error {
    readonly cause?: unknown | undefined;
    constructor(message: string, cause?: unknown | undefined);
}
interface GitWorktreeAdapterOptions {
    /** Repo root the worktrees fork from. */
    repoRoot: string;
    /** Directory worktrees are created under. Default: `<repoRoot>/.worktrees`. */
    worktreeDir?: string;
    /** Branch-name prefix. Default: `improve`. */
    branchPrefix?: string;
    /** Test seam — defaults to a real `git` runner. */
    git?: (args: string[], cwd: string) => string;
}
declare function gitWorktreeAdapter(opts: GitWorktreeAdapterOptions): WorktreeAdapter;
/** Resolve a `CodeSurface`'s worktreeRef to a directory the measurement can
 *  run the worker in. A path ref is returned as-is; anything else is treated
 *  as a ref under the adapter's worktree dir. */
declare function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string;

export { CampaignResult, CampaignStorage, CodeSurface, DispatchContext, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type GitWorktreeAdapterOptions, JudgeConfig, LabelTrust, LabeledScenarioRecord, LabeledScenarioSampleArgs, LabeledScenarioSource, LabeledScenarioStore, LabeledScenarioStoreError, LabeledScenarioWrite, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type RunProfileMatrixOptions, type RunProfileMatrixResult, Scenario, type ScenarioRollup, type Worktree, type WorktreeAdapter, WorktreeAdapterError, gitWorktreeAdapter, resolveWorktreePath, runProfileMatrix };
