import { A as AnalyzeTracesOptions, a as AnalyzeTracesInput, b as AnalyzeTracesResult } from '../analyst-C8HHvfJp.js';
import { S as Scenario, M as MutableSurface, b as DispatchContext, a as JudgeConfig, d as GenerationRecord, f as Gate, J as JudgeScore, L as LabeledScenarioStore, s as LabeledScenarioWrite, t as LabeledScenarioSampleArgs, u as LabeledScenarioRecord, v as LabelTrust, e as SurfaceProposer, w as ProposedCandidate, x as ProposeContext, y as LabeledScenarioSource, C as CampaignResult, n as CodeSurface } from '../types-D9tuReDv.js';
export { j as CampaignAggregates, k as CampaignArtifactWriter, l as CampaignCellResult, m as CampaignCostMeter, z as CampaignTokenUsage, c as CampaignTraceWriter, D as DispatchFn, g as GateContext, i as GateDecision, G as GateResult, o as GenerationCandidate, A as JudgeAggregate, p as JudgeDimension, h as Mutator, O as OptimizationProposer, q as OptimizerConfig, P as ParetoParent, R as RedactionStatus, B as ScenarioAggregate, r as SessionScript, T as TraceSpan, E as isProposedCandidate, F as labelTrustRank } from '../types-D9tuReDv.js';
import { R as RunCampaignOptions, c as RunImprovementLoopOptions, C as CampaignStorage } from '../gepa-3TG16SYf.js';
export { e as GepaProposerConstraints, G as GepaProposerOptions, O as OpenAutoPrOptions, h as OpenAutoPrResult, b as RunImprovementLoopResult, a as RunOptimizationOptions, j as RunOptimizationResult, k as countSentenceEdits, l as defaultRenderDiff, m as extractH2Sections, f as fsCampaignStorage, g as gepaProposer, i as inMemoryCampaignStorage, o as openAutoPr, r as runCampaign, d as runImprovementLoop, n as runOptimization, s as surfaceHash } from '../gepa-3TG16SYf.js';
export { A as AxisEvidence, a as AxisVerdict, B as BuildEvidenceVectorOptions, k as BuildLoopProvenanceArgs, D as DefaultProductionGateOptions, l as EmitLoopProvenanceArgs, m as EmitLoopProvenanceResult, E as EvidenceVector, b as EvolutionaryProposerOptions, H as HeldOutGateOptions, n as LoopProvenanceBackend, o as LoopProvenanceCandidate, L as LoopProvenanceRecord, O as ObjectiveSource, P as ParetoSignificanceGateOptions, c as PromotionObjective, d as PromotionPolicy, R as RunEvalOptions, e as buildEvidenceVector, q as buildLoopProvenanceRecord, f as composeGate, g as defaultProductionGate, s as emitLoopProvenance, h as evolutionaryProposer, i as heldOutGate, t as loopProvenanceSpans, p as paretoPolicy, j as paretoSignificanceGate, u as provenanceRecordPath, v as provenanceSpansPath, r as runEval, w as surfaceContentHash } from '../provenance-C5KAhiom.js';
import { S as SignedManifest, B as BackendIntegrityReport, C as CompletionRequirement, R as RuntimeEventLike, a as CompletionVerdict, P as ProducedState, b as CorrectnessChecker } from '../pre-registration-nfUdc9EQ.js';
import { E as EProcessState, a as PairedBootstrapResult } from '../statistics-xP-cWc5k.js';
import { L as LlmClientOptions } from '../llm-client-Bj7g0rqu.js';
import { AgentProfile } from '@tangle-network/agent-interface';
import { A as AgentEvalError } from '../errors-CzMUYo7b.js';
import { a as RunSplitTag, R as RunRecord } from '../run-record-CP2ObebC.js';
import { T as TraceAnalystKindSpec } from '../kind-factory-X3eDYbKn.js';
import { c as AnalystFinding } from '../types-B5x54y6n.js';
import '@ax-llm/ax';
import '../store-C1YxJDEK.js';
import '../red-team-BWdoyleI.js';
import '../dataset-BbGkaN2I.js';
import '../store-BcFXE6LG.js';
import '../schema-m0gsnbt3.js';
import '../pareto-E-pembql.js';
import '../hosted/index.js';
import '../insight-report-BnRjTibG.js';
import '../summary-report-CInXwsza.js';
import '../failure-cluster-DH9Flgcf.js';
import '../judge-calibration-0p2QcWNE.js';
import '@tangle-network/tcloud';
import '../verdict-C9MlYujm.js';
import '../types-C7DGg5ex.js';
import '../raw-provider-sink-C46HDghv.js';
import 'zod';

/**
 * Make the trace-analyst's OWN prompt a GEPA-optimizable surface.
 *
 * The analyst that drives self-improvement is itself a prompt — and a
 * hand-tuned one (a hardcoded, hand-versioned `const`). This module lets the
 * loop optimize it: the analyst `actorDescription` becomes a `MutableSurface`
 * that `gepaProposer` / `haloProposer` / any `SurfaceProposer` can mutate inside
 * `runImprovementLoop` or `compareProposers`. That is the second-order loop —
 * optimizing the optimizer's eyes, not just the agent's prompt.
 *
 * Two pieces, both deliberately small (the loop engine already exists — this
 * only supplies the analyst-shaped dispatch + an objective scorer):
 *
 *  - `buildAnalystSurfaceDispatch` — `dispatchWithSurface(surface, scenario)`
 *    runs `analyzeTraces` with `surface` as the actorDescription over the
 *    scenario's fixed trace corpus, returning its findings.
 *  - `failureModeRecallJudge` — a DETERMINISTIC judge (no LLM, no opinion)
 *    that scores those findings against the scenario's GROUND-TRUTH failure
 *    modes. This is what keeps optimizing the analyst prompt ungameable: the
 *    labels come from objective signal (e.g. AppWorld `world.evaluate()` tells
 *    us which task failed and which API calls were wrong), so we reward an
 *    analyst for surfacing the failures that really happened — not for
 *    pleasing a judge that could be talked into anything (Goodhart).
 *
 * Wiring (the loop is unchanged; you only pass these in):
 *
 *   const dispatchWithSurface = buildAnalystSurfaceDispatch({ analystOptions: { ai } })
 *   await runImprovementLoop({
 *     baselineSurface: TRACE_ANALYST_ACTOR_DESCRIPTION,  // the prompt under optimization
 *     scenarios: trainScenarios,                          // labeled trace corpora
 *     holdoutScenarios: heldOutScenarios,
 *     dispatchWithSurface,
 *     judges: [failureModeRecallJudge()],
 *     proposer: gepaProposer({ baseUrl, apiKey }),
 *     gate: heldOutGate({ minDelta: 0.02 }),
 *     autoOnPromote: 'none',
 *   })
 */

/**
 * A labeled trace scenario: a FIXED trace corpus plus the failure modes a
 * competent analyst MUST surface from it. The labels are ground truth — the
 * objective failures that actually occurred — which is what makes optimizing
 * the analyst prompt against them meaningful rather than circular.
 */
interface AnalystScenario extends Scenario {
    kind: 'analyst-surface';
    /** OTLP-JSONL path or an in-memory store of the traces to analyze. */
    source: AnalyzeTracesOptions['source'];
    /** The domain question handed to the analyst (framing lives here, not in
     *  the surface under optimization). */
    question: string;
    /**
     * Ground-truth failure modes a good analyst must identify. A finding "hits"
     * a mode when it contains ANY of the mode's case-insensitive cues. Derive
     * these from objective signal (failed task + which step broke), never from
     * the analyst's own prior output.
     */
    expectedFailureModes: Array<{
        id: string;
        cues: string[];
    }>;
    /**
     * Cues that mark a finding as HALLUCINATED / out-of-scope for this corpus —
     * naming a tool, error, or failure that did not occur. Presence penalizes
     * precision. Optional; omit to score recall only.
     */
    forbiddenCues?: string[];
}
/** The analyst's output for one scenario — the artifact the judge scores. */
interface AnalystArtifact {
    answer: string;
    findings: string[];
    /** The hardcoded-prompt version the analyst reported (provenance only; the
     *  optimized surface overrides the actual prompt text used). */
    actorPromptVersion: string;
}
interface BuildAnalystSurfaceDispatchOptions {
    /**
     * Everything `analyzeTraces` needs EXCEPT `actorDescription` (supplied by the
     * surface under optimization) and `source` (supplied by the scenario). `ai`
     * (the AxAIService) is required for a live run.
     */
    analystOptions: Omit<AnalyzeTracesOptions, 'actorDescription' | 'source'>;
    /** Test seam: defaults to the real `analyzeTraces`. */
    analyze?: (input: AnalyzeTracesInput, options: AnalyzeTracesOptions) => Promise<AnalyzeTracesResult>;
}
/**
 * Build the `dispatchWithSurface(surface, scenario, ctx)` the improvement loop
 * calls: run the analyst with `surface` as its actorDescription over the
 * scenario's trace corpus and return its findings.
 */
declare function buildAnalystSurfaceDispatch(opts: BuildAnalystSurfaceDispatchOptions): (surface: MutableSurface, scenario: AnalystScenario, ctx: DispatchContext) => Promise<AnalystArtifact>;
interface FailureModeRecallJudgeOptions {
    /** Weight on recall when precision is also scored (forbiddenCues present).
     *  Default 0.5 (equal). Recall-only when no forbiddenCues exist. */
    recallWeight?: number;
}
/**
 * Deterministic, ground-truth judge for analyst findings. Composite =
 * recall of the scenario's `expectedFailureModes` (optionally blended with a
 * precision term that penalizes findings tripping `forbiddenCues`). No LLM —
 * the score is a function of the labels, so the analyst prompt is optimized
 * toward surfacing real failures, not toward a judge it can flatter.
 */
declare function failureModeRecallJudge(opts?: FailureModeRecallJudgeOptions): JudgeConfig<AnalystArtifact, AnalystScenario>;

/**
 * Anytime-valid sequential promotion gate — an e-process (betting
 * test-martingale, see `eProcess` in `statistics.ts`) over paired
 * per-scenario deltas, so a campaign stops the MOMENT evidence decides
 * instead of burning a fixed-n budget. Decisions remain valid at any
 * data-dependent stopping time (Ville's inequality), which is exactly what
 * fixed-n machinery cannot offer: peeking at a bootstrap CI after every
 * observation and stopping on the first significant peek inflates type-I
 * error far beyond alpha.
 *
 * REPLACES, never layers on, a fixed-n gate. Running `heldoutSignificance`
 * or `paretoSignificanceGate` repeatedly on a growing sample and stopping
 * early is optional stopping no matter how it is dressed up; this gate is
 * the valid way to stop early. Use one or the other per evidence stream.
 *
 * Pre-registration binding: anytime validity holds only for the
 * PRE-REGISTERED statistic. When a `SignedManifest` is bound, the gate takes
 * alpha from `manifest.alpha`, the observation budget from
 * `manifest.preRegisteredN`, orients deltas by `manifest.direction`, and
 * shifts the null boundary by `manifest.minEffect` — re-deciding the same
 * stream under different parameters after seeing data would reopen optional
 * stopping under a fancier name. The manifest's content hash is verified at
 * construction (sync, same `sha256-content` scheme as `signManifest`).
 *
 * Non-iid caveat (stated honestly): the supermartingale guarantee needs each
 * delta's conditional mean under H0 to stay ≤ the null boundary given the
 * past — exchangeable scenario deltas suffice. Scenario streams ordered by
 * difficulty or by scenario family violate this; `decide(ctx)` therefore
 * shuffles the paired deltas with a SEEDED permutation by default (the
 * permutation is data-independent, so bet predictability is preserved).
 * Stratified betting (per-stratum λ) is future work, not implemented here.
 */

type SequentialDecision = 'promote' | 'continue' | 'undecided-at-maxN';
interface SequentialObservation {
    decision: SequentialDecision;
    /** Current e-value (the betting wealth) against H0. */
    eValue: number;
    /** Paired deltas consumed so far. */
    n: number;
    /** Names the decision basis. For 'undecided-at-maxN' it states explicitly
     *  that exhausting the budget is NOT evidence of no effect. */
    reason: string;
}
interface SequentialPairedGateOptions {
    /** Type-I budget. With `preRegistration` bound this MUST match
     *  `manifest.alpha` (conflict throws). Default 0.05. */
    alpha?: number;
    /** Minimum paired deltas before a promote may fire. The stopping rule is
     *  "first n ≥ minN with e-value ≥ 1/alpha" — still a valid stopping time.
     *  Default 5. */
    minN?: number;
    /** Pre-registered observation budget. Required unless `preRegistration`
     *  supplies it via `preRegisteredN` (conflict throws). */
    maxN?: number;
    /** Bet truncation forwarded to `eProcess`. Default 0.5. */
    maxBet?: number;
    /** Bound on |delta| in the judge's native scale; deltas are mapped to
     *  x = (d/scale + 1)/2 ∈ [0,1]. A delta outside ±scale throws (use
     *  `detectScale` to pick 1 vs 100 BEFORE streaming). Default 1. */
    scale?: number;
    /** Seed for the data-independent shuffle of paired deltas in `decide(ctx)`
     *  (exchangeability guard). Default 1337. */
    shuffleSeed?: number;
    /** Bind the pre-registered hypothesis. Verified (content hash) at
     *  construction; alpha/maxN/direction/minEffect come FROM the manifest. */
    preRegistration?: SignedManifest;
    /** Override the gate name in reports. */
    name?: string;
}
interface SequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario> extends Gate<TArtifact, TScenario> {
    /** Streaming entry point: feed one paired per-scenario delta
     *  (candidate − baseline, native scale). Each gate instance carries ONE
     *  observe-stream; `decide(ctx)` runs on its own fresh stream and never
     *  consumes or advances this one. 'promote' is sticky; observing past the
     *  pre-registered maxN throws (extending a finished stream after seeing
     *  the result reopens optional stopping — start a NEW pre-registered
     *  test). */
    observe(delta: number): SequentialObservation;
    /** Read-only snapshot of the observe-stream. */
    state(): EProcessState & {
        decision: SequentialDecision;
    };
}
/**
 * Anytime-valid sequential paired gate. Conforms to the existing `Gate`
 * contract (`decide(ctx)` consumes candidate vs baseline judge scores via
 * `pairHoldout` — same pairing granularity as the fixed-n gates: full cellId,
 * never scenarioId) and adds a streaming `observe(delta)` entry for campaigns
 * that score cells incrementally and want to stop mid-stream.
 *
 * Decision mapping onto the substrate's five-valued `GateDecision`:
 *   - 'promote'            → 'ship'
 *   - 'continue'           → 'need_more_work' (stream ended before maxN with
 *                            the e-value undecided — more reps could decide)
 *   - 'undecided-at-maxN'  → 'hold', with the reason stating it is NOT
 *                            evidence of no effect (never a silent default)
 */
declare function sequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(options: SequentialPairedGateOptions): SequentialPairedGate<TArtifact, TScenario>;
interface SequentialDecideOptions {
    /** Type-I budget for the early-stop evidence. Default 0.05. */
    alpha?: number;
    /** Minimum paired deltas before a stop may fire. Default 5. */
    minN?: number;
    /** Bet truncation forwarded to `eProcess`. Default 0.5. */
    maxBet?: number;
    /** Bound on |per-scenario composite delta|. Default 1. */
    scale?: number;
}
interface SequentialDecideFn {
    (args: {
        history: GenerationRecord[];
    }): {
        stop: boolean;
        reason?: string;
    };
    /** Read-only snapshot of the accumulated e-process (observability + tests). */
    state(): EProcessState;
}
/**
 * `SurfaceProposer.decide` adapter — stops the optimization loop the moment
 * the e-process decides the loop has produced a real improvement, instead of
 * always running `maxGenerations`.
 *
 * Stream: for each generation g ≥ 1, the per-scenario composite deltas of
 * generation g's top candidate vs the generation-0 top candidate (the
 * incumbent the loop set out to beat), paired by scenarioId. H0: no proposed
 * surface improves any scenario's expected composite over the incumbent —
 * under it every delta has conditional mean ≤ 0 and the e-process is valid.
 * Once wealth ≥ 1/alpha the loop stops and hands the winner to the promotion
 * gate (which re-scores on HELD-OUT data — this adapter only spends the
 * exploration budget, it never promotes).
 *
 * Honesty caveats: (1) the incumbent's scores are measured once and shared
 * across all generations' deltas, so type-I control is exact only insofar as
 * those scores approximate the incumbent's true per-scenario means (more reps
 * → tighter); (2) an UNDECIDED process never stops the loop — absence of a
 * crossing is NOT evidence of no effect, so the loop simply runs its normal
 * course. Calling the adapter repeatedly with a growing history consumes each
 * generation exactly once (re-feeding an already-seen record would double-count
 * evidence).
 */
declare function sequentialDecide(options?: SequentialDecideOptions): SequentialDecideFn;

/**
 * Statistical held-out promotion machinery — the trustworthy core the
 * point-estimate `heldout-delta` gate lacked.
 *
 * The shipped false positive it prevents: a winner re-scored against the
 * baseline on the holdout read run-to-run model NOISE (e.g. 91 vs 95) as a
 * "+4 lift" and shipped, because the gate compared point estimates with no
 * confidence interval. Here we pair candidate vs baseline holdout observations
 * and bootstrap a CI on the paired delta — a candidate ships only when the CI
 * lower bound clears the effect-size threshold (the gain is real at the
 * confidence level, not noise), and is blocked when a critical dimension
 * (e.g. `hallucination_free` for a legal agent) significantly regresses even if
 * the net composite rose (anti-Goodhart).
 *
 * Two traps this module is built around (both produce a NEW false positive if
 * gotten wrong):
 *   1. PAIRING GRANULARITY — pairs by FULL `cellId` (`scenario:rep`), never by
 *      `scenarioId` (which averages reps away and destroys the within-pair
 *      variance reduction that makes a paired bootstrap tighter than unpaired).
 *      One paired observation per cell ⇒ reps multiply n.
 *   2. SCALE — a judge may emit composites/dimensions on [0,1] or 0-100. The
 *      threshold + tolerance are interpreted in the judge's NATIVE scale; the
 *      per-dimension tolerance auto-scales off the observed baseline magnitudes
 *      so `-0.10` on [0,1] doesn't silently become a no-op on a 0-100 dimension.
 */

interface PairedHoldout {
    /** Baseline scalar per paired cell (same order as `after`/`cellIds`). */
    before: number[];
    /** Candidate scalar per paired cell. */
    after: number[];
    /** The full cellIds (`scenario:rep`) that paired, in order. */
    cellIds: string[];
}
/**
 * Pair candidate vs baseline holdout observations by FULL cellId. `select`
 * pulls the scalar from a cell's judge reports (composite, or a named
 * dimension); a cell contributes the mean of `select` across its judges. Cells
 * whose scenario is not in `scenarioIds`, or where `select` is undefined for
 * every judge on either side, are skipped on BOTH sides so the arrays stay
 * paired. Throws when the two maps disagree on which holdout cells exist — a
 * load-bearing invariant: the baseline + winner holdout campaigns run the same
 * scenarios with the same seed base, so their cellIds MUST align; a mismatch
 * means a silent pairing bug, not a soft fallback.
 */
declare function pairHoldout(candidate: Map<string, Record<string, JudgeScore>>, baseline: Map<string, Record<string, JudgeScore>>, scenarioIds: Set<string>, select: (s: JudgeScore) => number | undefined): PairedHoldout;
interface HeldoutSignificance {
    paired: PairedHoldout;
    bootstrap: PairedBootstrapResult;
    /** n paired observations. */
    n: number;
    /** True iff n >= minProductiveRuns AND the CI lower bound clears the threshold. */
    significant: boolean;
    /** Set when n < minProductiveRuns — too little evidence to claim significance. */
    fewRuns: boolean;
}
interface HeldoutSignificanceOptions {
    deltaThreshold?: number;
    minProductiveRuns?: number;
    confidence?: number;
    resamples?: number;
    /** Fixed by default for a deterministic, reproducible gate verdict. */
    seed?: number;
    statistic?: 'mean' | 'median';
}
/** Significance of the held-out composite lift: ship only when the paired
 *  bootstrap CI lower bound on (candidate − baseline) exceeds `deltaThreshold`
 *  (default 0 ⇒ "confidently positive"). Below `minProductiveRuns` paired
 *  observations there is not enough evidence to claim significance → not
 *  significant (`fewRuns`). Interpret `deltaThreshold` in the judge's native
 *  composite scale. */
declare function heldoutSignificance(paired: PairedHoldout, opts?: HeldoutSignificanceOptions): HeldoutSignificance;
interface DimensionRegression {
    dimension: string;
    bootstrap: PairedBootstrapResult;
    /** True iff the CI lower bound on (candidate − baseline) is below −tolerance:
     *  the candidate may have regressed this dimension by more than tolerance. */
    regressed: boolean;
    tolerance: number;
    n: number;
}
/** Detect the native scale of a set of scores: 0-100 when any magnitude clears
 *  1.5, else [0,1]. Used to auto-scale the regression tolerance so a default
 *  expressed for [0,1] is not silently a no-op on a 0-100 dimension. */
declare function detectScale(values: number[]): 1 | 100;
/** Per-critical-dimension regression guard. For each dimension, pair the
 *  candidate vs baseline values by full cellId and bootstrap the paired delta;
 *  a dimension is "regressed" when the CI lower bound < −tolerance (conservative
 *  — blocks if the credible worst case exceeds tolerance, which is the right
 *  posture for safety dimensions like `hallucination_free`). When `tolerance`
 *  is omitted it auto-scales: 0.05 on [0,1], 5 on 0-100. */
declare function dimensionRegressions(candidate: Map<string, Record<string, JudgeScore>>, baseline: Map<string, Record<string, JudgeScore>>, scenarioIds: Set<string>, criticalDimensions: string[], opts?: {
    tolerance?: number;
    confidence?: number;
    resamples?: number;
    seed?: number;
}): DimensionRegression[];

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

/**
 * FAPO (Fully Autonomous Prompt Optimization) is an orchestration policy, not
 * a new prompt mutation primitive. The paper's loop evaluates an inspectable
 * workflow, attributes failures to an edit level, proposes ONE scoped change,
 * reviews it, measures it, and escalates from prompt -> parameters -> structure
 * only when prompt-level search is exhausted and attribution supports the
 * higher-cost edit.
 *
 * This substrate proposer encodes that policy while keeping the edit generators
 * pluggable:
 *   - prompt: usually `gepaProposer`, `skillOptProposer`, or a runtime reflective proposer
 *   - parameter: `parameterSweepProposer` or a caller-supplied config proposer
 *   - structural: a caller-supplied code/worktree proposer from agent-runtime
 *
 * It deliberately does not import Claude Code, LangGraph, or Cisco's tenant
 * runtime. agent-eval owns measurement and proposer contracts; runtime-shaped
 * code generation stays downstream.
 *
 * Grounded sources:
 *   - Kassianik et al., "FAPO: Fully Autonomous Prompt Optimization of
 *     Multi-Step LLM Pipelines", arXiv:2606.19605v1.
 *   - cisco-foundation-ai/fully-automated-prompt-optimization at
 *     376b50c57d5e2423e5a5de46e0d315a761d272d8.
 */

type FapoOptimizationLevel = 'prompt' | 'parameter' | 'structural';
interface FapoScopeContract {
    /** Levels the tenant/playbook allows. Defaults to the levels with proposers. */
    allowedLevels?: readonly FapoOptimizationLevel[];
    /** Explicitly forbidden levels; wins over `allowedLevels`. */
    forbiddenLevels?: readonly FapoOptimizationLevel[];
}
interface FapoFailureCluster {
    label: string;
    level: FapoOptimizationLevel;
    count: number;
    confidence?: 'high' | 'medium' | 'low';
    suggestedFix?: string;
    caseIds?: string[];
}
interface FapoAttributionSignals {
    counts: Record<FapoOptimizationLevel, number>;
    clusters: FapoFailureCluster[];
}
interface FapoReviewIssue {
    checkName: string;
    severity: 'block' | 'warn';
    description: string;
    location?: string;
}
interface FapoReviewResult {
    verdict: 'pass' | 'warn' | 'fail';
    issues?: FapoReviewIssue[];
    suggestions?: string[];
}
interface FapoReviewInput<TFindings = unknown> {
    level: FapoOptimizationLevel;
    candidate: ProposedCandidate;
    context: ProposeContext<TFindings>;
    reason: string;
}
interface FapoProposerOptions<TFindings = unknown> {
    /** Level-specific candidate proposers. At least one is required. */
    proposers?: Partial<Record<FapoOptimizationLevel, SurfaceProposer<TFindings>>>;
    /** Convenience aliases for `proposers.<level>`. */
    promptProposer?: SurfaceProposer<TFindings>;
    parameterProposer?: SurfaceProposer<TFindings>;
    structuralProposer?: SurfaceProposer<TFindings>;
    /** Tenant/playbook-derived allowed and forbidden edit levels. */
    scope?: FapoScopeContract;
    /**
     * Independent reviewer hook. Return `fail` to block a candidate before eval,
     * mirroring FAPO's variant-reviewer phase.
     */
    reviewCandidate?: (input: FapoReviewInput<TFindings>) => Promise<FapoReviewResult>;
    /**
     * FAPO proposes one scoped change per cycle. Keep this at 1 unless you are
     * intentionally relaxing the paper loop for a batch experiment.
     */
    proposalsPerCycle?: number;
    /** Consecutive non-improving variants required before a level is exhausted. Default 3. */
    plateauWindow?: number;
    /** Distinct strategies required before declaring a plateau. Default 3. */
    minDistinctStrategies?: number;
    /** Candidate score delta needed to count as an improvement. Default 0. */
    minImprovement?: number;
    /** Paper-faithful default: try prompt edits before escalating. */
    promptFirst?: boolean;
    /** Paper-faithful default: try parameter/config edits before structural code edits. */
    parameterBeforeStructural?: boolean;
}
/** Build a FAPO policy proposer from level-specific candidate generators. */
declare function fapoProposer<TFindings = unknown>(opts: FapoProposerOptions<TFindings>): SurfaceProposer<TFindings>;
declare function extractFapoAttributionSignals(findings: readonly unknown[]): FapoAttributionSignals;
type JsonPrimitive = string | number | boolean | null;
type JsonValue = JsonPrimitive | JsonValue[] | {
    [key: string]: JsonValue;
};
interface ParameterChange {
    path: string | readonly string[];
    value: JsonValue;
}
interface ParameterCandidate {
    label: string;
    rationale: string;
    /** Deep-merged into the current JSON surface. */
    patch?: Record<string, JsonValue>;
    /** Dot-path writes, e.g. `{ path: 'retrieval.k', value: 10 }`. */
    changes?: readonly ParameterChange[];
}
interface ParameterSweepProposerOptions {
    candidates: readonly ParameterCandidate[];
    /** Optional parser for non-JSON config surface strings. */
    parse?: (surface: string) => Record<string, JsonValue>;
    /** Optional serializer for non-JSON config surface strings. */
    stringify?: (config: Record<string, JsonValue>) => string;
}
/** Config/parameter-level proposer for FAPO's middle escalation level. */
declare function parameterSweepProposer(opts: ParameterSweepProposerOptions): SurfaceProposer;

/**
 * `compareProposers` — a head-to-head lift benchmark across surface proposers
 * on ONE corpus. This is the forcing function: optimizer quality (GEPA
 * reflection vs GEPA+Pareto vs SkillOpt) becomes a NUMBER with a confidence
 * interval, so a proposer regression — or shipping a simplified proposer and
 * calling it the real one — turns a build red instead of going
 * measurement-invisible.
 *
 * Every entrant is scored the SAME way: each proposer returns the surface it
 * promoted, then the benchmark scores the baseline + every winner on the
 * SAME held-out scenarios with the SAME judges. Apples-to-apples by
 * construction — the comparison never depends on how a proposer measured itself.
 * The per-scenario held-out composites feed a paired bootstrap (`statistics.ts`)
 * for each proposer's lift CI and for the pairwise "which proposer wins" CI.
 */

/** What an optimizer produced: the surface it promoted + what it cost to get
 *  there. The comparison does the held-out scoring itself, so an entry only
 *  needs to run its loop and hand back the winner. */
interface ProposerEntry {
    name: string;
    optimize: () => Promise<{
        winnerSurface: MutableSurface;
        costUsd: number;
        durationMs?: number;
    }>;
}
interface ProposerScore {
    name: string;
    /** Mean held-out composite of the baseline (identical across proposers). */
    baselineComposite: number;
    /** Mean held-out composite of this proposer's promoted surface. */
    winnerComposite: number;
    /** Mean per-scenario held-out lift (winner − baseline). */
    lift: number;
    /** Paired-bootstrap CI of the per-scenario lift. `low > 0` ⇒ a real gain. */
    liftCi: {
        low: number;
        high: number;
    };
    costUsd: number;
    durationMs?: number;
    winnerSurface: MutableSurface;
    /** 1-based, by descending lift. */
    rank: number;
}
interface ProposerPairwise {
    /** Higher-ranked proposer. */
    a: string;
    b: string;
    /** Mean per-scenario held-out delta (a − b). */
    deltaMean: number;
    low: number;
    high: number;
    /** `a` if the CI clears 0, `b` if it is entirely negative, else `'tie'`. */
    favored: string;
}
interface ProposerComparison {
    /** Sorted by descending lift; `rank` set accordingly. */
    scores: ProposerScore[];
    best: ProposerScore;
    /** Best vs each other proposer, paired-bootstrap on the held-out winners. */
    pairwise: ProposerPairwise[];
    holdoutScenarioIds: string[];
}
interface CompareProposersOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'scenarios'> {
    proposers: ProposerEntry[];
    baselineSurface: MutableSurface;
    /** The held-out scenarios every winner is scored on. */
    holdoutScenarios: TScenario[];
    /** Scores a surface on a scenario — the same dispatcher the proposers used. */
    dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
    /** Bootstrap resamples for the lift CIs. Default 2000. */
    resamples?: number;
    /** CI confidence. Default 0.95. */
    confidence?: number;
}
declare function compareProposers<TScenario extends Scenario, TArtifact>(opts: CompareProposersOptions<TScenario, TArtifact>): Promise<ProposerComparison>;
/** Shared corpus + transport for the three built-in optimizer entries. */
interface OptimizerEntryConfig<TScenario extends Scenario, TArtifact> {
    baselineSurface: string;
    /** Training scenarios the proposers reflect on. */
    trainScenarios: TScenario[];
    /** Held-out scenarios (the gate axis + the benchmark scoring axis). */
    holdoutScenarios: TScenario[];
    dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
    judges: JudgeConfig<TArtifact, TScenario>[];
    llm: LlmClientOptions;
    model: string;
    target: string;
    runDir: string;
    seed?: number;
    /** GEPA population per generation. Default 2. */
    populationSize?: number;
    /** GEPA generations. Default 3. */
    maxGenerations?: number;
    /** SkillOpt epochs. Default 6. */
    maxEpochs?: number;
    mutationPrimitives?: string[];
    /** Static findings seed forwarded to each GEPA proposer's `propose()` as
     *  `ctx.findings`. Forwarded by `gepaReflectionEntry` / `gepaParetoEntry`;
     *  `skillOptEntry` runs without findings (see its doc). */
    findings?: unknown[];
    /** Per-generation findings producer: after each generation scores, this
     *  re-diagnoses and REPLACES `ctx.findings` for the
     *  next generation's `propose()`. Reuses the `runOptimization` field type so
     *  it cannot drift. GEPA entries only. */
    analyzeGeneration?: RunImprovementLoopOptions<TScenario, TArtifact>['analyzeGeneration'];
    /** Optional analysis report forwarded to `propose()` as `ctx.report`. */
    report?: unknown;
}
/** GEPA, reflection-only (single-parent, no Pareto combine). */
declare function gepaReflectionEntry<TScenario extends Scenario, TArtifact>(config: OptimizerEntryConfig<TScenario, TArtifact>, name?: string): ProposerEntry;
/** GEPA with the Pareto frontier + combine-complementary-lessons. */
declare function gepaParetoEntry<TScenario extends Scenario, TArtifact>(config: OptimizerEntryConfig<TScenario, TArtifact>, name?: string): ProposerEntry;
/** SkillOpt patch-mode hill-climb. Runs findings-BLIND: `runSkillOpt` owns its
 *  own epoch acceptance/budget loop and does not thread `analyzeGeneration`, so
 *  `config.findings` is intentionally NOT forwarded here. In a findings-fed
 *  comparison this entry is the blind control — do not read its result as
 *  findings-fed. (Threading findings into the SkillOpt epoch loop is a separate
 *  refactor, deferred not faked.) */
declare function skillOptEntry<TScenario extends Scenario, TArtifact>(config: OptimizerEntryConfig<TScenario, TArtifact>, name?: string): ProposerEntry;
/** FAPO reviewed-escalation policy. This is an orchestration layer over
 * level-specific proposers, not a new mutation operator:
 * prompt -> parameter -> structural, with scope + reviewer + plateau rules in
 * `fapoProposer`. The prompt proposer defaults to GEPA+Pareto because that is
 * the package's strongest prompt-tier proposer; parameter/structural proposers
 * are opt-in so we do not fake code-generation inside agent-eval. */
interface FapoEntryConfig<TScenario extends Scenario, TArtifact> extends OptimizerEntryConfig<TScenario, TArtifact> {
    /** Override the prompt-level proposer. Default: `gepaProposer({ combineParents: true })`. */
    promptProposer?: SurfaceProposer;
    /** Parameter/config-level proposer. If omitted, `parameterCandidates` builds one. */
    parameterProposer?: SurfaceProposer;
    /** Structural/code-level proposer, typically supplied by agent-runtime. */
    structuralProposer?: SurfaceProposer;
    /** Convenience: build a `parameterSweepProposer` from these candidates. */
    parameterCandidates?: readonly ParameterCandidate[];
    /** FAPO policy knobs: scope, reviewer, plateau thresholds. */
    fapo?: Omit<FapoProposerOptions, 'proposers' | 'promptProposer' | 'parameterProposer' | 'structuralProposer'>;
}
declare function fapoEscalationEntry<TScenario extends Scenario, TArtifact>(config: FapoEntryConfig<TScenario, TArtifact>, name?: string): ProposerEntry;

/**
 * `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;
    /** Corpus-by-default: derive the trajectory text (`prompt` + `completion`)
     *  for each cell from its artifact + scenario. When set, every produced
     *  record carries `prompt`/`completion` (a `CorpusRecord`) so the run's
     *  graded trajectories can be appended to the durable RL corpus with no
     *  side-channel — `appendToCorpus(result.records, path)`. Fail-soft: a
     *  throwing or undefined-returning extractor just omits the text. */
    corpusText?: (artifact: TArtifact, scenario: TScenario) => {
        prompt: string;
        completion: string;
    } | undefined;
}
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>>;

/**
 * Product-flow playback — drive the REAL product through a user story and
 * score the produced state per requirement (the launch "Jira tick-off").
 *
 * This is the substrate adapter + contract only. It plugs a `PlaybackDriver`
 * into the existing `runProfileMatrix` dispatch seam: a driver drives the real
 * product (a Playwright UI session or a sandbox workspace) and returns the
 * runtime event stream; `extractProducedState` + `verifyCompletion` then score
 * each requirement PASS/FAIL. The concrete drivers live in consumers — they
 * depend on browser / runtime infra the substrate must not import — so
 * agent-eval owns the seam, the `UserStory` contract, and the scoreboard.
 */

/** One step of a user story — what the user does. The driver interprets
 *  `payload` (a Playwright selector + action, or a sandbox chat turn). */
interface PlaybackStep {
    /** Human-readable action, captured verbatim in the UX narrative. */
    action: string;
    /** Driver-specific payload (e.g. `{ selector, fill }` or `{ turn }`). */
    payload?: Record<string, unknown>;
}
/**
 * A user story = a runnable product journey plus the requirements that define
 * "this story works". Each requirement is one Jira ticket line. Extends
 * `Scenario` so a catalog drops straight into `runProfileMatrix({ scenarios })`.
 */
interface UserStory extends Scenario {
    /** Human-readable story title (the ticket headline). */
    title: string;
    /** Ordered steps the driver executes. */
    steps: PlaybackStep[];
    /** What must hold in the produced state for the story to pass. */
    requirements: CompletionRequirement[];
}
/** Dispatch context plus the profile under test (which cheap model, etc.). */
interface PlaybackContext extends DispatchContext {
    profile: AgentProfile;
}
/**
 * Drives the real product through a story and returns the runtime event stream
 * `extractProducedState` consumes. Implemented by CONSUMERS —
 * `SandboxPlaybackDriver` (real API / sandbox workspace) and
 * `PlaywrightPlaybackDriver` (real UI) — because they depend on runtime /
 * browser infra the substrate must not import. The driver MUST report LLM
 * usage via `ctx.cost.observeTokens` so the backend-integrity guard sees real
 * tokens (a run that never reports tokens reads as a stub).
 */
interface PlaybackDriver<TStory extends UserStory = UserStory> {
    run(story: TStory, ctx: PlaybackContext): Promise<readonly RuntimeEventLike[]>;
}
/**
 * Adapt a `PlaybackDriver` into a `runProfileMatrix` dispatch. The artifact the
 * matrix scores is the `ProducedState` extracted from the driver's event
 * stream — grade it with `scoreUserStory` (or a judge wrapping it).
 */
declare function makePlaybackDispatch<TStory extends UserStory>(driver: PlaybackDriver<TStory>): ProfileDispatchFn<TStory, ProducedState>;
/** A scored user story — the completion verdict plus its human title. */
interface UserStoryVerdict extends CompletionVerdict {
    title: string;
}
/**
 * Score one story's produced state against its requirements. Thin wrapper over
 * `verifyCompletion` that builds the gold from the story and returns a
 * per-requirement PASS/FAIL verdict. `checkCorrectness` is injected — a
 * deterministic stub in tests, `createLlmCorrectnessChecker` in production.
 */
declare function scoreUserStory(story: UserStory, state: ProducedState, checkCorrectness: CorrectnessChecker): Promise<UserStoryVerdict>;
/** One row of the launch scoreboard — story × requirement → PASS/FAIL. */
interface ScoreboardRow {
    storyId: string;
    storyTitle: string;
    reqId: string;
    reqTitle: string;
    status: 'PASS' | 'FAIL';
    evidence: string[];
}
/**
 * Flatten story verdicts into the per-requirement scoreboard — the literal
 * Jira tick-off: one row per (story, requirement) with PASS/FAIL and the
 * evidence behind the verdict.
 */
declare function userStoryScoreboard(verdicts: readonly UserStoryVerdict[]): ScoreboardRow[];
/** Launch-readiness headline counts rolled up from the per-requirement rows. */
interface ScoreboardSummary {
    /** Distinct user stories on the board. */
    stories: number;
    /** Stories whose every requirement passed. */
    storiesFullyComplete: number;
    /** Total (story, requirement) rows. */
    requirements: number;
    /** Rows with status PASS. */
    passed: number;
    /** Rows with status FAIL. */
    failed: number;
    /** passed / requirements; 0 when there are no rows. */
    passRate: number;
}
/** Roll the per-requirement rows up into the launch headline counts. */
declare function scoreboardSummary(rows: readonly ScoreboardRow[]): ScoreboardSummary;
interface ScoreboardRenderOptions {
    /** Document H1. Defaults to a generic playback title. */
    title?: string;
    /** Key/value run metadata rendered under the headline (runId, backend, model, date). */
    meta?: Record<string, string>;
    /** Max chars of joined evidence shown per row. Default 160. */
    maxEvidenceChars?: number;
}
/**
 * Render the scoreboard as a launch-readiness Markdown document — the literal
 * "tick off every user story" artifact: a headline roll-up, the open tickets
 * (FAIL rows) up top as the launch blockers, then a per-story table of
 * requirement → PASS/FAIL with the evidence behind each verdict. Pure: same
 * rows in, same bytes out (no clock/random), so it is safe to snapshot.
 */
declare function renderScoreboardMarkdown(rows: readonly ScoreboardRow[], opts?: ScoreboardRenderOptions): string;

/**
 * SkillOpt patch primitives (Microsoft, arXiv:2605.23904 — "Executive
 * Strategy for Self-Evolving Agent Skills"). Where GEPA regenerates a surface
 * by reflection, SkillOpt emits BOUNDED, anchored edits to ONE skill document
 * — add / delete / replace — and accepts an edit only if it strictly improves
 * a held-out score. Bounded edits are the "textual learning rate": small,
 * reversible, and cheap to accept/reject, so a good rule introduced earlier is
 * not overwritten by a later sweeping rewrite.
 *
 * This module applies a patch deterministically and reports, per op, what
 * applied and what could not (a missing anchor is a rejected op, never a
 * silently dropped one). Pure, no I/O.
 */
/** A single bounded edit against a skill surface.
 *   - `add`     — insert `text` after the first line containing `after`
 *                 (append to the end when `after` is absent/empty).
 *   - `delete`  — remove the first line containing `anchor`.
 *   - `replace` — replace the first line containing `anchor` with `text`.
 *  `text` may be multi-line; it is spliced in as multiple lines. Anchors match
 *  the FIRST line that contains the substring (deterministic; SkillOpt is
 *  expected to anchor on unique text). */
type SkillPatchOp = {
    op: 'add';
    after?: string;
    text: string;
} | {
    op: 'delete';
    anchor: string;
} | {
    op: 'replace';
    anchor: string;
    text: string;
};
/** A named, attributable bundle of ops the optimizer proposes as one edit. */
interface SkillPatch {
    label: string;
    rationale: string;
    ops: SkillPatchOp[];
}
interface SkillPatchRejection {
    op: SkillPatchOp;
    reason: string;
}
interface ApplySkillPatchResult {
    surface: string;
    /** Count of ops that mutated the surface. */
    applied: number;
    /** Ops that could not apply (unanchored / empty), with the reason. The
     *  surface still reflects every APPLIED op — partial application is honest,
     *  and the caller decides whether a partial patch is worth scoring. */
    rejected: SkillPatchRejection[];
}
/**
 * Apply a SkillOpt patch to a text surface. Ops apply in array order against
 * the evolving line buffer (an `add after X` followed by a `delete X` sees the
 * inserted lines). A missing anchor rejects only that op; the rest still apply.
 */
declare function applySkillPatch(surface: string, patch: SkillPatch): ApplySkillPatchResult;
/** Total ops in a patch — the edit-budget axis (SkillOpt's "textual learning
 *  rate" caps this per epoch). */
declare function patchEditCount(patch: SkillPatch): number;

/**
 * `skillOptProposer` — a patch-mode `SurfaceProposer` implementing SkillOpt
 * (Microsoft, arXiv:2605.23904). Where `gepaProposer` regenerates the whole
 * surface by reflection, SkillOpt proposes BOUNDED, anchored edits
 * (add/delete/replace) to ONE skill document, so a good rule introduced
 * earlier is not clobbered by a later sweeping rewrite. The edit budget is the
 * paper's "textual learning rate"; a rejected-edit buffer + a slow-update
 * meta-note steer the optimizer away from dead ends.
 *
 * This module is the PROPOSER — the LLM call that turns evidence into
 * structured patches. The accept-only-if-held-out-improves loop, the budget
 * annealing, and the rejected buffer live in the `runSkillOpt` preset, which
 * owns the epoch hill-climb. The proposer also conforms to `SurfaceProposer`
 * (`propose` applies its patches to the current surface and returns the
 * candidate surfaces) so it is a drop-in for `runOptimization` and a fair
 * entrant in `compareProposers`.
 */

/** Evidence the optimizer reflects on: where the current surface is weakest.
 *  Computed by the caller (the preset uses a TRAIN campaign so proposals never
 *  see the held-out split; the generic loop derives it from history). */
interface SkillOptEvidence {
    /** Lowest-scoring scenarios (drives WHICH behavior to patch). */
    weakScenarios: Array<{
        scenarioId: string;
        composite: number;
    }>;
    /** Lowest-scoring judge dimensions (drives WHAT to patch for). */
    weakDimensions: Array<{
        dimension: string;
        score: number;
    }>;
}
/** A patch that was tried and not accepted — fed back to the model so it does
 *  not re-propose a dead end (SkillOpt's rejected-edit buffer). */
interface RejectedEdit {
    label: string;
    rationale: string;
    reason: string;
}
interface ProposePatchesArgs {
    surface: string;
    evidence: SkillOptEvidence;
    /** Max ops per patch this round (the annealed textual learning rate). */
    editBudget: number;
    rejectedBuffer: RejectedEdit[];
    /** Slow-update meta guidance accumulated across epochs. */
    metaNote?: string;
    /** Analyst findings + research report rendered as a prompt block so a patch
     *  targets a NAMED diagnosed root cause. Built by
     *  the proposer from `ctx.findings`/`ctx.report`; the patch-native `runSkillOpt`
     *  path may also supply it. */
    findingsNote?: string;
    /** How many candidate patches to propose. */
    count: number;
    signal: AbortSignal;
}
interface SkillOptProposerOptions {
    llm: LlmClientOptions;
    model: string;
    /** What the skill document governs — orients the prompt. */
    target: string;
    /** Default ops-per-patch cap when used as a bare `SurfaceProposer`. The
     *  `runSkillOpt` preset overrides this per epoch as it anneals. Default 3. */
    editBudget?: number;
    temperature?: number;
    maxTokens?: number;
    /** Top-K weak scenarios/dimensions surfaced as evidence. Default 3. */
    evidenceK?: number;
}
interface SkillOptProposer extends SurfaceProposer {
    /** Patch-native path used by `runSkillOpt` (the SkillOpt epoch loop owns
     *  acceptance/budget/buffer). Returns structured patches, NOT surfaces. */
    proposePatches(args: ProposePatchesArgs): Promise<SkillPatch[]>;
}
declare function skillOptProposer(opts: SkillOptProposerOptions): SkillOptProposer;
/** Parse + validate the patch response. Throws `SkillPatchParseError` when the
 *  response is not valid JSON at all (a router/model failure the caller must
 *  see — never a silent no-op epoch). Returns `[]` only for the legitimate
 *  "valid JSON, zero usable patches" case. Malformed ops within a patch are
 *  dropped (not silently mutated); each patch is truncated to the edit budget. */
declare class SkillPatchParseError extends Error {
    constructor(message: string);
}
declare function parseSkillPatchResponse(raw: string, maxPatches: number, editBudget: number): SkillPatch[];

/**
 * `runSkillOpt` — the SkillOpt epoch hill-climb (Microsoft, arXiv:2605.23904).
 * Unlike `runOptimization`'s population/promote-top-K search, SkillOpt is a
 * sequential, held-out-gated hill-climb on ONE skill document:
 *
 *   each epoch:
 *     1. reflect on the CURRENT surface's weakest TRAIN scenarios/dimensions
 *        (never the held-out split — proposals must not see the acceptance axis)
 *     2. propose ≤ `patchesPerEpoch` bounded patches (≤ `editBudget` ops each)
 *     3. apply each; score the candidate on the HELD-OUT split
 *     4. ACCEPT the first patch that STRICTLY improves the held-out composite;
 *        otherwise push it to the rejected-edit buffer (fed back so the model
 *        does not re-propose dead ends)
 *     5. anneal the edit budget down after consecutive rejections (the
 *        "textual learning rate" decay); refresh the slow-update meta note
 *     6. stop at `maxEpochs` or after `patience` epochs with no acceptance
 *
 * The accept-only-if-held-out-improves rule is the same discipline as
 * `HeldOutGate`/`defaultProductionGate`, applied per edit instead of once at
 * the end — which is why the held-out composite is monotonically
 * non-decreasing and a regression can never ship. `runCampaign` is the
 * measurement; `applySkillPatch` applies the edits; `skillOptProposer` proposes
 * them.
 */

interface RunSkillOptOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'scenarios'> {
    /** The skill document being optimized. */
    baselineSurface: string;
    /** Dispatcher taking the CURRENT skill surface + scenario → artifact. */
    dispatchWithSurface: (surface: string, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
    proposer: SkillOptProposer;
    /** Scenarios the optimizer reflects on for evidence. MUST be disjoint from
     *  `holdoutScenarios` — proposals never see the acceptance axis. */
    trainScenarios: TScenario[];
    /** Held-out scenarios. An edit is accepted ONLY if it strictly improves the
     *  mean composite here. */
    holdoutScenarios: TScenario[];
    maxEpochs: number;
    /** Candidate patches proposed per epoch. Default 2. */
    patchesPerEpoch?: number;
    /** Initial ops-per-patch cap (the textual learning rate). Default 3. */
    editBudget?: number;
    /** Strict acceptance margin: accept iff the held-out composite improves by
     *  MORE than this. Default 0 (any strict improvement). */
    minImprovement?: number;
    /** Stop after this many consecutive epochs with no acceptance. Default =
     *  `maxEpochs` (never early-stop). */
    patience?: number;
    /** Shrink the edit budget by 1 after 2 consecutive rejected epochs (min 1).
     *  Default true. */
    budgetAnneal?: boolean;
    /** Cap on the rejected-edit buffer (most-recent kept). Default 12. */
    rejectedBufferSize?: number;
    /** Refresh the slow-update meta note every N epochs. Default 2. 0 disables. */
    slowMetaEvery?: number;
    /** Top-K weak scenarios/dimensions surfaced as evidence each epoch. Default 3. */
    evidenceK?: number;
    /** Abort signal forwarded to the patch-proposing LLM calls. */
    signal?: AbortSignal;
}
interface AcceptedEdit {
    epoch: number;
    label: string;
    rationale: string;
    /** Held-out composite improvement vs the surface before this edit. */
    holdoutDelta: number;
}
interface SkillOptEpochRecord {
    epoch: number;
    editBudget: number;
    proposed: number;
    /** The accepted edit this epoch, or null if every proposal was rejected. */
    accepted: AcceptedEdit | null;
    rejected: RejectedEdit[];
    /** Held-out composite of the CURRENT surface at the END of the epoch. */
    holdoutComposite: number;
}
interface RunSkillOptResult {
    winnerSurface: string;
    baselineHoldoutComposite: number;
    winnerHoldoutComposite: number;
    /** `winnerHoldoutComposite - baselineHoldoutComposite` — monotonically ≥ 0
     *  by construction (only strictly-improving edits are accepted). */
    lift: number;
    acceptedEdits: AcceptedEdit[];
    rejectedEdits: RejectedEdit[];
    epochsRun: number;
    history: SkillOptEpochRecord[];
    /** Total cost across every scoring campaign (train evidence + holdout
     *  acceptance) the hill-climb ran. */
    totalCostUsd: number;
}
declare function runSkillOpt<TScenario extends Scenario, TArtifact>(opts: RunSkillOptOptions<TScenario, TArtifact>): Promise<RunSkillOptResult>;

/**
 * `aceProposer` — Agentic Context Engineering: an APPEND-MOSTLY curator, the
 * deliberate contrast to `memoryCurationProposer`'s dedup-and-replace. ACE's
 * thesis (arXiv:2510.04618) is that aggressively deduping/rewriting a context
 * causes "context collapse" — hard-won specific lessons get summarized away. So
 * the playbook GROWS by appending each generation's new lessons as provenance-
 * tagged delta bullets; existing bullets are preserved verbatim, never merged.
 *
 * Each generation it:
 *  1. reads the playbook block already in the parent surface (verbatim);
 *  2. turns this generation's `findings` into lessons, keeping only the ones not
 *     already present (idempotency — a recurring finding is not re-appended, but
 *     a genuinely NEW lesson always is, even if similar to an old one);
 *  3. appends the new lessons as `- [gN] <lesson>` deltas and re-emits the block.
 *
 * Bounded WITHOUT collapse: when the playbook exceeds `maxEntries`, the OLDEST
 * deltas are evicted (FIFO) — recency is kept, but no two distinct lessons are
 * ever merged into one. Deterministic (no LLM) so a lift is attributable to the
 * accumulated lessons, not a rewrite's model noise.
 *
 * Fail-loud: with no new lesson this generation it returns NO candidate (the
 * playbook is unchanged — nothing to propose), never a fabricated bullet.
 */

interface AceProposerOptions {
    /** Max delta bullets retained in the playbook. On overflow the OLDEST are
     *  evicted (FIFO) — never merged. Default 50 (ACE keeps a long context). */
    maxEntries?: number;
    /** Heading rendered above the bullets inside the block. */
    sectionHeading?: string;
}
declare function aceProposer(opts?: AceProposerOptions): SurfaceProposer;

/**
 * `haloProposer` — wraps the REAL halo-engine (Inference.net's hierarchical
 * agentic trace analyzer, `pip install halo-engine`, repo context-labs/halo)
 * as an agent-eval `SurfaceProposer`, so HALO competes head-to-head with
 * `gepaProposer` — and with our own `traceAnalystProposer` — inside `compareProposers`
 * on identical traces / scenarios / held-out scoring.
 *
 * It PRESERVES halo's actual working usage — `analyze` shells out to the
 * published CLI (`halo <traces.jsonl> -p <prompt> -m <model>`) and uses its real
 * RLM findings verbatim. We do NOT reimplement its analysis; that would make the
 * benchmark meaningless. The materialize/apply pipeline is the shared
 * `analysisEditProposer` — identical to `traceAnalystProposer`, which is what makes
 * the comparison apples-to-apples.
 *
 * Fail-loud: no traces → throw; halo errors → throw; empty findings → throw.
 */

interface HaloProposerOptions {
    /** OpenAI-compatible base URL for BOTH halo's RLM analysis and the apply
     *  step (e.g. the Tangle router `https://router.tangle.tools/v1`). */
    baseUrl: string;
    /** Bearer key (else relies on OPENAI_API_KEY in the env halo inherits). */
    apiKey?: string;
    /** Model for halo's `--model` (its RLM). Default 'gpt-5.4-mini' (halo's own default). */
    model?: string;
    /** Model used to APPLY halo's findings to the prompt surface. Default = `model`. */
    applyModel?: string;
    /** The real halo binary. Default 'halo' (from `pip install halo-engine`). */
    haloBin?: string;
    /** Resolve the OTLP traces (JSONL string) halo should analyze for THIS
     *  generation. Returning empty throws (halo has nothing to analyze). */
    resolveTraces: (ctx: ProposeContext) => string | Promise<string>;
    /** halo's analysis prompt (`-p`). Default targets the failure taxonomy. */
    analysisPrompt?: string;
    /** halo `--max-depth` / `--max-turns` passthrough. */
    maxDepth?: number;
    maxTurns?: number;
    /** Test seam: inject a fetch for the apply-step callLlm (no network in unit tests). */
    fetchImpl?: LlmClientOptions['fetch'];
}
/** Wrap the real halo-engine CLI as a SurfaceProposer (prompt-tier). */
declare function haloProposer(opts: HaloProposerOptions): SurfaceProposer;

/**
 * `memoryCurationProposer` — a CURATOR `SurfaceProposer`, the complement to the
 * OPTIMIZER proposers (`gepaProposer` rewrites the prompt; this one BUILDS a
 * searchable memory of what prior trajectories taught and grafts the most
 * relevant lessons onto the surface).
 *
 * Each generation it:
 *  1. collects lessons — this generation's trace-analyst `findings` PLUS the
 *     memory already carried in the parent surface (so memory accumulates
 *     across generations instead of resetting);
 *  2. curates them — normalizes, deduplicates near-identical lessons, and ranks
 *     by recurrence (a lesson seen across many findings outranks a one-off);
 *  3. retrieves the top-K and writes them back as a single delimited memory
 *     block in the surface (idempotent — the block is replaced, never stacked,
 *     so the prompt does not grow without bound).
 *
 * This is the substrate behind the "knowledge base of working trajectories" the
 * agent searches: the curated block IS the retrieved memory the next run reads.
 * Curation is DETERMINISTIC (no LLM) so a lift it produces is attributable to
 * the lessons, not to model noise in a rewrite. An optional `distill` LLM step
 * can compress raw findings into crisp imperatives; default is verbatim.
 *
 * Fail-loud: never fabricates a lesson. With no findings and no prior memory it
 * returns no candidate (nothing learned yet — gen 0). It does not throw on an
 * empty generation because early generations legitimately have no findings.
 */

interface MemoryCurationProposerOptions {
    /** Top-K lessons retained in the surface memory block. Default 12. */
    maxEntries?: number;
    /** Heading rendered above the lessons inside the block. Default below. */
    sectionHeading?: string;
    /**
     * Optional LLM distillation: compress raw findings into crisp, generalizable
     * one-line imperatives before curating. Omit for verbatim (deterministic).
     */
    distill?: {
        baseUrl: string;
        apiKey?: string;
        model: string;
        fetchImpl?: LlmClientOptions['fetch'];
    };
}
/** Build the CURATOR proposer. */
declare function memoryCurationProposer(opts?: MemoryCurationProposerOptions): SurfaceProposer;

/**
 * `traceAnalystProposer` — wraps agent-eval's OWN trace-analyst engine
 * (`AnalystRegistry` over the agentic OTLP reader) as a `SurfaceProposer`.
 * It is the symmetric opponent to `haloProposer`: both run the SAME shared
 * `analysisEditProposer` pipeline (materialize identical traces → apply via one
 * identical LLM edit), so a `compareProposers` lift delta isolates a single
 * variable — ANALYSIS QUALITY. The benchmark answers "is our HALO clone as good
 * as the real HALO?" as a held-out lift CI, not a vibe.
 *
 * Findings come from the REGISTRY (structured `AnalystFinding[]` carrying
 * area / severity / recommended_action), rendered into the report the shared
 * apply step consumes.
 *
 * Fail-loud: no traces → throw; analyst run errors → throw; zero findings →
 * throw. Never fabricate a candidate.
 */

interface TraceAnalystProposerOptions {
    /** OpenAI-compatible base URL for BOTH the analyst's agentic reads and the
     *  apply step (e.g. `https://api.deepseek.com/v1` or the Tangle router). */
    baseUrl: string;
    /** Bearer key. Required — the Ax AI service has no env fallback here. */
    apiKey: string;
    /** Model the analyst kinds use for their agentic trace reads. */
    model: string;
    /** Model used to APPLY findings to the prompt surface. Default = `model`.
     *  Keep this EQUAL to haloProposer's `applyModel` for an apples-to-apples run. */
    applyModel?: string;
    /** Ax provider name. Default 'openai' — works for any OpenAI-compatible base
     *  via `apiURL`. Use 'deepseek' to hit DeepSeek's native provider. */
    provider?: string;
    /** Which analyst kinds to run. Default = the full shipped suite. */
    kinds?: readonly TraceAnalystKindSpec[];
    /** Resolve the OTLP traces (JSONL string) the analyst should read for THIS
     *  generation — identical contract to `haloProposer.resolveTraces`. */
    resolveTraces: (ctx: ProposeContext) => string | Promise<string>;
    /** Override the findings producer. Default: the shipped `AnalystRegistry`
     *  over `kinds`. The unit suite injects canned findings here. */
    analyze?: (tracePath: string, ctx: ProposeContext) => Promise<ReadonlyArray<AnalystFinding>>;
    /** Test seam: inject a fetch for the apply-step `callLlm`. */
    fetchImpl?: LlmClientOptions['fetch'];
}
/** Wrap agent-eval's trace-analyst registry as a SurfaceProposer (prompt-tier). */
declare function traceAnalystProposer(opts: TraceAnalystProposerOptions): SurfaceProposer;

/**
 * Shared campaign-score reductions used by every optimizer preset
 * (`runOptimization`, `runSkillOpt`, `compareProposers`). ONE definition of
 * "composite of a campaign" and "per-scenario / per-dimension breakdown" so
 * the optimizers cannot drift on how a surface's score is computed.
 */

/** Mean composite across a campaign: per cell, the mean of its judges'
 *  composites; then the mean across cells. Cells with no judge scores are
 *  skipped. Empty ⇒ 0. */
declare function campaignMeanComposite<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): number;
interface CampaignBreakdown {
    /** Mean score per judge dimension across all cells. */
    dimensions: Record<string, number>;
    /** Per-scenario composite (mean over reps + judges) + the judge's free-form
     *  `notes` for that scenario (the "why" a reflective proposer grounds on). */
    scenarios: Array<{
        scenarioId: string;
        composite: number;
        notes?: string;
    }>;
}
/** Per-candidate evidence a reflective/patch proposer grounds its next proposal
 *  on: mean score per judge dimension + per-scenario composite. */
declare function campaignBreakdown<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): CampaignBreakdown;

/**
 * VCS-pluggable worktree adapter. One improvement = one worktree, PR-like
 * (multiple commits allowed). A code-tier proposer'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 proposer code. Only the git adapter
 * ships today. See `docs/design/loop-taxonomy.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 { type AcceptedEdit, type AceProposerOptions, type AnalystArtifact, type AnalystScenario, type ApplySkillPatchResult, type BuildAnalystSurfaceDispatchOptions, type CampaignBreakdown, CampaignResult, CampaignStorage, CodeSurface, type CompareProposersOptions, type DimensionRegression, DispatchContext, type FailureModeRecallJudgeOptions, type FapoAttributionSignals, type FapoEntryConfig, type FapoFailureCluster, type FapoOptimizationLevel, type FapoProposerOptions, type FapoReviewInput, type FapoReviewIssue, type FapoReviewResult, type FapoScopeContract, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, Gate, GenerationRecord, type GitWorktreeAdapterOptions, type HaloProposerOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type JsonPrimitive, type JsonValue, JudgeConfig, JudgeScore, LabelTrust, LabeledScenarioRecord, LabeledScenarioSampleArgs, LabeledScenarioSource, LabeledScenarioStore, LabeledScenarioStoreError, LabeledScenarioWrite, type MemoryCurationProposerOptions, MutableSurface, type OptimizerEntryConfig, type PairedHoldout, type ParameterCandidate, type ParameterChange, type ParameterSweepProposerOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, ProposeContext, type ProposePatchesArgs, ProposedCandidate, type ProposerComparison, type ProposerEntry, type ProposerPairwise, type ProposerScore, type RejectedEdit, RunCampaignOptions, RunImprovementLoopOptions, type RunProfileMatrixOptions, type RunProfileMatrixResult, type RunSkillOptOptions, type RunSkillOptResult, Scenario, type ScenarioRollup, type ScoreboardRenderOptions, type ScoreboardRow, type ScoreboardSummary, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SkillOptEpochRecord, type SkillOptEvidence, type SkillOptProposer, type SkillOptProposerOptions, type SkillPatch, type SkillPatchOp, SkillPatchParseError, type SkillPatchRejection, SurfaceProposer, type TraceAnalystProposerOptions, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, aceProposer, applySkillPatch, buildAnalystSurfaceDispatch, campaignBreakdown, campaignMeanComposite, compareProposers, detectScale, dimensionRegressions, extractFapoAttributionSignals, failureModeRecallJudge, fapoEscalationEntry, fapoProposer, gepaParetoEntry, gepaReflectionEntry, gitWorktreeAdapter, haloProposer, heldoutSignificance, makePlaybackDispatch, memoryCurationProposer, pairHoldout, parameterSweepProposer, parseSkillPatchResponse, patchEditCount, renderScoreboardMarkdown, resolveWorktreePath, runProfileMatrix, runSkillOpt, scoreUserStory, scoreboardSummary, sequentialDecide, sequentialPairedGate, skillOptEntry, skillOptProposer, traceAnalystProposer, userStoryScoreboard };
