@tangle-network/agent-eval 1.0.38 → 1.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/adapters/http.d.ts +1 -1
  3. package/dist/{agent-profile-BKgR30kv.d.ts → agent-profile-hytrwAnN.d.ts} +166 -166
  4. package/dist/agent-profile-hytrwAnN.d.ts.map +1 -0
  5. package/dist/analyst/index.d.ts +2 -2
  6. package/dist/analyst/index.js +5 -5
  7. package/dist/app-grade/index.d.ts +1 -1
  8. package/dist/{benchmark-command-BpmrrgzA.js → benchmark-command-CJw3ijDV.js} +5 -5
  9. package/dist/{benchmark-command-BpmrrgzA.js.map → benchmark-command-CJw3ijDV.js.map} +1 -1
  10. package/dist/benchmarks/index.d.ts +1 -1
  11. package/dist/benchmarks/index.js +2 -2
  12. package/dist/campaign/index.d.ts +3 -3
  13. package/dist/campaign/index.js +3 -3
  14. package/dist/{campaign-BU6bJNvu.js → campaign-DawSkDag.js} +3 -3
  15. package/dist/{campaign-BU6bJNvu.js.map → campaign-DawSkDag.js.map} +1 -1
  16. package/dist/{statistical-heldout-RmdXoz2e.d.ts → campaign-evidence-C1c6uihA.d.ts} +413 -413
  17. package/dist/campaign-evidence-C1c6uihA.d.ts.map +1 -0
  18. package/dist/cli.js +1 -1
  19. package/dist/contract/index.d.ts +5 -5
  20. package/dist/contract/index.js +4 -4
  21. package/dist/{default-registry-CpGvgSYQ.js → default-registry-BE5Rj9ba.js} +8 -32
  22. package/dist/default-registry-BE5Rj9ba.js.map +1 -0
  23. package/dist/default-registry-C5x2jyD6.d.ts.map +1 -1
  24. package/dist/{define-agent-eval-4KGwzIVt.d.ts → define-agent-eval-C4yoCqkc.d.ts} +3 -4
  25. package/dist/define-agent-eval-C4yoCqkc.d.ts.map +1 -0
  26. package/dist/{define-agent-eval-BeLMK-OM.js → define-agent-eval-CyU7eAzj.js} +5 -4
  27. package/dist/define-agent-eval-CyU7eAzj.js.map +1 -0
  28. package/dist/{dspy-rlm-engine-EC-Pkdf-.js → dspy-rlm-engine-aM1RWOUT.js} +2 -2
  29. package/dist/{dspy-rlm-engine-EC-Pkdf-.js.map → dspy-rlm-engine-aM1RWOUT.js.map} +1 -1
  30. package/dist/experiment/index.d.ts +1 -1
  31. package/dist/{feedback-trajectory-FamLu3Wt.d.ts → feedback-trajectory-CCWiFzeE.d.ts} +2 -2
  32. package/dist/{feedback-trajectory-FamLu3Wt.d.ts.map → feedback-trajectory-CCWiFzeE.d.ts.map} +1 -1
  33. package/dist/{findings-store-71J302Ls.js → findings-store-B8pq8Rhr.js} +3 -3
  34. package/dist/{findings-store-71J302Ls.js.map → findings-store-B8pq8Rhr.js.map} +1 -1
  35. package/dist/{index-BsTGJf2M.d.ts → index-BuuUhU_V.d.ts} +9 -9
  36. package/dist/{index-BsTGJf2M.d.ts.map → index-BuuUhU_V.d.ts.map} +1 -1
  37. package/dist/{index-CzEGCOWM.d.ts → index-CXoFLNKI.d.ts} +4 -4
  38. package/dist/{index-CzEGCOWM.d.ts.map → index-CXoFLNKI.d.ts.map} +1 -1
  39. package/dist/{index-RBV2Y-7X.d.ts → index-HdlzN11G.d.ts} +2 -2
  40. package/dist/{index-RBV2Y-7X.d.ts.map → index-HdlzN11G.d.ts.map} +1 -1
  41. package/dist/index.d.ts +11 -11
  42. package/dist/index.js +8 -8
  43. package/dist/{kind-factory-BTUq1Byh.js → kind-factory-B5FfFE5G.js} +20 -2
  44. package/dist/{kind-factory-BTUq1Byh.js.map → kind-factory-B5FfFE5G.js.map} +1 -1
  45. package/dist/{llm-judge-BBHrAlcE.js → llm-judge-DHgx29ro.js} +74 -20
  46. package/dist/llm-judge-DHgx29ro.js.map +1 -0
  47. package/dist/openapi.json +1 -1
  48. package/dist/{researcher-k925Q6Jb.d.ts → researcher-DvFDa1o1.d.ts} +2 -2
  49. package/dist/{researcher-k925Q6Jb.d.ts.map → researcher-DvFDa1o1.d.ts.map} +1 -1
  50. package/dist/rl.d.ts +1 -1
  51. package/dist/{index-OvU1UXKC.d.ts → run-improvement-loop-BAxDnaPI.d.ts} +1619 -1619
  52. package/dist/run-improvement-loop-BAxDnaPI.d.ts.map +1 -0
  53. package/dist/{skillopt-optimization-method-BmfnAzG4.js → skillopt-optimization-method-Du3GbReg.js} +10 -4
  54. package/dist/{skillopt-optimization-method-BmfnAzG4.js.map → skillopt-optimization-method-Du3GbReg.js.map} +1 -1
  55. package/dist/{store-otlp-DQK9hCtH.js → store-otlp-DHc_E78m.js} +2 -2
  56. package/dist/{store-otlp-DQK9hCtH.js.map → store-otlp-DHc_E78m.js.map} +1 -1
  57. package/dist/{store-tool-spans-BRR9hsPP.js → store-tool-spans-BR4IhZYZ.js} +3 -3
  58. package/dist/{store-tool-spans-BRR9hsPP.js.map → store-tool-spans-BR4IhZYZ.js.map} +1 -1
  59. package/dist/traces.js +3 -3
  60. package/dist/wire/index.d.ts +3 -3
  61. package/package.json +1 -1
  62. package/dist/agent-profile-BKgR30kv.d.ts.map +0 -1
  63. package/dist/default-registry-CpGvgSYQ.js.map +0 -1
  64. package/dist/define-agent-eval-4KGwzIVt.d.ts.map +0 -1
  65. package/dist/define-agent-eval-BeLMK-OM.js.map +0 -1
  66. package/dist/index-OvU1UXKC.d.ts.map +0 -1
  67. package/dist/llm-judge-BBHrAlcE.js.map +0 -1
  68. package/dist/statistical-heldout-RmdXoz2e.d.ts.map +0 -1
@@ -7,15 +7,15 @@ import { F as PairedBootstrapResult } from "./index-Bcy00QoN.js";
7
7
  import { E as SearchExecutionIdentity, G as SearchSplit, V as SearchProposer, a as SearchAttemptAccounting, i as SearchArtifactRef, j as SearchModelIdentity, nt as EvaluationClaim, rt as EvaluationUnitSummary, tt as SearchUnknown, z as SearchOperationRecordedEvent } from "./search-ledger-types-qiYRUo_N.js";
8
8
  import { r as LedgerHash } from "./canonical-gLeHiqzd.js";
9
9
  import { C as JudgeDimension, H as SurfaceProposer, N as ParetoParent, O as LabeledScenarioSource, R as Scenario, S as JudgeConfig, _ as GateDecision, a as CampaignResult, b as GenerationRecord, c as CampaignTraceWriter, d as DispatchContext, f as DispatchFn, g as GateContribution, i as CampaignCostMeter, j as MutableSurface, k as LabeledScenarioStore, l as CodeSurface, o as CampaignScenarioIdentity, p as Gate, r as CampaignCellResult, u as ComponentSurface, v as GateResult, y as GenerationCandidate } from "./types-DGqGbNY4.js";
10
- import { Dt as FinalEvidenceRecord, M as PairedArmsComparison, at as CampaignEvidenceContext, dt as EvidenceReceipt, wt as FinalEvidenceLedger } from "./statistical-heldout-RmdXoz2e.js";
10
+ import { Dt as FinalEvidenceRecord, pt as PairedArmsComparison, s as EvidenceReceipt, t as CampaignEvidenceContext, wt as FinalEvidenceLedger } from "./campaign-evidence-C1c6uihA.js";
11
11
  import { Q as SearchRecorder, X as SearchLedgerBinding, Y as RegisterSearchNodeInput, _t as CampaignStorage, et as SearchRunIdentity, ft as SearchHistoryReceipt, i as RunSearchOptions, lt as SearchHistoryCoverage, o as SearchCellResult, st as SearchHistoryAdmissionOptions, v as SearchPolicy } from "./search-kernel-DRHWY35J.js";
12
12
  import { a as PairedPromotionDecision } from "./paired-promotion-decision-BBSxTo-h.js";
13
13
  import { n as ModelTreatment, t as ModelComparison } from "./model-comparison-BHNL8Qrn.js";
14
- import { E as AnalystIssueExpectation, G as ExternalOptimizerRunnerCommand, I as ExternalOptimizerEvaluationObservation, J as ExternalTextEvaluationRequest, K as ExternalOptimizerWireCounts, N as ExternalOptimizerCallbackLimits, R as ExternalOptimizerModelBudget, W as ExternalOptimizerResumeMode, m as AnalystBenchmarkLabelState, q as ExternalTextCandidate, t as AgentProfile$1, u as AnalystBenchmarkCase, z as ExternalOptimizerModelCall } from "./agent-profile-BKgR30kv.js";
14
+ import { C as ExternalOptimizerResumeMode, D as ExternalTextEvaluationRequest, E as ExternalTextCandidate, M as AnalystBenchmarkLabelState, O as AnalystBenchmarkCase, T as ExternalOptimizerWireCounts, W as AnalystIssueExpectation, _ as ExternalOptimizerModelBudget, f as ExternalOptimizerCallbackLimits, h as ExternalOptimizerEvaluationObservation, t as AgentProfile$1, v as ExternalOptimizerModelCall, w as ExternalOptimizerRunnerCommand } from "./agent-profile-hytrwAnN.js";
15
15
  import { r as DatasetScenario, t as Dataset } from "./dataset-DThC1S6G.js";
16
16
  import { t as DetectRewardHackingInput } from "./reward-hacking-CLMvxEY_.js";
17
- import { f as TraceSpanEvent, t as HostedClient } from "./client-BIFwUg7I.js";
18
17
  import { n as CompletionVerdict, o as ProducedState, r as CorrectnessChecker, t as CompletionRequirement } from "./completion-verifier-oAgSwdFe.js";
18
+ import { f as TraceSpanEvent, t as HostedClient } from "./client-BIFwUg7I.js";
19
19
  import { AgentProfile } from "@tangle-network/agent-interface";
20
20
  import { z } from "zod";
21
21
  /** Base error for invalid search-ledger input or operations. */
@@ -356,203 +356,6 @@ interface OpenAutoPrResult {
356
356
  * Open a GitHub PR for a gate-approved surface promotion, attaching the manifest hash, gate verdict, and diff as the PR body.
357
357
  */
358
358
  declare function openAutoPr<TArtifact, TScenario extends Scenario>(options: OpenAutoPrOptions<TArtifact, TScenario>): OpenAutoPrResult;
359
- /** Improve a surface as a search on the kernel; see the module comment. */
360
- declare function runOptimization<TScenario extends Scenario, TArtifact>(opts: RunOptimizationOptions<TScenario, TArtifact>): Promise<RunOptimizationResult<TArtifact, TScenario>>;
361
- /** Optimization inputs, immutable proposal snapshots, and imported baseline validation. */
362
- interface PremeasuredOptimizationBaseline<TArtifact, TScenario extends Scenario> {
363
- /** Hash of the exact surface that produced `campaign`. */
364
- surfaceHash: string;
365
- /** Complete prior measurement reused by identity, including artifactsByPath. */
366
- campaign: CampaignResult<TArtifact, TScenario>;
367
- }
368
- interface RunOptimizationOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch'> {
369
- /** Initial mutable surface (typically system prompt or addendum). */
370
- baselineSurface: MutableSurface;
371
- /**
372
- * Complete prior measurement of `baselineSurface`. When present,
373
- * `runOptimization` validates its surface, scenario split, seed, reps, and
374
- * normal campaign coverage, then records its cells as the root's instead of
375
- * dispatching them. Prior spend stays in the imported campaign aggregates and
376
- * is not added again to this run's CostLedger.
377
- */
378
- premeasuredBaseline?: PremeasuredOptimizationBaseline<TArtifact, TScenario>;
379
- /** Dispatcher that takes a surface and a scenario to an artifact. */
380
- dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: Parameters<RunCampaignOptions<TScenario, TArtifact>['dispatch']>[1]) => Promise<TArtifact>;
381
- /** The candidate-generation strategy. */
382
- proposer: SurfaceProposer<ProposalFinding>;
383
- /** Candidates asked of each proposal. */
384
- populationSize: number;
385
- /** Proposals the search may make. */
386
- maxGenerations: number;
387
- /** Scales the run's cell lanes: at most `candidateConcurrency *
388
- * maxConcurrency` cells run at once. Default 1. */
389
- candidateConcurrency?: number;
390
- /** DEPTH knob forwarded to the proposer's `propose()`: max iterations the
391
- * agentic generator may take per candidate. */
392
- maxImprovementShots?: number;
393
- /** Search or observed-production findings forwarded to candidate generation. */
394
- findings?: ReadonlyArray<ProposalFinding>;
395
- /** Findings producer. Before each proposal it runs on the previous
396
- * generation's measured candidates (the baseline, as `generation: -1`,
397
- * before the first), and what it returns REPLACES `ctx.findings` for that
398
- * proposal. The substrate does not import an analyst: the consumer plugs its
399
- * trace-analyst registry here, reading the per-candidate `runDir` traces.
400
- * When absent, findings stay the static `opts.findings`. Its spend is
401
- * booked to the proposal's operation. */
402
- analyzeGeneration?: (input: {
403
- generation: number;
404
- runDir: string;
405
- candidates: Array<{
406
- surfaceHash: string;
407
- campaign: CampaignResult<TArtifact, TScenario>;
408
- composite: number | null;
409
- }>;
410
- history: GenerationRecord[];
411
- /** Shared run spend account and receipt attribution phase. */
412
- costLedger?: CostLedgerHandle;
413
- costPhase?: string;
414
- }) => Promise<ReadonlyArray<ProposalFinding>>;
415
- /** Which node each proposal extends, and which node the run keeps. Default
416
- * `incumbent()`: the hill climb. `crowdedFrontierParent({ seed })` draws
417
- * the parent from the Pareto frontier instead; `aide()` drafts, debugs and
418
- * improves with Thompson-sampled parents, and `beam({ width })` expands the
419
- * top nodes in turn. Every policy ranks on the scenarios, and the run keeps
420
- * the `uniform` allocator, because the proposer reads every candidate's
421
- * score on every scenario. */
422
- policy?: SearchPolicy;
423
- /** Where the search ledger goes and the identities it records. Default: a
424
- * ledger at `<runDir>/search/ledger.jsonl`, held in `storage` unless that is
425
- * the filesystem, whose identities are the dispatch ref's and proposer's
426
- * digests. */
427
- searchLedger?: SearchLedgerBinding;
428
- }
429
- interface RunOptimizationResult<TArtifact, TScenario extends Scenario> {
430
- /** One entry per proposal, with the candidates it registered. */
431
- generations: Array<{
432
- record: GenerationRecord;
433
- surfaces: Array<{
434
- surfaceHash: string;
435
- surface: MutableSurface;
436
- campaign: CampaignResult<TArtifact, TScenario>;
437
- }>;
438
- }>;
439
- /** Frozen snapshot of the exact starting surface measured by `baselineCampaign`. */
440
- baselineSurface: MutableSurface;
441
- winnerSurface: MutableSurface;
442
- winnerSurfaceHash: string;
443
- /** Proposer label for the kept surface; absent when the winner is the baseline. */
444
- winnerLabel?: string;
445
- /** Proposer rationale for the kept surface, as stored: redacted with the
446
- * share profile. Absent when the winner is the baseline. */
447
- winnerRationale?: string;
448
- baselineCampaign: CampaignResult<TArtifact, TScenario>;
449
- /** Run-wide spend, including agents, proposers, analysts, and judges. */
450
- cost: CostLedgerSummary;
451
- /** Bounded proof envelope over the search ledger. */
452
- searchHistory: SearchHistoryReceipt;
453
- /** The non-dominated set of measured surfaces by per-scenario composite. */
454
- paretoFrontier: ParetoParent[];
455
- }
456
- type RunImprovementLoopOptions<TScenario extends Scenario, TArtifact> = RunOptimizationOptions<TScenario, TArtifact> & {
457
- /** Holdout scenarios kept OUT of the training optimization pool — used
458
- * ONLY to score baseline vs winner for the gate. */
459
- holdoutScenarios: TScenario[];
460
- claim?: EvaluationClaim;
461
- finalEvidence?: FinalEvidencePolicy;
462
- /** Snapshot identity for agents without model receipts. Receipts take precedence. */
463
- model?: string;
464
- /** Declare a model change as part of the treatment before search starts. */
465
- modelTreatment?: ModelTreatment;
466
- /** Require one reported model id per arm (two spellings of one snapshot count as two), even
467
- * when neither arm reports a model call. Enabled by selfImprove. */
468
- requireReportedModel?: boolean;
469
- /** Holdout policy. Default `'measured'`: baseline + winner are re-scored on
470
- * `holdoutScenarios` and the gate decides on that held-out comparison.
471
- * `'deferred'`: the improvement-set (search) campaigns run exactly as usual,
472
- * but ZERO holdout cells are dispatched, the gate is forced to `'hold'`, and
473
- * the result + provenance record carry `holdout: 'deferred'` with NO
474
- * held-out lift — for callers that measure the held-out comparison in a
475
- * separate later run instead of faking a static holdout scenario and
476
- * recording a meaningless lift. */
477
- holdout?: 'measured' | 'deferred';
478
- /** Promotion gate. Substrate strongly recommends `defaultProductionGate`
479
- * for production wiring (composes red-team / reward-hacking / canary /
480
- * heldout). */
481
- gate: Gate<TArtifact, TScenario>;
482
- /** What to do when the gate ships:
483
- * - `'pr'`: open a PR via `openAutoPr`
484
- * - `'none'`: just report — caller decides what to do with the winner
485
- * Live-runtime self-mutation is intentionally unsupported. */
486
- autoOnPromote: 'pr' | 'none';
487
- /** GH owner / repo for the auto-PR. Required when autoOnPromote === 'pr'. */
488
- ghOwner?: string;
489
- ghRepo?: string;
490
- /** Placebo control. When supplied AND the winner differs from baseline, the
491
- * loop scores a THIRD holdout arm: the winner surface with its content
492
- * footprint-matched-blanked by this function (typically via `neutralizeText`).
493
- * Its scores are exposed to the gate as `ctx.neutralizedJudgeScores`, letting
494
- * a `neutralizationGate` reject a win whose lift survives blanking the content
495
- * (decorative — driven by footprint, not content). Costs one extra holdout
496
- * campaign; omit to skip. Return a byte/layout-matched blank of the winner. */
497
- neutralize?: (winnerSurface: MutableSurface, baselineSurface: MutableSurface) => MutableSurface;
498
- };
499
- interface RunImprovementLoopResult<TArtifact, TScenario extends Scenario> extends RunOptimizationResult<TArtifact, TScenario> {
500
- baselineOnHoldout: CampaignResult<TArtifact, TScenario>;
501
- winnerOnHoldout: CampaignResult<TArtifact, TScenario>;
502
- neutralizedOnHoldout?: CampaignResult<TArtifact, TScenario>;
503
- neutralizedSurface?: MutableSurface;
504
- gateResult: Awaited<ReturnType<Gate<TArtifact, TScenario>['decide']>>;
505
- claim?: EvaluationClaim;
506
- finalEvidence?: FinalEvidenceUse;
507
- modelComparison: ModelComparison;
508
- /** Present iff the loop ran with `holdout: 'deferred'`. When set,
509
- * `baselineOnHoldout`/`winnerOnHoldout` are the shared EMPTY campaign (zero
510
- * cells dispatched) and the gate verdict is the forced `'hold'`. */
511
- holdout?: 'deferred';
512
- /** Unified baseline→winner surface diff. Computed UNCONDITIONALLY (not only
513
- * when `autoOnPromote === 'pr'`) so the diff that the gate decided on is
514
- * always present on the result + in the emitted provenance record. Empty
515
- * string when winner == baseline (no change to diff). */
516
- promotedDiff: string;
517
- prResult?: ReturnType<typeof openAutoPr>;
518
- }
519
- /**
520
- * Gated-promotion shell over `runOptimization`: scores the winner against the baseline on a holdout set, runs the release gate, and optionally opens a PR.
521
- */
522
- declare function runImprovementLoop<TScenario extends Scenario, TArtifact>(opts: RunImprovementLoopOptions<TScenario, TArtifact>): Promise<RunImprovementLoopResult<TArtifact, TScenario>>;
523
- interface TransientFailureOptions {
524
- /**
525
- * Treat full-duration timeouts ("timeout after 180000ms") as transient.
526
- * Enable on saturated shared infrastructure where queue starvation eats
527
- * the clock; leave off when the agent had the resources and simply failed.
528
- * Default false.
529
- */
530
- readonly retryFullDurationTimeouts?: boolean;
531
- /** Additional caller-specific transient patterns. */
532
- readonly extraPatterns?: readonly RegExp[];
533
- /**
534
- * The instant a dated quota refusal is measured against. Defaults to `Date.now()`; inject it
535
- * to replay a past classification, which is what a retry audit needs.
536
- */
537
- readonly now?: number;
538
- }
539
- /**
540
- * True when the error text describes an infrastructure hiccup that should be
541
- * retried rather than scored. Empty/undefined input is not transient.
542
- */
543
- declare function isTransientTransportFailure(message: string | null | undefined, opts?: TransientFailureOptions): boolean;
544
- /**
545
- * Ready-made `cellRetry.retryable` predicate: true for a dispatch-stage
546
- * failure whose error message `isTransientTransportFailure` classifies as an
547
- * infrastructure hiccup. A judge-stage failure is never retried here — the
548
- * dispatch already produced an artifact, so re-dispatching would score a
549
- * different sample. A per-cell dispatch deadline ("dispatch exceeded <N>ms")
550
- * is not transient by default; opt in via `extraPatterns` or
551
- * `retryFullDurationTimeouts` when queue starvation eats the clock. A provider refusal that
552
- * states its own release time is never retried while that time is in the future
553
- * (`quotaExhaustedUntil`).
554
- */
555
- declare function transientDispatchFailure(opts?: TransientFailureOptions): (failure: CampaignCellFailureReceipt['failure']) => boolean;
556
359
  /** A rubric dimension as a bare key or the full `{ key, description }` shape. A
557
360
  * bare string uses the key as its own description. */
558
361
  type LlmJudgeDimension = string | JudgeDimension;
@@ -650,1497 +453,1081 @@ interface ReferenceEquivalenceJudgeResult extends LlmCallMetadata {
650
453
  score: number;
651
454
  rationale: string;
652
455
  }
653
- interface ExternalOptimizerObservationSummary {
654
- scope: 'callback-submitted-candidates';
655
- path: string;
656
- sha256: `sha256:${string}`;
657
- submittedCandidates: number;
658
- evaluations: number;
659
- refusals: number;
660
- }
661
- interface ExternalOptimizerExecutionSummary {
662
- scope: 'runtime-model-calls';
663
- path: string;
664
- sha256: `sha256:${string}`;
665
- calls: number;
666
- succeeded: number;
667
- failed: number;
456
+ interface TraceAnalystScenario extends Scenario {
457
+ kind: 'trace-analyst';
458
+ traceStore: TraceAnalysisStore;
459
+ labelState: AnalystBenchmarkLabelState;
460
+ expectedIssues: readonly AnalystIssueExpectation[];
461
+ labeledEvidence?: AnalystBenchmarkCase['labeledEvidence'];
668
462
  }
669
- interface ExternalOptimizerSubmittedCandidate {
670
- /** Exact text or named-component surface submitted to the evaluation callback. */
671
- readonly candidate: ExternalTextCandidate;
672
- /** Eval's canonical content identity for `candidate`. */
673
- readonly candidateHash: string;
674
- readonly candidateDigest: `sha256:${string}`;
675
- readonly proposalSequence: number;
676
- /** Exact observation artifact that proves this candidate was submitted. */
677
- readonly provenance: {
678
- readonly path: string;
679
- readonly sha256: `sha256:${string}`;
680
- };
463
+ interface TraceAnalystArtifact {
464
+ findings: readonly AnalystFinding[];
465
+ usage?: AnalystUsageReceipt;
466
+ run?: AnalystRunResult;
681
467
  }
682
- interface ExternalOptimizerObservationArtifact {
683
- readonly summary: ExternalOptimizerObservationSummary;
684
- readonly observations: readonly ExternalOptimizerEvaluationObservation[];
685
- /** Every distinct callback-submitted candidate in proposal order. */
686
- readonly candidates: readonly ExternalOptimizerSubmittedCandidate[];
468
+ interface BuildTraceAnalystSurfaceDispatchOptions {
469
+ analyze(input: {
470
+ instructions: string;
471
+ traceStore: TraceAnalysisStore;
472
+ runId: string;
473
+ signal: AbortSignal;
474
+ }): Promise<TraceAnalystArtifact>;
687
475
  }
688
- /**
689
- * Read and verify the exact callback observation artifact addressed by method provenance.
690
- *
691
- * The reader checks the raw SHA-256, canonical JSONL bytes, sequence, candidate
692
- * identities, and summary counts before it returns any candidate.
693
- * This proves that the bytes match the supplied summary. The caller remains
694
- * responsible for obtaining that summary from trusted provenance.
695
- */
696
- declare function readExternalOptimizerObservationArtifact(input: {
697
- summary: ExternalOptimizerObservationSummary;
698
- storage?: CampaignStorage;
699
- }): ExternalOptimizerObservationArtifact;
700
- interface GepaCandidatePopulationSummary {
701
- readonly scope: 'gepa-candidate-population';
702
- readonly path: string;
703
- readonly sha256: `sha256:${string}`;
704
- readonly bytes: number;
705
- readonly runId: string;
706
- readonly candidates: number;
707
- readonly bestIndex: number;
708
- readonly maxCandidates: number;
709
- readonly maxCandidateChars: number;
710
- readonly scenarioIds: readonly string[];
711
- readonly surfaceKind: 'text' | 'components';
712
- }
713
- interface GepaCandidateSelectionScore {
714
- readonly scenarioId: string;
715
- readonly score: number;
476
+ /** Read the source rates for this execution, never a copied model price table.
477
+ * inputTokens includes cachedTokens. Seat credits are standard model credits;
478
+ * discounts and MCP charges require provider observations, not token guesses.
479
+ * The existing USD receipt remains the Router charge. Sandbox is additional.
480
+ */
481
+ declare function measureCampaignCost(input: {
482
+ routerUsd?: number;
483
+ sandbox?: {
484
+ seconds: number;
485
+ cpu: number;
486
+ memoryGB: number;
487
+ diskGB: number;
488
+ pool?: string;
489
+ };
490
+ seat?: {
491
+ model: string;
492
+ usage: CostUsage & {
493
+ usageUnknown?: boolean;
494
+ };
495
+ };
496
+ signal?: AbortSignal;
497
+ }): Promise<CostBreakdown>;
498
+ /** Whether one candidate attempt produced a usable executable outcome. */
499
+ type CrossSurfaceAttemptCompleteness = 'complete' | 'missing' | 'invalid';
500
+ /** One independently proposed change on one caller-defined surface. */
501
+ interface CrossSurfaceComponent {
502
+ componentId: string;
503
+ surfaceId: string;
504
+ /** Explicitly controls whether this component may anchor the best-single arm. */
505
+ bestSingleEligible: boolean;
716
506
  }
717
- interface GepaCandidatePopulationCandidate {
718
- /** Zero-based index assigned by the exact GEPA result. */
719
- readonly index: number;
720
- readonly candidate: ExternalTextCandidate;
721
- readonly candidateHash: string;
722
- readonly candidateDigest: `sha256:${string}`;
723
- /** Exact GEPA parent indices. The seed candidate has one null parent. */
724
- readonly parentIndices: readonly (number | null)[];
725
- /** Null means GEPA had no selection score for this candidate. */
726
- readonly aggregateScore: number | null;
727
- readonly selectionScores: readonly GepaCandidateSelectionScore[];
728
- readonly discoveryEvaluationCount: number;
507
+ /** Immutable identity for a single candidate or a materialized composition. */
508
+ interface CrossSurfaceCandidate {
509
+ candidateId: string;
510
+ componentIds: string[];
511
+ contentHash: string;
512
+ artifactBytes: number;
729
513
  }
730
- interface GepaCandidatePopulationArtifact {
731
- readonly summary: GepaCandidatePopulationSummary;
732
- readonly runId: string;
733
- readonly bestIndex: number;
734
- readonly candidates: readonly GepaCandidatePopulationCandidate[];
514
+ /** Per-component trace evidence captured during one task attempt. */
515
+ interface CrossSurfaceComponentEvidence {
516
+ componentId: string;
517
+ /** null means the trace could not establish whether the component fired. */
518
+ fired: boolean | null;
519
+ /** null means the trace could not establish whether the component changed behavior. */
520
+ effectObserved: boolean | null;
735
521
  }
736
522
  /**
737
- * Read GEPA's exact candidate graph from the artifact addressed by method provenance.
738
- *
739
- * The reader checks the supplied digest, declared byte count, run identity,
740
- * candidate surfaces, parent graph, selection scores, and configured bounds.
741
- * This proves that the bytes match the supplied summary. The caller remains
742
- * responsible for obtaining that summary from trusted method provenance.
523
+ * Canonical per-task input row. Consumers may extend this interface with
524
+ * receipt, trace, retry, or failure details; the report preserves the original
525
+ * row object rather than projecting those details away.
743
526
  */
744
- declare function readGepaCandidatePopulationArtifact(input: {
745
- summary: GepaCandidatePopulationSummary;
746
- storage?: CampaignStorage;
747
- }): GepaCandidatePopulationArtifact;
748
- /** Cost reported by a method or by final test scoring. */
749
- interface ComparisonCost {
750
- /** Known subtotal. Consult `costProvenance` before treating this as total spend. */
751
- totalCostUsd: number;
752
- /** Exact origin of the total; uncaptured means `totalCostUsd` is only a known subtotal. */
753
- costProvenance: CostProvenance;
754
- accountingComplete: boolean;
755
- incompleteReasons: string[];
756
- }
757
- /** Keep the cost fields a custom optimization method must report. */
758
- declare function costFromLedgerSummary(summary: CostLedgerSummary): ComparisonCost;
759
- interface OptimizationTokenUsage {
760
- /** All input tokens, including cache reads and cache creation. */
761
- inputTokens: number;
762
- /** Input tokens served from a provider cache. */
763
- cachedInputTokens?: number;
764
- /** Input tokens used to create or write a provider cache entry. */
765
- cacheWriteInputTokens?: number;
766
- outputTokens: number;
767
- /** Reasoning tokens included in `outputTokens`. */
768
- reasoningTokens?: number;
769
- totalTokens: number;
770
- calls: number;
527
+ interface CrossSurfaceTaskRow {
528
+ taskId: string;
529
+ candidateId: string;
530
+ /** Repeated here so every persisted row remains self-describing. */
531
+ componentIds: string[];
532
+ completeness: CrossSurfaceAttemptCompleteness;
533
+ pass: boolean | null;
534
+ score: number | null;
535
+ /**
536
+ * Per-attempt deployment measurements. Every declared metric must have a
537
+ * known, non-negative value. Proposal, analysis, and selection spend belongs
538
+ * in the search ledger rather than being spread across task cells.
539
+ */
540
+ cost: Record<string, number | null>;
541
+ componentEvidence: CrossSurfaceComponentEvidence[];
542
+ /** Required for missing or invalid attempts; forbidden for complete attempts. */
543
+ rejectReason: string | null;
771
544
  }
772
- /** Shared campaign settings applied to every optimization method. */
773
- type OptimizationMethodRunOptions<TScenario extends Scenario, TArtifact> = Omit<RunCampaignOptions<TScenario, TArtifact>, 'costCeiling' | 'costLedger' | 'dispatch' | 'judges' | 'runDir' | 'scenarios' | 'seed'>;
774
- interface OptimizationPackageSource {
775
- kind: 'package';
776
- /** Whether package identity was inspected or supplied by caller code. */
777
- evidence: 'observed' | 'declared';
778
- package: string;
779
- version: string;
780
- sourceUrl?: string;
781
- revision?: string;
782
- /** SHA-256 of all installed module files observed before the run. */
783
- sourceSha256?: string;
545
+ interface CrossSurfaceBootstrapPolicy {
546
+ seed: number;
547
+ resamples: number;
548
+ confidence: number;
784
549
  }
785
- interface OptimizationModuleSource {
786
- module: string;
787
- sourceSha256: string;
550
+ /** Predeclared candidate eligibility and composition policy. */
551
+ interface CrossSurfaceSelectionPolicy {
552
+ minimumFiringTasks: number;
553
+ minimumEffectTasks: number;
554
+ requireObservedFiring: boolean;
555
+ requireObservedEffect: boolean;
556
+ /** Only named metrics are constrained; all declared metrics are still reported. */
557
+ maximumMedianCostRatioToBaseline: Record<string, number>;
558
+ /** A smaller terminal bundle is reported but cannot become the selected arm. */
559
+ minimumBundleComponents: number;
788
560
  }
789
- interface OptimizationPythonRuntime {
790
- implementation: string;
791
- version: string;
561
+ interface AnalyzeCrossSurfaceInteractionsInput<TRow extends CrossSurfaceTaskRow = CrossSurfaceTaskRow> {
562
+ components: readonly CrossSurfaceComponent[];
563
+ candidates: readonly CrossSurfaceCandidate[];
564
+ rows: readonly TRow[];
565
+ baselineCandidateId: string;
566
+ /** Exact shared task axis and its canonical output order. */
567
+ taskOrder: readonly string[];
568
+ /** Canonical materialization order for component sets and the naive stack. */
569
+ componentOrder: readonly string[];
570
+ /** Final deterministic tie-break; lower index wins. */
571
+ candidateOrder: readonly string[];
572
+ /** Declares every cost key and the order used for cost tie-breaks. */
573
+ costMetricOrder: readonly string[];
574
+ bootstrap: CrossSurfaceBootstrapPolicy;
575
+ selection: CrossSurfaceSelectionPolicy;
792
576
  }
793
- interface OptimizationMethodProvenance {
794
- /** External optimizer package. */
795
- source: OptimizationPackageSource;
796
- /** Python bridge package that invoked the optimizer. */
797
- bridge?: OptimizationPackageSource;
798
- /** Custom engine modules imported by the optimizer. */
799
- modules?: OptimizationModuleSource[];
800
- /** Python implementation used by the bridge process. */
801
- python?: OptimizationPythonRuntime;
802
- /** Exact model identifier configured for optimizer-owned model calls. */
803
- optimizerModel?: string;
804
- /** Stable public identity of the execution-owner callback. */
805
- optimizerCallRef?: string;
806
- runId: string;
807
- /** Content identity shared by compatible resumptions. */
808
- compatibleRunId?: string;
809
- resumed: boolean;
810
- /** Whether the run seed reached every external engine configuration. */
811
- seedApplied?: boolean;
812
- /** Evaluations the local callback metered — the trusted count. */
813
- evaluationCount: number;
814
- /**
815
- * Evaluation total the external optimizer reported from its own counters.
816
- * A difference from `evaluationCount` means upstream skipped, cached, or
817
- * double-counted work; inspect before trusting upstream-derived budgets.
818
- */
819
- upstreamReportedEvaluations?: number;
820
- artifactDir: string;
821
- tokenUsage?: OptimizationTokenUsage;
822
- /** Candidates submitted to the callback, per-case scores, and refusals. */
823
- observations?: ExternalOptimizerObservationSummary;
824
- /** Exact accepted GEPA candidates, parent indices, and selection scores. */
825
- gepaCandidatePopulation?: GepaCandidatePopulationSummary;
826
- /** Opaque Runtime execution evidence for every invoked optimizer-model call. */
827
- modelExecutions?: ExternalOptimizerExecutionSummary;
828
- /** Anthropic-endpoint proxy traffic from agent CLI engines, when enabled. */
829
- anthropicEndpoint?: ExternalOptimizerWireCounts;
577
+ interface CrossSurfaceDistribution {
578
+ n: number;
579
+ min: number;
580
+ median: number;
581
+ mean: number;
582
+ max: number;
583
+ total: number;
830
584
  }
831
- /** Shared inputs for one optimization method. Final test data is absent. */
832
- interface OptimizationMethodInput<TScenario extends Scenario, TArtifact> {
833
- /** Surface every method starts from. */
834
- readonly baselineSurface: MutableSurface;
835
- /** Evidence used to author or fit candidates. */
836
- readonly trainScenarios: readonly TScenario[];
837
- /** Data used for candidate acceptance, early stopping, and model selection. */
838
- readonly selectionScenarios: readonly TScenario[];
839
- /** Runs one scenario with a candidate surface. */
840
- readonly dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
841
- /** Scores artifacts produced by `dispatchWithSurface`. */
842
- readonly judges: readonly JudgeConfig<TArtifact, TScenario>[];
843
- /** Method-specific artifacts are written below this directory. */
844
- readonly runDir: string;
845
- readonly seed: number;
846
- /** Shared defaults for every method. A method may override them explicitly. */
847
- readonly runOptions: Readonly<OptimizationMethodRunOptions<TScenario, TArtifact>>;
848
- /** Durable spend account shared by every method and final scoring. */
849
- readonly costLedger: CostLedgerHandle;
850
- /** Invokes each method at the shared execution boundary, including composed children. */
851
- invokeMethod?(method: OptimizationMethod<TScenario, TArtifact>, input: OptimizationMethodInput<TScenario, TArtifact>): Promise<OptimizationMethodResult>;
852
- /** Maps this method's local surface into the complete outer candidate. */
853
- readonly surfaceToRoot?: (surface: MutableSurface) => MutableSurface;
585
+ interface CrossSurfaceEvidenceBreakdown {
586
+ componentId: string;
587
+ observedTaskIds: string[];
588
+ notObservedTaskIds: string[];
589
+ unobservedTaskIds: string[];
854
590
  }
855
- /** Exact child results; costs and usage remain attributable to their owning methods. */
856
- interface OptimizationMethodComposition {
857
- kind: 'scoped' | 'sequential';
858
- baselineSurfaceHash: string;
859
- stages: Array<{
860
- name: string;
861
- baselineSurfaceHash: string;
862
- result: OptimizationMethodResult;
863
- }>;
591
+ interface CrossSurfaceCandidateEvidence {
592
+ byComponent: CrossSurfaceEvidenceBreakdown[];
593
+ allObservedTaskIds: string[];
594
+ someObservedTaskIds: string[];
595
+ noneObservedTaskIds: string[];
596
+ unobservedTaskIds: string[];
864
597
  }
865
- interface OptimizationMethodResult {
866
- /** Surface selected without using the final test partition. */
867
- winnerSurface: MutableSurface;
868
- composition?: OptimizationMethodComposition;
869
- /** Optimization spend. Excludes final test scoring. */
870
- cost: ComparisonCost;
871
- /** Optimization duration. Excludes final test scoring. */
872
- durationMs?: number;
873
- /** Exact external implementation and run identity, when the method uses one. */
874
- provenance?: OptimizationMethodProvenance;
875
- /** Bounded proof envelope over the canonical SearchLedger for this optimization. */
876
- searchHistory?: SearchHistoryReceipt;
598
+ type CrossSurfaceIneligibilityReason = 'missing_attempt' | 'invalid_attempt' | 'baseline_outcome_missing' | 'benefit_not_greater_than_regression' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
599
+ interface CrossSurfaceEligibility {
600
+ eligible: boolean;
601
+ reasons: CrossSurfaceIneligibilityReason[];
877
602
  }
878
- /** A complete optimization method, including candidate generation and selection. */
879
- interface OptimizationMethod<TScenario extends Scenario = Scenario, TArtifact = unknown> {
880
- /** Unique, trimmed display name. Its normalized form must also be unique. */
881
- name: string;
882
- optimize: (input: OptimizationMethodInput<TScenario, TArtifact>) => Promise<OptimizationMethodResult>;
603
+ interface CrossSurfaceCandidateOutcome {
604
+ resolvedTaskIds: string[];
605
+ failedTaskIds: string[];
606
+ missingTaskIds: string[];
607
+ invalidTaskIds: string[];
608
+ benefitTaskIds: string[];
609
+ regressionTaskIds: string[];
610
+ comparisonMissingTaskIds: string[];
611
+ netBenefit: number;
883
612
  }
884
- interface ExternalOptimizationExample {
885
- id: string;
886
- data: unknown;
613
+ interface CrossSurfaceCandidateSummary {
614
+ candidate: CrossSurfaceCandidate;
615
+ outcome: CrossSurfaceCandidateOutcome;
616
+ score: CrossSurfaceDistribution | null;
617
+ costs: Record<string, CrossSurfaceDistribution>;
618
+ firing: CrossSurfaceCandidateEvidence;
619
+ effect: CrossSurfaceCandidateEvidence;
620
+ /** Reuses the package's paired McNemar/risk-difference/bootstrap statistics. */
621
+ comparisonToBaseline: PairedArmsComparison | null;
622
+ /** null only for the fixed baseline. */
623
+ eligibility: CrossSurfaceEligibility | null;
887
624
  }
888
- interface ExternalTextEvaluationResponse {
889
- score: number;
890
- info: {
891
- scenarioId: string;
892
- dimensions: Record<string, number>;
893
- /** Higher-is-better objectives consumed by GEPA hybrid/Pareto selection. */
894
- scores?: Record<string, number>;
895
- notes?: string;
896
- artifact?: unknown;
897
- /** The optimizer score is a finite protocol value; Eval remains the
898
- * authority for whether the underlying cell actually produced a score. */
899
- status?: 'scored' | 'failed';
900
- error?: {
901
- stage: 'dispatch' | 'judge' | 'unknown';
902
- message: string;
903
- };
904
- };
625
+ interface CrossSurfaceRelativeCost {
626
+ treatmentMedian: number;
627
+ comparatorMedian: number;
628
+ medianDelta: number;
629
+ /** null when the comparator median is zero but the treatment median is not. */
630
+ medianRatio: number | null;
905
631
  }
906
- declare function decodeExternalTextCandidate(candidate: ExternalTextCandidate): MutableSurface;
907
- interface ExternalTextOptimizerContext {
908
- readonly runId: string;
909
- readonly name: string;
910
- readonly objective: string;
911
- readonly evaluationId: string;
912
- readonly background?: string;
913
- readonly seedCandidate: ExternalTextCandidate;
914
- readonly trainSet: readonly ExternalOptimizationExample[];
915
- readonly selectionSet: readonly ExternalOptimizationExample[];
916
- readonly maxEvaluations: number;
917
- readonly seed: number;
918
- /** Stable directory for optimizer checkpoints from compatible attempts. */
919
- readonly stateDir: string;
920
- readonly restoreRequested: boolean;
921
- readonly artifactDir: string;
922
- readonly signal: AbortSignal;
923
- /** Record every optimizer-owned paid call through this attributed account. */
924
- readonly cost: CampaignCostMeter;
925
- readonly evaluate: (request: ExternalTextEvaluationRequest) => Promise<ExternalTextEvaluationResponse>;
632
+ interface CrossSurfaceCandidateComparison {
633
+ comparatorCandidateId: string;
634
+ treatmentCandidateId: string;
635
+ winsTaskIds: string[];
636
+ regressionTaskIds: string[];
637
+ missingTaskIds: string[];
638
+ paired: PairedArmsComparison;
639
+ relativeCost: Record<string, CrossSurfaceRelativeCost>;
926
640
  }
927
- interface ExternalTextOptimizerResult {
928
- bestCandidate: ExternalTextCandidate;
929
- resumed: boolean;
930
- costAccounting: {
931
- kind: 'metered';
932
- } | {
933
- kind: 'no-paid-work';
934
- } | {
935
- kind: 'external';
936
- reason: string;
937
- };
641
+ interface CrossSurfacePairEvidence {
642
+ bothTaskIds: string[];
643
+ leftOnlyTaskIds: string[];
644
+ rightOnlyTaskIds: string[];
645
+ neitherTaskIds: string[];
646
+ unobservedTaskIds: string[];
938
647
  }
939
- /**
940
- * Configuration for adapting another text optimizer.
941
- *
942
- * `run` owns search. Agent Eval owns split isolation, bounded candidate
943
- * evaluation, exact cost collection, provenance, and final comparison.
944
- */
945
- interface ExternalTextOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
946
- name: string;
947
- source: Omit<OptimizationPackageSource, 'evidence'>;
948
- objective: string;
949
- evaluationId: string;
950
- background?: string;
951
- maxEvaluations: number;
952
- /** Hard limit for calls made through `context.cost`. Use 0 for no paid work. */
953
- maxOptimizerCostUsd: number;
954
- /** Abort `context.signal` after this duration. Default: 30 minutes. */
955
- timeoutMs?: number;
956
- /** Default: `never`. Compatible runs reuse one state directory. */
957
- resume?: ExternalOptimizerResumeMode;
958
- maxCandidateChars?: number;
959
- maxEvidenceChars?: number;
960
- describeScenario?: (scenario: TScenario) => unknown;
961
- describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
962
- run: (context: ExternalTextOptimizerContext) => Promise<ExternalTextOptimizerResult>;
648
+ interface CrossSurfaceInteractionTask {
649
+ taskId: string;
650
+ /** Composition minus the additive expectation from the baseline and singles. */
651
+ passInteraction: number | null;
652
+ scoreInteraction: number | null;
963
653
  }
964
- /**
965
- * Adapt a third-party text optimizer without reimplementing its search.
966
- *
967
- * The callback never receives final test cases. Calls to `evaluate` are
968
- * counted before execution and stop at `maxEvaluations`.
969
- */
970
- declare function externalTextOptimizationMethod<TScenario extends Scenario, TArtifact>(config: ExternalTextOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
971
- type OptimizerModelBudget = ExternalOptimizerModelBudget;
972
- /** One metered model path supplied by the package that owns execution. */
973
- interface OpenAICompatibleOptimizerModel {
974
- model: string;
975
- budget: OptimizerModelBudget;
976
- /** Caller-owned execution path, such as Runtime's exact AgentProfile adapter. */
977
- call: ExternalOptimizerModelCall;
978
- /** Stable public identity included in resumable-run compatibility. */
979
- callRef: string;
980
- /**
981
- * Served-model acceptance for every proxied call. Default `'exact'`, which
982
- * rejects any substitution with a 502 to the child.
983
- * `'allow-within-family'` accepts a different model of the same provider
984
- * family; it keeps family-level claims valid and forfeits per-model claims.
985
- */
986
- servedModelPolicy?: ServedModelPolicy;
987
- /**
988
- * Also expose this metered model over the Anthropic Messages API
989
- * (`POST /v1/messages`) on the loopback proxy. Required for GEPA agent
990
- * engines that drive a `claude` CLI subprocess. Agent engines are chatty:
991
- * size `budget.maxRequests` for tens of calls per engine run. Default: false.
992
- */
993
- anthropicEndpoint?: boolean;
654
+ interface CrossSurfaceInteractionEffect {
655
+ perTask: CrossSurfaceInteractionTask[];
656
+ n: number;
657
+ nMissing: number;
658
+ meanPassInteraction: number | null;
659
+ meanScoreInteraction: number | null;
660
+ passBootstrap: PairedBootstrapResult | null;
661
+ scoreBootstrap: PairedBootstrapResult | null;
994
662
  }
995
- /** Shared settings for one bounded GEPA engine invocation. */
996
- interface GepaEngineOptions {
997
- /** GEPA engine name. GEPA validates names available in its Python runtime. */
998
- engine: string;
999
- /** Optional billed-USD stop. Omit when the execution owner reports USD as unknown. */
1000
- maxProposerCostUsd?: number;
1001
- /** Maximum concurrent evaluations inside this engine. Default: 1. */
1002
- maxConcurrency?: number;
1003
- /** Stop the engine after it reaches this score. */
1004
- stopAtScore?: number;
1005
- /** Isolate agent-based engines. Default: true. */
1006
- sandbox?: boolean;
1007
- /**
1008
- * JSON-safe configuration for the registered GEPA engine.
1009
- * Python callables and class instances cannot cross the process boundary.
1010
- */
1011
- engineConfig?: Record<string, unknown>;
663
+ type CrossSurfacePairIncompatibilityReason = 'constituent_not_ready' | 'pair_incomplete' | 'baseline_regression' | 'interference' | 'no_incremental_resolution' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
664
+ interface CrossSurfacePairCompatibility {
665
+ compatible: boolean;
666
+ reasons: CrossSurfacePairIncompatibilityReason[];
667
+ betterSingleCandidateId: string;
1012
668
  }
1013
- /** One independently budgeted GEPA engine invocation. */
1014
- interface GepaEngineRun extends GepaEngineOptions {
1015
- /** Maximum callback evaluations this engine may consume. */
1016
- maxEvaluations: number;
669
+ interface CrossSurfacePairwiseEntry {
670
+ componentIds: [string, string];
671
+ singleCandidateIds: [string, string];
672
+ compositionCandidateId: string;
673
+ benefitTaskIds: string[];
674
+ regressionTaskIds: string[];
675
+ synergyTaskIds: string[];
676
+ interferenceTaskIds: string[];
677
+ incrementalVsConstituents: [CrossSurfaceCandidateComparison, CrossSurfaceCandidateComparison];
678
+ relativeCostToBaseline: Record<string, CrossSurfaceRelativeCost>;
679
+ firing: CrossSurfacePairEvidence;
680
+ effect: CrossSurfacePairEvidence;
681
+ interaction: CrossSurfaceInteractionEffect;
682
+ compatibility: CrossSurfacePairCompatibility;
1017
683
  }
1018
- /** An engine in an adaptive run. All engines share the recipe evaluation limit. */
1019
- type GepaAdaptiveEngineRun = GepaEngineOptions;
1020
- /**
1021
- * A direct mapping to a GEPA optimization recipe.
1022
- *
1023
- * GEPA owns every search and composition operation represented here. Tangle
1024
- * supplies the candidate, data, execution callback, judges, and budgets.
1025
- */
1026
- type GepaOptimizationRecipe = {
1027
- kind: 'engine';
1028
- run: GepaEngineRun;
1029
- } | {
1030
- kind: 'sequential';
1031
- runs: readonly GepaEngineRun[];
1032
- } | {
1033
- kind: 'adaptive-sequential';
1034
- runs: readonly GepaAdaptiveEngineRun[];
1035
- /** One evaluation budget shared by every adaptive stage. */
1036
- maxEvaluations: number;
1037
- /** Switch engines after this many evaluations without improvement. */
1038
- plateauEvaluations: number;
1039
- patience?: number;
1040
- minEvaluationsPerStage?: number;
1041
- improvementEpsilon?: number;
1042
- cycle?: boolean;
1043
- maxSwitches?: number;
1044
- maxConcurrency?: number;
1045
- } | {
1046
- kind: 'best-of';
1047
- runs: readonly GepaEngineRun[];
1048
- maxWorkers?: number;
1049
- } | {
1050
- kind: 'vote';
1051
- runs: readonly GepaEngineRun[];
1052
- maxWorkers?: number;
1053
- } | {
1054
- kind: 'omni';
1055
- explore: readonly GepaEngineRun[];
1056
- continueWith: GepaEngineRun;
1057
- maxWorkers?: number;
1058
- };
1059
- /** The command that runs the Python GEPA bridge. */
1060
- type GepaRunnerCommand = ExternalOptimizerRunnerCommand;
1061
- interface GepaOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
1062
- /** Unique comparison-method name. Default identifies the GEPA recipe. */
1063
- name?: string;
1064
- /** A direct GEPA recipe. */
1065
- recipe: GepaOptimizationRecipe;
1066
- /** Plain-language goal shown to the external optimizer. */
1067
- objective: string;
1068
- /** Stable identity for the dispatch, judges, model settings, and scoring logic. */
1069
- evaluationId: string;
1070
- /** Optional bounded context about the surface and task. */
1071
- background?: string;
1072
- /**
1073
- * Public dotted Python modules imported before GEPA resolves engine names.
1074
- * Each module should call GEPA's official `register_engine()` API at import.
1075
- */
1076
- engineModules?: readonly string[];
1077
- /** Reject external candidates longer than this. Default: 200,000 characters. */
1078
- maxCandidateChars?: number;
1079
- /** Reject serialized score evidence longer than this. Default: 100,000 characters. */
1080
- maxEvidenceChars?: number;
1081
- /** Candidate-evaluation callback byte limits. Omitted fields use finite defaults. */
1082
- evaluationCallbackLimits?: Partial<ExternalOptimizerCallbackLimits>;
1083
- /** End the bridge process after this many milliseconds. Default: 30 minutes. */
1084
- timeoutMs?: number;
1085
- /**
1086
- * OpenAI-compatible model used by standard GEPA reflection.
1087
- * Calls pass through Agent Eval's local model proxy. Every recipe engine must
1088
- * be `gepa` when this is set.
1089
- */
1090
- optimizer?: OpenAICompatibleOptimizerModel;
1091
- /**
1092
- * Decide what the external optimizer may read for a train or selection case.
1093
- * The returned value must be JSON-serializable. The final comparison cases
1094
- * are not accepted by this API and cannot be serialized here.
1095
- */
1096
- describeScenario?: (scenario: TScenario) => unknown;
1097
- /** Optional bounded artifact evidence returned to GEPA after each evaluation. */
1098
- describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
1099
- /** Default: `never`. Compatible runs resume only when explicitly enabled. */
1100
- resume?: ExternalOptimizerResumeMode;
1101
- /**
1102
- * Required for resumable direct GEPA runs because upstream state uses Python
1103
- * pickle. Enable only for state created locally in a directory you control.
1104
- */
1105
- trustResumeState?: boolean;
1106
- runner?: GepaRunnerCommand;
1107
- /**
1108
- * Record GEPA's search into a search ledger and return the bounded receipt
1109
- * on the method result, so a comparison under `searchHistoryPolicy:
1110
- * 'require-complete'` accepts this method. The population becomes nodes and
1111
- * `correlated` edges, and every callback evaluation becomes a cell.
1112
- *
1113
- * `identity` declares the immutable revisions and the model the ledger
1114
- * requires and the bridge does not report. `path` defaults to
1115
- * `<runDir>/search-ledger.jsonl`.
1116
- */
1117
- searchLedger?: {
1118
- identity: SearchRunIdentity;
1119
- path?: string;
1120
- };
1121
- }
1122
- /**
1123
- * Turn an optional GEPA installation into an `OptimizationMethod`.
1124
- *
1125
- * GEPA receives only serialized train and selection cases. The caller's final
1126
- * test partition stays inside `compareOptimizationMethods`, which invokes this
1127
- * method without a test-set field. The local callback routes every candidate
1128
- * evaluation through the same dispatch and judges used by other methods.
1129
- */
1130
- /**
1131
- * Environment for a bridge child that spawns `claude` CLI subprocesses.
1132
- *
1133
- * Both agent CLI engines start the CLI with the bridge's own environment, so
1134
- * these variables travel bridge → engine → CLI. They merge AFTER
1135
- * `removeCredentialEnvironment`: the ephemeral loopback token is the only
1136
- * credential the child may see, and a caller-supplied ANTHROPIC_AUTH_TOKEN is
1137
- * stripped like any other credential.
1138
- */
1139
- declare function gepaOptimizationMethod<TScenario extends Scenario, TArtifact>(config: GepaOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
1140
- interface OptimizationMethodScore {
1141
- evidence?: {
1142
- baseline: EvidenceReceipt;
1143
- winner: EvidenceReceipt;
1144
- };
1145
- name: string;
1146
- /** Mean final-test composite of the baseline (identical across methods). */
1147
- baselineComposite: number;
1148
- /** Mean final-test composite of this method's selected surface. */
1149
- winnerComposite: number;
1150
- /** Mean final-test lift across independent units (winner minus baseline). */
1151
- lift: number;
1152
- /** Deciding interval, adjusted for every registered contrast. */
1153
- liftCi: {
1154
- low: number;
1155
- high: number;
1156
- };
1157
- decision: PairedPromotionDecision;
1158
- /** Search spend reconciled with recorded method calls. Excludes final test scoring. */
1159
- optimizationCost: ComparisonCost;
1160
- /** Optimization duration reported by the method. Excludes final test scoring. */
1161
- durationMs?: number;
1162
- /** Exact external implementation and run identity, when reported by the method. */
1163
- provenance?: OptimizationMethodProvenance;
1164
- /** Paired final-test values used to compute lift and its interval. */
1165
- scenarioScores: Array<{
1166
- scenarioId: string;
1167
- baselineComposite: number;
1168
- winnerComposite: number;
1169
- lift: number;
1170
- }>;
1171
- /** Scenario means averaged within each registered source unit before inference. */
1172
- unitScores: Array<{
1173
- unitId: string;
1174
- scenarios: number;
1175
- baselineComposite: number;
1176
- winnerComposite: number;
1177
- lift: number;
1178
- }>;
1179
- winnerSurface: MutableSurface;
1180
- composition?: OptimizationMethodComposition;
1181
- /** 1-based, by descending lift. */
1182
- rank: number;
1183
- }
1184
- interface OptimizationMethodPairwise {
1185
- /** Higher-ranked method. */
1186
- a: string;
1187
- b: string;
1188
- /** Mean final-test delta across independent units (a − b). */
1189
- deltaMean: number;
1190
- low: number;
1191
- high: number;
1192
- /** Favored only when the full paired decision clears the registered effect; null is inconclusive. */
1193
- favored: string | null;
1194
- decision: PairedPromotionDecision;
1195
- }
1196
- interface OptimizationMethodComparison {
1197
- claim?: EvaluationClaim;
1198
- finalEvidence?: FinalEvidenceUse;
1199
- /** Sorted by descending lift; `rank` set accordingly. */
1200
- scores: OptimizationMethodScore[];
1201
- best: OptimizationMethodScore;
1202
- /** Best observed method versus each alternative, with simultaneous paired decisions. */
1203
- pairwise: OptimizationMethodPairwise[];
1204
- testScenarioIds: string[];
1205
- units: EvaluationUnitSummary;
1206
- observationUnit: 'scenario' | 'registered';
1207
- /** Complete scenario-replicate pairs per contrast, before unit aggregation. */
1208
- pairedCellN: number;
1209
- /** Sum of method reports reconciled against each method's recorded calls. */
1210
- optimizationCost: ComparisonCost;
1211
- /** Baseline and distinct winner scoring on the final test partition. */
1212
- testCost: ComparisonCost;
1213
- /** Optimization plus final test scoring. */
1214
- totalCost: ComparisonCost;
1215
- /** Caller-requested simultaneous coverage across all reported contrasts. */
1216
- confidence: number;
1217
- /** Bonferroni-adjusted confidence used for each bootstrap interval. */
1218
- intervalConfidence: number;
1219
- /** Method-vs-baseline plus all possible method-vs-method contrasts. */
1220
- comparisonCount: number;
1221
- /** Deterministic bootstrap and campaign seed. */
1222
- seed: number;
1223
- /** Bootstrap draws used for each interval. */
1224
- resamples: number;
1225
- /** Agent runs averaged within each test scenario before resampling scenarios. */
1226
- reps: number;
1227
- /** Coverage of every method's canonical search history. */
1228
- searchHistory: SearchHistoryCoverage;
1229
- }
1230
- interface CompareOptimizationMethodsOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'judges' | 'scenarios'>, SearchHistoryAdmissionOptions {
1231
- /** Explicit caller authority and environment for receipts over actual final measurements. */
1232
- evidence?: CampaignEvidenceContext;
1233
- claim?: EvaluationClaim;
1234
- finalEvidence?: FinalEvidencePolicy;
1235
- methods: OptimizationMethod<TScenario, TArtifact>[];
1236
- baselineSurface: MutableSurface;
1237
- /** Evidence used by every optimizer to author or fit candidates. */
1238
- trainScenarios: TScenario[];
1239
- /** Candidate acceptance, early-stopping, and optimizer-selection data. */
1240
- selectionScenarios: TScenario[];
1241
- /** Untouched final comparison data. Never passed to an optimization method. */
1242
- testScenarios: TScenario[];
1243
- /** Scores a surface on a scenario. The methods and final test share this function. */
1244
- dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
1245
- judges: JudgeConfig<TArtifact, TScenario>[];
1246
- /** Bootstrap resamples for the lift intervals. Default is at least 2000 and
1247
- * rises when the requested simultaneous confidence needs finer tails. */
1248
- resamples?: number;
1249
- /** Shared defaults for each method's train and selection campaigns. */
1250
- optimizationRunOptions?: OptimizationMethodRunOptions<TScenario, TArtifact>;
1251
- /** Number of optimization methods to run concurrently. Default 1. */
1252
- optimizationConcurrency?: number;
1253
- /** Simultaneous confidence across method-vs-baseline and method-vs-method contrasts.
1254
- * Each bootstrap interval is Bonferroni-adjusted. Default 0.95. */
1255
- confidence?: number;
1256
- /** Shared spend limit across every method's optimizer and evaluation calls plus final scoring. */
1257
- costCeiling?: number;
1258
- }
1259
- /**
1260
- * Compare complete optimization methods on disjoint train, selection, and final test data.
1261
- */
1262
- declare function compareOptimizationMethods<TScenario extends Scenario, TArtifact>(rawOpts: CompareOptimizationMethodsOptions<TScenario, TArtifact>): Promise<OptimizationMethodComparison>;
1263
- interface SkillOptTrainerConfig {
1264
- epochs: number;
1265
- batchSize: number;
1266
- accumulation?: number;
1267
- editBudget?: number;
1268
- minEditBudget?: number;
1269
- analystWorkers?: number;
1270
- minibatchSize?: number;
1271
- mergeBatchSize?: number;
1272
- maxAnalystRounds?: number;
1273
- evaluationWorkers?: number;
1274
- learningRateSchedule?: 'constant' | 'linear' | 'cosine' | 'autonomous';
1275
- learningRateControl?: 'fixed' | 'autonomous' | 'none';
1276
- updateMode?: 'patch' | 'rewrite_from_suggestions' | 'full_rewrite_minibatch';
1277
- failureOnly?: boolean;
1278
- useSlowUpdate?: boolean;
1279
- useMetaSkill?: boolean;
1280
- /**
1281
- * Additional flat SkillOpt trainer settings. Tangle overwrites data,
1282
- * output, split, seed, validation, and activation settings.
1283
- */
1284
- overrides?: Record<string, unknown>;
1285
- }
1286
- type SkillOptRunnerCommand = ExternalOptimizerRunnerCommand;
1287
- interface SkillOptOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
1288
- name?: string;
1289
- /** Goal included with every described train and selection case. */
1290
- objective: string;
1291
- background?: string;
1292
- /** Stable identity for the dispatch, judges, model settings, and scoring logic. */
1293
- evaluationId: string;
1294
- trainer: SkillOptTrainerConfig;
1295
- /**
1296
- * OpenAI-compatible model connection and hard limits for SkillOpt's own
1297
- * optimizer calls.
1298
- */
1299
- optimizer: OpenAICompatibleOptimizerModel;
1300
- /** Hard cap on candidate-case callback requests. */
1301
- maxEvaluations: number;
1302
- /** Scores at or above this value count as hard successes. Default: 1. */
1303
- hardScoreThreshold?: number;
1304
- maxCandidateChars?: number;
1305
- /** Maximum serialized scenario plus evaluation evidence. Default: 100,000. */
1306
- maxEvidenceChars?: number;
1307
- /** Candidate-evaluation callback byte limits. Omitted fields use finite defaults. */
1308
- evaluationCallbackLimits?: Partial<ExternalOptimizerCallbackLimits>;
1309
- timeoutMs?: number;
1310
- describeScenario?: (scenario: TScenario) => unknown;
1311
- describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
1312
- resume?: ExternalOptimizerResumeMode;
1313
- runner?: SkillOptRunnerCommand;
1314
- /**
1315
- * Record SkillOpt's search into a search ledger and return the bounded
1316
- * receipt on the method result, so a comparison under `searchHistoryPolicy:
1317
- * 'require-complete'` accepts this method. Every candidate the callback
1318
- * evaluated becomes a node with an `unknown` edge (SkillOpt reports no
1319
- * parents), and every evaluation becomes a cell.
1320
- *
1321
- * `identity` declares the immutable revisions and the model the ledger
1322
- * requires and the bridge does not report. `path` defaults to
1323
- * `<runDir>/search-ledger.jsonl`.
1324
- */
1325
- searchLedger?: {
1326
- identity: SearchRunIdentity;
1327
- path?: string;
1328
- };
1329
- }
1330
- /** Run Microsoft's SkillOpt trainer as a complete optimization method. */
1331
- declare function skillOptOptimizationMethod<TScenario extends Scenario, TArtifact>(config: SkillOptOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
1332
- /** Compose gates — all must `ship` for the composite to `ship`. First
1333
- * non-ship verdict short-circuits the composite verdict, but ALL gates run
1334
- * (so the result records every gate's reason — useful for diagnostics). */
1335
- declare function composeGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(...gates: Array<Gate<TArtifact, TScenario>>): Gate<TArtifact, TScenario>;
1336
- type CanaryKind = 'silent_judge_fallback' | 'judge_calibration_drift' | 'distribution_shift';
1337
- type CanarySeverity = 'info' | 'warn' | 'error';
1338
- interface CanaryAlert {
1339
- kind: CanaryKind;
1340
- severity: CanarySeverity;
1341
- message: string;
1342
- /** Numbers that informed the decision — drop straight into a
1343
- * dashboard / paper figure. */
1344
- evidence: Record<string, unknown>;
1345
- }
1346
- interface CanaryReport {
1347
- alerts: CanaryAlert[];
1348
- /** Per-kind summary count. */
1349
- counts: Record<CanaryKind, number>;
1350
- /** Whether each enabled detector had enough observations to run. */
1351
- evaluations: CanaryEvaluation[];
1352
- }
1353
- interface CanaryEvaluation {
1354
- kind: CanaryKind;
1355
- status: 'evaluated' | 'not_evaluated';
1356
- observations: number;
1357
- reason?: string;
1358
- }
1359
- interface CanaryOptions {
1360
- /**
1361
- * Silent-fallback detection.
1362
- * - `constant`: confidence value treated as the fallback signal.
1363
- * Default 0.30 (matches the soft-fail default in
1364
- * `propose-review.ts`).
1365
- * - `consecutiveThreshold`: trip the alert after this many
1366
- * consecutive runs at `constant` (or `fallback === true`).
1367
- * Default 3.
1368
- */
1369
- silentFallback?: {
1370
- constant?: number;
1371
- consecutiveThreshold?: number;
1372
- /** Floating-point tolerance when comparing against `constant`. */
1373
- epsilon?: number;
1374
- };
1375
- /**
1376
- * Calibration-drift detection.
1377
- * - `historyWindow`: number of past runs (oldest-first) treated as
1378
- * the historical baseline. Default 50.
1379
- * - `recentWindow`: number of recent runs (newest-first) compared
1380
- * against history. Default 20.
1381
- * - `ksAlpha`: alpha for the KS statistic vs critical value.
1382
- * Default 0.05.
1383
- * - `minRecent`: minimum recent runs required to even attempt the
1384
- * check. Default 10.
1385
- */
1386
- calibrationDrift?: {
1387
- historyWindow?: number;
1388
- recentWindow?: number;
1389
- ksAlpha?: number;
1390
- minRecent?: number;
1391
- };
1392
- /**
1393
- * Distribution-shift detection.
1394
- * - `category`: function that maps a run to a categorical bucket.
1395
- * Required to enable this canary; if omitted the chi-square check
1396
- * is skipped entirely.
1397
- * - `chiSquareAlpha`: alpha. Default 0.05.
1398
- * - `historyWindow`, `recentWindow`, `minRecent`: like above.
1399
- */
1400
- distributionShift?: {
1401
- category: (run: RunRecord) => string | null;
1402
- chiSquareAlpha?: number;
1403
- historyWindow?: number;
1404
- recentWindow?: number;
1405
- minRecent?: number;
1406
- };
1407
- }
1408
- /**
1409
- * Run all configured canaries against a chronological run list.
1410
- * Runs MUST be sorted oldest-to-newest by the caller — the order of
1411
- * the input is used to define "recent" vs "historical" windows.
1412
- */
1413
- declare function runCanaries(runs: RunRecord[], opts?: CanaryOptions): CanaryReport;
1414
- type RedTeamCategory = 'prompt_injection_direct' | 'prompt_injection_indirect' | 'jailbreak_persona' | 'jailbreak_dan' | 'pii_leak' | 'permission_escalation' | 'data_exfil' | 'policy_override';
1415
- interface RedTeamPayload {
1416
- category: RedTeamCategory;
1417
- /** The hostile input the agent sees. */
1418
- input: string;
1419
- /**
1420
- * What a safe agent should do: "refuse" means explicit refusal,
1421
- * "ignore" means process benignly without executing the attack.
1422
- */
1423
- expected: 'refuse' | 'ignore';
1424
- /** Substring(s) that MUST NOT appear in output. */
1425
- forbiddenStrings?: string[];
1426
- /** Tool names the agent MUST NOT call for this scenario. */
1427
- forbiddenTools?: string[];
1428
- }
1429
- interface RedTeamCase extends DatasetScenario {
1430
- payload: RedTeamPayload;
1431
- }
1432
- interface RedTeamFinding {
1433
- scenarioId: string;
1434
- category: RedTeamCategory;
1435
- passed: boolean;
1436
- reason: string;
1437
- evidence?: string;
1438
- }
1439
- interface RedTeamReport {
1440
- findings: RedTeamFinding[];
1441
- passRateByCategory: Record<RedTeamCategory, number>;
1442
- overallPassRate: number;
1443
- }
1444
- /** Ship a canonical, small corpus. Consumers extend via `extendCorpus`. */
1445
- declare const DEFAULT_RED_TEAM_CORPUS: RedTeamCase[];
1446
- declare function redTeamDataset(extraCases?: RedTeamCase[]): Dataset;
1447
- /**
1448
- * Score a single agent response against the red-team case.
1449
- * `toolCalls` should be the names of tools the agent invoked during the run.
1450
- */
1451
- declare function scoreRedTeamOutput(output: string, toolCalls: string[], rtCase: RedTeamCase): RedTeamFinding;
1452
- /** Aggregate red-team findings into per-category pass rates. */
1453
- declare function redTeamReport(findings: RedTeamFinding[]): RedTeamReport;
1454
- type DefaultProductionGateCheck = 'dimension-regression' | 'budget' | 'red-team' | 'reward-hacking' | 'canary';
1455
- type DefaultProductionRewardHackingOptions = Omit<DetectRewardHackingInput, 'runs' | 'truthOf'> & {
1456
- truthOf: NonNullable<DetectRewardHackingInput['truthOf']>;
1457
- };
1458
- interface DefaultProductionGateOptions {
1459
- /** Required: scenarios held out from training; substrate compares
1460
- * candidate-on-holdout vs baseline-on-holdout. */
1461
- holdoutScenarios: Scenario[];
1462
- /**
1463
- * Independent sampling unit for every held-out scenario. Pair cells first,
1464
- * then average scores within each unit and give units equal weight.
1465
- * Omit only when execution cells on a fixed roster are the observation units.
1466
- */
1467
- independentUnitByScenarioId?: ReadonlyMap<string, string>;
1468
- /** Minimum held-out improvement under the shared paired decision rule.
1469
- * Default 0. The outcome shape and sample count determine the statistical
1470
- * test. Use native composite units, such as 2 for a 0-100 rubric. */
1471
- deltaThreshold?: number;
1472
- /** Confidence level for the held-out + dimension bootstraps. Default 0.95. */
1473
- confidence?: number;
1474
- /** Bootstrap resamples. Default 2000. */
1475
- bootstrapResamples?: number;
1476
- /** Fixed bootstrap seed for a deterministic verdict. Default 1337. */
1477
- bootstrapSeed?: number;
1478
- /** Minimum paired independent units (or cells when unconfigured) before a
1479
- * significance claim is allowed. The exact small-sample test may require
1480
- * more observations at the selected confidence. Default 3. */
1481
- minProductiveRuns?: number;
1482
- /** Ship statistic for the held-out significance test. Default `'mean'`
1483
- * (tie-robust — see `heldoutSignificance`). Pass `'median'` for
1484
- * outlier-robustness at the cost of tie-blindness. */
1485
- heldoutStatistic?: 'mean' | 'median';
1486
- /** Required judge dimensions checked for regression and complete evidence.
1487
- * A bootstrap lower bound below negative tolerance or a paired test proving
1488
- * a drop holds the gate. Thin or incomplete coverage is not_evaluated. */
1489
- criticalDimensions?: string[];
1490
- /** Tolerance for the per-dimension regression guard, in the dimension's
1491
- * native scale. When omitted it auto-scales off observed magnitudes:
1492
- * 0.05 on [0,1], 5 on 0-100. */
1493
- regressionTolerance?: number;
1494
- /** Total $ budget for the complete improvement run. Requires
1495
- * `GateContext.costLedger`; missing or incomplete accounting holds. */
1496
- budgetUsd?: number;
1497
- /** Static artifact-screening cases. Only `expected: 'ignore'` cases without
1498
- * tool assertions are valid because this check does not dispatch case inputs
1499
- * or observe tool calls. */
1500
- redTeamBattery?: RedTeamCase[];
1501
- /** Shared run history, oldest first. Supplying history does not enable either
1502
- * monitoring check; configure `rewardHacking` and/or `canary` explicitly. */
1503
- recentRuns?: RunRecord[];
1504
- /** Enable reward-hacking monitoring with a caller-owned independent truth channel. */
1505
- rewardHacking?: DefaultProductionRewardHackingOptions;
1506
- /** Enable canary monitoring. Pass `{}` to use the canary defaults. */
1507
- canary?: CanaryOptions;
1508
- /** Optional checks that must be evaluated even when their normal input is
1509
- * absent. Configuring a check's input also makes that check required.
1510
- * Missing evidence always records `not_evaluated`; required unevaluated
1511
- * checks hold the release decision. Held-out significance is always required. */
1512
- requiredChecks?: DefaultProductionGateCheck[];
1513
- }
1514
- /**
1515
- * Opinionated production gate composing held-out significance, red-team, reward-hacking, and canary checks into a single `Gate.decide` decision.
1516
- */
1517
- declare function defaultProductionGate<TArtifact, TScenario extends Scenario>(options: DefaultProductionGateOptions): Gate<TArtifact, TScenario>;
1518
- interface HeldOutGateOptions<TScenario extends Scenario = Scenario> {
1519
- scenarios: TScenario[];
1520
- /** Effect-size threshold the CI lower bound must clear, in the judge's native
1521
- * scale. Default 0.5. Equality holds; CI.low must be greater than this value. */
1522
- deltaThreshold?: number;
1523
- /** Bootstrap CI confidence. Default 0.95. */
1524
- confidence?: number;
1525
- /** Minimum paired holdout observations to claim significance. The exact
1526
- * small-sample test may require more observations at the selected
1527
- * confidence. Default 3. */
1528
- minProductiveRuns?: number;
1529
- /** Bootstrap resamples. Default 2000. */
1530
- resamples?: number;
1531
- /** Fixed bootstrap seed for deterministic verdicts. Default 1337. */
1532
- bootstrapSeed?: number;
1533
- }
1534
- /**
1535
- * Composable held-out gate: ships only when the lower bound of the DECIDING
1536
- * paired interval on the candidate-minus-baseline composite delta clears
1537
- * `deltaThreshold` — Tango's score interval on a pass/fail holdout, the mean
1538
- * bootstrap otherwise. See {@link decidePairedPromotion}.
1539
- */
1540
- declare function heldOutGate<TArtifact, TScenario extends Scenario>(options: HeldOutGateOptions<TScenario>): Gate<TArtifact, TScenario>;
1541
- interface CampaignComparisonUnits {
1542
- pairedCellN: number;
1543
- unitIds: string[];
1544
- /** Cells with no complete quality score on either arm. */
1545
- unscoredCellIds: string[];
1546
- /** Present when repetitions and source variants share an independent unit. */
1547
- independentUnitByScenarioId?: Record<string, string>;
1548
- }
1549
- /** Mean composite across cells with complete task-quality evidence.
1550
- * Partial judge results remain on their cells but never enter this value.
1551
- * A campaign with no complete score has no numeric mean and fails loudly. */
1552
- declare function campaignMeanComposite<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): number;
1553
- interface CampaignBreakdown {
1554
- /** Mean score per judge dimension across all cells. */
1555
- dimensions: Record<string, number>;
1556
- /** Per-scenario composite (mean over reps + judges) + the judge's free-form
1557
- * `notes` for that scenario (the "why" a reflective proposer grounds on) +
1558
- * an optional `emitted` excerpt of the candidate's raw output (the "what it
1559
- * actually did" a reflective proposer grounds on). */
1560
- scenarios: Array<{
1561
- scenarioId: string;
1562
- composite: number;
1563
- notes?: string;
1564
- emitted?: string;
1565
- }>;
684
+ interface CrossSurfaceRankedSingle {
685
+ rank: number;
686
+ candidateId: string;
687
+ componentId: string;
1566
688
  }
1567
- /** Per-candidate evidence a reflective/patch proposer grounds its next proposal
1568
- * on: mean score per judge dimension + per-scenario composite. */
1569
- declare function campaignBreakdown<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): CampaignBreakdown;
1570
- interface LoopProvenanceCandidate {
1571
- /** Generation index this candidate was proposed in. */
1572
- generation: number;
1573
- /** 16-char loop-identity fingerprint (matches `GenerationCandidate.surfaceHash`). */
1574
- surfaceHash: string;
1575
- /** Full sha256 content hash — byte-identical-verifiable. */
1576
- contentHash: string;
1577
- /** Exact scored rows that produced this candidate's search result. */
1578
- campaignDigest: `sha256:${string}`;
1579
- /** Proposer label, when the proposer returned a `ProposedCandidate`. */
1580
- label?: string;
1581
- /** Proposer rationale — the "because Z". When the proposer returned a bare
1582
- * surface (blind mutator) this is absent. */
1583
- rationale?: string;
1584
- /** Proposer-supplied typed attribution, carried unchanged from
1585
- * `GenerationCandidate.attribution`. Opaque here; the producer's schema tag
1586
- * governs interpretation. */
1587
- attribution?: Readonly<Record<string, unknown>>;
1588
- /** Whether the candidate completed every designed cell and could be selected. */
1589
- eligibleForPromotion: boolean;
1590
- /** Designed-denominator receipt retained even for incomplete candidates. */
1591
- coverage: NonNullable<GenerationCandidate['coverage']>;
1592
- /** Mean composite this candidate scored on the search split, or null when unscorable. */
1593
- composite: number | null;
1594
- /** Whether this candidate was promoted out of its generation. */
1595
- promoted: boolean;
689
+ interface CrossSurfaceBestSingleSelection {
690
+ candidateId: string;
691
+ componentId: string;
692
+ ranking: CrossSurfaceRankedSingle[];
1596
693
  }
1597
- interface LoopProvenanceBackend {
1598
- /** `assertRealBackend`-grade verdict over the worker call records. */
1599
- verdict: 'real' | 'mixed' | 'stub';
1600
- /** Number of worker LLM calls captured (the audit's "worker call count"). */
1601
- workerCallCount: number;
1602
- /** Distinct model ids observed across worker calls. */
1603
- models: string[];
1604
- totalInputTokens: number;
1605
- totalOutputTokens: number;
1606
- totalCostUsd: number;
694
+ interface CrossSurfaceNaiveStackSelection {
695
+ /** Every individually eligible single, stacked in canonical component order. */
696
+ candidateId: string;
697
+ componentIds: string[];
1607
698
  }
1608
- interface LoopProvenanceEvidence {
1609
- search: {
1610
- splitDigest: `sha256:${string}`;
1611
- baselineCampaignDigest: `sha256:${string}`;
1612
- };
1613
- holdout: {
1614
- splitDigest: `sha256:${string}`;
1615
- baselineCampaignDigest: `sha256:${string}`;
1616
- winnerCampaignDigest: `sha256:${string}`;
1617
- observations?: CampaignComparisonUnits;
1618
- neutralized?: {
1619
- contentHash: `sha256:${string}`;
1620
- campaignDigest: `sha256:${string}`;
1621
- composite: number;
1622
- lift: number;
1623
- };
1624
- };
1625
- costReceiptsDigest: `sha256:${string}`;
699
+ type CrossSurfaceAdditionRejectionReason = 'pair_incompatible' | 'full_bundle_not_evaluated' | 'bundle_incomplete' | 'baseline_regression' | 'no_incremental_resolution' | 'incremental_regression' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
700
+ interface CrossSurfaceAdditionDecision {
701
+ additionCandidateId: string;
702
+ additionComponentId: string;
703
+ bundleCandidateId: string | null;
704
+ incrementalResolutionTaskIds: string[];
705
+ incrementalRegressionTaskIds: string[];
706
+ incrementalMedianCost: Record<string, number> | null;
707
+ eligible: boolean;
708
+ selected: boolean;
709
+ reasons: CrossSurfaceAdditionRejectionReason[];
1626
710
  }
1627
- interface LoopProvenanceOptimizationMethod {
1628
- name: string;
1629
- cost: ComparisonCost;
1630
- durationMs?: number;
1631
- provenance?: OptimizationMethodProvenance;
711
+ interface CrossSurfaceCompositionStep {
712
+ fromCandidateId: string;
713
+ retainedComponentIds: string[];
714
+ considered: CrossSurfaceAdditionDecision[];
715
+ selectedCandidateId: string | null;
1632
716
  }
1633
- /**
1634
- * The durable provenance record: the baseline and winner measurements, the
1635
- * rationale, the explicit baseline→candidate diff, and backend provenance.
1636
- */
1637
- interface LoopProvenanceRecord {
1638
- schema: 'tangle.loop-provenance';
1639
- /** SHA-256 over the canonical record with this field omitted. */
1640
- recordDigest: `sha256:${string}`;
1641
- runId: string;
1642
- runDir: string;
1643
- timestamp: string;
1644
- /** Baseline + winner surface content hashes — distinguishable, byte-verifiable. */
1645
- baselineContentHash: string;
1646
- winnerContentHash: string;
1647
- /** Proposer label/rationale for the promoted change. Absent ⇒ winner == baseline. */
1648
- winnerLabel?: string;
1649
- winnerRationale?: string;
1650
- /** The explicit baseline→winner unified diff the gate decided on. */
1651
- diff: string;
1652
- /** Every candidate across every generation, with its rationale and structured cause. */
1653
- candidates: LoopProvenanceCandidate[];
1654
- /** Complete external method identity and spend, when one authored the candidate. */
1655
- optimizationMethod?: LoopProvenanceOptimizationMethod;
1656
- /** Exact campaign, split, surface, and receipt identities behind every summary. */
1657
- evidence: LoopProvenanceEvidence;
1658
- /** Baseline composite on the search split that generated the candidates. */
1659
- baselineSearchComposite: number;
1660
- claim?: EvaluationClaim;
1661
- /** The gate verdict — decision + reasons + contributing gates + delta. */
1662
- gate: {
1663
- decision: GateDecision;
1664
- reasons: string[];
1665
- delta?: number;
1666
- contributingGates: GateContribution[];
1667
- };
1668
- /** Present iff the loop ran with `holdout: 'deferred'` — the held-out
1669
- * comparison was intentionally not measured in this run, so the holdout
1670
- * composites and `heldOutLift` are ABSENT rather than recorded as a
1671
- * meaningless 0. */
1672
- holdout?: 'deferred';
1673
- /** baseline-on-holdout composite mean. Absent when `holdout === 'deferred'`. */
1674
- baselineHoldoutComposite?: number;
1675
- /** winner-on-holdout composite mean. Absent when `holdout === 'deferred'`. */
1676
- winnerHoldoutComposite?: number;
1677
- /** winnerHoldout - baselineHoldout — RECOMPUTABLE from this record. Absent
1678
- * when `holdout === 'deferred'` (no held-out measurement ran). */
1679
- heldOutLift?: number;
1680
- /** Backend provenance: stub-vs-real verdict + worker call count + models. */
1681
- backend: LoopProvenanceBackend;
1682
- totalCostUsd: number;
1683
- totalDurationMs: number;
717
+ /** One deterministic growth path starting from a compatible two-surface seed. */
718
+ interface CrossSurfaceInteractionPath {
719
+ seedCandidateId: string;
720
+ terminalCandidateId: string;
721
+ terminalComponentIds: string[];
722
+ qualified: boolean;
723
+ steps: CrossSurfaceCompositionStep[];
1684
724
  }
1685
- interface BuildLoopProvenanceArgs<TArtifact, TScenario extends Scenario> {
1686
- runId: string;
1687
- runDir: string;
1688
- timestamp: string;
1689
- baselineSurface: MutableSurface;
1690
- winnerSurface: MutableSurface;
1691
- winnerLabel?: string;
1692
- winnerRationale?: string;
1693
- /** Exact baseline campaign on the search split. */
1694
- baselineSearchCampaign: CampaignResult<TArtifact, TScenario>;
1695
- /** Per-generation candidate records straight off the loop result. */
1696
- generations: Array<{
1697
- generationIndex: number;
1698
- candidates: GenerationCandidate[];
1699
- promoted: string[];
1700
- /** Surfaces measured this generation, keyed by surface hash so the content
1701
- * hash can be computed and the loop identity rechecked from real bytes. */
1702
- surfaces: Array<{
1703
- surfaceHash: string;
1704
- surface: MutableSurface;
1705
- campaign: CampaignResult<TArtifact, TScenario>;
1706
- }>;
1707
- }>;
1708
- gate: GateResult;
1709
- /** Holdout policy the loop ran with. `'deferred'` ⇒ the holdout campaigns
1710
- * below are the shared empty campaign and the record omits the holdout
1711
- * composites + `heldOutLift`. Default `'measured'`. */
1712
- holdout?: 'measured' | 'deferred';
1713
- baselineOnHoldout: CampaignResult<TArtifact, TScenario>;
1714
- winnerOnHoldout: CampaignResult<TArtifact, TScenario>;
1715
- claim?: EvaluationClaim;
1716
- /** Required with a measured claim because campaign identities redact source fields. */
1717
- independentUnitByScenarioId?: ReadonlyMap<string, string>;
1718
- neutralizedSurface?: MutableSurface;
1719
- neutralizedOnHoldout?: CampaignResult<TArtifact, TScenario>;
1720
- /** Settled run-wide receipts — agent calls are the source for backend provenance. */
1721
- costReceipts: ReadonlyArray<CostReceipt>;
1722
- totalCostUsd: number;
1723
- totalDurationMs: number;
1724
- optimizationMethod?: LoopProvenanceOptimizationMethod;
725
+ interface CrossSurfaceInteractionAwareSelection {
726
+ /** Compatible pair that seeded the selected deterministic growth path. */
727
+ seedCandidateId: string;
728
+ /** Candidate reached by the winning path, even if the minimum size is not met. */
729
+ terminalCandidateId: string;
730
+ terminalComponentIds: string[];
731
+ /** null when no path produced a qualifying multi-component bundle. */
732
+ selectedCandidateId: string | null;
733
+ qualified: boolean;
734
+ /** Every compatible pair seed is retained so seed choice cannot hide an interaction. */
735
+ evaluatedPaths: CrossSurfaceInteractionPath[];
736
+ /** Convenience alias for the winning path's steps. */
737
+ steps: CrossSurfaceCompositionStep[];
1725
738
  }
1726
- interface LoopProvenanceArgsFromResult<TArtifact, TScenario extends Scenario> {
1727
- runId: string;
1728
- runDir: string;
1729
- timestamp: string;
1730
- baselineSurface: MutableSurface;
1731
- result: RunImprovementLoopResult<TArtifact, TScenario>;
1732
- costReceipts: ReadonlyArray<CostReceipt>;
1733
- totalCostUsd: number;
1734
- totalDurationMs: number;
1735
- independentUnitByScenarioId?: ReadonlyMap<string, string>;
739
+ interface CrossSurfaceSelections {
740
+ bestSingle: CrossSurfaceBestSingleSelection | null;
741
+ naiveStack: CrossSurfaceNaiveStackSelection | null;
742
+ interactionAware: CrossSurfaceInteractionAwareSelection | null;
1736
743
  }
1737
- /** SHA-256 over the RFC 8785 canonical JSON of `value`. Throws
1738
- * `LedgerCanonicalizationError` for a value with no canonical form. */
1739
- declare function canonicalDigest(value: unknown): `sha256:${string}`;
1740
- interface EmitLoopProvenanceResult {
1741
- record: LoopProvenanceRecord;
1742
- spans: TraceSpanEvent[];
1743
- /** Absolute paths the record + spans were written to, when storage persists. */
1744
- recordPath: string;
1745
- spansPath: string;
744
+ interface CrossSurfaceInteractionReport<TRow extends CrossSurfaceTaskRow = CrossSurfaceTaskRow> {
745
+ taskIds: string[];
746
+ componentIds: string[];
747
+ candidateIds: string[];
748
+ costMetrics: string[];
749
+ /** Canonical candidate × task order; no input row is dropped. */
750
+ rows: TRow[];
751
+ missingAttempts: TRow[];
752
+ invalidAttempts: TRow[];
753
+ candidates: CrossSurfaceCandidateSummary[];
754
+ pairwise: CrossSurfacePairwiseEntry[];
755
+ selections: CrossSurfaceSelections;
1746
756
  }
1747
- interface EmitLoopProvenanceArgs<TArtifact, TScenario extends Scenario> extends BuildLoopProvenanceArgs<TArtifact, TScenario> {
1748
- /** Storage the record + spans are written through. */
1749
- storage: CampaignStorage;
1750
- /** When set, the spans are also shipped to the hosted `/v1/ingest/traces`
1751
- * endpoint so the collector receives the full loop, not just `cost.*`. */
1752
- hostedClient?: HostedClient;
757
+ /**
758
+ * Build the complete cross-surface evidence matrix and derive all three frozen
759
+ * candidates. The task/candidate/component orders are part of the input so
760
+ * neither insertion order nor an after-the-fact tie-break can change a result.
761
+ */
762
+ declare function analyzeCrossSurfaceInteractions<TRow extends CrossSurfaceTaskRow>(input: AnalyzeCrossSurfaceInteractionsInput<TRow>): CrossSurfaceInteractionReport<TRow>;
763
+ interface ExternalOptimizerObservationSummary {
764
+ scope: 'callback-submitted-candidates';
765
+ path: string;
766
+ sha256: `sha256:${string}`;
767
+ submittedCandidates: number;
768
+ evaluations: number;
769
+ refusals: number;
770
+ }
771
+ interface ExternalOptimizerExecutionSummary {
772
+ scope: 'runtime-model-calls';
773
+ path: string;
774
+ sha256: `sha256:${string}`;
775
+ calls: number;
776
+ succeeded: number;
777
+ failed: number;
778
+ }
779
+ interface ExternalOptimizerSubmittedCandidate {
780
+ /** Exact text or named-component surface submitted to the evaluation callback. */
781
+ readonly candidate: ExternalTextCandidate;
782
+ /** Eval's canonical content identity for `candidate`. */
783
+ readonly candidateHash: string;
784
+ readonly candidateDigest: `sha256:${string}`;
785
+ readonly proposalSequence: number;
786
+ /** Exact observation artifact that proves this candidate was submitted. */
787
+ readonly provenance: {
788
+ readonly path: string;
789
+ readonly sha256: `sha256:${string}`;
790
+ };
791
+ }
792
+ interface ExternalOptimizerObservationArtifact {
793
+ readonly summary: ExternalOptimizerObservationSummary;
794
+ readonly observations: readonly ExternalOptimizerEvaluationObservation[];
795
+ /** Every distinct callback-submitted candidate in proposal order. */
796
+ readonly candidates: readonly ExternalOptimizerSubmittedCandidate[];
1753
797
  }
1754
798
  /**
1755
- * Build the provenance record + OTel spans and persist them durably under the
1756
- * run dir (and ship spans to a hosted collector when one is wired). Returns
1757
- * both artifacts so the caller can assert on / re-derive from them.
799
+ * Read and verify the exact callback observation artifact addressed by method provenance.
1758
800
  *
1759
- * Fail-loud: the durable write throws on storage failure (a swallowed write is
1760
- * exactly the "emitted but lost" failure this closes). The hosted span ship is
1761
- * the one best-effort leg — its failure is logged, not thrown, so an offline
1762
- * collector never fails the loop (the durable artifact is the source of truth).
801
+ * The reader checks the raw SHA-256, canonical JSONL bytes, sequence, candidate
802
+ * identities, and summary counts before it returns any candidate.
803
+ * This proves that the bytes match the supplied summary. The caller remains
804
+ * responsible for obtaining that summary from trusted provenance.
1763
805
  */
1764
- declare function emitLoopProvenance<TArtifact, TScenario extends Scenario>(args: EmitLoopProvenanceArgs<TArtifact, TScenario>): Promise<EmitLoopProvenanceResult>;
1765
- interface TraceAnalystScenario extends Scenario {
1766
- kind: 'trace-analyst';
1767
- traceStore: TraceAnalysisStore;
1768
- labelState: AnalystBenchmarkLabelState;
1769
- expectedIssues: readonly AnalystIssueExpectation[];
1770
- labeledEvidence?: AnalystBenchmarkCase['labeledEvidence'];
806
+ declare function readExternalOptimizerObservationArtifact(input: {
807
+ summary: ExternalOptimizerObservationSummary;
808
+ storage?: CampaignStorage;
809
+ }): ExternalOptimizerObservationArtifact;
810
+ interface GepaCandidatePopulationSummary {
811
+ readonly scope: 'gepa-candidate-population';
812
+ readonly path: string;
813
+ readonly sha256: `sha256:${string}`;
814
+ readonly bytes: number;
815
+ readonly runId: string;
816
+ readonly candidates: number;
817
+ readonly bestIndex: number;
818
+ readonly maxCandidates: number;
819
+ readonly maxCandidateChars: number;
820
+ readonly scenarioIds: readonly string[];
821
+ readonly surfaceKind: 'text' | 'components';
1771
822
  }
1772
- interface TraceAnalystArtifact {
1773
- findings: readonly AnalystFinding[];
1774
- usage?: AnalystUsageReceipt;
1775
- run?: AnalystRunResult;
823
+ interface GepaCandidateSelectionScore {
824
+ readonly scenarioId: string;
825
+ readonly score: number;
1776
826
  }
1777
- interface BuildTraceAnalystSurfaceDispatchOptions {
1778
- analyze(input: {
1779
- instructions: string;
1780
- traceStore: TraceAnalysisStore;
1781
- runId: string;
1782
- signal: AbortSignal;
1783
- }): Promise<TraceAnalystArtifact>;
827
+ interface GepaCandidatePopulationCandidate {
828
+ /** Zero-based index assigned by the exact GEPA result. */
829
+ readonly index: number;
830
+ readonly candidate: ExternalTextCandidate;
831
+ readonly candidateHash: string;
832
+ readonly candidateDigest: `sha256:${string}`;
833
+ /** Exact GEPA parent indices. The seed candidate has one null parent. */
834
+ readonly parentIndices: readonly (number | null)[];
835
+ /** Null means GEPA had no selection score for this candidate. */
836
+ readonly aggregateScore: number | null;
837
+ readonly selectionScores: readonly GepaCandidateSelectionScore[];
838
+ readonly discoveryEvaluationCount: number;
1784
839
  }
1785
- /** Read the source rates for this execution, never a copied model price table.
1786
- * inputTokens includes cachedTokens. Seat credits are standard model credits;
1787
- * discounts and MCP charges require provider observations, not token guesses.
1788
- * The existing USD receipt remains the Router charge. Sandbox is additional.
1789
- */
1790
- declare function measureCampaignCost(input: {
1791
- routerUsd?: number;
1792
- sandbox?: {
1793
- seconds: number;
1794
- cpu: number;
1795
- memoryGB: number;
1796
- diskGB: number;
1797
- pool?: string;
1798
- };
1799
- seat?: {
1800
- model: string;
1801
- usage: CostUsage & {
1802
- usageUnknown?: boolean;
1803
- };
1804
- };
1805
- signal?: AbortSignal;
1806
- }): Promise<CostBreakdown>;
1807
- /** Whether one candidate attempt produced a usable executable outcome. */
1808
- type CrossSurfaceAttemptCompleteness = 'complete' | 'missing' | 'invalid';
1809
- /** One independently proposed change on one caller-defined surface. */
1810
- interface CrossSurfaceComponent {
1811
- componentId: string;
1812
- surfaceId: string;
1813
- /** Explicitly controls whether this component may anchor the best-single arm. */
1814
- bestSingleEligible: boolean;
840
+ interface GepaCandidatePopulationArtifact {
841
+ readonly summary: GepaCandidatePopulationSummary;
842
+ readonly runId: string;
843
+ readonly bestIndex: number;
844
+ readonly candidates: readonly GepaCandidatePopulationCandidate[];
1815
845
  }
1816
- /** Immutable identity for a single candidate or a materialized composition. */
1817
- interface CrossSurfaceCandidate {
1818
- candidateId: string;
1819
- componentIds: string[];
1820
- contentHash: string;
1821
- artifactBytes: number;
846
+ /**
847
+ * Read GEPA's exact candidate graph from the artifact addressed by method provenance.
848
+ *
849
+ * The reader checks the supplied digest, declared byte count, run identity,
850
+ * candidate surfaces, parent graph, selection scores, and configured bounds.
851
+ * This proves that the bytes match the supplied summary. The caller remains
852
+ * responsible for obtaining that summary from trusted method provenance.
853
+ */
854
+ declare function readGepaCandidatePopulationArtifact(input: {
855
+ summary: GepaCandidatePopulationSummary;
856
+ storage?: CampaignStorage;
857
+ }): GepaCandidatePopulationArtifact;
858
+ /** Cost reported by a method or by final test scoring. */
859
+ interface ComparisonCost {
860
+ /** Known subtotal. Consult `costProvenance` before treating this as total spend. */
861
+ totalCostUsd: number;
862
+ /** Exact origin of the total; uncaptured means `totalCostUsd` is only a known subtotal. */
863
+ costProvenance: CostProvenance;
864
+ accountingComplete: boolean;
865
+ incompleteReasons: string[];
1822
866
  }
1823
- /** Per-component trace evidence captured during one task attempt. */
1824
- interface CrossSurfaceComponentEvidence {
1825
- componentId: string;
1826
- /** null means the trace could not establish whether the component fired. */
1827
- fired: boolean | null;
1828
- /** null means the trace could not establish whether the component changed behavior. */
1829
- effectObserved: boolean | null;
867
+ /** Keep the cost fields a custom optimization method must report. */
868
+ declare function costFromLedgerSummary(summary: CostLedgerSummary): ComparisonCost;
869
+ interface OptimizationTokenUsage {
870
+ /** All input tokens, including cache reads and cache creation. */
871
+ inputTokens: number;
872
+ /** Input tokens served from a provider cache. */
873
+ cachedInputTokens?: number;
874
+ /** Input tokens used to create or write a provider cache entry. */
875
+ cacheWriteInputTokens?: number;
876
+ outputTokens: number;
877
+ /** Reasoning tokens included in `outputTokens`. */
878
+ reasoningTokens?: number;
879
+ totalTokens: number;
880
+ calls: number;
1830
881
  }
1831
- /**
1832
- * Canonical per-task input row. Consumers may extend this interface with
1833
- * receipt, trace, retry, or failure details; the report preserves the original
1834
- * row object rather than projecting those details away.
1835
- */
1836
- interface CrossSurfaceTaskRow {
1837
- taskId: string;
1838
- candidateId: string;
1839
- /** Repeated here so every persisted row remains self-describing. */
1840
- componentIds: string[];
1841
- completeness: CrossSurfaceAttemptCompleteness;
1842
- pass: boolean | null;
1843
- score: number | null;
1844
- /**
1845
- * Per-attempt deployment measurements. Every declared metric must have a
1846
- * known, non-negative value. Proposal, analysis, and selection spend belongs
1847
- * in the search ledger rather than being spread across task cells.
1848
- */
1849
- cost: Record<string, number | null>;
1850
- componentEvidence: CrossSurfaceComponentEvidence[];
1851
- /** Required for missing or invalid attempts; forbidden for complete attempts. */
1852
- rejectReason: string | null;
882
+ /** Shared campaign settings applied to every optimization method. */
883
+ type OptimizationMethodRunOptions<TScenario extends Scenario, TArtifact> = Omit<RunCampaignOptions<TScenario, TArtifact>, 'costCeiling' | 'costLedger' | 'dispatch' | 'judges' | 'runDir' | 'scenarios' | 'seed'>;
884
+ interface OptimizationPackageSource {
885
+ kind: 'package';
886
+ /** Whether package identity was inspected or supplied by caller code. */
887
+ evidence: 'observed' | 'declared';
888
+ package: string;
889
+ version: string;
890
+ sourceUrl?: string;
891
+ revision?: string;
892
+ /** SHA-256 of all installed module files observed before the run. */
893
+ sourceSha256?: string;
1853
894
  }
1854
- interface CrossSurfaceBootstrapPolicy {
1855
- seed: number;
1856
- resamples: number;
1857
- confidence: number;
895
+ interface OptimizationModuleSource {
896
+ module: string;
897
+ sourceSha256: string;
1858
898
  }
1859
- /** Predeclared candidate eligibility and composition policy. */
1860
- interface CrossSurfaceSelectionPolicy {
1861
- minimumFiringTasks: number;
1862
- minimumEffectTasks: number;
1863
- requireObservedFiring: boolean;
1864
- requireObservedEffect: boolean;
1865
- /** Only named metrics are constrained; all declared metrics are still reported. */
1866
- maximumMedianCostRatioToBaseline: Record<string, number>;
1867
- /** A smaller terminal bundle is reported but cannot become the selected arm. */
1868
- minimumBundleComponents: number;
899
+ interface OptimizationPythonRuntime {
900
+ implementation: string;
901
+ version: string;
1869
902
  }
1870
- interface AnalyzeCrossSurfaceInteractionsInput<TRow extends CrossSurfaceTaskRow = CrossSurfaceTaskRow> {
1871
- components: readonly CrossSurfaceComponent[];
1872
- candidates: readonly CrossSurfaceCandidate[];
1873
- rows: readonly TRow[];
1874
- baselineCandidateId: string;
1875
- /** Exact shared task axis and its canonical output order. */
1876
- taskOrder: readonly string[];
1877
- /** Canonical materialization order for component sets and the naive stack. */
1878
- componentOrder: readonly string[];
1879
- /** Final deterministic tie-break; lower index wins. */
1880
- candidateOrder: readonly string[];
1881
- /** Declares every cost key and the order used for cost tie-breaks. */
1882
- costMetricOrder: readonly string[];
1883
- bootstrap: CrossSurfaceBootstrapPolicy;
1884
- selection: CrossSurfaceSelectionPolicy;
903
+ interface OptimizationMethodProvenance {
904
+ /** External optimizer package. */
905
+ source: OptimizationPackageSource;
906
+ /** Python bridge package that invoked the optimizer. */
907
+ bridge?: OptimizationPackageSource;
908
+ /** Custom engine modules imported by the optimizer. */
909
+ modules?: OptimizationModuleSource[];
910
+ /** Python implementation used by the bridge process. */
911
+ python?: OptimizationPythonRuntime;
912
+ /** Exact model identifier configured for optimizer-owned model calls. */
913
+ optimizerModel?: string;
914
+ /** Stable public identity of the execution-owner callback. */
915
+ optimizerCallRef?: string;
916
+ runId: string;
917
+ /** Content identity shared by compatible resumptions. */
918
+ compatibleRunId?: string;
919
+ resumed: boolean;
920
+ /** Whether the run seed reached every external engine configuration. */
921
+ seedApplied?: boolean;
922
+ /** Evaluations the local callback metered — the trusted count. */
923
+ evaluationCount: number;
924
+ /**
925
+ * Evaluation total the external optimizer reported from its own counters.
926
+ * A difference from `evaluationCount` means upstream skipped, cached, or
927
+ * double-counted work; inspect before trusting upstream-derived budgets.
928
+ */
929
+ upstreamReportedEvaluations?: number;
930
+ artifactDir: string;
931
+ tokenUsage?: OptimizationTokenUsage;
932
+ /** Candidates submitted to the callback, per-case scores, and refusals. */
933
+ observations?: ExternalOptimizerObservationSummary;
934
+ /** Exact accepted GEPA candidates, parent indices, and selection scores. */
935
+ gepaCandidatePopulation?: GepaCandidatePopulationSummary;
936
+ /** Opaque Runtime execution evidence for every invoked optimizer-model call. */
937
+ modelExecutions?: ExternalOptimizerExecutionSummary;
938
+ /** Anthropic-endpoint proxy traffic from agent CLI engines, when enabled. */
939
+ anthropicEndpoint?: ExternalOptimizerWireCounts;
1885
940
  }
1886
- interface CrossSurfaceDistribution {
1887
- n: number;
1888
- min: number;
1889
- median: number;
1890
- mean: number;
1891
- max: number;
1892
- total: number;
941
+ /** Shared inputs for one optimization method. Final test data is absent. */
942
+ interface OptimizationMethodInput<TScenario extends Scenario, TArtifact> {
943
+ /** Surface every method starts from. */
944
+ readonly baselineSurface: MutableSurface;
945
+ /** Evidence used to author or fit candidates. */
946
+ readonly trainScenarios: readonly TScenario[];
947
+ /** Data used for candidate acceptance, early stopping, and model selection. */
948
+ readonly selectionScenarios: readonly TScenario[];
949
+ /** Runs one scenario with a candidate surface. */
950
+ readonly dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
951
+ /** Scores artifacts produced by `dispatchWithSurface`. */
952
+ readonly judges: readonly JudgeConfig<TArtifact, TScenario>[];
953
+ /** Method-specific artifacts are written below this directory. */
954
+ readonly runDir: string;
955
+ readonly seed: number;
956
+ /** Shared defaults for every method. A method may override them explicitly. */
957
+ readonly runOptions: Readonly<OptimizationMethodRunOptions<TScenario, TArtifact>>;
958
+ /** Durable spend account shared by every method and final scoring. */
959
+ readonly costLedger: CostLedgerHandle;
960
+ /** Invokes each method at the shared execution boundary, including composed children. */
961
+ invokeMethod?(method: OptimizationMethod<TScenario, TArtifact>, input: OptimizationMethodInput<TScenario, TArtifact>): Promise<OptimizationMethodResult>;
962
+ /** Maps this method's local surface into the complete outer candidate. */
963
+ readonly surfaceToRoot?: (surface: MutableSurface) => MutableSurface;
1893
964
  }
1894
- interface CrossSurfaceEvidenceBreakdown {
1895
- componentId: string;
1896
- observedTaskIds: string[];
1897
- notObservedTaskIds: string[];
1898
- unobservedTaskIds: string[];
965
+ /** Exact child results; costs and usage remain attributable to their owning methods. */
966
+ interface OptimizationMethodComposition {
967
+ kind: 'scoped' | 'sequential';
968
+ baselineSurfaceHash: string;
969
+ stages: Array<{
970
+ name: string;
971
+ baselineSurfaceHash: string;
972
+ result: OptimizationMethodResult;
973
+ }>;
1899
974
  }
1900
- interface CrossSurfaceCandidateEvidence {
1901
- byComponent: CrossSurfaceEvidenceBreakdown[];
1902
- allObservedTaskIds: string[];
1903
- someObservedTaskIds: string[];
1904
- noneObservedTaskIds: string[];
1905
- unobservedTaskIds: string[];
975
+ interface OptimizationMethodResult {
976
+ /** Surface selected without using the final test partition. */
977
+ winnerSurface: MutableSurface;
978
+ composition?: OptimizationMethodComposition;
979
+ /** Optimization spend. Excludes final test scoring. */
980
+ cost: ComparisonCost;
981
+ /** Optimization duration. Excludes final test scoring. */
982
+ durationMs?: number;
983
+ /** Exact external implementation and run identity, when the method uses one. */
984
+ provenance?: OptimizationMethodProvenance;
985
+ /** Bounded proof envelope over the canonical SearchLedger for this optimization. */
986
+ searchHistory?: SearchHistoryReceipt;
1906
987
  }
1907
- type CrossSurfaceIneligibilityReason = 'missing_attempt' | 'invalid_attempt' | 'baseline_outcome_missing' | 'benefit_not_greater_than_regression' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
1908
- interface CrossSurfaceEligibility {
1909
- eligible: boolean;
1910
- reasons: CrossSurfaceIneligibilityReason[];
988
+ /** A complete optimization method, including candidate generation and selection. */
989
+ interface OptimizationMethod<TScenario extends Scenario = Scenario, TArtifact = unknown> {
990
+ /** Unique, trimmed display name. Its normalized form must also be unique. */
991
+ name: string;
992
+ optimize: (input: OptimizationMethodInput<TScenario, TArtifact>) => Promise<OptimizationMethodResult>;
1911
993
  }
1912
- interface CrossSurfaceCandidateOutcome {
1913
- resolvedTaskIds: string[];
1914
- failedTaskIds: string[];
1915
- missingTaskIds: string[];
1916
- invalidTaskIds: string[];
1917
- benefitTaskIds: string[];
1918
- regressionTaskIds: string[];
1919
- comparisonMissingTaskIds: string[];
1920
- netBenefit: number;
994
+ interface ExternalOptimizationExample {
995
+ id: string;
996
+ data: unknown;
1921
997
  }
1922
- interface CrossSurfaceCandidateSummary {
1923
- candidate: CrossSurfaceCandidate;
1924
- outcome: CrossSurfaceCandidateOutcome;
1925
- score: CrossSurfaceDistribution | null;
1926
- costs: Record<string, CrossSurfaceDistribution>;
1927
- firing: CrossSurfaceCandidateEvidence;
1928
- effect: CrossSurfaceCandidateEvidence;
1929
- /** Reuses the package's paired McNemar/risk-difference/bootstrap statistics. */
1930
- comparisonToBaseline: PairedArmsComparison | null;
1931
- /** null only for the fixed baseline. */
1932
- eligibility: CrossSurfaceEligibility | null;
998
+ interface ExternalTextEvaluationResponse {
999
+ score: number;
1000
+ info: {
1001
+ scenarioId: string;
1002
+ dimensions: Record<string, number>;
1003
+ /** Higher-is-better objectives consumed by GEPA hybrid/Pareto selection. */
1004
+ scores?: Record<string, number>;
1005
+ notes?: string;
1006
+ artifact?: unknown;
1007
+ /** The optimizer score is a finite protocol value; Eval remains the
1008
+ * authority for whether the underlying cell actually produced a score. */
1009
+ status?: 'scored' | 'failed';
1010
+ error?: {
1011
+ stage: 'dispatch' | 'judge' | 'unknown';
1012
+ message: string;
1013
+ };
1014
+ };
1933
1015
  }
1934
- interface CrossSurfaceRelativeCost {
1935
- treatmentMedian: number;
1936
- comparatorMedian: number;
1937
- medianDelta: number;
1938
- /** null when the comparator median is zero but the treatment median is not. */
1939
- medianRatio: number | null;
1016
+ declare function decodeExternalTextCandidate(candidate: ExternalTextCandidate): MutableSurface;
1017
+ interface ExternalTextOptimizerContext {
1018
+ readonly runId: string;
1019
+ readonly name: string;
1020
+ readonly objective: string;
1021
+ readonly evaluationId: string;
1022
+ readonly background?: string;
1023
+ readonly seedCandidate: ExternalTextCandidate;
1024
+ readonly trainSet: readonly ExternalOptimizationExample[];
1025
+ readonly selectionSet: readonly ExternalOptimizationExample[];
1026
+ readonly maxEvaluations: number;
1027
+ readonly seed: number;
1028
+ /** Stable directory for optimizer checkpoints from compatible attempts. */
1029
+ readonly stateDir: string;
1030
+ readonly restoreRequested: boolean;
1031
+ readonly artifactDir: string;
1032
+ readonly signal: AbortSignal;
1033
+ /** Record every optimizer-owned paid call through this attributed account. */
1034
+ readonly cost: CampaignCostMeter;
1035
+ readonly evaluate: (request: ExternalTextEvaluationRequest) => Promise<ExternalTextEvaluationResponse>;
1940
1036
  }
1941
- interface CrossSurfaceCandidateComparison {
1942
- comparatorCandidateId: string;
1943
- treatmentCandidateId: string;
1944
- winsTaskIds: string[];
1945
- regressionTaskIds: string[];
1946
- missingTaskIds: string[];
1947
- paired: PairedArmsComparison;
1948
- relativeCost: Record<string, CrossSurfaceRelativeCost>;
1037
+ interface ExternalTextOptimizerResult {
1038
+ bestCandidate: ExternalTextCandidate;
1039
+ resumed: boolean;
1040
+ costAccounting: {
1041
+ kind: 'metered';
1042
+ } | {
1043
+ kind: 'no-paid-work';
1044
+ } | {
1045
+ kind: 'external';
1046
+ reason: string;
1047
+ };
1949
1048
  }
1950
- interface CrossSurfacePairEvidence {
1951
- bothTaskIds: string[];
1952
- leftOnlyTaskIds: string[];
1953
- rightOnlyTaskIds: string[];
1954
- neitherTaskIds: string[];
1955
- unobservedTaskIds: string[];
1049
+ /**
1050
+ * Configuration for adapting another text optimizer.
1051
+ *
1052
+ * `run` owns search. Agent Eval owns split isolation, bounded candidate
1053
+ * evaluation, exact cost collection, provenance, and final comparison.
1054
+ */
1055
+ interface ExternalTextOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
1056
+ name: string;
1057
+ source: Omit<OptimizationPackageSource, 'evidence'>;
1058
+ objective: string;
1059
+ evaluationId: string;
1060
+ background?: string;
1061
+ maxEvaluations: number;
1062
+ /** Hard limit for calls made through `context.cost`. Use 0 for no paid work. */
1063
+ maxOptimizerCostUsd: number;
1064
+ /** Abort `context.signal` after this duration. Default: 30 minutes. */
1065
+ timeoutMs?: number;
1066
+ /** Default: `never`. Compatible runs reuse one state directory. */
1067
+ resume?: ExternalOptimizerResumeMode;
1068
+ maxCandidateChars?: number;
1069
+ maxEvidenceChars?: number;
1070
+ describeScenario?: (scenario: TScenario) => unknown;
1071
+ describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
1072
+ run: (context: ExternalTextOptimizerContext) => Promise<ExternalTextOptimizerResult>;
1956
1073
  }
1957
- interface CrossSurfaceInteractionTask {
1958
- taskId: string;
1959
- /** Composition minus the additive expectation from the baseline and singles. */
1960
- passInteraction: number | null;
1961
- scoreInteraction: number | null;
1074
+ /**
1075
+ * Adapt a third-party text optimizer without reimplementing its search.
1076
+ *
1077
+ * The callback never receives final test cases. Calls to `evaluate` are
1078
+ * counted before execution and stop at `maxEvaluations`.
1079
+ */
1080
+ declare function externalTextOptimizationMethod<TScenario extends Scenario, TArtifact>(config: ExternalTextOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
1081
+ type EvalFixtureValidationMode = 'vitest' | 'none';
1082
+ interface EvalFixtureFile {
1083
+ path: string;
1084
+ sha256: string;
1085
+ bytes: number;
1962
1086
  }
1963
- interface CrossSurfaceInteractionEffect {
1964
- perTask: CrossSurfaceInteractionTask[];
1965
- n: number;
1966
- nMissing: number;
1967
- meanPassInteraction: number | null;
1968
- meanScoreInteraction: number | null;
1969
- passBootstrap: PairedBootstrapResult | null;
1970
- scoreBootstrap: PairedBootstrapResult | null;
1087
+ interface EvalFixture {
1088
+ name: string;
1089
+ path: string;
1090
+ promptPath: string;
1091
+ evalPath?: string;
1092
+ packageJsonPath?: string;
1093
+ prompt: string;
1094
+ files: EvalFixtureFile[];
1095
+ fingerprint: string;
1971
1096
  }
1972
- type CrossSurfacePairIncompatibilityReason = 'constituent_not_ready' | 'pair_incomplete' | 'baseline_regression' | 'interference' | 'no_incremental_resolution' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
1973
- interface CrossSurfacePairCompatibility {
1974
- compatible: boolean;
1975
- reasons: CrossSurfacePairIncompatibilityReason[];
1976
- betterSingleCandidateId: string;
1097
+ interface EvalFixtureScenario extends Scenario {
1098
+ kind: 'eval-fixture';
1099
+ fixtureName: string;
1100
+ fixturePath: string;
1101
+ promptPath: string;
1102
+ evalPath?: string;
1103
+ packageJsonPath?: string;
1104
+ prompt: string;
1105
+ fingerprint: string;
1977
1106
  }
1978
- interface CrossSurfacePairwiseEntry {
1979
- componentIds: [string, string];
1980
- singleCandidateIds: [string, string];
1981
- compositionCandidateId: string;
1982
- benefitTaskIds: string[];
1983
- regressionTaskIds: string[];
1984
- synergyTaskIds: string[];
1985
- interferenceTaskIds: string[];
1986
- incrementalVsConstituents: [CrossSurfaceCandidateComparison, CrossSurfaceCandidateComparison];
1987
- relativeCostToBaseline: Record<string, CrossSurfaceRelativeCost>;
1988
- firing: CrossSurfacePairEvidence;
1989
- effect: CrossSurfacePairEvidence;
1990
- interaction: CrossSurfaceInteractionEffect;
1991
- compatibility: CrossSurfacePairCompatibility;
1107
+ interface EvalFixtureLoadOptions {
1108
+ /** `vitest` requires EVAL.ts/EVAL.tsx and package.json type=module. `none` only requires PROMPT.md. */
1109
+ validation?: EvalFixtureValidationMode;
1110
+ /** Extra caller-owned knobs that affect fixture behavior, folded into the fingerprint. */
1111
+ fingerprintConfig?: unknown;
1992
1112
  }
1993
- interface CrossSurfaceRankedSingle {
1994
- rank: number;
1995
- candidateId: string;
1996
- componentId: string;
1113
+ interface LoadEvalFixtureScenariosOptions extends EvalFixtureLoadOptions {
1114
+ names?: string[];
1997
1115
  }
1998
- interface CrossSurfaceBestSingleSelection {
1999
- candidateId: string;
2000
- componentId: string;
2001
- ranking: CrossSurfaceRankedSingle[];
1116
+ interface PlanEvalFixtureRunOptions<TArtifact = unknown> extends Pick<PlanCampaignRunOptions<EvalFixtureScenario, TArtifact>, 'dispatchRef' | 'judges' | 'seed' | 'reps' | 'resumable' | 'runDir'> {
1117
+ evalsDir: string;
1118
+ validation?: EvalFixtureValidationMode;
1119
+ fingerprintConfig?: unknown;
1120
+ names?: string[];
1121
+ storage?: CampaignStorage;
2002
1122
  }
2003
- interface CrossSurfaceNaiveStackSelection {
2004
- /** Every individually eligible single, stacked in canonical component order. */
2005
- candidateId: string;
2006
- componentIds: string[];
1123
+ type EvalFixtureRunPlan = CampaignRunPlan & {
1124
+ fixtures: Array<Pick<EvalFixtureScenario, 'fixtureName' | 'fixturePath' | 'fingerprint'>>;
1125
+ };
1126
+ /** Walk `evalsDir` and return the relative name of every fixture directory (one containing an exact-case `PROMPT.md`). */
1127
+ declare function discoverEvalFixtures(evalsDir: string): string[];
1128
+ /**
1129
+ * Load ONE fixture by name: reads `PROMPT.md` (plus `EVAL.ts`/`EVAL.tsx` and `package.json` under
1130
+ * `vitest` validation) and content-fingerprints the full file set for cache identity.
1131
+ */
1132
+ declare function loadEvalFixture(evalsDir: string, name: string, options?: EvalFixtureLoadOptions): EvalFixture;
1133
+ /** Load fixtures (all discovered, or just `names`) as campaign `Scenario`s tagged `eval-fixture`. */
1134
+ declare function loadEvalFixtureScenarios(evalsDir: string, options?: LoadEvalFixtureScenariosOptions): EvalFixtureScenario[];
1135
+ /**
1136
+ * Dry-run planner for a fixture campaign: loads the scenarios, delegates to `planCampaignRun`,
1137
+ * and returns the plan plus each fixture's name/path/fingerprint.
1138
+ */
1139
+ declare function planEvalFixtureRun<TArtifact = unknown>(options: PlanEvalFixtureRunOptions<TArtifact>): EvalFixtureRunPlan;
1140
+ /** Compose gates — all must `ship` for the composite to `ship`. First
1141
+ * non-ship verdict short-circuits the composite verdict, but ALL gates run
1142
+ * (so the result records every gate's reason — useful for diagnostics). */
1143
+ declare function composeGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(...gates: Array<Gate<TArtifact, TScenario>>): Gate<TArtifact, TScenario>;
1144
+ type CanaryKind = 'silent_judge_fallback' | 'judge_calibration_drift' | 'distribution_shift';
1145
+ type CanarySeverity = 'info' | 'warn' | 'error';
1146
+ interface CanaryAlert {
1147
+ kind: CanaryKind;
1148
+ severity: CanarySeverity;
1149
+ message: string;
1150
+ /** Numbers that informed the decision — drop straight into a
1151
+ * dashboard / paper figure. */
1152
+ evidence: Record<string, unknown>;
2007
1153
  }
2008
- type CrossSurfaceAdditionRejectionReason = 'pair_incompatible' | 'full_bundle_not_evaluated' | 'bundle_incomplete' | 'baseline_regression' | 'no_incremental_resolution' | 'incremental_regression' | 'firing_below_minimum' | 'firing_unobserved' | 'effect_below_minimum' | 'effect_unobserved' | 'cost_limit_exceeded';
2009
- interface CrossSurfaceAdditionDecision {
2010
- additionCandidateId: string;
2011
- additionComponentId: string;
2012
- bundleCandidateId: string | null;
2013
- incrementalResolutionTaskIds: string[];
2014
- incrementalRegressionTaskIds: string[];
2015
- incrementalMedianCost: Record<string, number> | null;
2016
- eligible: boolean;
2017
- selected: boolean;
2018
- reasons: CrossSurfaceAdditionRejectionReason[];
1154
+ interface CanaryReport {
1155
+ alerts: CanaryAlert[];
1156
+ /** Per-kind summary count. */
1157
+ counts: Record<CanaryKind, number>;
1158
+ /** Whether each enabled detector had enough observations to run. */
1159
+ evaluations: CanaryEvaluation[];
2019
1160
  }
2020
- interface CrossSurfaceCompositionStep {
2021
- fromCandidateId: string;
2022
- retainedComponentIds: string[];
2023
- considered: CrossSurfaceAdditionDecision[];
2024
- selectedCandidateId: string | null;
1161
+ interface CanaryEvaluation {
1162
+ kind: CanaryKind;
1163
+ status: 'evaluated' | 'not_evaluated';
1164
+ observations: number;
1165
+ reason?: string;
2025
1166
  }
2026
- /** One deterministic growth path starting from a compatible two-surface seed. */
2027
- interface CrossSurfaceInteractionPath {
2028
- seedCandidateId: string;
2029
- terminalCandidateId: string;
2030
- terminalComponentIds: string[];
2031
- qualified: boolean;
2032
- steps: CrossSurfaceCompositionStep[];
1167
+ interface CanaryOptions {
1168
+ /**
1169
+ * Silent-fallback detection.
1170
+ * - `constant`: confidence value treated as the fallback signal.
1171
+ * Default 0.30 (matches the soft-fail default in
1172
+ * `propose-review.ts`).
1173
+ * - `consecutiveThreshold`: trip the alert after this many
1174
+ * consecutive runs at `constant` (or `fallback === true`).
1175
+ * Default 3.
1176
+ */
1177
+ silentFallback?: {
1178
+ constant?: number;
1179
+ consecutiveThreshold?: number;
1180
+ /** Floating-point tolerance when comparing against `constant`. */
1181
+ epsilon?: number;
1182
+ };
1183
+ /**
1184
+ * Calibration-drift detection.
1185
+ * - `historyWindow`: number of past runs (oldest-first) treated as
1186
+ * the historical baseline. Default 50.
1187
+ * - `recentWindow`: number of recent runs (newest-first) compared
1188
+ * against history. Default 20.
1189
+ * - `ksAlpha`: alpha for the KS statistic vs critical value.
1190
+ * Default 0.05.
1191
+ * - `minRecent`: minimum recent runs required to even attempt the
1192
+ * check. Default 10.
1193
+ */
1194
+ calibrationDrift?: {
1195
+ historyWindow?: number;
1196
+ recentWindow?: number;
1197
+ ksAlpha?: number;
1198
+ minRecent?: number;
1199
+ };
1200
+ /**
1201
+ * Distribution-shift detection.
1202
+ * - `category`: function that maps a run to a categorical bucket.
1203
+ * Required to enable this canary; if omitted the chi-square check
1204
+ * is skipped entirely.
1205
+ * - `chiSquareAlpha`: alpha. Default 0.05.
1206
+ * - `historyWindow`, `recentWindow`, `minRecent`: like above.
1207
+ */
1208
+ distributionShift?: {
1209
+ category: (run: RunRecord) => string | null;
1210
+ chiSquareAlpha?: number;
1211
+ historyWindow?: number;
1212
+ recentWindow?: number;
1213
+ minRecent?: number;
1214
+ };
2033
1215
  }
2034
- interface CrossSurfaceInteractionAwareSelection {
2035
- /** Compatible pair that seeded the selected deterministic growth path. */
2036
- seedCandidateId: string;
2037
- /** Candidate reached by the winning path, even if the minimum size is not met. */
2038
- terminalCandidateId: string;
2039
- terminalComponentIds: string[];
2040
- /** null when no path produced a qualifying multi-component bundle. */
2041
- selectedCandidateId: string | null;
2042
- qualified: boolean;
2043
- /** Every compatible pair seed is retained so seed choice cannot hide an interaction. */
2044
- evaluatedPaths: CrossSurfaceInteractionPath[];
2045
- /** Convenience alias for the winning path's steps. */
2046
- steps: CrossSurfaceCompositionStep[];
1216
+ /**
1217
+ * Run all configured canaries against a chronological run list.
1218
+ * Runs MUST be sorted oldest-to-newest by the caller — the order of
1219
+ * the input is used to define "recent" vs "historical" windows.
1220
+ */
1221
+ declare function runCanaries(runs: RunRecord[], opts?: CanaryOptions): CanaryReport;
1222
+ type RedTeamCategory = 'prompt_injection_direct' | 'prompt_injection_indirect' | 'jailbreak_persona' | 'jailbreak_dan' | 'pii_leak' | 'permission_escalation' | 'data_exfil' | 'policy_override';
1223
+ interface RedTeamPayload {
1224
+ category: RedTeamCategory;
1225
+ /** The hostile input the agent sees. */
1226
+ input: string;
1227
+ /**
1228
+ * What a safe agent should do: "refuse" means explicit refusal,
1229
+ * "ignore" means process benignly without executing the attack.
1230
+ */
1231
+ expected: 'refuse' | 'ignore';
1232
+ /** Substring(s) that MUST NOT appear in output. */
1233
+ forbiddenStrings?: string[];
1234
+ /** Tool names the agent MUST NOT call for this scenario. */
1235
+ forbiddenTools?: string[];
2047
1236
  }
2048
- interface CrossSurfaceSelections {
2049
- bestSingle: CrossSurfaceBestSingleSelection | null;
2050
- naiveStack: CrossSurfaceNaiveStackSelection | null;
2051
- interactionAware: CrossSurfaceInteractionAwareSelection | null;
1237
+ interface RedTeamCase extends DatasetScenario {
1238
+ payload: RedTeamPayload;
2052
1239
  }
2053
- interface CrossSurfaceInteractionReport<TRow extends CrossSurfaceTaskRow = CrossSurfaceTaskRow> {
2054
- taskIds: string[];
2055
- componentIds: string[];
2056
- candidateIds: string[];
2057
- costMetrics: string[];
2058
- /** Canonical candidate × task order; no input row is dropped. */
2059
- rows: TRow[];
2060
- missingAttempts: TRow[];
2061
- invalidAttempts: TRow[];
2062
- candidates: CrossSurfaceCandidateSummary[];
2063
- pairwise: CrossSurfacePairwiseEntry[];
2064
- selections: CrossSurfaceSelections;
1240
+ interface RedTeamFinding {
1241
+ scenarioId: string;
1242
+ category: RedTeamCategory;
1243
+ passed: boolean;
1244
+ reason: string;
1245
+ evidence?: string;
1246
+ }
1247
+ interface RedTeamReport {
1248
+ findings: RedTeamFinding[];
1249
+ passRateByCategory: Record<RedTeamCategory, number>;
1250
+ overallPassRate: number;
2065
1251
  }
1252
+ /** Ship a canonical, small corpus. Consumers extend via `extendCorpus`. */
1253
+ declare const DEFAULT_RED_TEAM_CORPUS: RedTeamCase[];
1254
+ declare function redTeamDataset(extraCases?: RedTeamCase[]): Dataset;
2066
1255
  /**
2067
- * Build the complete cross-surface evidence matrix and derive all three frozen
2068
- * candidates. The task/candidate/component orders are part of the input so
2069
- * neither insertion order nor an after-the-fact tie-break can change a result.
1256
+ * Score a single agent response against the red-team case.
1257
+ * `toolCalls` should be the names of tools the agent invoked during the run.
2070
1258
  */
2071
- declare function analyzeCrossSurfaceInteractions<TRow extends CrossSurfaceTaskRow>(input: AnalyzeCrossSurfaceInteractionsInput<TRow>): CrossSurfaceInteractionReport<TRow>;
2072
- type EvalFixtureValidationMode = 'vitest' | 'none';
2073
- interface EvalFixtureFile {
2074
- path: string;
2075
- sha256: string;
2076
- bytes: number;
2077
- }
2078
- interface EvalFixture {
2079
- name: string;
2080
- path: string;
2081
- promptPath: string;
2082
- evalPath?: string;
2083
- packageJsonPath?: string;
2084
- prompt: string;
2085
- files: EvalFixtureFile[];
2086
- fingerprint: string;
1259
+ declare function scoreRedTeamOutput(output: string, toolCalls: string[], rtCase: RedTeamCase): RedTeamFinding;
1260
+ /** Aggregate red-team findings into per-category pass rates. */
1261
+ declare function redTeamReport(findings: RedTeamFinding[]): RedTeamReport;
1262
+ type DefaultProductionGateCheck = 'dimension-regression' | 'budget' | 'red-team' | 'reward-hacking' | 'canary';
1263
+ type DefaultProductionRewardHackingOptions = Omit<DetectRewardHackingInput, 'runs' | 'truthOf'> & {
1264
+ truthOf: NonNullable<DetectRewardHackingInput['truthOf']>;
1265
+ };
1266
+ interface DefaultProductionGateOptions {
1267
+ /** Required: scenarios held out from training; substrate compares
1268
+ * candidate-on-holdout vs baseline-on-holdout. */
1269
+ holdoutScenarios: Scenario[];
1270
+ /**
1271
+ * Independent sampling unit for every held-out scenario. Pair cells first,
1272
+ * then average scores within each unit and give units equal weight.
1273
+ * Omit only when execution cells on a fixed roster are the observation units.
1274
+ */
1275
+ independentUnitByScenarioId?: ReadonlyMap<string, string>;
1276
+ /** Minimum held-out improvement under the shared paired decision rule.
1277
+ * Default 0. The outcome shape and sample count determine the statistical
1278
+ * test. Use native composite units, such as 2 for a 0-100 rubric. */
1279
+ deltaThreshold?: number;
1280
+ /** Confidence level for the held-out + dimension bootstraps. Default 0.95. */
1281
+ confidence?: number;
1282
+ /** Bootstrap resamples. Default 2000. */
1283
+ bootstrapResamples?: number;
1284
+ /** Fixed bootstrap seed for a deterministic verdict. Default 1337. */
1285
+ bootstrapSeed?: number;
1286
+ /** Minimum paired independent units (or cells when unconfigured) before a
1287
+ * significance claim is allowed. The exact small-sample test may require
1288
+ * more observations at the selected confidence. Default 3. */
1289
+ minProductiveRuns?: number;
1290
+ /** Ship statistic for the held-out significance test. Default `'mean'`
1291
+ * (tie-robust — see `heldoutSignificance`). Pass `'median'` for
1292
+ * outlier-robustness at the cost of tie-blindness. */
1293
+ heldoutStatistic?: 'mean' | 'median';
1294
+ /** Required judge dimensions checked for regression and complete evidence.
1295
+ * A bootstrap lower bound below negative tolerance or a paired test proving
1296
+ * a drop holds the gate. Thin or incomplete coverage is not_evaluated. */
1297
+ criticalDimensions?: string[];
1298
+ /** Tolerance for the per-dimension regression guard, in the dimension's
1299
+ * native scale. When omitted it auto-scales off observed magnitudes:
1300
+ * 0.05 on [0,1], 5 on 0-100. */
1301
+ regressionTolerance?: number;
1302
+ /** Total $ budget for the complete improvement run. Requires
1303
+ * `GateContext.costLedger`; missing or incomplete accounting holds. */
1304
+ budgetUsd?: number;
1305
+ /** Static artifact-screening cases. Only `expected: 'ignore'` cases without
1306
+ * tool assertions are valid because this check does not dispatch case inputs
1307
+ * or observe tool calls. */
1308
+ redTeamBattery?: RedTeamCase[];
1309
+ /** Shared run history, oldest first. Supplying history does not enable either
1310
+ * monitoring check; configure `rewardHacking` and/or `canary` explicitly. */
1311
+ recentRuns?: RunRecord[];
1312
+ /** Enable reward-hacking monitoring with a caller-owned independent truth channel. */
1313
+ rewardHacking?: DefaultProductionRewardHackingOptions;
1314
+ /** Enable canary monitoring. Pass `{}` to use the canary defaults. */
1315
+ canary?: CanaryOptions;
1316
+ /** Optional checks that must be evaluated even when their normal input is
1317
+ * absent. Configuring a check's input also makes that check required.
1318
+ * Missing evidence always records `not_evaluated`; required unevaluated
1319
+ * checks hold the release decision. Held-out significance is always required. */
1320
+ requiredChecks?: DefaultProductionGateCheck[];
2087
1321
  }
2088
- interface EvalFixtureScenario extends Scenario {
2089
- kind: 'eval-fixture';
2090
- fixtureName: string;
2091
- fixturePath: string;
2092
- promptPath: string;
2093
- evalPath?: string;
2094
- packageJsonPath?: string;
2095
- prompt: string;
2096
- fingerprint: string;
1322
+ /**
1323
+ * Opinionated production gate composing held-out significance, red-team, reward-hacking, and canary checks into a single `Gate.decide` decision.
1324
+ */
1325
+ declare function defaultProductionGate<TArtifact, TScenario extends Scenario>(options: DefaultProductionGateOptions): Gate<TArtifact, TScenario>;
1326
+ interface HeldOutGateOptions<TScenario extends Scenario = Scenario> {
1327
+ scenarios: TScenario[];
1328
+ /** Effect-size threshold the CI lower bound must clear, in the judge's native
1329
+ * scale. Default 0.5. Equality holds; CI.low must be greater than this value. */
1330
+ deltaThreshold?: number;
1331
+ /** Bootstrap CI confidence. Default 0.95. */
1332
+ confidence?: number;
1333
+ /** Minimum paired holdout observations to claim significance. The exact
1334
+ * small-sample test may require more observations at the selected
1335
+ * confidence. Default 3. */
1336
+ minProductiveRuns?: number;
1337
+ /** Bootstrap resamples. Default 2000. */
1338
+ resamples?: number;
1339
+ /** Fixed bootstrap seed for deterministic verdicts. Default 1337. */
1340
+ bootstrapSeed?: number;
2097
1341
  }
2098
- interface EvalFixtureLoadOptions {
2099
- /** `vitest` requires EVAL.ts/EVAL.tsx and package.json type=module. `none` only requires PROMPT.md. */
2100
- validation?: EvalFixtureValidationMode;
2101
- /** Extra caller-owned knobs that affect fixture behavior, folded into the fingerprint. */
2102
- fingerprintConfig?: unknown;
1342
+ /**
1343
+ * Composable held-out gate: ships only when the lower bound of the DECIDING
1344
+ * paired interval on the candidate-minus-baseline composite delta clears
1345
+ * `deltaThreshold` — Tango's score interval on a pass/fail holdout, the mean
1346
+ * bootstrap otherwise. See {@link decidePairedPromotion}.
1347
+ */
1348
+ declare function heldOutGate<TArtifact, TScenario extends Scenario>(options: HeldOutGateOptions<TScenario>): Gate<TArtifact, TScenario>;
1349
+ interface NeutralizationGateOptions<TScenario extends Scenario = Scenario> {
1350
+ scenarios: TScenario[];
1351
+ /** Reject when the neutralized (content-blanked, footprint-matched) variant
1352
+ * reproduces at least this fraction of the candidate's held-out lift. Default
1353
+ * 0.5 — if blanking the content keeps half the lift, the content is decorative.
1354
+ * Equality rejects: a neutralized lift == threshold·candidateLift is decorative. */
1355
+ maxDecorativeFraction?: number;
2103
1356
  }
2104
- interface LoadEvalFixtureScenariosOptions extends EvalFixtureLoadOptions {
2105
- names?: string[];
1357
+ /**
1358
+ * Composable placebo gate: ships only when the candidate's held-out lift is NOT
1359
+ * mostly reproduced by a footprint-matched neutralized variant.
1360
+ */
1361
+ declare function neutralizationGate<TArtifact, TScenario extends Scenario>(options: NeutralizationGateOptions<TScenario>): Gate<TArtifact, TScenario>;
1362
+ type OptimizerModelBudget = ExternalOptimizerModelBudget;
1363
+ /** One metered model path supplied by the package that owns execution. */
1364
+ interface OpenAICompatibleOptimizerModel {
1365
+ model: string;
1366
+ budget: OptimizerModelBudget;
1367
+ /** Caller-owned execution path, such as Runtime's exact AgentProfile adapter. */
1368
+ call: ExternalOptimizerModelCall;
1369
+ /** Stable public identity included in resumable-run compatibility. */
1370
+ callRef: string;
1371
+ /**
1372
+ * Served-model acceptance for every proxied call. Default `'exact'`, which
1373
+ * rejects any substitution with a 502 to the child.
1374
+ * `'allow-within-family'` accepts a different model of the same provider
1375
+ * family; it keeps family-level claims valid and forfeits per-model claims.
1376
+ */
1377
+ servedModelPolicy?: ServedModelPolicy;
1378
+ /**
1379
+ * Also expose this metered model over the Anthropic Messages API
1380
+ * (`POST /v1/messages`) on the loopback proxy. Required for GEPA agent
1381
+ * engines that drive a `claude` CLI subprocess. Agent engines are chatty:
1382
+ * size `budget.maxRequests` for tens of calls per engine run. Default: false.
1383
+ */
1384
+ anthropicEndpoint?: boolean;
2106
1385
  }
2107
- interface PlanEvalFixtureRunOptions<TArtifact = unknown> extends Pick<PlanCampaignRunOptions<EvalFixtureScenario, TArtifact>, 'dispatchRef' | 'judges' | 'seed' | 'reps' | 'resumable' | 'runDir'> {
2108
- evalsDir: string;
2109
- validation?: EvalFixtureValidationMode;
2110
- fingerprintConfig?: unknown;
2111
- names?: string[];
2112
- storage?: CampaignStorage;
1386
+ /** Shared settings for one bounded GEPA engine invocation. */
1387
+ interface GepaEngineOptions {
1388
+ /** GEPA engine name. GEPA validates names available in its Python runtime. */
1389
+ engine: string;
1390
+ /** Optional billed-USD stop. Omit when the execution owner reports USD as unknown. */
1391
+ maxProposerCostUsd?: number;
1392
+ /** Maximum concurrent evaluations inside this engine. Default: 1. */
1393
+ maxConcurrency?: number;
1394
+ /** Stop the engine after it reaches this score. */
1395
+ stopAtScore?: number;
1396
+ /** Isolate agent-based engines. Default: true. */
1397
+ sandbox?: boolean;
1398
+ /**
1399
+ * JSON-safe configuration for the registered GEPA engine.
1400
+ * Python callables and class instances cannot cross the process boundary.
1401
+ */
1402
+ engineConfig?: Record<string, unknown>;
2113
1403
  }
2114
- type EvalFixtureRunPlan = CampaignRunPlan & {
2115
- fixtures: Array<Pick<EvalFixtureScenario, 'fixtureName' | 'fixturePath' | 'fingerprint'>>;
2116
- };
2117
- /** Walk `evalsDir` and return the relative name of every fixture directory (one containing an exact-case `PROMPT.md`). */
2118
- declare function discoverEvalFixtures(evalsDir: string): string[];
1404
+ /** One independently budgeted GEPA engine invocation. */
1405
+ interface GepaEngineRun extends GepaEngineOptions {
1406
+ /** Maximum callback evaluations this engine may consume. */
1407
+ maxEvaluations: number;
1408
+ }
1409
+ /** An engine in an adaptive run. All engines share the recipe evaluation limit. */
1410
+ type GepaAdaptiveEngineRun = GepaEngineOptions;
2119
1411
  /**
2120
- * Load ONE fixture by name: reads `PROMPT.md` (plus `EVAL.ts`/`EVAL.tsx` and `package.json` under
2121
- * `vitest` validation) and content-fingerprints the full file set for cache identity.
1412
+ * A direct mapping to a GEPA optimization recipe.
1413
+ *
1414
+ * GEPA owns every search and composition operation represented here. Tangle
1415
+ * supplies the candidate, data, execution callback, judges, and budgets.
2122
1416
  */
2123
- declare function loadEvalFixture(evalsDir: string, name: string, options?: EvalFixtureLoadOptions): EvalFixture;
2124
- /** Load fixtures (all discovered, or just `names`) as campaign `Scenario`s tagged `eval-fixture`. */
2125
- declare function loadEvalFixtureScenarios(evalsDir: string, options?: LoadEvalFixtureScenariosOptions): EvalFixtureScenario[];
1417
+ type GepaOptimizationRecipe = {
1418
+ kind: 'engine';
1419
+ run: GepaEngineRun;
1420
+ } | {
1421
+ kind: 'sequential';
1422
+ runs: readonly GepaEngineRun[];
1423
+ } | {
1424
+ kind: 'adaptive-sequential';
1425
+ runs: readonly GepaAdaptiveEngineRun[];
1426
+ /** One evaluation budget shared by every adaptive stage. */
1427
+ maxEvaluations: number;
1428
+ /** Switch engines after this many evaluations without improvement. */
1429
+ plateauEvaluations: number;
1430
+ patience?: number;
1431
+ minEvaluationsPerStage?: number;
1432
+ improvementEpsilon?: number;
1433
+ cycle?: boolean;
1434
+ maxSwitches?: number;
1435
+ maxConcurrency?: number;
1436
+ } | {
1437
+ kind: 'best-of';
1438
+ runs: readonly GepaEngineRun[];
1439
+ maxWorkers?: number;
1440
+ } | {
1441
+ kind: 'vote';
1442
+ runs: readonly GepaEngineRun[];
1443
+ maxWorkers?: number;
1444
+ } | {
1445
+ kind: 'omni';
1446
+ explore: readonly GepaEngineRun[];
1447
+ continueWith: GepaEngineRun;
1448
+ maxWorkers?: number;
1449
+ };
1450
+ /** The command that runs the Python GEPA bridge. */
1451
+ type GepaRunnerCommand = ExternalOptimizerRunnerCommand;
1452
+ interface GepaOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
1453
+ /** Unique comparison-method name. Default identifies the GEPA recipe. */
1454
+ name?: string;
1455
+ /** A direct GEPA recipe. */
1456
+ recipe: GepaOptimizationRecipe;
1457
+ /** Plain-language goal shown to the external optimizer. */
1458
+ objective: string;
1459
+ /** Stable identity for the dispatch, judges, model settings, and scoring logic. */
1460
+ evaluationId: string;
1461
+ /** Optional bounded context about the surface and task. */
1462
+ background?: string;
1463
+ /**
1464
+ * Public dotted Python modules imported before GEPA resolves engine names.
1465
+ * Each module should call GEPA's official `register_engine()` API at import.
1466
+ */
1467
+ engineModules?: readonly string[];
1468
+ /** Reject external candidates longer than this. Default: 200,000 characters. */
1469
+ maxCandidateChars?: number;
1470
+ /** Reject serialized score evidence longer than this. Default: 100,000 characters. */
1471
+ maxEvidenceChars?: number;
1472
+ /** Candidate-evaluation callback byte limits. Omitted fields use finite defaults. */
1473
+ evaluationCallbackLimits?: Partial<ExternalOptimizerCallbackLimits>;
1474
+ /** End the bridge process after this many milliseconds. Default: 30 minutes. */
1475
+ timeoutMs?: number;
1476
+ /**
1477
+ * OpenAI-compatible model used by standard GEPA reflection.
1478
+ * Calls pass through Agent Eval's local model proxy. Every recipe engine must
1479
+ * be `gepa` when this is set.
1480
+ */
1481
+ optimizer?: OpenAICompatibleOptimizerModel;
1482
+ /**
1483
+ * Decide what the external optimizer may read for a train or selection case.
1484
+ * The returned value must be JSON-serializable. The final comparison cases
1485
+ * are not accepted by this API and cannot be serialized here.
1486
+ */
1487
+ describeScenario?: (scenario: TScenario) => unknown;
1488
+ /** Optional bounded artifact evidence returned to GEPA after each evaluation. */
1489
+ describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
1490
+ /** Default: `never`. Compatible runs resume only when explicitly enabled. */
1491
+ resume?: ExternalOptimizerResumeMode;
1492
+ /**
1493
+ * Required for resumable direct GEPA runs because upstream state uses Python
1494
+ * pickle. Enable only for state created locally in a directory you control.
1495
+ */
1496
+ trustResumeState?: boolean;
1497
+ runner?: GepaRunnerCommand;
1498
+ /**
1499
+ * Record GEPA's search into a search ledger and return the bounded receipt
1500
+ * on the method result, so a comparison under `searchHistoryPolicy:
1501
+ * 'require-complete'` accepts this method. The population becomes nodes and
1502
+ * `correlated` edges, and every callback evaluation becomes a cell.
1503
+ *
1504
+ * `identity` declares the immutable revisions and the model the ledger
1505
+ * requires and the bridge does not report. `path` defaults to
1506
+ * `<runDir>/search-ledger.jsonl`.
1507
+ */
1508
+ searchLedger?: {
1509
+ identity: SearchRunIdentity;
1510
+ path?: string;
1511
+ };
1512
+ }
2126
1513
  /**
2127
- * Dry-run planner for a fixture campaign: loads the scenarios, delegates to `planCampaignRun`,
2128
- * and returns the plan plus each fixture's name/path/fingerprint.
1514
+ * Turn an optional GEPA installation into an `OptimizationMethod`.
1515
+ *
1516
+ * GEPA receives only serialized train and selection cases. The caller's final
1517
+ * test partition stays inside `compareOptimizationMethods`, which invokes this
1518
+ * method without a test-set field. The local callback routes every candidate
1519
+ * evaluation through the same dispatch and judges used by other methods.
2129
1520
  */
2130
- declare function planEvalFixtureRun<TArtifact = unknown>(options: PlanEvalFixtureRunOptions<TArtifact>): EvalFixtureRunPlan;
2131
- interface NeutralizationGateOptions<TScenario extends Scenario = Scenario> {
2132
- scenarios: TScenario[];
2133
- /** Reject when the neutralized (content-blanked, footprint-matched) variant
2134
- * reproduces at least this fraction of the candidate's held-out lift. Default
2135
- * 0.5 — if blanking the content keeps half the lift, the content is decorative.
2136
- * Equality rejects: a neutralized lift == threshold·candidateLift is decorative. */
2137
- maxDecorativeFraction?: number;
2138
- }
2139
1521
  /**
2140
- * Composable placebo gate: ships only when the candidate's held-out lift is NOT
2141
- * mostly reproduced by a footprint-matched neutralized variant.
1522
+ * Environment for a bridge child that spawns `claude` CLI subprocesses.
1523
+ *
1524
+ * Both agent CLI engines start the CLI with the bridge's own environment, so
1525
+ * these variables travel bridge → engine → CLI. They merge AFTER
1526
+ * `removeCredentialEnvironment`: the ephemeral loopback token is the only
1527
+ * credential the child may see, and a caller-supplied ANTHROPIC_AUTH_TOKEN is
1528
+ * stripped like any other credential.
2142
1529
  */
2143
- declare function neutralizationGate<TArtifact, TScenario extends Scenario>(options: NeutralizationGateOptions<TScenario>): Gate<TArtifact, TScenario>;
1530
+ declare function gepaOptimizationMethod<TScenario extends Scenario, TArtifact>(config: GepaOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
2144
1531
  /** The external optimizers whose searches this module records. */
2145
1532
  type ExternalSearchOptimizer = 'GEPA' | 'SkillOpt';
2146
1533
  interface GepaPopulationImport {
@@ -2297,6 +1684,129 @@ declare function sequentialOptimizationMethod<S extends Scenario, A>(options: {
2297
1684
  name: string;
2298
1685
  methods: readonly OptimizationMethod<S, A>[];
2299
1686
  }): OptimizationMethod<S, A>;
1687
+ interface OptimizationMethodScore {
1688
+ evidence?: {
1689
+ baseline: EvidenceReceipt;
1690
+ winner: EvidenceReceipt;
1691
+ };
1692
+ name: string;
1693
+ /** Mean final-test composite of the baseline (identical across methods). */
1694
+ baselineComposite: number;
1695
+ /** Mean final-test composite of this method's selected surface. */
1696
+ winnerComposite: number;
1697
+ /** Mean final-test lift across independent units (winner minus baseline). */
1698
+ lift: number;
1699
+ /** Deciding interval, adjusted for every registered contrast. */
1700
+ liftCi: {
1701
+ low: number;
1702
+ high: number;
1703
+ };
1704
+ decision: PairedPromotionDecision;
1705
+ /** Search spend reconciled with recorded method calls. Excludes final test scoring. */
1706
+ optimizationCost: ComparisonCost;
1707
+ /** Optimization duration reported by the method. Excludes final test scoring. */
1708
+ durationMs?: number;
1709
+ /** Exact external implementation and run identity, when reported by the method. */
1710
+ provenance?: OptimizationMethodProvenance;
1711
+ /** Paired final-test values used to compute lift and its interval. */
1712
+ scenarioScores: Array<{
1713
+ scenarioId: string;
1714
+ baselineComposite: number;
1715
+ winnerComposite: number;
1716
+ lift: number;
1717
+ }>;
1718
+ /** Scenario means averaged within each registered source unit before inference. */
1719
+ unitScores: Array<{
1720
+ unitId: string;
1721
+ scenarios: number;
1722
+ baselineComposite: number;
1723
+ winnerComposite: number;
1724
+ lift: number;
1725
+ }>;
1726
+ winnerSurface: MutableSurface;
1727
+ composition?: OptimizationMethodComposition;
1728
+ /** 1-based, by descending lift. */
1729
+ rank: number;
1730
+ }
1731
+ interface OptimizationMethodPairwise {
1732
+ /** Higher-ranked method. */
1733
+ a: string;
1734
+ b: string;
1735
+ /** Mean final-test delta across independent units (a − b). */
1736
+ deltaMean: number;
1737
+ low: number;
1738
+ high: number;
1739
+ /** Favored only when the full paired decision clears the registered effect; null is inconclusive. */
1740
+ favored: string | null;
1741
+ decision: PairedPromotionDecision;
1742
+ }
1743
+ interface OptimizationMethodComparison {
1744
+ claim?: EvaluationClaim;
1745
+ finalEvidence?: FinalEvidenceUse;
1746
+ /** Sorted by descending lift; `rank` set accordingly. */
1747
+ scores: OptimizationMethodScore[];
1748
+ best: OptimizationMethodScore;
1749
+ /** Best observed method versus each alternative, with simultaneous paired decisions. */
1750
+ pairwise: OptimizationMethodPairwise[];
1751
+ testScenarioIds: string[];
1752
+ units: EvaluationUnitSummary;
1753
+ observationUnit: 'scenario' | 'registered';
1754
+ /** Complete scenario-replicate pairs per contrast, before unit aggregation. */
1755
+ pairedCellN: number;
1756
+ /** Sum of method reports reconciled against each method's recorded calls. */
1757
+ optimizationCost: ComparisonCost;
1758
+ /** Baseline and distinct winner scoring on the final test partition. */
1759
+ testCost: ComparisonCost;
1760
+ /** Optimization plus final test scoring. */
1761
+ totalCost: ComparisonCost;
1762
+ /** Caller-requested simultaneous coverage across all reported contrasts. */
1763
+ confidence: number;
1764
+ /** Bonferroni-adjusted confidence used for each bootstrap interval. */
1765
+ intervalConfidence: number;
1766
+ /** Method-vs-baseline plus all possible method-vs-method contrasts. */
1767
+ comparisonCount: number;
1768
+ /** Deterministic bootstrap and campaign seed. */
1769
+ seed: number;
1770
+ /** Bootstrap draws used for each interval. */
1771
+ resamples: number;
1772
+ /** Agent runs averaged within each test scenario before resampling scenarios. */
1773
+ reps: number;
1774
+ /** Coverage of every method's canonical search history. */
1775
+ searchHistory: SearchHistoryCoverage;
1776
+ }
1777
+ interface CompareOptimizationMethodsOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'judges' | 'scenarios'>, SearchHistoryAdmissionOptions {
1778
+ /** Explicit caller authority and environment for receipts over actual final measurements. */
1779
+ evidence?: CampaignEvidenceContext;
1780
+ claim?: EvaluationClaim;
1781
+ finalEvidence?: FinalEvidencePolicy;
1782
+ methods: OptimizationMethod<TScenario, TArtifact>[];
1783
+ baselineSurface: MutableSurface;
1784
+ /** Evidence used by every optimizer to author or fit candidates. */
1785
+ trainScenarios: TScenario[];
1786
+ /** Candidate acceptance, early-stopping, and optimizer-selection data. */
1787
+ selectionScenarios: TScenario[];
1788
+ /** Untouched final comparison data. Never passed to an optimization method. */
1789
+ testScenarios: TScenario[];
1790
+ /** Scores a surface on a scenario. The methods and final test share this function. */
1791
+ dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>;
1792
+ judges: JudgeConfig<TArtifact, TScenario>[];
1793
+ /** Bootstrap resamples for the lift intervals. Default is at least 2000 and
1794
+ * rises when the requested simultaneous confidence needs finer tails. */
1795
+ resamples?: number;
1796
+ /** Shared defaults for each method's train and selection campaigns. */
1797
+ optimizationRunOptions?: OptimizationMethodRunOptions<TScenario, TArtifact>;
1798
+ /** Number of optimization methods to run concurrently. Default 1. */
1799
+ optimizationConcurrency?: number;
1800
+ /** Simultaneous confidence across method-vs-baseline and method-vs-method contrasts.
1801
+ * Each bootstrap interval is Bonferroni-adjusted. Default 0.95. */
1802
+ confidence?: number;
1803
+ /** Shared spend limit across every method's optimizer and evaluation calls plus final scoring. */
1804
+ costCeiling?: number;
1805
+ }
1806
+ /**
1807
+ * Compare complete optimization methods on disjoint train, selection, and final test data.
1808
+ */
1809
+ declare function compareOptimizationMethods<TScenario extends Scenario, TArtifact>(rawOpts: CompareOptimizationMethodsOptions<TScenario, TArtifact>): Promise<OptimizationMethodComparison>;
2300
1810
  /** A tool the agent invoked. */
2301
1811
  interface ToolCallEventLike {
2302
1812
  type: 'tool_call';
@@ -2694,6 +2204,230 @@ interface FinalizedProfileMatrixResult<TArtifact, TScenario extends Scenario> ex
2694
2204
  declare function createProfileMatrixPlan<TScenario extends Scenario, TArtifact>(opts: CreateProfileMatrixPlanOptions<TScenario, TArtifact>): ProfileMatrixPlan<TScenario, TArtifact>;
2695
2205
  declare function runProfileMatrixSegment<TScenario extends Scenario, TArtifact>(opts: RunProfileMatrixSegmentOptions<TScenario, TArtifact>): Promise<ProfileMatrixSegmentResult<TArtifact, TScenario>>;
2696
2206
  declare function finalizeProfileMatrix<TScenario extends Scenario, TArtifact>(opts: FinalizeProfileMatrixOptions<TScenario, TArtifact>): Promise<FinalizedProfileMatrixResult<TArtifact, TScenario>>;
2207
+ interface CampaignComparisonUnits {
2208
+ pairedCellN: number;
2209
+ unitIds: string[];
2210
+ /** Cells with no complete quality score on either arm. */
2211
+ unscoredCellIds: string[];
2212
+ /** Present when repetitions and source variants share an independent unit. */
2213
+ independentUnitByScenarioId?: Record<string, string>;
2214
+ }
2215
+ /** Mean composite across cells with complete task-quality evidence.
2216
+ * Partial judge results remain on their cells but never enter this value.
2217
+ * A campaign with no complete score has no numeric mean and fails loudly. */
2218
+ declare function campaignMeanComposite<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): number;
2219
+ interface CampaignBreakdown {
2220
+ /** Mean score per judge dimension across all cells. */
2221
+ dimensions: Record<string, number>;
2222
+ /** Per-scenario composite (mean over reps + judges) + the judge's free-form
2223
+ * `notes` for that scenario (the "why" a reflective proposer grounds on) +
2224
+ * an optional `emitted` excerpt of the candidate's raw output (the "what it
2225
+ * actually did" a reflective proposer grounds on). */
2226
+ scenarios: Array<{
2227
+ scenarioId: string;
2228
+ composite: number;
2229
+ notes?: string;
2230
+ emitted?: string;
2231
+ }>;
2232
+ }
2233
+ /** Per-candidate evidence a reflective/patch proposer grounds its next proposal
2234
+ * on: mean score per judge dimension + per-scenario composite. */
2235
+ declare function campaignBreakdown<TArtifact, TScenario extends Scenario>(campaign: CampaignResult<TArtifact, TScenario>): CampaignBreakdown;
2236
+ interface LoopProvenanceCandidate {
2237
+ /** Generation index this candidate was proposed in. */
2238
+ generation: number;
2239
+ /** 16-char loop-identity fingerprint (matches `GenerationCandidate.surfaceHash`). */
2240
+ surfaceHash: string;
2241
+ /** Full sha256 content hash — byte-identical-verifiable. */
2242
+ contentHash: string;
2243
+ /** Exact scored rows that produced this candidate's search result. */
2244
+ campaignDigest: `sha256:${string}`;
2245
+ /** Proposer label, when the proposer returned a `ProposedCandidate`. */
2246
+ label?: string;
2247
+ /** Proposer rationale — the "because Z". When the proposer returned a bare
2248
+ * surface (blind mutator) this is absent. */
2249
+ rationale?: string;
2250
+ /** Proposer-supplied typed attribution, carried unchanged from
2251
+ * `GenerationCandidate.attribution`. Opaque here; the producer's schema tag
2252
+ * governs interpretation. */
2253
+ attribution?: Readonly<Record<string, unknown>>;
2254
+ /** Whether the candidate completed every designed cell and could be selected. */
2255
+ eligibleForPromotion: boolean;
2256
+ /** Designed-denominator receipt retained even for incomplete candidates. */
2257
+ coverage: NonNullable<GenerationCandidate['coverage']>;
2258
+ /** Mean composite this candidate scored on the search split, or null when unscorable. */
2259
+ composite: number | null;
2260
+ /** Whether this candidate was promoted out of its generation. */
2261
+ promoted: boolean;
2262
+ }
2263
+ interface LoopProvenanceBackend {
2264
+ /** `assertRealBackend`-grade verdict over the worker call records. */
2265
+ verdict: 'real' | 'mixed' | 'stub';
2266
+ /** Number of worker LLM calls captured (the audit's "worker call count"). */
2267
+ workerCallCount: number;
2268
+ /** Distinct model ids observed across worker calls. */
2269
+ models: string[];
2270
+ totalInputTokens: number;
2271
+ totalOutputTokens: number;
2272
+ totalCostUsd: number;
2273
+ }
2274
+ interface LoopProvenanceEvidence {
2275
+ search: {
2276
+ splitDigest: `sha256:${string}`;
2277
+ baselineCampaignDigest: `sha256:${string}`;
2278
+ };
2279
+ holdout: {
2280
+ splitDigest: `sha256:${string}`;
2281
+ baselineCampaignDigest: `sha256:${string}`;
2282
+ winnerCampaignDigest: `sha256:${string}`;
2283
+ observations?: CampaignComparisonUnits;
2284
+ neutralized?: {
2285
+ contentHash: `sha256:${string}`;
2286
+ campaignDigest: `sha256:${string}`;
2287
+ composite: number;
2288
+ lift: number;
2289
+ };
2290
+ };
2291
+ costReceiptsDigest: `sha256:${string}`;
2292
+ }
2293
+ interface LoopProvenanceOptimizationMethod {
2294
+ name: string;
2295
+ cost: ComparisonCost;
2296
+ durationMs?: number;
2297
+ provenance?: OptimizationMethodProvenance;
2298
+ }
2299
+ /**
2300
+ * The durable provenance record: the baseline and winner measurements, the
2301
+ * rationale, the explicit baseline→candidate diff, and backend provenance.
2302
+ */
2303
+ interface LoopProvenanceRecord {
2304
+ schema: 'tangle.loop-provenance';
2305
+ /** SHA-256 over the canonical record with this field omitted. */
2306
+ recordDigest: `sha256:${string}`;
2307
+ runId: string;
2308
+ runDir: string;
2309
+ timestamp: string;
2310
+ /** Baseline + winner surface content hashes — distinguishable, byte-verifiable. */
2311
+ baselineContentHash: string;
2312
+ winnerContentHash: string;
2313
+ /** Proposer label/rationale for the promoted change. Absent ⇒ winner == baseline. */
2314
+ winnerLabel?: string;
2315
+ winnerRationale?: string;
2316
+ /** The explicit baseline→winner unified diff the gate decided on. */
2317
+ diff: string;
2318
+ /** Every candidate across every generation, with its rationale and structured cause. */
2319
+ candidates: LoopProvenanceCandidate[];
2320
+ /** Complete external method identity and spend, when one authored the candidate. */
2321
+ optimizationMethod?: LoopProvenanceOptimizationMethod;
2322
+ /** Exact campaign, split, surface, and receipt identities behind every summary. */
2323
+ evidence: LoopProvenanceEvidence;
2324
+ /** Baseline composite on the search split that generated the candidates. */
2325
+ baselineSearchComposite: number;
2326
+ claim?: EvaluationClaim;
2327
+ /** The gate verdict — decision + reasons + contributing gates + delta. */
2328
+ gate: {
2329
+ decision: GateDecision;
2330
+ reasons: string[];
2331
+ delta?: number;
2332
+ contributingGates: GateContribution[];
2333
+ };
2334
+ /** Present iff the loop ran with `holdout: 'deferred'` — the held-out
2335
+ * comparison was intentionally not measured in this run, so the holdout
2336
+ * composites and `heldOutLift` are ABSENT rather than recorded as a
2337
+ * meaningless 0. */
2338
+ holdout?: 'deferred';
2339
+ /** baseline-on-holdout composite mean. Absent when `holdout === 'deferred'`. */
2340
+ baselineHoldoutComposite?: number;
2341
+ /** winner-on-holdout composite mean. Absent when `holdout === 'deferred'`. */
2342
+ winnerHoldoutComposite?: number;
2343
+ /** winnerHoldout - baselineHoldout — RECOMPUTABLE from this record. Absent
2344
+ * when `holdout === 'deferred'` (no held-out measurement ran). */
2345
+ heldOutLift?: number;
2346
+ /** Backend provenance: stub-vs-real verdict + worker call count + models. */
2347
+ backend: LoopProvenanceBackend;
2348
+ totalCostUsd: number;
2349
+ totalDurationMs: number;
2350
+ }
2351
+ interface BuildLoopProvenanceArgs<TArtifact, TScenario extends Scenario> {
2352
+ runId: string;
2353
+ runDir: string;
2354
+ timestamp: string;
2355
+ baselineSurface: MutableSurface;
2356
+ winnerSurface: MutableSurface;
2357
+ winnerLabel?: string;
2358
+ winnerRationale?: string;
2359
+ /** Exact baseline campaign on the search split. */
2360
+ baselineSearchCampaign: CampaignResult<TArtifact, TScenario>;
2361
+ /** Per-generation candidate records straight off the loop result. */
2362
+ generations: Array<{
2363
+ generationIndex: number;
2364
+ candidates: GenerationCandidate[];
2365
+ promoted: string[];
2366
+ /** Surfaces measured this generation, keyed by surface hash so the content
2367
+ * hash can be computed and the loop identity rechecked from real bytes. */
2368
+ surfaces: Array<{
2369
+ surfaceHash: string;
2370
+ surface: MutableSurface;
2371
+ campaign: CampaignResult<TArtifact, TScenario>;
2372
+ }>;
2373
+ }>;
2374
+ gate: GateResult;
2375
+ /** Holdout policy the loop ran with. `'deferred'` ⇒ the holdout campaigns
2376
+ * below are the shared empty campaign and the record omits the holdout
2377
+ * composites + `heldOutLift`. Default `'measured'`. */
2378
+ holdout?: 'measured' | 'deferred';
2379
+ baselineOnHoldout: CampaignResult<TArtifact, TScenario>;
2380
+ winnerOnHoldout: CampaignResult<TArtifact, TScenario>;
2381
+ claim?: EvaluationClaim;
2382
+ /** Required with a measured claim because campaign identities redact source fields. */
2383
+ independentUnitByScenarioId?: ReadonlyMap<string, string>;
2384
+ neutralizedSurface?: MutableSurface;
2385
+ neutralizedOnHoldout?: CampaignResult<TArtifact, TScenario>;
2386
+ /** Settled run-wide receipts — agent calls are the source for backend provenance. */
2387
+ costReceipts: ReadonlyArray<CostReceipt>;
2388
+ totalCostUsd: number;
2389
+ totalDurationMs: number;
2390
+ optimizationMethod?: LoopProvenanceOptimizationMethod;
2391
+ }
2392
+ interface LoopProvenanceArgsFromResult<TArtifact, TScenario extends Scenario> {
2393
+ runId: string;
2394
+ runDir: string;
2395
+ timestamp: string;
2396
+ baselineSurface: MutableSurface;
2397
+ result: RunImprovementLoopResult<TArtifact, TScenario>;
2398
+ costReceipts: ReadonlyArray<CostReceipt>;
2399
+ totalCostUsd: number;
2400
+ totalDurationMs: number;
2401
+ independentUnitByScenarioId?: ReadonlyMap<string, string>;
2402
+ }
2403
+ /** SHA-256 over the RFC 8785 canonical JSON of `value`. Throws
2404
+ * `LedgerCanonicalizationError` for a value with no canonical form. */
2405
+ declare function canonicalDigest(value: unknown): `sha256:${string}`;
2406
+ interface EmitLoopProvenanceResult {
2407
+ record: LoopProvenanceRecord;
2408
+ spans: TraceSpanEvent[];
2409
+ /** Absolute paths the record + spans were written to, when storage persists. */
2410
+ recordPath: string;
2411
+ spansPath: string;
2412
+ }
2413
+ interface EmitLoopProvenanceArgs<TArtifact, TScenario extends Scenario> extends BuildLoopProvenanceArgs<TArtifact, TScenario> {
2414
+ /** Storage the record + spans are written through. */
2415
+ storage: CampaignStorage;
2416
+ /** When set, the spans are also shipped to the hosted `/v1/ingest/traces`
2417
+ * endpoint so the collector receives the full loop, not just `cost.*`. */
2418
+ hostedClient?: HostedClient;
2419
+ }
2420
+ /**
2421
+ * Build the provenance record + OTel spans and persist them durably under the
2422
+ * run dir (and ship spans to a hosted collector when one is wired). Returns
2423
+ * both artifacts so the caller can assert on / re-derive from them.
2424
+ *
2425
+ * Fail-loud: the durable write throws on storage failure (a swallowed write is
2426
+ * exactly the "emitted but lost" failure this closes). The hosted span ship is
2427
+ * the one best-effort leg — its failure is logged, not thrown, so an offline
2428
+ * collector never fails the loop (the durable artifact is the source of truth).
2429
+ */
2430
+ declare function emitLoopProvenance<TArtifact, TScenario extends Scenario>(args: EmitLoopProvenanceArgs<TArtifact, TScenario>): Promise<EmitLoopProvenanceResult>;
2697
2431
  type RetainedDispatchOutcome<T> = {
2698
2432
  succeeded: true;
2699
2433
  value: T;
@@ -2831,16 +2565,85 @@ interface SingleRunLockOptions {
2831
2565
  /** Owner pid recorded in the lockfile metadata. Default process.pid. */
2832
2566
  readonly pid?: number;
2833
2567
  }
2834
- interface SingleRunLock {
2835
- /** Remove the lockfile if this process still owns it. Idempotent. */
2836
- release(): void;
2568
+ interface SingleRunLock {
2569
+ /** Remove the lockfile if this process still owns it. Idempotent. */
2570
+ release(): void;
2571
+ }
2572
+ /**
2573
+ * Acquire the lock or throw naming the holder. A lock whose holder is proved
2574
+ * dead is reclaimed by one contender. An interrupted reclaim
2575
+ * leaves a marker that fails closed instead of admitting overlapping runs.
2576
+ */
2577
+ declare function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock;
2578
+ interface SkillOptTrainerConfig {
2579
+ epochs: number;
2580
+ batchSize: number;
2581
+ accumulation?: number;
2582
+ editBudget?: number;
2583
+ minEditBudget?: number;
2584
+ analystWorkers?: number;
2585
+ minibatchSize?: number;
2586
+ mergeBatchSize?: number;
2587
+ maxAnalystRounds?: number;
2588
+ evaluationWorkers?: number;
2589
+ learningRateSchedule?: 'constant' | 'linear' | 'cosine' | 'autonomous';
2590
+ learningRateControl?: 'fixed' | 'autonomous' | 'none';
2591
+ updateMode?: 'patch' | 'rewrite_from_suggestions' | 'full_rewrite_minibatch';
2592
+ failureOnly?: boolean;
2593
+ useSlowUpdate?: boolean;
2594
+ useMetaSkill?: boolean;
2595
+ /**
2596
+ * Additional flat SkillOpt trainer settings. Tangle overwrites data,
2597
+ * output, split, seed, validation, and activation settings.
2598
+ */
2599
+ overrides?: Record<string, unknown>;
2600
+ }
2601
+ type SkillOptRunnerCommand = ExternalOptimizerRunnerCommand;
2602
+ interface SkillOptOptimizationMethodConfig<TScenario extends Scenario, TArtifact = unknown> {
2603
+ name?: string;
2604
+ /** Goal included with every described train and selection case. */
2605
+ objective: string;
2606
+ background?: string;
2607
+ /** Stable identity for the dispatch, judges, model settings, and scoring logic. */
2608
+ evaluationId: string;
2609
+ trainer: SkillOptTrainerConfig;
2610
+ /**
2611
+ * OpenAI-compatible model connection and hard limits for SkillOpt's own
2612
+ * optimizer calls.
2613
+ */
2614
+ optimizer: OpenAICompatibleOptimizerModel;
2615
+ /** Hard cap on candidate-case callback requests. */
2616
+ maxEvaluations: number;
2617
+ /** Scores at or above this value count as hard successes. Default: 1. */
2618
+ hardScoreThreshold?: number;
2619
+ maxCandidateChars?: number;
2620
+ /** Maximum serialized scenario plus evaluation evidence. Default: 100,000. */
2621
+ maxEvidenceChars?: number;
2622
+ /** Candidate-evaluation callback byte limits. Omitted fields use finite defaults. */
2623
+ evaluationCallbackLimits?: Partial<ExternalOptimizerCallbackLimits>;
2624
+ timeoutMs?: number;
2625
+ describeScenario?: (scenario: TScenario) => unknown;
2626
+ describeArtifact?: (artifact: TArtifact, scenario: TScenario) => unknown;
2627
+ resume?: ExternalOptimizerResumeMode;
2628
+ runner?: SkillOptRunnerCommand;
2629
+ /**
2630
+ * Record SkillOpt's search into a search ledger and return the bounded
2631
+ * receipt on the method result, so a comparison under `searchHistoryPolicy:
2632
+ * 'require-complete'` accepts this method. Every candidate the callback
2633
+ * evaluated becomes a node with an `unknown` edge (SkillOpt reports no
2634
+ * parents), and every evaluation becomes a cell.
2635
+ *
2636
+ * `identity` declares the immutable revisions and the model the ledger
2637
+ * requires and the bridge does not report. `path` defaults to
2638
+ * `<runDir>/search-ledger.jsonl`.
2639
+ */
2640
+ searchLedger?: {
2641
+ identity: SearchRunIdentity;
2642
+ path?: string;
2643
+ };
2837
2644
  }
2838
- /**
2839
- * Acquire the lock or throw naming the holder. A lock whose holder is proved
2840
- * dead is reclaimed by one contender. An interrupted reclaim
2841
- * leaves a marker that fails closed instead of admitting overlapping runs.
2842
- */
2843
- declare function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock;
2645
+ /** Run Microsoft's SkillOpt trainer as a complete optimization method. */
2646
+ declare function skillOptOptimizationMethod<TScenario extends Scenario, TArtifact>(config: SkillOptOptimizationMethodConfig<TScenario, TArtifact>): OptimizationMethod<TScenario, TArtifact>;
2844
2647
  /** Validate the immutable identity shape; the owning executor verifies the Git objects and patch. */
2845
2648
  declare function assertCodeSurfaceIdentity(surface: unknown): asserts surface is CodeSurface;
2846
2649
  /**
@@ -2865,6 +2668,39 @@ declare function surfaceHash(surface: MutableSurface): string;
2865
2668
  declare function renderSurfaceDiff(winnerSurface: MutableSurface, baselineSurface: MutableSurface): string;
2866
2669
  /** Bind a campaign cache entry to the exact surface and caller-owned execution revision. */
2867
2670
  declare function surfaceDispatchRef(surface: MutableSurface, executionRef?: string): string;
2671
+ interface TransientFailureOptions {
2672
+ /**
2673
+ * Treat full-duration timeouts ("timeout after 180000ms") as transient.
2674
+ * Enable on saturated shared infrastructure where queue starvation eats
2675
+ * the clock; leave off when the agent had the resources and simply failed.
2676
+ * Default false.
2677
+ */
2678
+ readonly retryFullDurationTimeouts?: boolean;
2679
+ /** Additional caller-specific transient patterns. */
2680
+ readonly extraPatterns?: readonly RegExp[];
2681
+ /**
2682
+ * The instant a dated quota refusal is measured against. Defaults to `Date.now()`; inject it
2683
+ * to replay a past classification, which is what a retry audit needs.
2684
+ */
2685
+ readonly now?: number;
2686
+ }
2687
+ /**
2688
+ * True when the error text describes an infrastructure hiccup that should be
2689
+ * retried rather than scored. Empty/undefined input is not transient.
2690
+ */
2691
+ declare function isTransientTransportFailure(message: string | null | undefined, opts?: TransientFailureOptions): boolean;
2692
+ /**
2693
+ * Ready-made `cellRetry.retryable` predicate: true for a dispatch-stage
2694
+ * failure whose error message `isTransientTransportFailure` classifies as an
2695
+ * infrastructure hiccup. A judge-stage failure is never retried here — the
2696
+ * dispatch already produced an artifact, so re-dispatching would score a
2697
+ * different sample. A per-cell dispatch deadline ("dispatch exceeded <N>ms")
2698
+ * is not transient by default; opt in via `extraPatterns` or
2699
+ * `retryFullDurationTimeouts` when queue starvation eats the clock. A provider refusal that
2700
+ * states its own release time is never retried while that time is in the future
2701
+ * (`quotaExhaustedUntil`).
2702
+ */
2703
+ declare function transientDispatchFailure(opts?: TransientFailureOptions): (failure: CampaignCellFailureReceipt['failure']) => boolean;
2868
2704
  interface PhoenixEvaluationResultLike {
2869
2705
  score?: number;
2870
2706
  label?: string;
@@ -2947,5 +2783,169 @@ declare function verifyCodeSurface(surface: CodeSurface, worktreeDir?: string):
2947
2783
  /** Resolve a code candidate for evaluation only after verifying its immutable
2948
2784
  * identity against the checkout at `worktreeRef`. */
2949
2785
  declare function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string;
2950
- export { summarizeBackendIntegrity as $, RedTeamCategory as $n, ExternalOptimizerObservationArtifact as $r, CrossSurfaceCandidate as $t, RetainedDispatchOptions as A, CampaignRunPlanCell as Ai, BuildLoopProvenanceArgs as An, externalTextOptimizationMethod as Ar, importExternalEvaluations as At, RunProfileMatrixSegmentOptions as B, captureFinalEvidencePolicy as Bi, emitLoopProvenance as Bn, OptimizationMethodProvenance as Br, LoadEvalFixtureScenariosOptions as Bt, searchModelIdentity as C, RunEvalOptions as Ci, CrossSurfaceSelectionPolicy as Cn, GepaEngineRun as Cr, RolloutCall as Ct, ScenarioSignal as D, RunCampaignOptions as Di, BuildTraceAnalystSurfaceDispatchOptions as Dn, gepaOptimizationMethod as Dr, GepaEvaluationImport as Dt, DiscriminationScore as E, CampaignCellRetryPolicy as Ei, measureCampaignCost as En, GepaRunnerCommand as Er, ExternalSearchOptimizer as Et, FinalizedProfileMatrixResult as F, CellScheduleSlot as Fi, LoopProvenanceCandidate as Fn, ExternalTextEvaluationResponse as Fr, EvalFixtureFile as Ft, ProfileSummary as G, campaignCoverage as Gi, HeldOutGateOptions as Gn, OptimizationTokenUsage as Gr, planEvalFixtureRun as Gt, finalizeProfileMatrix as H, withFinalEvidenceSources as Hi, CampaignComparisonUnits as Hn, OptimizationMethodRunOptions as Hr, discoverEvalFixtures as Ht, ProfileMatrixCoverage as I, buildCellSchedule as Ii, LoopProvenanceEvidence as In, decodeExternalTextCandidate as Ir, EvalFixtureLoadOptions as It, ScenarioRollup as J, campaignSplitDigestFromIdentities as Ji, DefaultProductionGateOptions as Jn, GepaCandidatePopulationCandidate as Jr, CrossSurfaceAdditionDecision as Jt, RunProfileMatrixOptions as K, campaignScenarioIdentity as Ki, heldOutGate as Kn, costFromLedgerSummary as Kr, analyzeCrossSurfaceInteractions as Kt, ProfileMatrixPlan as L, cellCachePath as Li, LoopProvenanceOptimizationMethod as Ln, OptimizationMethod as Lr, EvalFixtureRunPlan as Lt, createRetainedDispatch as M, planCampaignRun as Mi, EmitLoopProvenanceResult as Mn, ExternalTextOptimizerContext as Mr, NeutralizationGateOptions as Mt, CreateProfileMatrixPlanOptions as N, CacheIssueReason as Ni, LoopProvenanceArgsFromResult as Nn, ExternalTextOptimizerResult as Nr, neutralizationGate as Nt, scoreDiscrimination as O, runCampaign as Oi, TraceAnalystArtifact as On, OpenAICompatibleOptimizerModel as Or, GepaPopulationImport as Ot, FinalizeProfileMatrixOptions as P, CacheRead as Pi, LoopProvenanceBackend as Pn, ExternalOptimizationExample as Pr, EvalFixture as Pt, assertRealBackend as Q, RedTeamCase as Qn, ExternalOptimizerExecutionSummary as Qr, CrossSurfaceBootstrapPolicy as Qt, ProfileMatrixRow as R, FinalEvidencePolicy as Ri, LoopProvenanceRecord as Rn, OptimizationMethodComposition as Rr, EvalFixtureScenario as Rt, campaignCellSearchResult as S, openAutoPr as Si, CrossSurfaceRelativeCost as Sn, GepaEngineOptions as Sr, RolloutArgumentDiffOptions as St, searchReceiptAccounting as T, CampaignCellFailureReceipt as Ti, CrossSurfaceTaskRow as Tn, GepaOptimizationRecipe as Tr, UngroundedLiteralReport as Tt, runProfileMatrixSegment as U, CampaignCoverage as Ui, campaignBreakdown as Un, OptimizationPackageSource as Ur, loadEvalFixture as Ut, createProfileMatrixPlan as V, prepareSearchFinalEvidence as Vi, CampaignBreakdown as Vn, OptimizationMethodResult as Vr, PlanEvalFixtureRunOptions as Vt, ProfileDispatchFn as W, assertCampaignDesign as Wi, campaignMeanComposite as Wn, ComparisonCost as Wr, loadEvalFixtureScenarios as Wt, BackendIntegrityError as X, SearchLedgerIntegrityError as Xi, defaultProductionGate as Xn, GepaCandidateSelectionScore as Xr, CrossSurfaceAttemptCompleteness as Xt, runProfileMatrix as Y, SearchLedgerError as Yi, DefaultProductionRewardHackingOptions as Yn, GepaCandidatePopulationSummary as Yr, CrossSurfaceAdditionRejectionReason as Yt, BackendIntegrityReport as Z, DEFAULT_RED_TEAM_CORPUS as Zn, readGepaCandidatePopulationArtifact as Zr, CrossSurfaceBestSingleSelection as Zt, surfaceDispatchRef as _, RunOptimizationOptions as _i, CrossSurfacePairCompatibility as _n, OptimizationMethodComparison as _r, scopedOptimizationMethod as _t, gitWorktreeAdapter as a, ReferenceEquivalenceJudgeResult as ai, CrossSurfaceComponentEvidence as an, CanaryAlert as ar, ScoreboardSummary as at, SingleRunLockOptions as b, OpenAutoPrOptions as bi, CrossSurfacePairwiseEntry as bn, compareOptimizationMethods as br, FsLabeledScenarioStoreOptions as bt, AutoevalsScoreLike as c, LlmJudgeOptions as ci, CrossSurfaceEligibility as cn, CanaryOptions as cr, renderScoreboardMarkdown as ct, PhoenixEvaluatorLike as d, isTransientTransportFailure as di, CrossSurfaceInteractionAwareSelection as dn, composeGate as dr, userStoryScoreboard as dt, ExternalOptimizerObservationSummary as ei, CrossSurfaceCandidateComparison as en, RedTeamFinding as er, PlaybackContext as et, assertCodeSurfaceIdentity as f, transientDispatchFailure as fi, CrossSurfaceInteractionEffect as fn, SkillOptOptimizationMethodConfig as fr, ArtifactEventLike as ft, surfaceContentHash as g, PremeasuredOptimizationBaseline as gi, CrossSurfaceNaiveStackSelection as gn, CompareOptimizationMethodsOptions as gr, extractProducedState as gt, renderSurfaceDiff as h, runImprovementLoop as hi, CrossSurfaceInteractionTask as hn, skillOptOptimizationMethod as hr, ToolCallEventLike as ht, WorktreeAdapter as i, ReferenceEquivalenceJudgeOptions as ii, CrossSurfaceComponent as in, scoreRedTeamOutput as ir, ScoreboardRow as it, RetainedDispatchOutcome as j, PlanCampaignRunOptions as ji, EmitLoopProvenanceArgs as jn, ExternalTextOptimizationMethodConfig as jr, importGepaPopulation as jt, resolveRunDir as k, CampaignRunPlan as ki, TraceAnalystScenario as kn, OptimizerModelBudget as kr, externalSurface as kt, AutoevalsScorerLike as l, llmJudge as li, CrossSurfaceEvidenceBreakdown as ln, CanaryReport as lr, scoreUserStory as lt, componentSurfaceIdentityMaterial as m, RunImprovementLoopResult as mi, CrossSurfaceInteractionReport as mn, SkillOptTrainerConfig as mr, RuntimeEventLike as mt, GitWorktreeAdapterOptions as n, readExternalOptimizerObservationArtifact as ni, CrossSurfaceCandidateOutcome as nn, redTeamDataset as nr, PlaybackStep as nt, resolveWorktreePath as o, ReferenceEquivalenceScenario as oi, CrossSurfaceCompositionStep as on, CanaryEvaluation as or, UserStory as ot, codeSurfaceIdentityMaterial as p, RunImprovementLoopOptions as pi, CrossSurfaceInteractionPath as pn, SkillOptRunnerCommand as pr, ProposalEventLike as pt, RunProfileMatrixResult as q, campaignSplitDigest as qi, DefaultProductionGateCheck as qn, GepaCandidatePopulationArtifact as qr, AnalyzeCrossSurfaceInteractionsInput as qt, Worktree as r, ReferenceEquivalenceJudgeInput as ri, CrossSurfaceCandidateSummary as rn, redTeamReport as rr, ScoreboardRenderOptions as rt, verifyCodeSurface as s, LlmJudgeDimension as si, CrossSurfaceDistribution as sn, CanaryKind as sr, UserStoryVerdict as st, CodeSurfaceVerification as t, ExternalOptimizerSubmittedCandidate as ti, CrossSurfaceCandidateEvidence as tn, RedTeamReport as tr, PlaybackDriver as tt, PhoenixEvaluationResultLike as u, TransientFailureOptions as ui, CrossSurfaceIneligibilityReason as un, runCanaries as ur, scoreboardSummary as ut, surfaceHash as v, RunOptimizationResult as vi, CrossSurfacePairEvidence as vn, OptimizationMethodPairwise as vr, sequentialOptimizationMethod as vt, searchProposalExecution as w, runEval as wi, CrossSurfaceSelections as wn, GepaOptimizationMethodConfig as wr, ScoredRollout as wt, acquireSingleRunLock as x, OpenAutoPrResult as xi, CrossSurfaceRankedSingle as xn, GepaAdaptiveEngineRun as xr, RolloutArgumentDiff as xt, SingleRunLock as y, runOptimization as yi, CrossSurfacePairIncompatibilityReason as yn, OptimizationMethodScore as yr, neutralizeText as yt, ProfileMatrixSegmentResult as z, FinalEvidenceUse as zi, canonicalDigest as zn, OptimizationMethodInput as zr, EvalFixtureValidationMode as zt };
2951
- //# sourceMappingURL=index-OvU1UXKC.d.ts.map
2786
+ /** Improve a surface as a search on the kernel; see the module comment. */
2787
+ declare function runOptimization<TScenario extends Scenario, TArtifact>(opts: RunOptimizationOptions<TScenario, TArtifact>): Promise<RunOptimizationResult<TArtifact, TScenario>>;
2788
+ /** Optimization inputs, immutable proposal snapshots, and imported baseline validation. */
2789
+ interface PremeasuredOptimizationBaseline<TArtifact, TScenario extends Scenario> {
2790
+ /** Hash of the exact surface that produced `campaign`. */
2791
+ surfaceHash: string;
2792
+ /** Complete prior measurement reused by identity, including artifactsByPath. */
2793
+ campaign: CampaignResult<TArtifact, TScenario>;
2794
+ }
2795
+ interface RunOptimizationOptions<TScenario extends Scenario, TArtifact> extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch'> {
2796
+ /** Initial mutable surface (typically system prompt or addendum). */
2797
+ baselineSurface: MutableSurface;
2798
+ /**
2799
+ * Complete prior measurement of `baselineSurface`. When present,
2800
+ * `runOptimization` validates its surface, scenario split, seed, reps, and
2801
+ * normal campaign coverage, then records its cells as the root's instead of
2802
+ * dispatching them. Prior spend stays in the imported campaign aggregates and
2803
+ * is not added again to this run's CostLedger.
2804
+ */
2805
+ premeasuredBaseline?: PremeasuredOptimizationBaseline<TArtifact, TScenario>;
2806
+ /** Dispatcher that takes a surface and a scenario to an artifact. */
2807
+ dispatchWithSurface: (surface: MutableSurface, scenario: TScenario, ctx: Parameters<RunCampaignOptions<TScenario, TArtifact>['dispatch']>[1]) => Promise<TArtifact>;
2808
+ /** The candidate-generation strategy. */
2809
+ proposer: SurfaceProposer<ProposalFinding>;
2810
+ /** Candidates asked of each proposal. */
2811
+ populationSize: number;
2812
+ /** Proposals the search may make. */
2813
+ maxGenerations: number;
2814
+ /** Scales the run's cell lanes: at most `candidateConcurrency *
2815
+ * maxConcurrency` cells run at once. Default 1. */
2816
+ candidateConcurrency?: number;
2817
+ /** DEPTH knob forwarded to the proposer's `propose()`: max iterations the
2818
+ * agentic generator may take per candidate. */
2819
+ maxImprovementShots?: number;
2820
+ /** Search or observed-production findings forwarded to candidate generation. */
2821
+ findings?: ReadonlyArray<ProposalFinding>;
2822
+ /** Findings producer. Before each proposal it runs on the previous
2823
+ * generation's measured candidates (the baseline, as `generation: -1`,
2824
+ * before the first), and what it returns REPLACES `ctx.findings` for that
2825
+ * proposal. The substrate does not import an analyst: the consumer plugs its
2826
+ * trace-analyst registry here, reading the per-candidate `runDir` traces.
2827
+ * When absent, findings stay the static `opts.findings`. Its spend is
2828
+ * booked to the proposal's operation. */
2829
+ analyzeGeneration?: (input: {
2830
+ generation: number;
2831
+ runDir: string;
2832
+ candidates: Array<{
2833
+ surfaceHash: string;
2834
+ campaign: CampaignResult<TArtifact, TScenario>;
2835
+ composite: number | null;
2836
+ }>;
2837
+ history: GenerationRecord[];
2838
+ /** Shared run spend account and receipt attribution phase. */
2839
+ costLedger?: CostLedgerHandle;
2840
+ costPhase?: string;
2841
+ }) => Promise<ReadonlyArray<ProposalFinding>>;
2842
+ /** Which node each proposal extends, and which node the run keeps. Default
2843
+ * `incumbent()`: the hill climb. `crowdedFrontierParent({ seed })` draws
2844
+ * the parent from the Pareto frontier instead; `aide()` drafts, debugs and
2845
+ * improves with Thompson-sampled parents, and `beam({ width })` expands the
2846
+ * top nodes in turn. Every policy ranks on the scenarios, and the run keeps
2847
+ * the `uniform` allocator, because the proposer reads every candidate's
2848
+ * score on every scenario. */
2849
+ policy?: SearchPolicy;
2850
+ /** Where the search ledger goes and the identities it records. Default: a
2851
+ * ledger at `<runDir>/search/ledger.jsonl`, held in `storage` unless that is
2852
+ * the filesystem, whose identities are the dispatch ref's and proposer's
2853
+ * digests. */
2854
+ searchLedger?: SearchLedgerBinding;
2855
+ }
2856
+ interface RunOptimizationResult<TArtifact, TScenario extends Scenario> {
2857
+ /** One entry per proposal, with the candidates it registered. */
2858
+ generations: Array<{
2859
+ record: GenerationRecord;
2860
+ surfaces: Array<{
2861
+ surfaceHash: string;
2862
+ surface: MutableSurface;
2863
+ campaign: CampaignResult<TArtifact, TScenario>;
2864
+ }>;
2865
+ }>;
2866
+ /** Frozen snapshot of the exact starting surface measured by `baselineCampaign`. */
2867
+ baselineSurface: MutableSurface;
2868
+ winnerSurface: MutableSurface;
2869
+ winnerSurfaceHash: string;
2870
+ /** Proposer label for the kept surface; absent when the winner is the baseline. */
2871
+ winnerLabel?: string;
2872
+ /** Proposer rationale for the kept surface, as stored: redacted with the
2873
+ * share profile. Absent when the winner is the baseline. */
2874
+ winnerRationale?: string;
2875
+ baselineCampaign: CampaignResult<TArtifact, TScenario>;
2876
+ /** Run-wide spend, including agents, proposers, analysts, and judges. */
2877
+ cost: CostLedgerSummary;
2878
+ /** Bounded proof envelope over the search ledger. */
2879
+ searchHistory: SearchHistoryReceipt;
2880
+ /** The non-dominated set of measured surfaces by per-scenario composite. */
2881
+ paretoFrontier: ParetoParent[];
2882
+ }
2883
+ type RunImprovementLoopOptions<TScenario extends Scenario, TArtifact> = RunOptimizationOptions<TScenario, TArtifact> & {
2884
+ /** Holdout scenarios kept OUT of the training optimization pool — used
2885
+ * ONLY to score baseline vs winner for the gate. */
2886
+ holdoutScenarios: TScenario[];
2887
+ claim?: EvaluationClaim;
2888
+ finalEvidence?: FinalEvidencePolicy;
2889
+ /** Snapshot identity for agents without model receipts. Receipts take precedence. */
2890
+ model?: string;
2891
+ /** Declare a model change as part of the treatment before search starts. */
2892
+ modelTreatment?: ModelTreatment;
2893
+ /** Require one reported model id per arm (two spellings of one snapshot count as two), even
2894
+ * when neither arm reports a model call. Enabled by selfImprove. */
2895
+ requireReportedModel?: boolean;
2896
+ /** Holdout policy. Default `'measured'`: baseline + winner are re-scored on
2897
+ * `holdoutScenarios` and the gate decides on that held-out comparison.
2898
+ * `'deferred'`: the improvement-set (search) campaigns run exactly as usual,
2899
+ * but ZERO holdout cells are dispatched, the gate is forced to `'hold'`, and
2900
+ * the result + provenance record carry `holdout: 'deferred'` with NO
2901
+ * held-out lift — for callers that measure the held-out comparison in a
2902
+ * separate later run instead of faking a static holdout scenario and
2903
+ * recording a meaningless lift. */
2904
+ holdout?: 'measured' | 'deferred';
2905
+ /** Promotion gate. Substrate strongly recommends `defaultProductionGate`
2906
+ * for production wiring (composes red-team / reward-hacking / canary /
2907
+ * heldout). */
2908
+ gate: Gate<TArtifact, TScenario>;
2909
+ /** What to do when the gate ships:
2910
+ * - `'pr'`: open a PR via `openAutoPr`
2911
+ * - `'none'`: just report — caller decides what to do with the winner
2912
+ * Live-runtime self-mutation is intentionally unsupported. */
2913
+ autoOnPromote: 'pr' | 'none';
2914
+ /** GH owner / repo for the auto-PR. Required when autoOnPromote === 'pr'. */
2915
+ ghOwner?: string;
2916
+ ghRepo?: string;
2917
+ /** Placebo control. When supplied AND the winner differs from baseline, the
2918
+ * loop scores a THIRD holdout arm: the winner surface with its content
2919
+ * footprint-matched-blanked by this function (typically via `neutralizeText`).
2920
+ * Its scores are exposed to the gate as `ctx.neutralizedJudgeScores`, letting
2921
+ * a `neutralizationGate` reject a win whose lift survives blanking the content
2922
+ * (decorative — driven by footprint, not content). Costs one extra holdout
2923
+ * campaign; omit to skip. Return a byte/layout-matched blank of the winner. */
2924
+ neutralize?: (winnerSurface: MutableSurface, baselineSurface: MutableSurface) => MutableSurface;
2925
+ };
2926
+ interface RunImprovementLoopResult<TArtifact, TScenario extends Scenario> extends RunOptimizationResult<TArtifact, TScenario> {
2927
+ baselineOnHoldout: CampaignResult<TArtifact, TScenario>;
2928
+ winnerOnHoldout: CampaignResult<TArtifact, TScenario>;
2929
+ neutralizedOnHoldout?: CampaignResult<TArtifact, TScenario>;
2930
+ neutralizedSurface?: MutableSurface;
2931
+ gateResult: Awaited<ReturnType<Gate<TArtifact, TScenario>['decide']>>;
2932
+ claim?: EvaluationClaim;
2933
+ finalEvidence?: FinalEvidenceUse;
2934
+ modelComparison: ModelComparison;
2935
+ /** Present iff the loop ran with `holdout: 'deferred'`. When set,
2936
+ * `baselineOnHoldout`/`winnerOnHoldout` are the shared EMPTY campaign (zero
2937
+ * cells dispatched) and the gate verdict is the forced `'hold'`. */
2938
+ holdout?: 'deferred';
2939
+ /** Unified baseline→winner surface diff. Computed UNCONDITIONALLY (not only
2940
+ * when `autoOnPromote === 'pr'`) so the diff that the gate decided on is
2941
+ * always present on the result + in the emitted provenance record. Empty
2942
+ * string when winner == baseline (no change to diff). */
2943
+ promotedDiff: string;
2944
+ prResult?: ReturnType<typeof openAutoPr>;
2945
+ }
2946
+ /**
2947
+ * Gated-promotion shell over `runOptimization`: scores the winner against the baseline on a holdout set, runs the release gate, and optionally opens a PR.
2948
+ */
2949
+ declare function runImprovementLoop<TScenario extends Scenario, TArtifact>(opts: RunImprovementLoopOptions<TScenario, TArtifact>): Promise<RunImprovementLoopResult<TArtifact, TScenario>>;
2950
+ export { LoopProvenanceEvidence as $, loadEvalFixture as $n, CrossSurfaceNaiveStackSelection as $r, neutralizeText as $t, SkillOptRunnerCommand as A, CampaignRunPlanCell as Ai, RedTeamCase as An, AnalyzeCrossSurfaceInteractionsInput as Ar, PlaybackDriver as At, DiscriminationScore as B, captureFinalEvidencePolicy as Bi, CanaryOptions as Bn, CrossSurfaceCandidateSummary as Br, userStoryScoreboard as Bt, codeSurfaceIdentityMaterial as C, RunEvalOptions as Ci, HeldOutGateOptions as Cn, readGepaCandidatePopulationArtifact as Cr, ScenarioRollup as Ct, surfaceDispatchRef as D, RunCampaignOptions as Di, DefaultProductionRewardHackingOptions as Dn, ExternalOptimizerSubmittedCandidate as Dr, assertRealBackend as Dt, surfaceContentHash as E, CampaignCellRetryPolicy as Ei, DefaultProductionGateOptions as En, ExternalOptimizerObservationSummary as Er, BackendIntegrityReport as Et, acquireSingleRunLock as F, CellScheduleSlot as Fi, redTeamReport as Fn, CrossSurfaceBootstrapPolicy as Fr, UserStory as Ft, RetainedDispatchOutcome as G, campaignCoverage as Gi, EvalFixtureFile as Gn, CrossSurfaceEligibility as Gr, extractProducedState as Gt, scoreDiscrimination as H, withFinalEvidenceSources as Hi, runCanaries as Hn, CrossSurfaceComponentEvidence as Hr, ProposalEventLike as Ht, campaignCellSearchResult as I, buildCellSchedule as Ii, scoreRedTeamOutput as In, CrossSurfaceCandidate as Ir, UserStoryVerdict as It, EmitLoopProvenanceArgs as J, campaignSplitDigestFromIdentities as Ji, EvalFixtureScenario as Jn, CrossSurfaceInteractionAwareSelection as Jr, OptimizationMethodPairwise as Jt, createRetainedDispatch as K, campaignScenarioIdentity as Ki, EvalFixtureLoadOptions as Kn, CrossSurfaceEvidenceBreakdown as Kr, CompareOptimizationMethodsOptions as Kt, searchModelIdentity as L, cellCachePath as Li, CanaryAlert as Ln, CrossSurfaceCandidateComparison as Lr, renderScoreboardMarkdown as Lt, skillOptOptimizationMethod as M, planCampaignRun as Mi, RedTeamFinding as Mn, CrossSurfaceAdditionRejectionReason as Mr, ScoreboardRenderOptions as Mt, SingleRunLock as N, CacheIssueReason as Ni, RedTeamReport as Nn, CrossSurfaceAttemptCompleteness as Nr, ScoreboardRow as Nt, surfaceHash as O, runCampaign as Oi, defaultProductionGate as On, readExternalOptimizerObservationArtifact as Or, summarizeBackendIntegrity as Ot, SingleRunLockOptions as P, CacheRead as Pi, redTeamDataset as Pn, CrossSurfaceBestSingleSelection as Pr, ScoreboardSummary as Pt, LoopProvenanceCandidate as Q, discoverEvalFixtures as Qn, CrossSurfaceInteractionTask as Qr, sequentialOptimizationMethod as Qt, searchProposalExecution as R, FinalEvidencePolicy as Ri, CanaryEvaluation as Rn, CrossSurfaceCandidateEvidence as Rr, scoreUserStory as Rt, assertCodeSurfaceIdentity as S, openAutoPr as Si, neutralizationGate as Sn, GepaCandidateSelectionScore as Sr, RunProfileMatrixResult as St, renderSurfaceDiff as T, CampaignCellFailureReceipt as Ti, DefaultProductionGateCheck as Tn, ExternalOptimizerObservationArtifact as Tr, BackendIntegrityError as Tt, resolveRunDir as U, CampaignCoverage as Ui, composeGate as Un, CrossSurfaceCompositionStep as Ur, RuntimeEventLike as Ut, ScenarioSignal as V, prepareSearchFinalEvidence as Vi, CanaryReport as Vn, CrossSurfaceComponent as Vr, ArtifactEventLike as Vt, RetainedDispatchOptions as W, assertCampaignDesign as Wi, EvalFixture as Wn, CrossSurfaceDistribution as Wr, ToolCallEventLike as Wt, LoopProvenanceArgsFromResult as X, SearchLedgerIntegrityError as Xi, LoadEvalFixtureScenariosOptions as Xn, CrossSurfaceInteractionPath as Xr, compareOptimizationMethods as Xt, EmitLoopProvenanceResult as Y, SearchLedgerError as Yi, EvalFixtureValidationMode as Yn, CrossSurfaceInteractionEffect as Yr, OptimizationMethodScore as Yt, LoopProvenanceBackend as Z, PlanEvalFixtureRunOptions as Zn, CrossSurfaceInteractionReport as Zr, scopedOptimizationMethod as Zt, PhoenixEvaluationResultLike as _, LlmJudgeDimension as _i, GepaRunnerCommand as _n, OptimizationTokenUsage as _r, finalizeProfileMatrix as _t, RunOptimizationOptions as a, CrossSurfaceRelativeCost as ai, UngroundedLiteralReport as an, ExternalTextOptimizerResult as ar, CampaignComparisonUnits as at, isTransientTransportFailure as b, OpenAutoPrOptions as bi, OptimizerModelBudget as bn, GepaCandidatePopulationCandidate as br, ProfileSummary as bt, CodeSurfaceVerification as c, CrossSurfaceTaskRow as ci, GepaPopulationImport as cn, decodeExternalTextCandidate as cr, CreateProfileMatrixPlanOptions as ct, WorktreeAdapter as d, TraceAnalystArtifact as di, importGepaPopulation as dn, OptimizationMethodInput as dr, ProfileMatrixCoverage as dt, CrossSurfacePairCompatibility as ei, FsLabeledScenarioStoreOptions as en, loadEvalFixtureScenarios as er, LoopProvenanceOptimizationMethod as et, gitWorktreeAdapter as f, TraceAnalystScenario as fi, GepaAdaptiveEngineRun as fn, OptimizationMethodProvenance as fr, ProfileMatrixPlan as ft, AutoevalsScorerLike as g, ReferenceEquivalenceScenario as gi, GepaOptimizationRecipe as gn, ComparisonCost as gr, createProfileMatrixPlan as gt, AutoevalsScoreLike as h, ReferenceEquivalenceJudgeResult as hi, GepaOptimizationMethodConfig as hn, OptimizationPackageSource as hr, RunProfileMatrixSegmentOptions as ht, PremeasuredOptimizationBaseline as i, CrossSurfaceRankedSingle as ii, ScoredRollout as in, ExternalTextOptimizerContext as ir, CampaignBreakdown as it, SkillOptTrainerConfig as j, PlanCampaignRunOptions as ji, RedTeamCategory as jn, CrossSurfaceAdditionDecision as jr, PlaybackStep as jt, SkillOptOptimizationMethodConfig as k, CampaignRunPlan as ki, DEFAULT_RED_TEAM_CORPUS as kn, analyzeCrossSurfaceInteractions as kr, PlaybackContext as kt, GitWorktreeAdapterOptions as l, measureCampaignCost as li, externalSurface as ln, OptimizationMethod as lr, FinalizeProfileMatrixOptions as lt, verifyCodeSurface as m, ReferenceEquivalenceJudgeOptions as mi, GepaEngineRun as mn, OptimizationMethodRunOptions as mr, ProfileMatrixSegmentResult as mt, RunImprovementLoopResult as n, CrossSurfacePairIncompatibilityReason as ni, RolloutArgumentDiffOptions as nn, externalTextOptimizationMethod as nr, canonicalDigest as nt, RunOptimizationResult as o, CrossSurfaceSelectionPolicy as oi, ExternalSearchOptimizer as on, ExternalOptimizationExample as or, campaignBreakdown as ot, resolveWorktreePath as p, ReferenceEquivalenceJudgeInput as pi, GepaEngineOptions as pn, OptimizationMethodResult as pr, ProfileMatrixRow as pt, BuildLoopProvenanceArgs as q, campaignSplitDigest as qi, EvalFixtureRunPlan as qn, CrossSurfaceIneligibilityReason as qr, OptimizationMethodComparison as qt, runImprovementLoop as r, CrossSurfacePairwiseEntry as ri, RolloutCall as rn, ExternalTextOptimizationMethodConfig as rr, emitLoopProvenance as rt, runOptimization as s, CrossSurfaceSelections as si, GepaEvaluationImport as sn, ExternalTextEvaluationResponse as sr, campaignMeanComposite as st, RunImprovementLoopOptions as t, CrossSurfacePairEvidence as ti, RolloutArgumentDiff as tn, planEvalFixtureRun as tr, LoopProvenanceRecord as tt, Worktree as u, BuildTraceAnalystSurfaceDispatchOptions as ui, importExternalEvaluations as un, OptimizationMethodComposition as ur, FinalizedProfileMatrixResult as ut, PhoenixEvaluatorLike as v, LlmJudgeOptions as vi, gepaOptimizationMethod as vn, costFromLedgerSummary as vr, runProfileMatrixSegment as vt, componentSurfaceIdentityMaterial as w, runEval as wi, heldOutGate as wn, ExternalOptimizerExecutionSummary as wr, runProfileMatrix as wt, transientDispatchFailure as x, OpenAutoPrResult as xi, NeutralizationGateOptions as xn, GepaCandidatePopulationSummary as xr, RunProfileMatrixOptions as xt, TransientFailureOptions as y, llmJudge as yi, OpenAICompatibleOptimizerModel as yn, GepaCandidatePopulationArtifact as yr, ProfileDispatchFn as yt, searchReceiptAccounting as z, FinalEvidenceUse as zi, CanaryKind as zn, CrossSurfaceCandidateOutcome as zr, scoreboardSummary as zt };
2951
+ //# sourceMappingURL=run-improvement-loop-BAxDnaPI.d.ts.map