@tangle-network/agent-eval 0.175.0 → 0.177.0

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 (106) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/adapters/http.d.ts +1 -1
  3. package/dist/agent-profile-cell-0gSi5ffD.js +374 -0
  4. package/dist/agent-profile-cell-0gSi5ffD.js.map +1 -0
  5. package/dist/analyst/index.d.ts +2 -2
  6. package/dist/analyst/index.js +3 -3
  7. package/dist/{benchmark-command-D_5xG9LG.js → benchmark-command-BrsZhMSk.js} +7 -7
  8. package/dist/{benchmark-command-D_5xG9LG.js.map → benchmark-command-BrsZhMSk.js.map} +1 -1
  9. package/dist/benchmarks/index.d.ts +1 -1
  10. package/dist/benchmarks/index.js +3 -3
  11. package/dist/campaign/index.d.ts +3 -3
  12. package/dist/campaign/index.js +9 -9
  13. package/dist/{campaign-BzMSCejE.js → campaign-CIn-ErlJ.js} +111 -13
  14. package/dist/campaign-CIn-ErlJ.js.map +1 -0
  15. package/dist/campaign-evidence-D8DBLqLI.js +2083 -0
  16. package/dist/campaign-evidence-D8DBLqLI.js.map +1 -0
  17. package/dist/cli.js +1 -1
  18. package/dist/contract/index.d.ts +4 -4
  19. package/dist/contract/index.js +8 -8
  20. package/dist/{define-agent-eval-ox5McL6e.js → define-agent-eval-CJG7LD9M.js} +54 -36
  21. package/dist/define-agent-eval-CJG7LD9M.js.map +1 -0
  22. package/dist/{define-agent-eval-V1jQyCDR.d.ts → define-agent-eval-CqmlXUfQ.d.ts} +11 -4
  23. package/dist/define-agent-eval-CqmlXUfQ.d.ts.map +1 -0
  24. package/dist/{dspy-rlm-engine-Caz2pl4L.js → dspy-rlm-engine-DqjER2sV.js} +2 -2
  25. package/dist/{dspy-rlm-engine-Caz2pl4L.js.map → dspy-rlm-engine-DqjER2sV.js.map} +1 -1
  26. package/dist/{eval-campaign-BeAjdhzC.js → eval-campaign-Cs-7MiCs.js} +4 -5
  27. package/dist/{eval-campaign-BeAjdhzC.js.map → eval-campaign-Cs-7MiCs.js.map} +1 -1
  28. package/dist/experiment/index.d.ts +3 -68
  29. package/dist/experiment/index.d.ts.map +1 -1
  30. package/dist/experiment/index.js +6 -128
  31. package/dist/experiment/index.js.map +1 -1
  32. package/dist/{attestation-XSUpbc4o.js → experiment-tracker-BKEumQug.js} +2 -96
  33. package/dist/experiment-tracker-BKEumQug.js.map +1 -0
  34. package/dist/{attestation-c1QvaBdX.d.ts → experiment-tracker-CNwqCZFD.d.ts} +2 -78
  35. package/dist/experiment-tracker-CNwqCZFD.d.ts.map +1 -0
  36. package/dist/{external-optimizer-process-CxnFL1hd.js → external-optimizer-process-Dlz8YxrT.js} +3 -3
  37. package/dist/{external-optimizer-process-CxnFL1hd.js.map → external-optimizer-process-Dlz8YxrT.js.map} +1 -1
  38. package/dist/{external-optimizer-subprocess-CQi27uEI.js → external-optimizer-subprocess-q3VzlGAO.js} +2 -2
  39. package/dist/{external-optimizer-subprocess-CQi27uEI.js.map → external-optimizer-subprocess-q3VzlGAO.js.map} +1 -1
  40. package/dist/{index-DKXuBPXf.d.ts → index-CtGf6e6X.d.ts} +50 -10
  41. package/dist/index-CtGf6e6X.d.ts.map +1 -0
  42. package/dist/{index-BTrx5s8m.d.ts → index-DuaNwvse.d.ts} +4 -4
  43. package/dist/{index-BTrx5s8m.d.ts.map → index-DuaNwvse.d.ts.map} +1 -1
  44. package/dist/{index-D-UdhAmg.d.ts → index-u0d1Jp4F.d.ts} +4 -2
  45. package/dist/{index-D-UdhAmg.d.ts.map → index-u0d1Jp4F.d.ts.map} +1 -1
  46. package/dist/index.d.ts +4 -4
  47. package/dist/index.js +14 -15
  48. package/dist/index.js.map +1 -1
  49. package/dist/ledger-core/index.d.ts +2 -2
  50. package/dist/ledger-core/index.js +2 -2
  51. package/dist/{ledger-core-PIfjCbKn.js → ledger-core-Cs9f7385.js} +60 -47
  52. package/dist/{ledger-core-PIfjCbKn.js.map → ledger-core-Cs9f7385.js.map} +1 -1
  53. package/dist/{llm-judge-DmNaBrXB.js → llm-judge-CV80fkYA.js} +1039 -1517
  54. package/dist/llm-judge-CV80fkYA.js.map +1 -0
  55. package/dist/{mint-vWOdD8Ae.js → mint-Cc1_zwRQ.js} +2 -2
  56. package/dist/{mint-vWOdD8Ae.js.map → mint-Cc1_zwRQ.js.map} +1 -1
  57. package/dist/openapi.json +1 -1
  58. package/dist/{produced-state-B8mw6zj9.js → produced-state-CQFi465p.js} +3 -2
  59. package/dist/{produced-state-B8mw6zj9.js.map → produced-state-CQFi465p.js.map} +1 -1
  60. package/dist/profile-cell.js +1 -268
  61. package/dist/{promotion-policy-LY9mVQ7W.js → promotion-policy-DWOm70gx.js} +2 -2
  62. package/dist/{promotion-policy-LY9mVQ7W.js.map → promotion-policy-DWOm70gx.js.map} +1 -1
  63. package/dist/{release-confidence-BsGEg_xg.js → release-confidence-BcGCclTB.js} +2 -2
  64. package/dist/{release-confidence-BsGEg_xg.js.map → release-confidence-BcGCclTB.js.map} +1 -1
  65. package/dist/reporting.js +2 -2
  66. package/dist/{reward-hacking-CKW4teig.js → reward-hacking-D0XwhVWE.js} +2 -215
  67. package/dist/reward-hacking-D0XwhVWE.js.map +1 -0
  68. package/dist/rl.js +5 -4
  69. package/dist/rl.js.map +1 -1
  70. package/dist/rollout/index.js +2 -2
  71. package/dist/{rollout-CGlDq1GI.js → rollout-DmoJVqrF.js} +2 -2
  72. package/dist/{rollout-CGlDq1GI.js.map → rollout-DmoJVqrF.js.map} +1 -1
  73. package/dist/run-record-CR63CpHK.js +216 -0
  74. package/dist/run-record-CR63CpHK.js.map +1 -0
  75. package/dist/{run-record-ZIsR9Fif.js → run-record-DQpSf7t-.js} +2 -2
  76. package/dist/{run-record-ZIsR9Fif.js.map → run-record-DQpSf7t-.js.map} +1 -1
  77. package/dist/{semantic-concept-judge-E3s_fEjB.js → semantic-concept-judge-Dw-f7TEs.js} +3 -3
  78. package/dist/{semantic-concept-judge-E3s_fEjB.js.map → semantic-concept-judge-Dw-f7TEs.js.map} +1 -1
  79. package/dist/{sequential-B51qAYE4.js → sequential-B5gXgcyp.js} +3 -3
  80. package/dist/{sequential-B51qAYE4.js.map → sequential-B5gXgcyp.js.map} +1 -1
  81. package/dist/{skillopt-optimization-method-f7399oGb.js → skillopt-optimization-method-D0o2c2yM.js} +6 -749
  82. package/dist/skillopt-optimization-method-D0o2c2yM.js.map +1 -0
  83. package/dist/{statistical-heldout-Cqb73yE9.d.ts → statistical-heldout-Z9NROFFS.d.ts} +156 -3
  84. package/dist/statistical-heldout-Z9NROFFS.d.ts.map +1 -0
  85. package/dist/{summary-report-Bgh8CpNK.js → summary-report-B16xy9Kd.js} +2 -2
  86. package/dist/{summary-report-Bgh8CpNK.js.map → summary-report-B16xy9Kd.js.map} +1 -1
  87. package/dist/traces.js +1 -1
  88. package/docs/campaign-proposers.md +44 -0
  89. package/docs/public-api.md +62 -39
  90. package/docs/search-history-receipts.md +48 -1
  91. package/package.json +1 -1
  92. package/dist/attestation-XSUpbc4o.js.map +0 -1
  93. package/dist/attestation-c1QvaBdX.d.ts.map +0 -1
  94. package/dist/campaign-BzMSCejE.js.map +0 -1
  95. package/dist/define-agent-eval-V1jQyCDR.d.ts.map +0 -1
  96. package/dist/define-agent-eval-ox5McL6e.js.map +0 -1
  97. package/dist/index-DKXuBPXf.d.ts.map +0 -1
  98. package/dist/llm-judge-DmNaBrXB.js.map +0 -1
  99. package/dist/power-preflight-CFXm0Vjo.js +0 -502
  100. package/dist/power-preflight-CFXm0Vjo.js.map +0 -1
  101. package/dist/pre-registration-D94b7Of5.js +0 -110
  102. package/dist/pre-registration-D94b7Of5.js.map +0 -1
  103. package/dist/profile-cell.js.map +0 -1
  104. package/dist/reward-hacking-CKW4teig.js.map +0 -1
  105. package/dist/skillopt-optimization-method-f7399oGb.js.map +0 -1
  106. package/dist/statistical-heldout-Cqb73yE9.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sequential-B51qAYE4.js","names":[],"sources":["../src/campaign/gates/sequential.ts"],"sourcesContent":["/**\n * Anytime-valid sequential promotion gate — an e-process (betting\n * test-martingale, see `eProcess` in `statistics.ts`) over paired\n * per-scenario deltas, so a campaign stops the MOMENT evidence decides\n * instead of burning a fixed-n budget. Decisions remain valid at any\n * data-dependent stopping time (Ville's inequality), which is exactly what\n * fixed-n machinery cannot offer: peeking at a bootstrap CI after every\n * observation and stopping on the first significant peek inflates type-I\n * error far beyond alpha.\n *\n * REPLACES, never layers on, a fixed-n gate. Running `heldoutSignificance`\n * or `paretoSignificanceGate` repeatedly on a growing sample and stopping\n * early is optional stopping no matter how it is dressed up; this gate is\n * the valid way to stop early. Use one or the other per evidence stream.\n *\n * Pre-registration binding: anytime validity holds only for the\n * PRE-REGISTERED statistic. When a `SignedManifest` is bound, the gate takes\n * alpha from `manifest.alpha`, the observation budget from\n * `manifest.preRegisteredN`, orients deltas by `manifest.direction`, and\n * shifts the null boundary by `manifest.minEffect` — re-deciding the same\n * stream under different parameters after seeing data would reopen optional\n * stopping under a fancier name. The manifest's content hash is verified at\n * construction (sync, same `sha256-content` scheme as `signManifest`).\n *\n * Non-iid caveat (stated honestly): the supermartingale guarantee needs each\n * delta's conditional mean under H0 to stay ≤ the null boundary given the\n * past — exchangeable scenario deltas suffice. Scenario streams ordered by\n * difficulty or by scenario family violate this; `decide(ctx)` therefore\n * shuffles the paired deltas with a SEEDED permutation by default (the\n * permutation is data-independent, so bet predictability is preserved).\n * Stratified betting (per-stratum λ) is future work, not implemented here.\n */\n\nimport { manifestContentDigest, type SignedManifest } from '../../pre-registration'\nimport { type EProcessState, eProcess, mulberry32 } from '../../statistics'\nimport type { Gate, GateContext, GateResult, GenerationRecord, Scenario } from '../types'\nimport { pairHoldout } from './statistical-heldout'\n\nexport type SequentialDecision = 'promote' | 'continue' | 'undecided-at-maxN'\n\nexport interface SequentialObservation {\n decision: SequentialDecision\n /** Current e-value (the betting wealth) against H0. */\n eValue: number\n /** Paired deltas consumed so far. */\n n: number\n /** Names the decision basis. For 'undecided-at-maxN' it states explicitly\n * that exhausting the budget is NOT evidence of no effect. */\n reason: string\n}\n\nexport interface SequentialPairedGateOptions {\n /** Type-I budget. With `preRegistration` bound this MUST match\n * `manifest.alpha` (conflict throws). Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a promote may fire. The stopping rule is\n * \"first n ≥ minN with e-value ≥ 1/alpha\" — still a valid stopping time.\n * Default 5. */\n minN?: number\n /** Pre-registered observation budget. Required unless `preRegistration`\n * supplies it via `preRegisteredN` (conflict throws). */\n maxN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |delta| in the judge's native scale; deltas are mapped to\n * x = (d/scale + 1)/2 ∈ [0,1]. A delta outside ±scale throws (use\n * `detectScale` to pick 1 vs 100 BEFORE streaming). Default 1. */\n scale?: number\n /** Seed for the data-independent shuffle of paired deltas in `decide(ctx)`\n * (exchangeability guard). Default 1337. */\n shuffleSeed?: number\n /** Bind the pre-registered hypothesis. Verified (content hash) at\n * construction; alpha/maxN/direction/minEffect come FROM the manifest. */\n preRegistration?: SignedManifest\n /** Override the gate name in reports. */\n name?: string\n /** Continue the observe-stream from a `state()` snapshot taken before a\n * restart. The gate's parameters still resolve from this options object\n * (and the manifest); the snapshot must have been recorded under the same\n * alpha, maxBet, and null boundary, and its decision must be one this\n * configuration could have reached at its n, or construction throws.\n * `decide(ctx)` is unaffected — it always runs on a fresh stream. */\n resume?: SequentialStreamState\n}\n\n/** Snapshot of one observe-stream: the e-process state plus the gate's own\n * decision, which applies `minN` and `maxN` on top of the core latch. A\n * gate rebuilt with `resume` from this value continues exactly where the\n * snapshot was taken. */\nexport type SequentialStreamState = EProcessState & { decision: SequentialDecision }\n\nexport interface SequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>\n extends Gate<TArtifact, TScenario> {\n /** Streaming entry point: feed one paired per-scenario delta\n * (candidate − baseline, native scale). Each gate instance carries ONE\n * observe-stream; `decide(ctx)` runs on its own fresh stream and never\n * consumes or advances this one. 'promote' is sticky; observing past the\n * pre-registered maxN throws (extending a finished stream after seeing\n * the result reopens optional stopping — start a NEW pre-registered\n * test). */\n observe(delta: number): SequentialObservation\n /** Read-only snapshot of the observe-stream. Pass it back as\n * `resume` to continue the stream after a restart. */\n state(): SequentialStreamState\n}\n\ninterface ResolvedConfig {\n alpha: number\n minN: number\n maxN: number\n maxBet: number\n scale: number\n shuffleSeed: number\n /** 'decrease' negates deltas so \"better\" is always positive. */\n direction: 'increase' | 'decrease'\n /** H0 boundary in x-space: 1/2 + minEffect/(2·scale). */\n nullMean: number\n minEffect: number\n}\n\n/** Sync twin of `verifyManifest`, so gate construction stays synchronous and\n * fails loud before any observation is consumed. The digest scheme belongs to\n * `pre-registration`; this gate only compares. */\nfunction verifyManifestSync(m: SignedManifest): boolean {\n return manifestContentDigest(m) === m.contentHash\n}\n\nfunction resolveConfig(opts: SequentialPairedGateOptions): ResolvedConfig {\n const m = opts.preRegistration\n let alpha: number\n let maxN: number\n let direction: 'increase' | 'decrease'\n let minEffect: number\n if (m) {\n if (!verifyManifestSync(m)) {\n throw new Error(\n `sequentialPairedGate: pre-registration manifest '${m.id}' content hash mismatch (tampered)`,\n )\n }\n if (opts.alpha !== undefined && opts.alpha !== m.alpha) {\n throw new Error(\n `sequentialPairedGate: alpha ${opts.alpha} conflicts with pre-registered alpha ${m.alpha} — ` +\n `the registered statistic is the only one anytime validity covers`,\n )\n }\n if (opts.maxN !== undefined && opts.maxN !== m.preRegisteredN) {\n throw new Error(\n `sequentialPairedGate: maxN ${opts.maxN} conflicts with pre-registered N ${m.preRegisteredN}`,\n )\n }\n alpha = m.alpha\n maxN = m.preRegisteredN\n direction = m.direction\n minEffect = m.minEffect\n } else {\n alpha = opts.alpha ?? 0.05\n if (opts.maxN === undefined) {\n throw new Error(\n 'sequentialPairedGate: maxN is required (or bind a preRegistration manifest whose ' +\n 'preRegisteredN is the budget) — an unbounded stream has no pre-registered budget',\n )\n }\n maxN = opts.maxN\n direction = 'increase'\n minEffect = 0\n }\n const scale = opts.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialPairedGate: scale must be > 0, got ${scale}`)\n }\n if (!Number.isInteger(maxN) || maxN < 1) {\n throw new Error(`sequentialPairedGate: maxN must be a positive integer, got ${maxN}`)\n }\n const minN = opts.minN ?? 5\n if (!Number.isInteger(minN) || minN < 1 || minN > maxN) {\n throw new Error(\n `sequentialPairedGate: minN must be an integer in [1, maxN=${maxN}], got ${minN}`,\n )\n }\n if (!Number.isFinite(minEffect) || minEffect < 0 || minEffect >= scale) {\n throw new Error(\n `sequentialPairedGate: minEffect must be in [0, scale=${scale}), got ${minEffect}`,\n )\n }\n // H0: mean delta ≤ minEffect. In x = (d/scale + 1)/2 space that is\n // E[x] ≤ 1/2 + minEffect/(2·scale) — a shifted null boundary, NOT a clamp\n // of the observations (clamping is mean-distorting for skewed deltas).\n const nullMean = 0.5 + minEffect / (2 * scale)\n return {\n alpha,\n minN,\n maxN,\n maxBet: opts.maxBet ?? 0.5,\n scale,\n shuffleSeed: opts.shuffleSeed ?? 1337,\n direction,\n nullMean,\n minEffect,\n }\n}\n\ninterface SequentialStream {\n observe(delta: number): SequentialObservation\n state(): SequentialStreamState\n}\n\nconst SEQUENTIAL_DECISIONS: readonly SequentialDecision[] = [\n 'promote',\n 'continue',\n 'undecided-at-maxN',\n]\n\n/** Refuse a snapshot whose gate decision this configuration could not have\n * reached at the snapshot's n. The e-process parameters are checked by\n * `eProcess` itself; this covers the gate's own stopping rule. */\nfunction assertResumableStream(resume: SequentialStreamState, cfg: ResolvedConfig): void {\n const fail = (detail: string): never => {\n throw new Error(`sequentialPairedGate: cannot resume — ${detail}`)\n }\n if (!SEQUENTIAL_DECISIONS.includes(resume.decision)) {\n fail(`unknown decision '${String(resume.decision)}'`)\n }\n if (resume.n > cfg.maxN) {\n fail(`snapshot n=${resume.n} exceeds the pre-registered maxN=${cfg.maxN}`)\n }\n const threshold = 1 / cfg.alpha\n switch (resume.decision) {\n case 'promote':\n if (resume.n < cfg.minN) {\n fail(`decision 'promote' at n=${resume.n} is below minN=${cfg.minN}`)\n }\n break\n case 'undecided-at-maxN':\n if (resume.n !== cfg.maxN) {\n fail(`decision 'undecided-at-maxN' at n=${resume.n} does not match maxN=${cfg.maxN}`)\n }\n break\n case 'continue':\n if (resume.n >= cfg.maxN) {\n fail(`decision 'continue' at n=${resume.n} with maxN=${cfg.maxN}; the stream is finished`)\n }\n if (resume.n >= cfg.minN && resume.wealth >= threshold) {\n fail(\n `decision 'continue' at n=${resume.n} ≥ minN=${cfg.minN} with e-value ` +\n `${resume.wealth} ≥ 1/α=${threshold}; this stream would have promoted`,\n )\n }\n break\n }\n}\n\nfunction makeStream(cfg: ResolvedConfig, resume?: SequentialStreamState): SequentialStream {\n if (resume !== undefined) assertResumableStream(resume, cfg)\n const proc = eProcess({\n alpha: cfg.alpha,\n maxBet: cfg.maxBet,\n nullMean: cfg.nullMean,\n ...(resume === undefined ? {} : { resume }),\n })\n const threshold = 1 / cfg.alpha\n let terminal: SequentialDecision | undefined =\n resume === undefined || resume.decision === 'continue' ? undefined : resume.decision\n return {\n observe(delta: number): SequentialObservation {\n if (terminal === 'undecided-at-maxN') {\n throw new Error(\n `sequentialPairedGate: pre-registered maxN=${cfg.maxN} exhausted — extending the ` +\n 'stream after seeing the result reopens optional stopping; start a NEW ' +\n 'pre-registered test',\n )\n }\n if (!Number.isFinite(delta) || Math.abs(delta) > cfg.scale) {\n throw new Error(\n `sequentialPairedGate: delta ${delta} outside ±scale=${cfg.scale} — pass the judge's ` +\n `native scale explicitly (detectScale helps pick 1 vs 100)`,\n )\n }\n const d = cfg.direction === 'decrease' ? -delta : delta\n const step = proc.update((d / cfg.scale + 1) / 2)\n // Stopping rule: FIRST n ≥ minN with current wealth ≥ 1/alpha — a valid\n // stopping time (measurable w.r.t. the past), sticky once latched. The\n // core's own `decided` latch ignores minN, so the gate re-derives the\n // decision from current wealth here.\n if (terminal === undefined && step.n >= cfg.minN && step.wealth >= threshold) {\n terminal = 'promote'\n }\n if (terminal === 'promote') {\n return {\n decision: 'promote',\n eValue: step.wealth,\n n: step.n,\n reason:\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} at n=${step.n} ` +\n `(minN=${cfg.minN}): the paired improvement exceeds ${cfg.minEffect} at anytime-valid ` +\n `level α=${cfg.alpha}`,\n }\n }\n if (step.n >= cfg.maxN) {\n terminal = 'undecided-at-maxN'\n return {\n decision: 'undecided-at-maxN',\n eValue: step.wealth,\n n: step.n,\n reason:\n `undecided at pre-registered maxN=${cfg.maxN} (e-value ${step.wealth.toFixed(2)} < ` +\n `1/α=${threshold.toFixed(2)}). This is NOT evidence of no effect — the effect may be ` +\n 'real but smaller than this budget can detect; re-register with a larger N to test that',\n }\n }\n return {\n decision: 'continue',\n eValue: step.wealth,\n n: step.n,\n reason: `e-value ${step.wealth.toFixed(2)} < 1/α=${threshold.toFixed(2)} at n=${step.n}/${cfg.maxN} — keep observing`,\n }\n },\n state() {\n return { ...proc.state(), decision: terminal ?? 'continue' }\n },\n }\n}\n\n/** Data-independent in-place Fisher–Yates with a seeded PRNG — the permutation\n * depends only on the seed, never the values, so bet predictability survives. */\nfunction seededShuffle<T>(items: T[], seed: number): T[] {\n const rng = mulberry32(seed)\n for (let i = items.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n const tmp = items[i]!\n items[i] = items[j]!\n items[j] = tmp\n }\n return items\n}\n\n/**\n * Anytime-valid sequential paired gate. Conforms to the existing `Gate`\n * contract (`decide(ctx)` consumes candidate vs baseline judge scores via\n * `pairHoldout` — same pairing granularity as the fixed-n gates: full cellId,\n * never scenarioId) and adds a streaming `observe(delta)` entry for campaigns\n * that score cells incrementally and want to stop mid-stream.\n *\n * Decision mapping onto the substrate's five-valued `GateDecision`:\n * - 'promote' → 'ship'\n * - 'continue' → 'need_more_work' (stream ended before maxN with\n * the e-value undecided — more reps could decide)\n * - 'undecided-at-maxN' → 'hold', with the reason stating it is NOT\n * evidence of no effect (never a silent default)\n */\nexport function sequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n options: SequentialPairedGateOptions,\n): SequentialPairedGate<TArtifact, TScenario> {\n const cfg = resolveConfig(options)\n const name = options.name ?? 'sequentialPairedGate'\n const manifest = options.preRegistration\n const observeStream = makeStream(cfg, options.resume)\n\n return {\n name,\n observe(delta: number): SequentialObservation {\n return observeStream.observe(delta)\n },\n state() {\n return observeStream.state()\n },\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n `${name}: ctx.baselineJudgeScores is required — falling back to the candidate's own ` +\n 'scores would compare the candidate against itself (delta 0, silent no-op)',\n )\n }\n const scenarioIds = new Set(ctx.scenarios.map((s) => s.id))\n const paired = pairHoldout(\n ctx.judgeScores,\n ctx.baselineJudgeScores,\n scenarioIds,\n (s) => s.composite,\n )\n const deltas = paired.after.map((a, i) => a - paired.before[i]!)\n seededShuffle(deltas, cfg.shuffleSeed)\n\n const stream = makeStream(cfg)\n let last: SequentialObservation | undefined\n for (const d of deltas) {\n last = stream.observe(d)\n if (last.decision !== 'continue') break\n }\n\n const detail = {\n ...stream.state(),\n minN: cfg.minN,\n maxN: cfg.maxN,\n scale: cfg.scale,\n shuffleSeed: cfg.shuffleSeed,\n direction: cfg.direction,\n minEffect: cfg.minEffect,\n pairedN: deltas.length,\n ...(manifest ? { preRegisteredId: manifest.id, metric: manifest.metric } : {}),\n }\n const meanDelta =\n deltas.length === 0 ? undefined : deltas.reduce((s, d) => s + d, 0) / deltas.length\n\n if (last === undefined) {\n return {\n decision: 'need_more_work',\n reasons: [`${name}: no paired holdout observations — nothing to test`],\n contributingGates: [{ name, status: 'not_evaluated', detail }],\n }\n }\n const decision =\n last.decision === 'promote'\n ? 'ship'\n : last.decision === 'continue'\n ? 'need_more_work'\n : 'hold'\n return {\n decision,\n reasons: [`${name}: ${last.reason}`],\n contributingGates: [\n {\n name,\n status:\n decision === 'ship'\n ? 'pass'\n : decision === 'need_more_work'\n ? 'not_evaluated'\n : 'fail',\n detail,\n },\n ],\n delta: meanDelta,\n }\n },\n }\n}\n\nexport interface SequentialDecideOptions {\n /** Type-I budget for the early-stop evidence. Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a stop may fire. Default 5. */\n minN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |per-scenario composite delta|. Default 1. */\n scale?: number\n}\n\nexport interface SequentialDecideFn {\n (args: { history: GenerationRecord[] }): { stop: boolean; reason?: string }\n /** Read-only snapshot of the accumulated e-process (observability + tests). */\n state(): EProcessState\n}\n\n/**\n * `SurfaceProposer.decide` adapter — stops the optimization loop the moment\n * the e-process decides the loop has produced a real improvement, instead of\n * always running `maxGenerations`.\n *\n * Stream: for each generation g ≥ 1, the per-scenario composite deltas of\n * generation g's top candidate vs the generation-0 top candidate (the\n * incumbent the loop set out to beat), paired by scenarioId. H0: no proposed\n * surface improves any scenario's expected composite over the incumbent —\n * under it every delta has conditional mean ≤ 0 and the e-process is valid.\n * Once wealth ≥ 1/alpha the loop stops and hands the winner to the promotion\n * gate (which re-scores on HELD-OUT data — this adapter only spends the\n * exploration budget, it never promotes).\n *\n * Honesty caveats: (1) the incumbent's scores are measured once and shared\n * across all generations' deltas, so type-I control is exact only insofar as\n * those scores approximate the incumbent's true per-scenario means (more reps\n * → tighter); (2) an UNDECIDED process never stops the loop — absence of a\n * crossing is NOT evidence of no effect, so the loop simply runs its normal\n * course. Calling the adapter repeatedly with a growing history consumes each\n * generation exactly once (re-feeding an already-seen record would double-count\n * evidence).\n */\nexport function sequentialDecide(options: SequentialDecideOptions = {}): SequentialDecideFn {\n const alpha = options.alpha ?? 0.05\n const minN = options.minN ?? 5\n const scale = options.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialDecide: scale must be > 0, got ${scale}`)\n }\n const proc = eProcess({ alpha, maxBet: options.maxBet ?? 0.5, nullMean: 0.5 })\n const threshold = 1 / alpha\n let processedGenerations = 0\n let reference: Map<string, number> | undefined\n let stopped: { stop: true; reason: string } | undefined\n\n const topCandidate = (record: GenerationRecord) => {\n if (record.candidates.length === 0) {\n throw new Error(\n `sequentialDecide: generation ${record.generationIndex} has no candidates — ` +\n 'cannot extract a top candidate',\n )\n }\n return record.candidates.reduce((best, candidate) => {\n if (best.composite === null) return candidate\n if (candidate.composite === null) return best\n return candidate.composite > best.composite ? candidate : best\n })\n }\n\n const decide: SequentialDecideFn = ({ history }) => {\n if (stopped) return stopped\n if (history.length === 0) return { stop: false }\n if (reference === undefined) {\n reference = new Map(\n topCandidate(history[0]!).scenarios.map((s) => [s.scenarioId, s.composite]),\n )\n }\n // Consume only generations not yet seen; start at 1 — generation 0 IS the\n // reference and would contribute all-zero deltas (pure wealth dilution).\n for (let g = Math.max(1, processedGenerations); g < history.length; g++) {\n const top = topCandidate(history[g]!)\n const byScenario = new Map(top.scenarios.map((s) => [s.scenarioId, s.composite]))\n for (const [scenarioId, refComposite] of reference) {\n const candComposite = byScenario.get(scenarioId)\n if (candComposite === undefined) {\n throw new Error(\n `sequentialDecide: generation ${history[g]!.generationIndex} top candidate is missing ` +\n `scenario '${scenarioId}' — generations must score the same scenario set to pair`,\n )\n }\n const delta = candComposite - refComposite\n if (!Number.isFinite(delta) || Math.abs(delta) > scale) {\n throw new Error(\n `sequentialDecide: paired delta ${delta} outside ±scale=${scale} on scenario ` +\n `'${scenarioId}' — pass the composite scale explicitly`,\n )\n }\n const step = proc.update((delta / scale + 1) / 2)\n if (step.n >= minN && step.wealth >= threshold) {\n stopped = {\n stop: true,\n reason:\n `sequential e-process decided at generation ${history[g]!.generationIndex}: ` +\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} after n=${step.n} ` +\n 'paired deltas vs the generation-0 incumbent — the improvement is real at ' +\n `α=${alpha}; stop exploring and promote via the gate`,\n }\n processedGenerations = history.length\n return stopped\n }\n }\n }\n processedGenerations = history.length\n return { stop: false }\n }\n decide.state = () => proc.state()\n return decide\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,SAAS,mBAAmB,GAA4B;CACtD,OAAO,sBAAsB,CAAC,MAAM,EAAE;AACxC;AAEA,SAAS,cAAc,MAAmD;CACxE,MAAM,IAAI,KAAK;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,GAAG;EACL,IAAI,CAAC,mBAAmB,CAAC,GACvB,MAAM,IAAI,MACR,oDAAoD,EAAE,GAAG,mCAC3D;EAEF,IAAI,KAAK,UAAU,KAAA,KAAa,KAAK,UAAU,EAAE,OAC/C,MAAM,IAAI,MACR,+BAA+B,KAAK,MAAM,uCAAuC,EAAE,MAAM,oEAE3F;EAEF,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS,EAAE,gBAC7C,MAAM,IAAI,MACR,8BAA8B,KAAK,KAAK,mCAAmC,EAAE,gBAC/E;EAEF,QAAQ,EAAE;EACV,OAAO,EAAE;EACT,YAAY,EAAE;EACd,YAAY,EAAE;CAChB,OAAO;EACL,QAAQ,KAAK,SAAS;EACtB,IAAI,KAAK,SAAS,KAAA,GAChB,MAAM,IAAI,MACR,mKAEF;EAEF,OAAO,KAAK;EACZ,YAAY;EACZ,YAAY;CACd;CACA,MAAM,QAAQ,KAAK,SAAS;CAC5B,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,gDAAgD,OAAO;CAEzE,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,GACpC,MAAM,IAAI,MAAM,8DAA8D,MAAM;CAEtF,MAAM,OAAO,KAAK,QAAQ;CAC1B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,MAChD,MAAM,IAAI,MACR,6D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AE,WAAW,KAAK,EAAE,8EAE7E,MAAM;KACf;KACA,uBAAuB,QAAQ;KAC/B,OAAO;IACT;GACF;EACF;EACA,uBAAuB,QAAQ;EAC/B,OAAO,EAAE,MAAM,MAAM;CACvB;CACA,OAAO,cAAc,KAAK,MAAM;CAChC,OAAO;AACT"}
1
+ {"version":3,"file":"sequential-B5gXgcyp.js","names":[],"sources":["../src/campaign/gates/sequential.ts"],"sourcesContent":["/**\n * Anytime-valid sequential promotion gate — an e-process (betting\n * test-martingale, see `eProcess` in `statistics.ts`) over paired\n * per-scenario deltas, so a campaign stops the MOMENT evidence decides\n * instead of burning a fixed-n budget. Decisions remain valid at any\n * data-dependent stopping time (Ville's inequality), which is exactly what\n * fixed-n machinery cannot offer: peeking at a bootstrap CI after every\n * observation and stopping on the first significant peek inflates type-I\n * error far beyond alpha.\n *\n * REPLACES, never layers on, a fixed-n gate. Running `heldoutSignificance`\n * or `paretoSignificanceGate` repeatedly on a growing sample and stopping\n * early is optional stopping no matter how it is dressed up; this gate is\n * the valid way to stop early. Use one or the other per evidence stream.\n *\n * Pre-registration binding: anytime validity holds only for the\n * PRE-REGISTERED statistic. When a `SignedManifest` is bound, the gate takes\n * alpha from `manifest.alpha`, the observation budget from\n * `manifest.preRegisteredN`, orients deltas by `manifest.direction`, and\n * shifts the null boundary by `manifest.minEffect` — re-deciding the same\n * stream under different parameters after seeing data would reopen optional\n * stopping under a fancier name. The manifest's content hash is verified at\n * construction (sync, same `sha256-content` scheme as `signManifest`).\n *\n * Non-iid caveat (stated honestly): the supermartingale guarantee needs each\n * delta's conditional mean under H0 to stay ≤ the null boundary given the\n * past — exchangeable scenario deltas suffice. Scenario streams ordered by\n * difficulty or by scenario family violate this; `decide(ctx)` therefore\n * shuffles the paired deltas with a SEEDED permutation by default (the\n * permutation is data-independent, so bet predictability is preserved).\n * Stratified betting (per-stratum λ) is future work, not implemented here.\n */\n\nimport { manifestContentDigest, type SignedManifest } from '../../pre-registration'\nimport { type EProcessState, eProcess, mulberry32 } from '../../statistics'\nimport type { Gate, GateContext, GateResult, GenerationRecord, Scenario } from '../types'\nimport { pairHoldout } from './statistical-heldout'\n\nexport type SequentialDecision = 'promote' | 'continue' | 'undecided-at-maxN'\n\nexport interface SequentialObservation {\n decision: SequentialDecision\n /** Current e-value (the betting wealth) against H0. */\n eValue: number\n /** Paired deltas consumed so far. */\n n: number\n /** Names the decision basis. For 'undecided-at-maxN' it states explicitly\n * that exhausting the budget is NOT evidence of no effect. */\n reason: string\n}\n\nexport interface SequentialPairedGateOptions {\n /** Type-I budget. With `preRegistration` bound this MUST match\n * `manifest.alpha` (conflict throws). Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a promote may fire. The stopping rule is\n * \"first n ≥ minN with e-value ≥ 1/alpha\" — still a valid stopping time.\n * Default 5. */\n minN?: number\n /** Pre-registered observation budget. Required unless `preRegistration`\n * supplies it via `preRegisteredN` (conflict throws). */\n maxN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |delta| in the judge's native scale; deltas are mapped to\n * x = (d/scale + 1)/2 ∈ [0,1]. A delta outside ±scale throws (use\n * `detectScale` to pick 1 vs 100 BEFORE streaming). Default 1. */\n scale?: number\n /** Seed for the data-independent shuffle of paired deltas in `decide(ctx)`\n * (exchangeability guard). Default 1337. */\n shuffleSeed?: number\n /** Bind the pre-registered hypothesis. Verified (content hash) at\n * construction; alpha/maxN/direction/minEffect come FROM the manifest. */\n preRegistration?: SignedManifest\n /** Override the gate name in reports. */\n name?: string\n /** Continue the observe-stream from a `state()` snapshot taken before a\n * restart. The gate's parameters still resolve from this options object\n * (and the manifest); the snapshot must have been recorded under the same\n * alpha, maxBet, and null boundary, and its decision must be one this\n * configuration could have reached at its n, or construction throws.\n * `decide(ctx)` is unaffected — it always runs on a fresh stream. */\n resume?: SequentialStreamState\n}\n\n/** Snapshot of one observe-stream: the e-process state plus the gate's own\n * decision, which applies `minN` and `maxN` on top of the core latch. A\n * gate rebuilt with `resume` from this value continues exactly where the\n * snapshot was taken. */\nexport type SequentialStreamState = EProcessState & { decision: SequentialDecision }\n\nexport interface SequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>\n extends Gate<TArtifact, TScenario> {\n /** Streaming entry point: feed one paired per-scenario delta\n * (candidate − baseline, native scale). Each gate instance carries ONE\n * observe-stream; `decide(ctx)` runs on its own fresh stream and never\n * consumes or advances this one. 'promote' is sticky; observing past the\n * pre-registered maxN throws (extending a finished stream after seeing\n * the result reopens optional stopping — start a NEW pre-registered\n * test). */\n observe(delta: number): SequentialObservation\n /** Read-only snapshot of the observe-stream. Pass it back as\n * `resume` to continue the stream after a restart. */\n state(): SequentialStreamState\n}\n\ninterface ResolvedConfig {\n alpha: number\n minN: number\n maxN: number\n maxBet: number\n scale: number\n shuffleSeed: number\n /** 'decrease' negates deltas so \"better\" is always positive. */\n direction: 'increase' | 'decrease'\n /** H0 boundary in x-space: 1/2 + minEffect/(2·scale). */\n nullMean: number\n minEffect: number\n}\n\n/** Sync twin of `verifyManifest`, so gate construction stays synchronous and\n * fails loud before any observation is consumed. The digest scheme belongs to\n * `pre-registration`; this gate only compares. */\nfunction verifyManifestSync(m: SignedManifest): boolean {\n return manifestContentDigest(m) === m.contentHash\n}\n\nfunction resolveConfig(opts: SequentialPairedGateOptions): ResolvedConfig {\n const m = opts.preRegistration\n let alpha: number\n let maxN: number\n let direction: 'increase' | 'decrease'\n let minEffect: number\n if (m) {\n if (!verifyManifestSync(m)) {\n throw new Error(\n `sequentialPairedGate: pre-registration manifest '${m.id}' content hash mismatch (tampered)`,\n )\n }\n if (opts.alpha !== undefined && opts.alpha !== m.alpha) {\n throw new Error(\n `sequentialPairedGate: alpha ${opts.alpha} conflicts with pre-registered alpha ${m.alpha} — ` +\n `the registered statistic is the only one anytime validity covers`,\n )\n }\n if (opts.maxN !== undefined && opts.maxN !== m.preRegisteredN) {\n throw new Error(\n `sequentialPairedGate: maxN ${opts.maxN} conflicts with pre-registered N ${m.preRegisteredN}`,\n )\n }\n alpha = m.alpha\n maxN = m.preRegisteredN\n direction = m.direction\n minEffect = m.minEffect\n } else {\n alpha = opts.alpha ?? 0.05\n if (opts.maxN === undefined) {\n throw new Error(\n 'sequentialPairedGate: maxN is required (or bind a preRegistration manifest whose ' +\n 'preRegisteredN is the budget) — an unbounded stream has no pre-registered budget',\n )\n }\n maxN = opts.maxN\n direction = 'increase'\n minEffect = 0\n }\n const scale = opts.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialPairedGate: scale must be > 0, got ${scale}`)\n }\n if (!Number.isInteger(maxN) || maxN < 1) {\n throw new Error(`sequentialPairedGate: maxN must be a positive integer, got ${maxN}`)\n }\n const minN = opts.minN ?? 5\n if (!Number.isInteger(minN) || minN < 1 || minN > maxN) {\n throw new Error(\n `sequentialPairedGate: minN must be an integer in [1, maxN=${maxN}], got ${minN}`,\n )\n }\n if (!Number.isFinite(minEffect) || minEffect < 0 || minEffect >= scale) {\n throw new Error(\n `sequentialPairedGate: minEffect must be in [0, scale=${scale}), got ${minEffect}`,\n )\n }\n // H0: mean delta ≤ minEffect. In x = (d/scale + 1)/2 space that is\n // E[x] ≤ 1/2 + minEffect/(2·scale) — a shifted null boundary, NOT a clamp\n // of the observations (clamping is mean-distorting for skewed deltas).\n const nullMean = 0.5 + minEffect / (2 * scale)\n return {\n alpha,\n minN,\n maxN,\n maxBet: opts.maxBet ?? 0.5,\n scale,\n shuffleSeed: opts.shuffleSeed ?? 1337,\n direction,\n nullMean,\n minEffect,\n }\n}\n\ninterface SequentialStream {\n observe(delta: number): SequentialObservation\n state(): SequentialStreamState\n}\n\nconst SEQUENTIAL_DECISIONS: readonly SequentialDecision[] = [\n 'promote',\n 'continue',\n 'undecided-at-maxN',\n]\n\n/** Refuse a snapshot whose gate decision this configuration could not have\n * reached at the snapshot's n. The e-process parameters are checked by\n * `eProcess` itself; this covers the gate's own stopping rule. */\nfunction assertResumableStream(resume: SequentialStreamState, cfg: ResolvedConfig): void {\n const fail = (detail: string): never => {\n throw new Error(`sequentialPairedGate: cannot resume — ${detail}`)\n }\n if (!SEQUENTIAL_DECISIONS.includes(resume.decision)) {\n fail(`unknown decision '${String(resume.decision)}'`)\n }\n if (resume.n > cfg.maxN) {\n fail(`snapshot n=${resume.n} exceeds the pre-registered maxN=${cfg.maxN}`)\n }\n const threshold = 1 / cfg.alpha\n switch (resume.decision) {\n case 'promote':\n if (resume.n < cfg.minN) {\n fail(`decision 'promote' at n=${resume.n} is below minN=${cfg.minN}`)\n }\n break\n case 'undecided-at-maxN':\n if (resume.n !== cfg.maxN) {\n fail(`decision 'undecided-at-maxN' at n=${resume.n} does not match maxN=${cfg.maxN}`)\n }\n break\n case 'continue':\n if (resume.n >= cfg.maxN) {\n fail(`decision 'continue' at n=${resume.n} with maxN=${cfg.maxN}; the stream is finished`)\n }\n if (resume.n >= cfg.minN && resume.wealth >= threshold) {\n fail(\n `decision 'continue' at n=${resume.n} ≥ minN=${cfg.minN} with e-value ` +\n `${resume.wealth} ≥ 1/α=${threshold}; this stream would have promoted`,\n )\n }\n break\n }\n}\n\nfunction makeStream(cfg: ResolvedConfig, resume?: SequentialStreamState): SequentialStream {\n if (resume !== undefined) assertResumableStream(resume, cfg)\n const proc = eProcess({\n alpha: cfg.alpha,\n maxBet: cfg.maxBet,\n nullMean: cfg.nullMean,\n ...(resume === undefined ? {} : { resume }),\n })\n const threshold = 1 / cfg.alpha\n let terminal: SequentialDecision | undefined =\n resume === undefined || resume.decision === 'continue' ? undefined : resume.decision\n return {\n observe(delta: number): SequentialObservation {\n if (terminal === 'undecided-at-maxN') {\n throw new Error(\n `sequentialPairedGate: pre-registered maxN=${cfg.maxN} exhausted — extending the ` +\n 'stream after seeing the result reopens optional stopping; start a NEW ' +\n 'pre-registered test',\n )\n }\n if (!Number.isFinite(delta) || Math.abs(delta) > cfg.scale) {\n throw new Error(\n `sequentialPairedGate: delta ${delta} outside ±scale=${cfg.scale} — pass the judge's ` +\n `native scale explicitly (detectScale helps pick 1 vs 100)`,\n )\n }\n const d = cfg.direction === 'decrease' ? -delta : delta\n const step = proc.update((d / cfg.scale + 1) / 2)\n // Stopping rule: FIRST n ≥ minN with current wealth ≥ 1/alpha — a valid\n // stopping time (measurable w.r.t. the past), sticky once latched. The\n // core's own `decided` latch ignores minN, so the gate re-derives the\n // decision from current wealth here.\n if (terminal === undefined && step.n >= cfg.minN && step.wealth >= threshold) {\n terminal = 'promote'\n }\n if (terminal === 'promote') {\n return {\n decision: 'promote',\n eValue: step.wealth,\n n: step.n,\n reason:\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} at n=${step.n} ` +\n `(minN=${cfg.minN}): the paired improvement exceeds ${cfg.minEffect} at anytime-valid ` +\n `level α=${cfg.alpha}`,\n }\n }\n if (step.n >= cfg.maxN) {\n terminal = 'undecided-at-maxN'\n return {\n decision: 'undecided-at-maxN',\n eValue: step.wealth,\n n: step.n,\n reason:\n `undecided at pre-registered maxN=${cfg.maxN} (e-value ${step.wealth.toFixed(2)} < ` +\n `1/α=${threshold.toFixed(2)}). This is NOT evidence of no effect — the effect may be ` +\n 'real but smaller than this budget can detect; re-register with a larger N to test that',\n }\n }\n return {\n decision: 'continue',\n eValue: step.wealth,\n n: step.n,\n reason: `e-value ${step.wealth.toFixed(2)} < 1/α=${threshold.toFixed(2)} at n=${step.n}/${cfg.maxN} — keep observing`,\n }\n },\n state() {\n return { ...proc.state(), decision: terminal ?? 'continue' }\n },\n }\n}\n\n/** Data-independent in-place Fisher–Yates with a seeded PRNG — the permutation\n * depends only on the seed, never the values, so bet predictability survives. */\nfunction seededShuffle<T>(items: T[], seed: number): T[] {\n const rng = mulberry32(seed)\n for (let i = items.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n const tmp = items[i]!\n items[i] = items[j]!\n items[j] = tmp\n }\n return items\n}\n\n/**\n * Anytime-valid sequential paired gate. Conforms to the existing `Gate`\n * contract (`decide(ctx)` consumes candidate vs baseline judge scores via\n * `pairHoldout` — same pairing granularity as the fixed-n gates: full cellId,\n * never scenarioId) and adds a streaming `observe(delta)` entry for campaigns\n * that score cells incrementally and want to stop mid-stream.\n *\n * Decision mapping onto the substrate's five-valued `GateDecision`:\n * - 'promote' → 'ship'\n * - 'continue' → 'need_more_work' (stream ended before maxN with\n * the e-value undecided — more reps could decide)\n * - 'undecided-at-maxN' → 'hold', with the reason stating it is NOT\n * evidence of no effect (never a silent default)\n */\nexport function sequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n options: SequentialPairedGateOptions,\n): SequentialPairedGate<TArtifact, TScenario> {\n const cfg = resolveConfig(options)\n const name = options.name ?? 'sequentialPairedGate'\n const manifest = options.preRegistration\n const observeStream = makeStream(cfg, options.resume)\n\n return {\n name,\n observe(delta: number): SequentialObservation {\n return observeStream.observe(delta)\n },\n state() {\n return observeStream.state()\n },\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n `${name}: ctx.baselineJudgeScores is required — falling back to the candidate's own ` +\n 'scores would compare the candidate against itself (delta 0, silent no-op)',\n )\n }\n const scenarioIds = new Set(ctx.scenarios.map((s) => s.id))\n const paired = pairHoldout(\n ctx.judgeScores,\n ctx.baselineJudgeScores,\n scenarioIds,\n (s) => s.composite,\n )\n const deltas = paired.after.map((a, i) => a - paired.before[i]!)\n seededShuffle(deltas, cfg.shuffleSeed)\n\n const stream = makeStream(cfg)\n let last: SequentialObservation | undefined\n for (const d of deltas) {\n last = stream.observe(d)\n if (last.decision !== 'continue') break\n }\n\n const detail = {\n ...stream.state(),\n minN: cfg.minN,\n maxN: cfg.maxN,\n scale: cfg.scale,\n shuffleSeed: cfg.shuffleSeed,\n direction: cfg.direction,\n minEffect: cfg.minEffect,\n pairedN: deltas.length,\n ...(manifest ? { preRegisteredId: manifest.id, metric: manifest.metric } : {}),\n }\n const meanDelta =\n deltas.length === 0 ? undefined : deltas.reduce((s, d) => s + d, 0) / deltas.length\n\n if (last === undefined) {\n return {\n decision: 'need_more_work',\n reasons: [`${name}: no paired holdout observations — nothing to test`],\n contributingGates: [{ name, status: 'not_evaluated', detail }],\n }\n }\n const decision =\n last.decision === 'promote'\n ? 'ship'\n : last.decision === 'continue'\n ? 'need_more_work'\n : 'hold'\n return {\n decision,\n reasons: [`${name}: ${last.reason}`],\n contributingGates: [\n {\n name,\n status:\n decision === 'ship'\n ? 'pass'\n : decision === 'need_more_work'\n ? 'not_evaluated'\n : 'fail',\n detail,\n },\n ],\n delta: meanDelta,\n }\n },\n }\n}\n\nexport interface SequentialDecideOptions {\n /** Type-I budget for the early-stop evidence. Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a stop may fire. Default 5. */\n minN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |per-scenario composite delta|. Default 1. */\n scale?: number\n}\n\nexport interface SequentialDecideFn {\n (args: { history: GenerationRecord[] }): { stop: boolean; reason?: string }\n /** Read-only snapshot of the accumulated e-process (observability + tests). */\n state(): EProcessState\n}\n\n/**\n * `SurfaceProposer.decide` adapter — stops the optimization loop the moment\n * the e-process decides the loop has produced a real improvement, instead of\n * always running `maxGenerations`.\n *\n * Stream: for each generation g ≥ 1, the per-scenario composite deltas of\n * generation g's top candidate vs the generation-0 top candidate (the\n * incumbent the loop set out to beat), paired by scenarioId. H0: no proposed\n * surface improves any scenario's expected composite over the incumbent —\n * under it every delta has conditional mean ≤ 0 and the e-process is valid.\n * Once wealth ≥ 1/alpha the loop stops and hands the winner to the promotion\n * gate (which re-scores on HELD-OUT data — this adapter only spends the\n * exploration budget, it never promotes).\n *\n * Honesty caveats: (1) the incumbent's scores are measured once and shared\n * across all generations' deltas, so type-I control is exact only insofar as\n * those scores approximate the incumbent's true per-scenario means (more reps\n * → tighter); (2) an UNDECIDED process never stops the loop — absence of a\n * crossing is NOT evidence of no effect, so the loop simply runs its normal\n * course. Calling the adapter repeatedly with a growing history consumes each\n * generation exactly once (re-feeding an already-seen record would double-count\n * evidence).\n */\nexport function sequentialDecide(options: SequentialDecideOptions = {}): SequentialDecideFn {\n const alpha = options.alpha ?? 0.05\n const minN = options.minN ?? 5\n const scale = options.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialDecide: scale must be > 0, got ${scale}`)\n }\n const proc = eProcess({ alpha, maxBet: options.maxBet ?? 0.5, nullMean: 0.5 })\n const threshold = 1 / alpha\n let processedGenerations = 0\n let reference: Map<string, number> | undefined\n let stopped: { stop: true; reason: string } | undefined\n\n const topCandidate = (record: GenerationRecord) => {\n if (record.candidates.length === 0) {\n throw new Error(\n `sequentialDecide: generation ${record.generationIndex} has no candidates — ` +\n 'cannot extract a top candidate',\n )\n }\n return record.candidates.reduce((best, candidate) => {\n if (best.composite === null) return candidate\n if (candidate.composite === null) return best\n return candidate.composite > best.composite ? candidate : best\n })\n }\n\n const decide: SequentialDecideFn = ({ history }) => {\n if (stopped) return stopped\n if (history.length === 0) return { stop: false }\n if (reference === undefined) {\n reference = new Map(\n topCandidate(history[0]!).scenarios.map((s) => [s.scenarioId, s.composite]),\n )\n }\n // Consume only generations not yet seen; start at 1 — generation 0 IS the\n // reference and would contribute all-zero deltas (pure wealth dilution).\n for (let g = Math.max(1, processedGenerations); g < history.length; g++) {\n const top = topCandidate(history[g]!)\n const byScenario = new Map(top.scenarios.map((s) => [s.scenarioId, s.composite]))\n for (const [scenarioId, refComposite] of reference) {\n const candComposite = byScenario.get(scenarioId)\n if (candComposite === undefined) {\n throw new Error(\n `sequentialDecide: generation ${history[g]!.generationIndex} top candidate is missing ` +\n `scenario '${scenarioId}' — generations must score the same scenario set to pair`,\n )\n }\n const delta = candComposite - refComposite\n if (!Number.isFinite(delta) || Math.abs(delta) > scale) {\n throw new Error(\n `sequentialDecide: paired delta ${delta} outside ±scale=${scale} on scenario ` +\n `'${scenarioId}' — pass the composite scale explicitly`,\n )\n }\n const step = proc.update((delta / scale + 1) / 2)\n if (step.n >= minN && step.wealth >= threshold) {\n stopped = {\n stop: true,\n reason:\n `sequential e-process decided at generation ${history[g]!.generationIndex}: ` +\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} after n=${step.n} ` +\n 'paired deltas vs the generation-0 incumbent — the improvement is real at ' +\n `α=${alpha}; stop exploring and promote via the gate`,\n }\n processedGenerations = history.length\n return stopped\n }\n }\n }\n processedGenerations = history.length\n return { stop: false }\n }\n decide.state = () => proc.state()\n return decide\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,SAAS,mBAAmB,GAA4B;CACtD,OAAO,sBAAsB,CAAC,MAAM,EAAE;AACxC;AAEA,SAAS,cAAc,MAAmD;CACxE,MAAM,IAAI,KAAK;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,GAAG;EACL,IAAI,CAAC,mBAAmB,CAAC,GACvB,MAAM,IAAI,MACR,oDAAoD,EAAE,GAAG,mCAC3D;EAEF,IAAI,KAAK,UAAU,KAAA,KAAa,KAAK,UAAU,EAAE,OAC/C,MAAM,IAAI,MACR,+BAA+B,KAAK,MAAM,uCAAuC,EAAE,MAAM,oEAE3F;EAEF,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS,EAAE,gBAC7C,MAAM,IAAI,MACR,8BAA8B,KAAK,KAAK,mCAAmC,EAAE,gBAC/E;EAEF,QAAQ,EAAE;EACV,OAAO,EAAE;EACT,YAAY,EAAE;EACd,YAAY,EAAE;CAChB,OAAO;EACL,QAAQ,KAAK,SAAS;EACtB,IAAI,KAAK,SAAS,KAAA,GAChB,MAAM,IAAI,MACR,mKAEF;EAEF,OAAO,KAAK;EACZ,YAAY;EACZ,YAAY;CACd;CACA,MAAM,QAAQ,KAAK,SAAS;CAC5B,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MA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