@tangle-network/agent-eval 0.118.1 → 0.118.2
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.
- package/CHANGELOG.md +7 -0
- package/dist/analyst/index.d.ts +10 -3
- package/dist/analyst/index.js +6 -6
- package/dist/benchmarks/index.js +9 -9
- package/dist/campaign/index.d.ts +22 -15
- package/dist/campaign/index.js +8 -8
- package/dist/{chunk-3EHHMC6E.js → chunk-63KG3ASG.js} +2 -2
- package/dist/{chunk-FTUMG2U7.js → chunk-6JQE3YVE.js} +10 -39
- package/dist/chunk-6JQE3YVE.js.map +1 -0
- package/dist/{chunk-SVH2ANFD.js → chunk-7V3QDWNL.js} +2 -2
- package/dist/{chunk-QKEGNI5B.js → chunk-BUBU3YHT.js} +2 -2
- package/dist/{chunk-BFW56GTT.js → chunk-DRSFTBKU.js} +3 -3
- package/dist/{chunk-BFW56GTT.js.map → chunk-DRSFTBKU.js.map} +1 -1
- package/dist/{chunk-OIIMMLRB.js → chunk-DZBCDDIE.js} +3 -3
- package/dist/chunk-DZBCDDIE.js.map +1 -0
- package/dist/{chunk-IDZTTFRR.js → chunk-EGNRE7VA.js} +2 -2
- package/dist/chunk-EGNRE7VA.js.map +1 -0
- package/dist/{chunk-Q442S5AS.js → chunk-GCT3DQWU.js} +7 -7
- package/dist/chunk-GCT3DQWU.js.map +1 -0
- package/dist/{chunk-YLMUS4MM.js → chunk-I42AAGHL.js} +5 -5
- package/dist/chunk-I42AAGHL.js.map +1 -0
- package/dist/{chunk-33JA4TFA.js → chunk-J23QK2U5.js} +8 -3
- package/dist/chunk-J23QK2U5.js.map +1 -0
- package/dist/{chunk-LTVG32KX.js → chunk-JTMFT5QZ.js} +2 -2
- package/dist/chunk-JTMFT5QZ.js.map +1 -0
- package/dist/{chunk-JSDVRFAP.js → chunk-KK2O4VWA.js} +2 -2
- package/dist/{chunk-VCTY3W6J.js → chunk-MLHRFWQK.js} +1 -1
- package/dist/chunk-MLHRFWQK.js.map +1 -0
- package/dist/chunk-NW4AQBXD.js +53 -0
- package/dist/chunk-NW4AQBXD.js.map +1 -0
- package/dist/{chunk-KSDQVPLR.js → chunk-TVXPJJ7H.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/contract/index.d.ts +17 -10
- package/dist/contract/index.js +9 -9
- package/dist/contract/index.js.map +1 -1
- package/dist/fuzz.d.ts +8 -1
- package/dist/fuzz.js +1 -1
- package/dist/fuzz.js.map +1 -1
- package/dist/index.d.ts +44 -17
- package/dist/index.js +21 -15
- package/dist/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{run-campaign-IM26A6PD.js → run-campaign-DWC67KJP.js} +3 -3
- package/dist/trace-attributes.d.ts +21 -1
- package/dist/trace-attributes.js +9 -3
- package/dist/traces.d.ts +21 -1
- package/dist/traces.js +12 -6
- package/dist/wire/index.d.ts +8 -1
- package/dist/wire/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-33JA4TFA.js.map +0 -1
- package/dist/chunk-FTUMG2U7.js.map +0 -1
- package/dist/chunk-IDZTTFRR.js.map +0 -1
- package/dist/chunk-LTVG32KX.js.map +0 -1
- package/dist/chunk-OIIMMLRB.js.map +0 -1
- package/dist/chunk-Q442S5AS.js.map +0 -1
- package/dist/chunk-VCTY3W6J.js.map +0 -1
- package/dist/chunk-WDHBCA3M.js +0 -31
- package/dist/chunk-WDHBCA3M.js.map +0 -1
- package/dist/chunk-YLMUS4MM.js.map +0 -1
- /package/dist/{chunk-3EHHMC6E.js.map → chunk-63KG3ASG.js.map} +0 -0
- /package/dist/{chunk-SVH2ANFD.js.map → chunk-7V3QDWNL.js.map} +0 -0
- /package/dist/{chunk-QKEGNI5B.js.map → chunk-BUBU3YHT.js.map} +0 -0
- /package/dist/{chunk-JSDVRFAP.js.map → chunk-KK2O4VWA.js.map} +0 -0
- /package/dist/{chunk-KSDQVPLR.js.map → chunk-TVXPJJ7H.js.map} +0 -0
- /package/dist/{run-campaign-IM26A6PD.js.map → run-campaign-DWC67KJP.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/campaign/lineage.ts","../src/campaign/analyst-surface.ts","../src/paired-arms.ts","../src/campaign/cross-surface-context.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/gates/sequential.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/campaign/proposers/fapo.ts","../src/campaign/skill-patch.ts","../src/campaign/proposers/skill-opt.ts","../src/campaign/presets/run-skill-opt.ts","../src/campaign/presets/compare-proposers.ts","../src/completion-verifier.ts","../src/produced-state.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/run-lineage-loop.ts","../src/campaign/presets/run-profile-matrix.ts","../src/agent-profile.ts","../src/campaign/proposers/_findings-text.ts","../src/campaign/proposers/ace.ts","../src/campaign/proposers/composite.ts","../src/campaign/proposers/halo.ts","../src/campaign/proposers/analysis-edit.ts","../src/campaign/proposers/llm-policy-edit.ts","../src/campaign/proposers/policy-edit.ts","../src/campaign/proposers/policy-edit-author-context.ts","../src/campaign/proposers/memory.ts","../src/campaign/proposers/trace-analyst.ts","../src/campaign/scenario-selection.ts","../src/campaign/search-ledger.ts","../src/campaign/single-run-lock.ts","../src/campaign/transient-failure.ts","../src/campaign/worktree/index.ts"],"sourcesContent":["/**\n * Lineage DAG — a git-graph of improvement candidates.\n *\n * The improvement loop (`run-optimization.ts`) records a LINEAR `GenerationRecord[]`\n * with no parent pointers, computes a Pareto frontier within a run, then collapses\n * to one gated winner and discards the rest. This module adds the missing\n * first-class structure: a directed acyclic graph of candidate versions where\n *\n * - a node with ONE parent is a mutation,\n * - a node with ZERO parents is a root/seed,\n * - a node with 2+ parents is a MERGE (a \"collapse\") — nothing special-cased,\n * just a multi-parent node,\n * - a `track` groups a lineage into an island, and each track runs a distinct\n * `vision` (a proposer strategy — e.g. a \"solve\" vision, an \"outside-the-box\"\n * vision, and an adversarial \"contrarian\" vision that attacks the leader).\n *\n * An agent-managed {@link Governor} decides the next operation (extend / branch /\n * merge / prune / stop), so branching AND collapsing are choices a supervisor\n * makes by reading the graph, not hard-coded control flow.\n *\n * DETERMINISM is a hard invariant: no `Date.now`, `Math.random`, or `new Date`.\n * Ids are content+lineage hashes; order is a monotone insertion counter; every\n * query returns nodes in `seq` order. Same inputs ⇒ identical graph.\n */\n\nimport { createHash } from 'node:crypto'\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface LineageNode {\n /** Deterministic content+lineage hash (see {@link lineageNodeId}). */\n id: string\n /** `[]` = root/seed; `[x]` = mutation; `[x, y, ...]` = MERGE (collapse). */\n parentIds: string[]\n /** Logical island/track this node belongs to. */\n track: string\n /** Human label for the strategy driving this track (e.g. `solve`, `contrarian`). */\n vision?: string\n /** Candidate content (prompt text, skill document, config JSON, ...). */\n surface: string\n /** Scalar fitness (e.g. mean holdout composite); higher is better. */\n score: number\n /** Optional per-scenario objective vector for Pareto dominance. */\n scoreVector?: number[]\n /** Which proposer produced it (`gepa`, `skill-opt`, `merge`, `seed`, ...). */\n proposer: string\n rationale?: string\n /** Gate verdict, when this node was gated. */\n gate?: 'ship' | 'hold'\n /** Step index within its track (root = 0). */\n generation: number\n /** Monotone global insertion order (assigned by {@link Lineage.addNode}). */\n seq: number\n}\n\nexport interface LineageEdge {\n /** Parent node id. */\n from: string\n /** Child node id. */\n to: string\n}\n\nexport interface LineageGraph {\n nodes: LineageNode[]\n edges: LineageEdge[]\n}\n\n/** Deterministic node id: a hash of the node's lineage + content + proposer.\n * Pure — identical inputs always yield the same id (a re-derived node collapses\n * onto its original rather than duplicating). */\nexport function lineageNodeId(input: {\n parentIds: string[]\n track: string\n surface: string\n proposer: string\n}): string {\n const parents = [...input.parentIds].sort().join(',')\n const payload = `${parents}|${input.track}|${input.surface}|${input.proposer}`\n return createHash('sha256').update(payload).digest('hex').slice(0, 16)\n}\n\n/** Input to {@link Lineage.addNode}: everything but the derived `id`/`seq` and the\n * optional `generation` (derived from parents when omitted). */\nexport type LineageNodeInput = Omit<LineageNode, 'id' | 'seq' | 'generation'> & {\n generation?: number\n}\n\n/** Deterministic improvement-candidate graph with mutation, merge, frontier, and persistence helpers. */\nexport class Lineage {\n private readonly byId = new Map<string, LineageNode>()\n private readonly childIds = new Map<string, string[]>()\n private nextSeq = 0\n\n constructor(nodes?: readonly LineageNode[]) {\n if (!nodes) return\n // Rehydrate in seq order so parents always precede children and the monotone\n // counter resumes past the highest persisted seq.\n for (const node of [...nodes].sort((a, b) => a.seq - b.seq)) {\n this.index(node)\n this.nextSeq = Math.max(this.nextSeq, node.seq + 1)\n }\n }\n\n /** Append a node. Derives `id` (via {@link lineageNodeId}), assigns the next\n * `seq`, and derives `generation` as `max(parent.generation) + 1` (root = 0)\n * when omitted. Throws on an unknown parent. Idempotent: re-adding an identical\n * node returns the existing one.\n *\n * Acyclicity is guaranteed by construction, not by a runtime check: every\n * parent must already exist (a child can never point at a not-yet-added node),\n * ids are immutable content hashes (an existing node can never gain new\n * parents), and the store is append-only — so no back-edge can form. (Traversal\n * is still cycle-safe against hand-corrupted deserialized input via visited\n * sets in {@link ancestors}/{@link descendants}.) */\n addNode(input: LineageNodeInput): LineageNode {\n for (const parentId of input.parentIds) {\n if (!this.byId.has(parentId)) {\n throw new Error(`Lineage.addNode: unknown parent '${parentId}'`)\n }\n }\n const id = lineageNodeId({\n parentIds: input.parentIds,\n track: input.track,\n surface: input.surface,\n proposer: input.proposer,\n })\n const existing = this.byId.get(id)\n if (existing) return existing\n\n const generation =\n input.generation ??\n (input.parentIds.length === 0\n ? 0\n : Math.max(...input.parentIds.map((p) => this.byId.get(p)!.generation)) + 1)\n\n const node: LineageNode = {\n id,\n parentIds: [...input.parentIds],\n track: input.track,\n surface: input.surface,\n score: input.score,\n proposer: input.proposer,\n generation,\n seq: this.nextSeq++,\n ...(input.vision !== undefined ? { vision: input.vision } : {}),\n ...(input.scoreVector !== undefined ? { scoreVector: [...input.scoreVector] } : {}),\n ...(input.rationale !== undefined ? { rationale: input.rationale } : {}),\n ...(input.gate !== undefined ? { gate: input.gate } : {}),\n }\n this.index(node)\n return node\n }\n\n /** Collapse 2+ parents into a single node (a merge/\"collapse\"). A merge is an\n * ordinary multi-parent node; this is a guarded convenience. */\n merge(input: {\n parentIds: string[]\n track: string\n surface: string\n score: number\n proposer?: string\n vision?: string\n scoreVector?: number[]\n rationale?: string\n }): LineageNode {\n if (input.parentIds.length < 2) {\n throw new Error(`Lineage.merge: a merge needs >= 2 parents, got ${input.parentIds.length}`)\n }\n return this.addNode({ ...input, proposer: input.proposer ?? 'merge' })\n }\n\n get(id: string): LineageNode | undefined {\n return this.byId.get(id)\n }\n\n has(id: string): boolean {\n return this.byId.has(id)\n }\n\n /** All nodes, in insertion (`seq`) order. */\n all(): LineageNode[] {\n return [...this.byId.values()].sort(bySeq)\n }\n\n roots(): LineageNode[] {\n return this.all().filter((n) => n.parentIds.length === 0)\n }\n\n parents(id: string): LineageNode[] {\n const node = this.byId.get(id)\n if (!node) return []\n return node.parentIds\n .map((p) => this.byId.get(p))\n .filter((n): n is LineageNode => n !== undefined)\n .sort(bySeq)\n }\n\n children(id: string): LineageNode[] {\n return (this.childIds.get(id) ?? []).map((c) => this.byId.get(c)!).sort(bySeq)\n }\n\n /** Transitive ancestors (excludes `id`). */\n ancestors(id: string): Set<string> {\n const out = new Set<string>()\n const stack = [...(this.byId.get(id)?.parentIds ?? [])]\n while (stack.length > 0) {\n const cur = stack.pop()!\n if (out.has(cur)) continue\n out.add(cur)\n const node = this.byId.get(cur)\n if (node) stack.push(...node.parentIds)\n }\n return out\n }\n\n /** Transitive descendants (excludes `id`). */\n descendants(id: string): Set<string> {\n const out = new Set<string>()\n const stack = [...(this.childIds.get(id) ?? [])]\n while (stack.length > 0) {\n const cur = stack.pop()!\n if (out.has(cur)) continue\n out.add(cur)\n stack.push(...(this.childIds.get(cur) ?? []))\n }\n return out\n }\n\n /** Nodes with no children (leaf/branch tips). */\n tips(): LineageNode[] {\n return this.all().filter((n) => (this.childIds.get(n.id) ?? []).length === 0)\n }\n\n /** Distinct track ids, in first-seen (`seq`) order. */\n tracks(): string[] {\n const seen = new Set<string>()\n const out: string[] = []\n for (const node of this.all()) {\n if (!seen.has(node.track)) {\n seen.add(node.track)\n out.push(node.track)\n }\n }\n return out\n }\n\n trackNodes(track: string): LineageNode[] {\n return this.all().filter((n) => n.track === track)\n }\n\n /** The highest-`score` tip of a track (ties broken by lowest `seq`). */\n trackTip(track: string): LineageNode | undefined {\n return pickBest(this.tips().filter((n) => n.track === track))\n }\n\n /** The highest-`score` node overall (ties broken by lowest `seq`). */\n best(): LineageNode | undefined {\n return pickBest(this.all())\n }\n\n /** The Pareto-non-dominated set among TIPS. Uses `scoreVector` when every\n * compared tip carries one, else the scalar `score`. A dominates B iff A is\n * >= B on every component and > B on at least one. */\n frontier(): LineageNode[] {\n const tips = this.tips()\n const useVector = tips.length > 0 && tips.every((n) => n.scoreVector !== undefined)\n const vecOf = (n: LineageNode): number[] => (useVector ? n.scoreVector! : [n.score])\n return tips\n .filter((a) => !tips.some((b) => b.id !== a.id && dominates(vecOf(b), vecOf(a))))\n .sort(bySeq)\n }\n\n toGraph(): LineageGraph {\n const nodes = this.all()\n const edges: LineageEdge[] = []\n for (const node of nodes) {\n for (const parentId of node.parentIds) {\n edges.push({ from: parentId, to: node.id })\n }\n }\n return { nodes, edges }\n }\n\n /** One JSON node per line, in `seq` order. */\n toJSONL(): string {\n return this.all()\n .map((n) => JSON.stringify(n))\n .join('\\n')\n }\n\n static fromJSONL(text: string): Lineage {\n const nodes = text\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as LineageNode)\n return new Lineage(nodes)\n }\n\n private index(node: LineageNode): void {\n this.byId.set(node.id, node)\n for (const parentId of node.parentIds) {\n const list = this.childIds.get(parentId)\n if (list) {\n if (!list.includes(node.id)) list.push(node.id)\n } else {\n this.childIds.set(parentId, [node.id])\n }\n }\n }\n}\n\nfunction bySeq(a: LineageNode, b: LineageNode): number {\n return a.seq - b.seq\n}\n\n/** Highest score, ties broken by lowest seq. */\nfunction pickBest(nodes: LineageNode[]): LineageNode | undefined {\n let best: LineageNode | undefined\n for (const node of nodes) {\n if (!best || node.score > best.score || (node.score === best.score && node.seq < best.seq)) {\n best = node\n }\n }\n return best\n}\n\n/** True iff `a` Pareto-dominates `b`: `a[i] >= b[i]` for all i and `a[i] > b[i]`\n * for some i. Vectors of unequal length never dominate (incomparable). */\nfunction dominates(a: number[], b: number[]): boolean {\n if (a.length !== b.length) return false\n let strictlyBetter = false\n for (let i = 0; i < a.length; i += 1) {\n if (a[i]! < b[i]!) return false\n if (a[i]! > b[i]!) strictlyBetter = true\n }\n return strictlyBetter\n}\n\n// ── Persistence ──────────────────────────────────────────────────────────────\n\nexport interface LineageStore {\n /** Load the persisted lineage (an empty `Lineage` when nothing is stored). */\n load(): Promise<Lineage>\n /** Append one node durably. */\n append(node: LineageNode): Promise<void>\n /** Overwrite with a full snapshot. */\n save(lineage: Lineage): Promise<void>\n}\n\n/** JSONL-file store: append-only durability, snapshot via rewrite, `load` parses\n * through {@link Lineage.fromJSONL}. */\nexport function fsLineageStore(path: string): LineageStore {\n const ensureDir = () => mkdir(dirname(path), { recursive: true })\n return {\n async load() {\n try {\n return Lineage.fromJSONL(await readFile(path, 'utf8'))\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return new Lineage()\n throw err\n }\n },\n async append(node) {\n await ensureDir()\n await appendFile(path, `${JSON.stringify(node)}\\n`, 'utf8')\n },\n async save(lineage) {\n await ensureDir()\n const jsonl = lineage.toJSONL()\n await writeFile(path, jsonl.length > 0 ? `${jsonl}\\n` : '', 'utf8')\n },\n }\n}\n\n/** In-memory store (default; for tests and ephemeral runs). */\nexport function memLineageStore(): LineageStore {\n const nodes: LineageNode[] = []\n return {\n async load() {\n return new Lineage(nodes)\n },\n async append(node) {\n nodes.push(node)\n },\n async save(lineage) {\n nodes.length = 0\n nodes.push(...lineage.all())\n },\n }\n}\n\n// ── Governor (agent-managed decision layer) ──────────────────────────────────\n\nexport type GovernorOp =\n | { op: 'extend'; track: string }\n | { op: 'branch'; fromNodeId: string; track: string; proposer: string; vision?: string }\n | { op: 'merge'; parentIds: string[]; track: string }\n | { op: 'prune'; track: string }\n | { op: 'stop' }\n\nexport interface GovernorContext {\n lineage: Lineage\n /** Operations executed so far. */\n step: number\n budgetRemaining: number\n /** Tracks already pruned — the governor must not target these for extend/branch. */\n prunedTracks: string[]\n}\n\nexport interface Governor {\n decide(ctx: GovernorContext): Promise<GovernorOp> | GovernorOp\n}\n\nexport interface HeuristicGovernorOptions {\n /** Cap on live tracks before branching a new one. Default 3. */\n maxTracks?: number\n /** Non-improving steps a track may take before it is pruned. Default 2. */\n plateauSteps?: number\n /** Frontier-tip count (across distinct tracks) that triggers a merge. Default 2. */\n mergeFrontierAt?: number\n}\n\n/** The reference deterministic policy an agent {@link Governor} can replace.\n * Reads only the lineage + context — no LLM, no randomness. */\nexport function heuristicGovernor(opts: HeuristicGovernorOptions = {}): Governor {\n const maxTracks = opts.maxTracks ?? 3\n const plateauSteps = opts.plateauSteps ?? 2\n const mergeFrontierAt = opts.mergeFrontierAt ?? 2\n\n return {\n decide(ctx: GovernorContext): GovernorOp {\n const { lineage } = ctx\n if (ctx.budgetRemaining <= 0) return { op: 'stop' }\n\n const pruned = new Set(ctx.prunedTracks)\n const liveTracks = lineage.tracks().filter((t) => !pruned.has(t))\n if (liveTracks.length === 0) return { op: 'stop' }\n\n // Merge first: when distinct-track frontier tips have accumulated, collapse\n // them into the best-scoring track so parallel progress consolidates.\n const frontierByTrack = new Map<string, LineageNode>()\n for (const tip of lineage.frontier()) {\n if (pruned.has(tip.track)) continue\n if (!frontierByTrack.has(tip.track)) frontierByTrack.set(tip.track, tip)\n }\n if (frontierByTrack.size >= mergeFrontierAt) {\n const tips = [...frontierByTrack.values()].sort(bySeq)\n const target = pickBest(tips)!\n return { op: 'merge', parentIds: tips.map((t) => t.id), track: target.track }\n }\n\n // Prune a plateaued track (best score unchanged over the last `plateauSteps`\n // nodes of the track).\n for (const track of liveTracks) {\n if (isPlateaued(lineage.trackNodes(track), plateauSteps)) {\n // Only prune if another live track remains OR we can branch — otherwise\n // pruning the last track just stops the run prematurely.\n if (liveTracks.length > 1 || liveTracks.length < maxTracks) {\n return { op: 'prune', track }\n }\n }\n }\n\n // Branch a fresh track when there is headroom and the leader has plateaued.\n const leader = pickBest(liveTracks.map((t) => lineage.trackTip(t)!).filter(Boolean))\n if (\n leader &&\n liveTracks.length < maxTracks &&\n isPlateaued(lineage.trackNodes(leader.track), plateauSteps)\n ) {\n return {\n op: 'branch',\n fromNodeId: leader.id,\n track: `${leader.track}+${lineage.tracks().length}`,\n proposer: 'gepa',\n }\n }\n\n // Otherwise extend the best climbing track.\n if (leader) return { op: 'extend', track: leader.track }\n return { op: 'stop' }\n },\n }\n}\n\n/** The LLM-supervisor slot: a governor whose `decide` defers to a caller-supplied\n * async function (which may read `ctx.lineage.toGraph()`). */\nexport function callbackGovernor(decide: (ctx: GovernorContext) => Promise<GovernorOp>): Governor {\n return { decide }\n}\n\n/** A track is plateaued when its best score has not improved across its most\n * recent `window` nodes (needs > `window` nodes to judge). */\nfunction isPlateaued(trackNodes: LineageNode[], window: number): boolean {\n if (trackNodes.length <= window) return false\n const ordered = [...trackNodes].sort(bySeq)\n const head = ordered.slice(0, ordered.length - window)\n const tail = ordered.slice(ordered.length - window)\n const bestBefore = Math.max(...head.map((n) => n.score))\n const bestRecent = Math.max(...tail.map((n) => n.score))\n return bestRecent <= bestBefore\n}\n\n// ── Orchestration ────────────────────────────────────────────────────────────\n\nexport interface RunLineageSeed {\n surface: string\n track: string\n vision?: string\n proposer: string\n score: number\n scoreVector?: number[]\n}\n\nexport interface RunLineageStepResult {\n surface: string\n score: number\n scoreVector?: number[]\n rationale?: string\n gate?: 'ship' | 'hold'\n}\n\nexport interface RunLineageOptions {\n seeds: RunLineageSeed[]\n /** Produce one new candidate from a track's tip (propose + measure + gate in\n * real use; a pure function in tests). */\n step: (args: {\n track: string\n proposer: string\n tip: LineageNode\n }) => Promise<RunLineageStepResult>\n /** Collapse 2+ parent surfaces into one (GEPA crossover / LLM merge in real use). */\n merge: (args: {\n parents: LineageNode[]\n track: string\n }) => Promise<Omit<RunLineageStepResult, 'gate'>>\n governor: Governor\n budget: { maxSteps: number }\n store?: LineageStore\n log?: (msg: string, fields?: Record<string, unknown>) => void\n}\n\nexport interface RunLineageResult {\n lineage: Lineage\n best: LineageNode | undefined\n steps: number\n}\n\n/** Drive a multi-track improvement DAG under an agent-managed governor. Seeds each\n * entry as a root, then repeatedly asks the governor for the next operation\n * (extend / branch / merge / prune / stop) up to `budget.maxSteps`, persisting\n * every node. Honors `prune`: a pruned track is never extended or branched again. */\nexport async function runLineage(opts: RunLineageOptions): Promise<RunLineageResult> {\n const store = opts.store ?? memLineageStore()\n const lineage = await store.load()\n const log = opts.log ?? (() => {})\n const pruned = new Set<string>()\n\n // The proposer a track extends with — seeded, inherited by branches.\n const trackProposer = new Map<string, string>()\n\n const persist = async (node: LineageNode) => {\n await store.append(node)\n }\n\n for (const seed of opts.seeds) {\n const node = lineage.addNode({\n parentIds: [],\n track: seed.track,\n surface: seed.surface,\n score: seed.score,\n proposer: seed.proposer,\n ...(seed.vision !== undefined ? { vision: seed.vision } : {}),\n ...(seed.scoreVector !== undefined ? { scoreVector: seed.scoreVector } : {}),\n })\n trackProposer.set(seed.track, seed.proposer)\n await persist(node)\n }\n\n let steps = 0\n while (steps < opts.budget.maxSteps) {\n const op = await opts.governor.decide({\n lineage,\n step: steps,\n budgetRemaining: opts.budget.maxSteps - steps,\n prunedTracks: [...pruned],\n })\n\n if (op.op === 'stop') {\n log('lineage: governor stop', { steps })\n break\n }\n\n if (op.op === 'prune') {\n pruned.add(op.track)\n log('lineage: prune', { track: op.track })\n steps += 1\n continue\n }\n\n if (op.op === 'merge') {\n const parents = op.parentIds\n .map((id) => lineage.get(id))\n .filter((n): n is LineageNode => n !== undefined)\n if (parents.length < 2) {\n log('lineage: merge skipped (fewer than 2 known parents)', { op })\n steps += 1\n continue\n }\n const result = await opts.merge({ parents, track: op.track })\n const node = lineage.merge({\n parentIds: parents.map((p) => p.id),\n track: op.track,\n surface: result.surface,\n score: result.score,\n ...(parents[0]!.vision !== undefined ? { vision: parents[0]!.vision } : {}),\n ...(result.scoreVector !== undefined ? { scoreVector: result.scoreVector } : {}),\n ...(result.rationale !== undefined ? { rationale: result.rationale } : {}),\n })\n await persist(node)\n steps += 1\n continue\n }\n\n if (op.op === 'branch') {\n if (pruned.has(op.track)) {\n log('lineage: branch skipped (target track pruned)', { track: op.track })\n steps += 1\n continue\n }\n const from = lineage.get(op.fromNodeId)\n if (!from) {\n log('lineage: branch skipped (unknown fromNodeId)', { op })\n steps += 1\n continue\n }\n trackProposer.set(op.track, op.proposer)\n const result = await opts.step({ track: op.track, proposer: op.proposer, tip: from })\n const node = lineage.addNode({\n parentIds: [from.id],\n track: op.track,\n surface: result.surface,\n score: result.score,\n proposer: op.proposer,\n ...(op.vision !== undefined ? { vision: op.vision } : {}),\n ...(result.scoreVector !== undefined ? { scoreVector: result.scoreVector } : {}),\n ...(result.rationale !== undefined ? { rationale: result.rationale } : {}),\n ...(result.gate !== undefined ? { gate: result.gate } : {}),\n })\n await persist(node)\n steps += 1\n continue\n }\n\n // op.op === 'extend'\n if (pruned.has(op.track)) {\n log('lineage: extend skipped (track pruned)', { track: op.track })\n steps += 1\n continue\n }\n const tip = lineage.trackTip(op.track)\n if (!tip) {\n log('lineage: extend skipped (no tip for track)', { track: op.track })\n steps += 1\n continue\n }\n const proposer = trackProposer.get(op.track) ?? tip.proposer\n const result = await opts.step({ track: op.track, proposer, tip })\n const node = lineage.addNode({\n parentIds: [tip.id],\n track: op.track,\n surface: result.surface,\n score: result.score,\n proposer,\n ...(tip.vision !== undefined ? { vision: tip.vision } : {}),\n ...(result.scoreVector !== undefined ? { scoreVector: result.scoreVector } : {}),\n ...(result.rationale !== undefined ? { rationale: result.rationale } : {}),\n ...(result.gate !== undefined ? { gate: result.gate } : {}),\n })\n await persist(node)\n steps += 1\n }\n\n return { lineage, best: lineage.best(), steps }\n}\n","/**\n * Make the trace-analyst's OWN prompt a GEPA-optimizable surface.\n *\n * The analyst that drives self-improvement is itself a prompt — and a\n * hand-tuned one (a hardcoded, hand-versioned `const`). This module lets the\n * loop optimize it: the analyst `actorDescription` becomes a `MutableSurface`\n * that `gepaProposer` / `haloProposer` / any `SurfaceProposer` can mutate inside\n * `runImprovementLoop` or `compareProposers`. That is the second-order loop —\n * optimizing the optimizer's eyes, not just the agent's prompt.\n *\n * Two pieces, both deliberately small (the loop engine already exists — this\n * only supplies the analyst-shaped dispatch + an objective scorer):\n *\n * - `buildAnalystSurfaceDispatch` — `dispatchWithSurface(surface, scenario)`\n * runs `analyzeTraces` with `surface` as the actorDescription over the\n * scenario's fixed trace corpus, returning its findings.\n * - `failureModeRecallJudge` — a DETERMINISTIC judge (no LLM, no opinion)\n * that scores those findings against the scenario's GROUND-TRUTH failure\n * modes. This is what keeps optimizing the analyst prompt ungameable: the\n * labels come from objective signal (e.g. AppWorld `world.evaluate()` tells\n * us which task failed and which API calls were wrong), so we reward an\n * analyst for surfacing the failures that really happened — not for\n * pleasing a judge that could be talked into anything (Goodhart).\n *\n * Wiring (the loop is unchanged; you only pass these in):\n *\n * const dispatchWithSurface = buildAnalystSurfaceDispatch({ analystOptions: { ai } })\n * await runImprovementLoop({\n * baselineSurface: TRACE_ANALYST_ACTOR_DESCRIPTION, // the prompt under optimization\n * scenarios: trainScenarios, // labeled trace corpora\n * holdoutScenarios: heldOutScenarios,\n * dispatchWithSurface,\n * judges: [failureModeRecallJudge()],\n * proposer: gepaProposer({ baseUrl, apiKey }),\n * gate: heldOutGate({ minDelta: 0.02 }),\n * autoOnPromote: 'none',\n * })\n */\n\nimport type {\n AnalyzeTracesInput,\n AnalyzeTracesOptions,\n AnalyzeTracesResult,\n} from '../trace-analyst/analyst'\nimport { analyzeTraces } from '../trace-analyst/analyst'\nimport type { DispatchContext, JudgeConfig, MutableSurface, Scenario } from './types'\n\n/**\n * A labeled trace scenario: a FIXED trace corpus plus the failure modes a\n * competent analyst MUST surface from it. The labels are ground truth — the\n * objective failures that actually occurred — which is what makes optimizing\n * the analyst prompt against them meaningful rather than circular.\n */\nexport interface AnalystScenario extends Scenario {\n kind: 'analyst-surface'\n /** OTLP-JSONL path or an in-memory store of the traces to analyze. */\n source: AnalyzeTracesOptions['source']\n /** The domain question handed to the analyst (framing lives here, not in\n * the surface under optimization). */\n question: string\n /**\n * Ground-truth failure modes a good analyst must identify. A finding \"hits\"\n * a mode when it contains ANY of the mode's case-insensitive cues. Derive\n * these from objective signal (failed task + which step broke), never from\n * the analyst's own prior output.\n */\n expectedFailureModes: Array<{ id: string; cues: string[] }>\n /**\n * Cues that mark a finding as HALLUCINATED / out-of-scope for this corpus —\n * naming a tool, error, or failure that did not occur. Presence penalizes\n * precision. Optional; omit to score recall only.\n */\n forbiddenCues?: string[]\n}\n\n/** The analyst's output for one scenario — the artifact the judge scores. */\nexport interface AnalystArtifact {\n answer: string\n findings: string[]\n /** The hardcoded-prompt version the analyst reported (provenance only; the\n * optimized surface overrides the actual prompt text used). */\n actorPromptVersion: string\n}\n\nexport interface BuildAnalystSurfaceDispatchOptions {\n /**\n * Everything `analyzeTraces` needs EXCEPT `actorDescription` (supplied by the\n * surface under optimization) and `source` (supplied by the scenario). `ai`\n * (the AxAIService) is required for a live run.\n */\n analystOptions: Omit<AnalyzeTracesOptions, 'actorDescription' | 'source'>\n /** Test seam: defaults to the real `analyzeTraces`. */\n analyze?: (\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n ) => Promise<AnalyzeTracesResult>\n}\n\nfunction surfaceToText(surface: MutableSurface): string {\n if (typeof surface === 'string') return surface\n // A code-tier surface can't be an analyst prompt — fail loud rather than\n // silently analyzing with an empty actorDescription.\n throw new Error(\n 'buildAnalystSurfaceDispatch: the analyst surface must be a string actorDescription, ' +\n `got a ${surface.kind}-tier surface (${surface.worktreeRef}). The analyst prompt is prompt-tier.`,\n )\n}\n\n/**\n * Build the `dispatchWithSurface(surface, scenario, ctx)` the improvement loop\n * calls: run the analyst with `surface` as its actorDescription over the\n * scenario's trace corpus and return its findings.\n */\nexport function buildAnalystSurfaceDispatch(\n opts: BuildAnalystSurfaceDispatchOptions,\n): (\n surface: MutableSurface,\n scenario: AnalystScenario,\n ctx: DispatchContext,\n) => Promise<AnalystArtifact> {\n const analyze = opts.analyze ?? analyzeTraces\n return async (surface, scenario, _ctx) => {\n const actorDescription = surfaceToText(surface)\n const res = await analyze(\n { question: scenario.question },\n { ...opts.analystOptions, actorDescription, source: scenario.source },\n )\n return {\n answer: res.answer,\n findings: res.findings,\n actorPromptVersion: res.actorPromptVersion,\n }\n }\n}\n\nexport interface FailureModeRecallJudgeOptions {\n /** Weight on recall when precision is also scored (forbiddenCues present).\n * Default 0.5 (equal). Recall-only when no forbiddenCues exist. */\n recallWeight?: number\n}\n\n/**\n * Deterministic, ground-truth judge for analyst findings. Composite =\n * recall of the scenario's `expectedFailureModes` (optionally blended with a\n * precision term that penalizes findings tripping `forbiddenCues`). No LLM —\n * the score is a function of the labels, so the analyst prompt is optimized\n * toward surfacing real failures, not toward a judge it can flatter.\n */\nexport function failureModeRecallJudge(\n opts: FailureModeRecallJudgeOptions = {},\n): JudgeConfig<AnalystArtifact, AnalystScenario> {\n const recallWeight = opts.recallWeight ?? 0.5\n return {\n name: 'failure-mode-recall',\n dimensions: [\n { key: 'recall', description: 'fraction of ground-truth failure modes the analyst surfaced' },\n {\n key: 'precision',\n description:\n '1 − share of findings that named a failure/tool/error absent from this corpus',\n },\n ],\n appliesTo: (s) => s.kind === 'analyst-surface',\n score({ artifact, scenario }) {\n const modes = scenario.expectedFailureModes\n if (modes.length === 0) {\n throw new Error(\n `failureModeRecallJudge: scenario '${scenario.id}' has no expectedFailureModes — refusing to score (a vacuous 1.0 would corrupt the comparison)`,\n )\n }\n const hay = artifact.findings.join('\\n').toLowerCase()\n const matched = modes.filter((m) => m.cues.some((c) => hay.includes(c.toLowerCase())))\n const recall = matched.length / modes.length\n\n const forbidden = (scenario.forbiddenCues ?? []).map((c) => c.toLowerCase())\n let precision = 1\n let hallucinated = 0\n if (forbidden.length > 0) {\n const denom = Math.max(1, artifact.findings.length)\n hallucinated = artifact.findings.filter((f) =>\n forbidden.some((c) => f.toLowerCase().includes(c)),\n ).length\n precision = 1 - hallucinated / denom\n }\n\n const composite =\n forbidden.length > 0 ? recallWeight * recall + (1 - recallWeight) * precision : recall\n const missed = modes.filter((m) => !matched.includes(m)).map((m) => m.id)\n const notes =\n `matched ${matched.length}/${modes.length} failure modes` +\n (missed.length ? `; missed [${missed.join(', ')}]` : '') +\n (hallucinated ? `; ${hallucinated} out-of-corpus finding(s)` : '')\n return { dimensions: { recall, precision }, composite, notes }\n },\n }\n}\n","/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport { ValidationError } from './errors'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit when the comparison has no pass/fail notion. */\n pass?: boolean\n /** Named numeric measurements (score, cost, latency, …). */\n metrics?: Record<string, number>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n pairs.push({ pairKey, repIndex: 0, baseline: b[0]!, treatment: t[0]! })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta; NaN when `n === 0` (no data ≠ measured zero). */\n medianDelta: number\n /** Mean paired delta; NaN when `n === 0`. */\n meanDelta: number\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass === undefined || pair.treatment.pass === undefined) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi === null ? Number.NaN : bootstrapCi.median,\n meanDelta: bootstrapCi === null ? Number.NaN : bootstrapCi.mean,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v === undefined) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`,\n )\n }\n return v\n}\n","import { ValidationError } from '../errors'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceCandidate,\n CrossSurfaceComponent,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/** Validated indexes shared by analysis and deterministic selection. */\nexport interface CrossSurfaceAnalysisContext<TRow extends CrossSurfaceTaskRow> {\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>\n components: CrossSurfaceComponent[]\n candidates: CrossSurfaceCandidate[]\n componentById: Map<string, CrossSurfaceComponent>\n candidateById: Map<string, CrossSurfaceCandidate>\n candidateByComponents: Map<string, CrossSurfaceCandidate>\n singleByComponent: Map<string, CrossSurfaceCandidate>\n rowsByCandidate: Map<string, Map<string, TRow>>\n componentIndex: Map<string, number>\n candidateIndex: Map<string, number>\n}\n\nexport function validateCrossSurfaceInput<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceAnalysisContext<TRow> {\n assertNonEmptyUnique(input.taskOrder, 'taskOrder')\n assertNonEmptyUnique(input.componentOrder, 'componentOrder')\n if (input.componentOrder.length < 2) {\n throw new ValidationError(\n 'analyzeCrossSurfaceInteractions: componentOrder must contain at least two surfaces',\n )\n }\n assertNonEmptyUnique(input.candidateOrder, 'candidateOrder')\n assertNonEmptyUnique(input.costMetricOrder, 'costMetricOrder')\n if (input.costMetricOrder.includes('score')) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: costMetricOrder cannot contain reserved metric 'score'`,\n )\n }\n validateBootstrap(input)\n validateSelection(input)\n\n const componentById = indexUnique(\n input.components,\n (component) => component.componentId,\n 'component',\n )\n assertExactSet(input.componentOrder, componentById.keys(), 'componentOrder', 'components')\n const surfaces = new Set<string>()\n for (const component of componentById.values()) {\n assertNonEmpty(component.componentId, 'componentId')\n assertNonEmpty(component.surfaceId, `surfaceId for component '${component.componentId}'`)\n if (surfaces.has(component.surfaceId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: surfaceId '${component.surfaceId}' has more than one component; ` +\n 'the interaction stage requires one independently selected finalist per surface',\n )\n }\n surfaces.add(component.surfaceId)\n if (typeof component.bestSingleEligible !== 'boolean') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: component '${component.componentId}' must declare bestSingleEligible`,\n )\n }\n }\n\n const componentIndex = new Map(input.componentOrder.map((id, index) => [id, index]))\n const candidateById = indexUnique(\n input.candidates,\n (candidate) => candidate.candidateId,\n 'candidate',\n )\n assertExactSet(input.candidateOrder, candidateById.keys(), 'candidateOrder', 'candidates')\n if (!candidateById.has(input.baselineCandidateId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown baselineCandidateId '${input.baselineCandidateId}'`,\n )\n }\n\n const candidateByComponents = new Map<string, CrossSurfaceCandidate>()\n const singleByComponent = new Map<string, CrossSurfaceCandidate>()\n for (const candidate of candidateById.values()) {\n validateCandidate(candidate, componentById, componentIndex, input.baselineCandidateId)\n const key = crossSurfaceComponentSetKey(candidate.componentIds)\n const duplicate = candidateByComponents.get(key)\n if (duplicate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidates '${duplicate.candidateId}' and ` +\n `'${candidate.candidateId}' materialize the same component set`,\n )\n }\n candidateByComponents.set(key, candidate)\n if (candidate.componentIds.length === 1) {\n singleByComponent.set(candidate.componentIds[0]!, candidate)\n }\n }\n const baseline = candidateById.get(input.baselineCandidateId)!\n if (baseline.componentIds.length !== 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: baseline '${baseline.candidateId}' must have zero components`,\n )\n }\n for (const componentId of input.componentOrder) {\n if (!singleByComponent.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: no single-surface candidate for component '${componentId}'`,\n )\n }\n }\n for (let left = 0; left < input.componentOrder.length; left++) {\n for (let right = left + 1; right < input.componentOrder.length; right++) {\n const ids = [input.componentOrder[left]!, input.componentOrder[right]!]\n if (!candidateByComponents.has(crossSurfaceComponentSetKey(ids))) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: missing pair candidate for components [${ids.join(', ')}]`,\n )\n }\n }\n }\n\n const rowsByCandidate = new Map<string, Map<string, TRow>>()\n const taskIds = new Set(input.taskOrder)\n for (const row of input.rows) {\n const candidate = candidateById.get(row.candidateId)\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for task '${row.taskId}' names unknown candidate '${row.candidateId}'`,\n )\n }\n if (!taskIds.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row for candidate '${row.candidateId}' names task '${row.taskId}' ` +\n 'outside the declared taskOrder',\n )\n }\n validateRow(input, row, candidate)\n const byTask = rowsByCandidate.get(row.candidateId) ?? new Map<string, TRow>()\n if (byTask.has(row.taskId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: duplicate row for candidate '${row.candidateId}' and task '${row.taskId}'`,\n )\n }\n byTask.set(row.taskId, row)\n rowsByCandidate.set(row.candidateId, byTask)\n }\n for (const candidateId of input.candidateOrder) {\n const byTask = rowsByCandidate.get(candidateId)\n const missing = input.taskOrder.filter((taskId) => !byTask?.has(taskId))\n if (missing.length > 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidateId}' is missing declared task row(s) ` +\n `[${missing.join(', ')}]; encode failed attempts explicitly instead of changing the task axis`,\n )\n }\n }\n const expectedRows = input.candidateOrder.length * input.taskOrder.length\n if (input.rows.length !== expectedRows) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: expected exactly ${expectedRows} candidate × task rows, got ${input.rows.length}`,\n )\n }\n\n return {\n input,\n components: input.componentOrder.map((id) => componentById.get(id)!),\n candidates: input.candidateOrder.map((id) => candidateById.get(id)!),\n componentById,\n candidateById,\n candidateByComponents,\n singleByComponent,\n rowsByCandidate,\n componentIndex,\n candidateIndex: new Map(input.candidateOrder.map((id, index) => [id, index])),\n }\n}\n\nexport function crossSurfaceRowsFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n): TRow[] {\n return context.input.taskOrder.map((taskId) => crossSurfaceRowFor(context, candidateId, taskId))\n}\n\nexport function crossSurfaceRowFor<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n candidateId: string,\n taskId: string,\n): TRow {\n return context.rowsByCandidate.get(candidateId)!.get(taskId)!\n}\n\nexport function canonicalCrossSurfaceComponents<TRow extends CrossSurfaceTaskRow>(\n context: CrossSurfaceAnalysisContext<TRow>,\n componentIds: string[],\n): string[] {\n return [...componentIds].sort(\n (left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!,\n )\n}\n\nexport function crossSurfaceComponentSetKey(componentIds: readonly string[]): string {\n return JSON.stringify(componentIds)\n}\n\nfunction validateBootstrap<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const { seed, resamples, confidence } = input.bootstrap\n if (!Number.isInteger(seed)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: bootstrap.seed must be an integer`)\n }\n if (!Number.isInteger(resamples) || resamples <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.resamples must be a positive integer`,\n )\n }\n if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: bootstrap.confidence must be in (0,1)`,\n )\n }\n}\n\nfunction validateSelection<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): void {\n const policy = input.selection\n for (const [name, value] of [\n ['minimumFiringTasks', policy.minimumFiringTasks],\n ['minimumEffectTasks', policy.minimumEffectTasks],\n ] as const) {\n if (!Number.isInteger(value) || value < 0 || value > input.taskOrder.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.${name} must be an integer in [0,${input.taskOrder.length}]`,\n )\n }\n }\n if (\n !Number.isInteger(policy.minimumBundleComponents) ||\n policy.minimumBundleComponents < 2 ||\n policy.minimumBundleComponents > input.componentOrder.length\n ) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: selection.minimumBundleComponents must be an integer in ` +\n `[2,${input.componentOrder.length}]`,\n )\n }\n for (const [metric, limit] of Object.entries(policy.maximumMedianCostRatioToBaseline)) {\n if (!input.costMetricOrder.includes(metric)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost limit names undeclared metric '${metric}'`,\n )\n }\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: cost ratio limit for '${metric}' must be positive and finite`,\n )\n }\n }\n}\n\nfunction validateCandidate(\n candidate: CrossSurfaceCandidate,\n componentById: Map<string, CrossSurfaceComponent>,\n componentIndex: Map<string, number>,\n baselineCandidateId: string,\n): void {\n assertNonEmpty(candidate.candidateId, 'candidateId')\n assertNonEmpty(candidate.contentHash, `contentHash for candidate '${candidate.candidateId}'`)\n if (!Number.isInteger(candidate.artifactBytes) || candidate.artifactBytes < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: artifactBytes for candidate '${candidate.candidateId}' must be a non-negative integer`,\n )\n }\n assertUnique(candidate.componentIds, `componentIds for candidate '${candidate.candidateId}'`)\n for (const componentId of candidate.componentIds) {\n if (!componentById.has(componentId)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' names unknown component '${componentId}'`,\n )\n }\n }\n const canonical = [...candidate.componentIds].sort(\n (left, right) => componentIndex.get(left)! - componentIndex.get(right)!,\n )\n if (!arraysEqual(candidate.componentIds, canonical)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: candidate '${candidate.candidateId}' components must follow componentOrder`,\n )\n }\n if (candidate.candidateId !== baselineCandidateId && candidate.componentIds.length === 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: only baseline '${baselineCandidateId}' may have zero components`,\n )\n }\n}\n\nfunction validateRow<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n row: TRow,\n candidate: CrossSurfaceCandidate,\n): void {\n if (!arraysEqual(row.componentIds, candidate.componentIds)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' componentIds do not match its candidate`,\n )\n }\n if (!['complete', 'missing', 'invalid'].includes(row.completeness)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: row '${row.candidateId}/${row.taskId}' has unknown completeness '${String(row.completeness)}'`,\n )\n }\n if (row.completeness === 'complete') {\n if (typeof row.pass !== 'boolean' || !Number.isFinite(row.score)) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' requires boolean pass and finite score`,\n )\n }\n if (row.rejectReason !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: complete row '${row.candidateId}/${row.taskId}' cannot carry rejectReason`,\n )\n }\n } else {\n if (row.pass !== null || row.score !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' must use null pass and score`,\n )\n }\n if (typeof row.rejectReason !== 'string' || row.rejectReason.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${row.completeness} row '${row.candidateId}/${row.taskId}' requires rejectReason`,\n )\n }\n }\n assertExactSet(\n input.costMetricOrder,\n Object.keys(row.cost),\n `cost keys for row '${row.candidateId}/${row.taskId}'`,\n 'costMetricOrder',\n )\n for (const metric of input.costMetricOrder) {\n const value = row.cost[metric]\n if (value === null || value === undefined || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: unknown or invalid cost '${metric}' on row ` +\n `'${row.candidateId}/${row.taskId}'; every attempt must report a non-negative finite value`,\n )\n }\n }\n const evidenceByComponent = indexUnique(\n row.componentEvidence,\n (evidence) => evidence.componentId,\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n )\n assertExactSet(\n candidate.componentIds,\n evidenceByComponent.keys(),\n `componentEvidence on row '${row.candidateId}/${row.taskId}'`,\n 'candidate components',\n )\n for (const evidence of evidenceByComponent.values()) {\n assertTriState(evidence.fired, 'fired', row)\n assertTriState(evidence.effectObserved, 'effectObserved', row)\n if (evidence.effectObserved === true && evidence.fired !== true) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: effectObserved=true requires fired=true for component ` +\n `'${evidence.componentId}' on row '${row.candidateId}/${row.taskId}'`,\n )\n }\n }\n}\n\nfunction assertTriState<TRow extends CrossSurfaceTaskRow>(\n value: boolean | null,\n field: string,\n row: TRow,\n): void {\n if (value !== true && value !== false && value !== null) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${field} on row '${row.candidateId}/${row.taskId}' must be boolean or null`,\n )\n }\n}\n\nfunction indexUnique<T>(\n items: readonly T[],\n id: (item: T) => string,\n label: string,\n): Map<string, T> {\n const result = new Map<string, T>()\n for (const item of items) {\n const key = id(item)\n assertNonEmpty(key, `${label} id`)\n if (result.has(key)) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: duplicate ${label} id '${key}'`)\n }\n result.set(key, item)\n }\n return result\n}\n\nfunction assertNonEmptyUnique(values: readonly string[], label: string): void {\n if (values.length === 0) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} is empty`)\n }\n assertUnique(values, label)\n for (const value of values) assertNonEmpty(value, label)\n}\n\nfunction assertUnique(values: readonly string[], label: string): void {\n if (new Set(values).size !== values.length) {\n throw new ValidationError(`analyzeCrossSurfaceInteractions: ${label} contains duplicates`)\n }\n}\n\nfunction assertNonEmpty(value: string, label: string): void {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${label} must be a non-empty string`,\n )\n }\n}\n\nfunction assertExactSet(\n expected: readonly string[],\n actualIterable: Iterable<string>,\n actualLabel: string,\n expectedLabel: string,\n): void {\n const actual = [...actualIterable]\n const expectedSet = new Set(expected)\n const actualSet = new Set(actual)\n const missing = expected.filter((value) => !actualSet.has(value))\n const extra = actual.filter((value) => !expectedSet.has(value))\n if (missing.length > 0 || extra.length > 0 || actual.length !== expected.length) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: ${actualLabel} does not match ${expectedLabel}; ` +\n `missing=[${missing.join(', ')}], extra=[${extra.join(', ')}]`,\n )\n }\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n","/**\n * Task-paired comparison and deterministic selection for independently\n * proposed agent surfaces. Unlike factorial cell-mean attribution, every\n * benefit, regression, and interaction remains attached to its task row.\n */\n\nimport { ValidationError } from '../errors'\nimport { comparePairedArms, type PairedArmRow, type PairedArmsComparison } from '../paired-arms'\nimport { pairedBootstrap } from '../statistics'\nimport {\n type CrossSurfaceAnalysisContext as AnalysisContext,\n canonicalCrossSurfaceComponents as canonicalComponents,\n crossSurfaceComponentSetKey as componentSetKey,\n crossSurfaceRowFor as rowFor,\n crossSurfaceRowsFor as rowsFor,\n validateCrossSurfaceInput as validateAndIndex,\n} from './cross-surface-context'\nimport type {\n AnalyzeCrossSurfaceInteractionsInput,\n CrossSurfaceAdditionDecision,\n CrossSurfaceAdditionRejectionReason,\n CrossSurfaceCandidate,\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateEvidence,\n CrossSurfaceCandidateOutcome,\n CrossSurfaceCandidateSummary,\n CrossSurfaceCompositionStep,\n CrossSurfaceDistribution,\n CrossSurfaceEligibility,\n CrossSurfaceEvidenceBreakdown,\n CrossSurfaceIneligibilityReason,\n CrossSurfaceInteractionAwareSelection,\n CrossSurfaceInteractionEffect,\n CrossSurfaceInteractionPath,\n CrossSurfaceInteractionReport,\n CrossSurfaceNaiveStackSelection,\n CrossSurfacePairCompatibility,\n CrossSurfacePairEvidence,\n CrossSurfacePairIncompatibilityReason,\n CrossSurfacePairwiseEntry,\n CrossSurfaceRankedSingle,\n CrossSurfaceRelativeCost,\n CrossSurfaceSelections,\n CrossSurfaceTaskRow,\n} from './cross-surface-types'\n\n/**\n * Build the complete cross-surface evidence matrix and derive all three frozen\n * candidates. The task/candidate/component orders are part of the input so\n * neither insertion order nor an after-the-fact tie-break can change a result.\n */\nexport function analyzeCrossSurfaceInteractions<TRow extends CrossSurfaceTaskRow>(\n input: AnalyzeCrossSurfaceInteractionsInput<TRow>,\n): CrossSurfaceInteractionReport<TRow> {\n const context = validateAndIndex(input)\n const baseline = context.candidateById.get(input.baselineCandidateId)!\n\n const preliminary = context.candidates.map((candidate) =>\n summarizeCandidate(context, candidate, baseline),\n )\n const baselineSummary = preliminary.find(\n (summary) => summary.candidate.candidateId === input.baselineCandidateId,\n )!\n const summaries = preliminary.map((summary) =>\n summary.candidate.candidateId === input.baselineCandidateId\n ? summary\n : {\n ...summary,\n eligibility: candidateEligibility(context, summary, baselineSummary),\n },\n )\n const summaryById = new Map(summaries.map((summary) => [summary.candidate.candidateId, summary]))\n const eligibleSingles = rankedEligibleSingles(context, summaryById)\n const interactionReadySingles = rankedInteractionReadySingles(context, summaryById)\n const pairwise = buildPairwise(context, summaryById, interactionReadySingles, baselineSummary)\n const selections = selectCandidates(\n context,\n summaryById,\n eligibleSingles,\n interactionReadySingles,\n pairwise,\n )\n const rows = context.candidates.flatMap((candidate) =>\n input.taskOrder.map(\n (taskId) => context.rowsByCandidate.get(candidate.candidateId)!.get(taskId)!,\n ),\n )\n\n return {\n taskIds: [...input.taskOrder],\n componentIds: [...input.componentOrder],\n candidateIds: [...input.candidateOrder],\n costMetrics: [...input.costMetricOrder],\n rows,\n missingAttempts: rows.filter((row) => row.completeness === 'missing'),\n invalidAttempts: rows.filter((row) => row.completeness === 'invalid'),\n candidates: summaries,\n pairwise,\n selections,\n }\n}\n\nfunction summarizeCandidate<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n candidate: CrossSurfaceCandidate,\n baseline: CrossSurfaceCandidate,\n): CrossSurfaceCandidateSummary {\n const rows = rowsFor(context, candidate.candidateId)\n const baselineRows = rowsFor(context, baseline.candidateId)\n const outcome = summarizeOutcome(\n context,\n rows,\n baselineRows,\n candidate.candidateId === baseline.candidateId,\n )\n const completeScores = rows\n .filter((row) => row.completeness === 'complete')\n .map((row) => row.score as number)\n const costs = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n distribution(rows.map((row) => row.cost[metric] as number)),\n ]),\n )\n return {\n candidate,\n outcome,\n score: completeScores.length === 0 ? null : distribution(completeScores),\n costs,\n firing: summarizeCandidateEvidence(rows, candidate.componentIds, 'fired'),\n effect: summarizeCandidateEvidence(rows, candidate.componentIds, 'effectObserved'),\n comparisonToBaseline:\n candidate.candidateId === baseline.candidateId\n ? null\n : pairedComparison(context, baseline.candidateId, candidate.candidateId),\n eligibility: null,\n }\n}\n\nfunction summarizeOutcome<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n rows: TRow[],\n baselineRows: TRow[],\n isBaseline: boolean,\n): CrossSurfaceCandidateOutcome {\n const resolvedTaskIds: string[] = []\n const failedTaskIds: string[] = []\n const missingTaskIds: string[] = []\n const invalidTaskIds: string[] = []\n const benefitTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const comparisonMissingTaskIds: string[] = []\n for (let index = 0; index < context.input.taskOrder.length; index++) {\n const row = rows[index]!\n const baseline = baselineRows[index]!\n if (row.completeness === 'missing') missingTaskIds.push(row.taskId)\n else if (row.completeness === 'invalid') invalidTaskIds.push(row.taskId)\n else if (row.pass) resolvedTaskIds.push(row.taskId)\n else failedTaskIds.push(row.taskId)\n\n if (isBaseline) continue\n if (row.completeness !== 'complete' || baseline.completeness !== 'complete') {\n comparisonMissingTaskIds.push(row.taskId)\n } else if (row.pass && !baseline.pass) benefitTaskIds.push(row.taskId)\n else if (!row.pass && baseline.pass) regressionTaskIds.push(row.taskId)\n }\n return {\n resolvedTaskIds,\n failedTaskIds,\n missingTaskIds,\n invalidTaskIds,\n benefitTaskIds,\n regressionTaskIds,\n comparisonMissingTaskIds,\n netBenefit: benefitTaskIds.length - regressionTaskIds.length,\n }\n}\n\nfunction summarizeCandidateEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n componentIds: string[],\n field: 'fired' | 'effectObserved',\n): CrossSurfaceCandidateEvidence {\n if (componentIds.length === 0) {\n return {\n byComponent: [],\n allObservedTaskIds: [],\n someObservedTaskIds: [],\n noneObservedTaskIds: [],\n unobservedTaskIds: [],\n }\n }\n const byComponent: CrossSurfaceEvidenceBreakdown[] = componentIds.map((componentId) => {\n const observedTaskIds: string[] = []\n const notObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const value = evidenceValue(row, componentId, field)\n if (value === true) observedTaskIds.push(row.taskId)\n else if (value === false) notObservedTaskIds.push(row.taskId)\n else unobservedTaskIds.push(row.taskId)\n }\n return { componentId, observedTaskIds, notObservedTaskIds, unobservedTaskIds }\n })\n const allObservedTaskIds: string[] = []\n const someObservedTaskIds: string[] = []\n const noneObservedTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const values = componentIds.map((componentId) => evidenceValue(row, componentId, field))\n if (values.some((value) => value === null)) unobservedTaskIds.push(row.taskId)\n else if (values.every(Boolean)) allObservedTaskIds.push(row.taskId)\n else if (values.some(Boolean)) someObservedTaskIds.push(row.taskId)\n else noneObservedTaskIds.push(row.taskId)\n }\n return {\n byComponent,\n allObservedTaskIds,\n someObservedTaskIds,\n noneObservedTaskIds,\n unobservedTaskIds,\n }\n}\n\nfunction candidateEligibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summary: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfaceEligibility {\n const reasons: CrossSurfaceIneligibilityReason[] = []\n if (summary.outcome.missingTaskIds.length > 0) reasons.push('missing_attempt')\n if (summary.outcome.invalidTaskIds.length > 0) reasons.push('invalid_attempt')\n if (summary.outcome.comparisonMissingTaskIds.length > 0) reasons.push('baseline_outcome_missing')\n if (summary.outcome.benefitTaskIds.length <= summary.outcome.regressionTaskIds.length) {\n reasons.push('benefit_not_greater_than_regression')\n }\n appendEvidenceEligibilityReasons(\n reasons,\n summary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendEvidenceEligibilityReasons(\n reasons,\n summary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, summary, baseline)) reasons.push('cost_limit_exceeded')\n return { eligible: reasons.length === 0, reasons: unique(reasons) }\n}\n\nfunction appendEvidenceEligibilityReasons(\n reasons: CrossSurfaceIneligibilityReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceIneligibilityReason,\n unobservedReason: CrossSurfaceIneligibilityReason,\n): void {\n if (evidence.byComponent.some((component) => component.observedTaskIds.length < minimum)) {\n reasons.push(belowReason)\n }\n if (\n requireObserved &&\n evidence.byComponent.some((component) => component.unobservedTaskIds.length > 0)\n ) {\n reasons.push(unobservedReason)\n }\n}\n\nfunction rankedEligibleSingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter((summary) => summary.eligibility?.eligible)\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\n/**\n * A neutral constituent may seed a composition when it has complete, bounded,\n * observed evidence and causes no baseline regression. Individual benefit is\n * deliberately left to the best-single arm rather than used as a pair gate.\n */\nfunction rankedInteractionReadySingles<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n): CrossSurfaceCandidateSummary[] {\n return [...context.singleByComponent.values()]\n .map((candidate) => summaryById.get(candidate.candidateId)!)\n .filter(\n (summary) =>\n summary.outcome.regressionTaskIds.length === 0 &&\n summary.eligibility?.reasons.every(\n (reason) => reason === 'benefit_not_greater_than_regression',\n ),\n )\n .sort((left, right) => compareSingleSummaries(context, left, right))\n}\n\nfunction compareSingleSummaries<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n left: CrossSurfaceCandidateSummary,\n right: CrossSurfaceCandidateSummary,\n): number {\n const byNetBenefit = right.outcome.netBenefit - left.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit = right.outcome.benefitTaskIds.length - left.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n left.outcome.regressionTaskIds.length - right.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.costs[metric]!.median - right.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = left.candidate.artifactBytes - right.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.candidate.candidateId)! -\n context.candidateIndex.get(right.candidate.candidateId)!\n )\n}\n\nfunction buildPairwise<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n baseline: CrossSurfaceCandidateSummary,\n): CrossSurfacePairwiseEntry[] {\n const interactionReadyIds = new Set(\n interactionReadySingles.map((summary) => summary.candidate.candidateId),\n )\n const entries: CrossSurfacePairwiseEntry[] = []\n for (let leftIndex = 0; leftIndex < context.components.length; leftIndex++) {\n for (let rightIndex = leftIndex + 1; rightIndex < context.components.length; rightIndex++) {\n const leftComponent = context.components[leftIndex]!\n const rightComponent = context.components[rightIndex]!\n const leftSingle = context.singleByComponent.get(leftComponent.componentId)!\n const rightSingle = context.singleByComponent.get(rightComponent.componentId)!\n const pair = context.candidateByComponents.get(\n componentSetKey([leftComponent.componentId, rightComponent.componentId]),\n )!\n const pairSummary = summaryById.get(pair.candidateId)!\n const leftSummary = summaryById.get(leftSingle.candidateId)!\n const rightSummary = summaryById.get(rightSingle.candidateId)!\n const synergyTaskIds: string[] = []\n const interferenceTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const pairRow = rowFor(context, pair.candidateId, taskId)\n const leftRow = rowFor(context, leftSingle.candidateId, taskId)\n const rightRow = rowFor(context, rightSingle.candidateId, taskId)\n if (![pairRow, leftRow, rightRow].every((row) => row.completeness === 'complete')) continue\n if (pairRow.pass && !leftRow.pass && !rightRow.pass) synergyTaskIds.push(taskId)\n if (!pairRow.pass && (leftRow.pass || rightRow.pass)) interferenceTaskIds.push(taskId)\n }\n const incrementalVsConstituents: [\n CrossSurfaceCandidateComparison,\n CrossSurfaceCandidateComparison,\n ] = [\n compareCandidates(context, summaryById, leftSingle.candidateId, pair.candidateId),\n compareCandidates(context, summaryById, rightSingle.candidateId, pair.candidateId),\n ]\n const betterSingle =\n compareSingleSummaries(context, leftSummary, rightSummary) <= 0 ? leftSummary : rightSummary\n const firing = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'fired',\n )\n const effect = summarizePairEvidence(\n rowsFor(context, pair.candidateId),\n leftComponent.componentId,\n rightComponent.componentId,\n 'effectObserved',\n )\n const compatibility = pairCompatibility(\n context,\n pairSummary,\n baseline,\n betterSingle,\n incrementalVsConstituents,\n interactionReadyIds.has(leftSingle.candidateId) &&\n interactionReadyIds.has(rightSingle.candidateId),\n interferenceTaskIds,\n firing,\n effect,\n )\n entries.push({\n componentIds: [leftComponent.componentId, rightComponent.componentId],\n singleCandidateIds: [leftSingle.candidateId, rightSingle.candidateId],\n compositionCandidateId: pair.candidateId,\n benefitTaskIds: [...pairSummary.outcome.benefitTaskIds],\n regressionTaskIds: [...pairSummary.outcome.regressionTaskIds],\n synergyTaskIds,\n interferenceTaskIds,\n incrementalVsConstituents,\n relativeCostToBaseline: relativeCosts(context, pairSummary, baseline),\n firing,\n effect,\n interaction: interactionEffect(\n context,\n baseline.candidate,\n [leftSingle, rightSingle],\n pair,\n ),\n compatibility,\n })\n }\n }\n return entries\n}\n\nfunction pairCompatibility<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n pair: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n betterSingle: CrossSurfaceCandidateSummary,\n comparisons: [CrossSurfaceCandidateComparison, CrossSurfaceCandidateComparison],\n constituentsReady: boolean,\n interferenceTaskIds: string[],\n firing: CrossSurfacePairEvidence,\n effect: CrossSurfacePairEvidence,\n): CrossSurfacePairCompatibility {\n const reasons: CrossSurfacePairIncompatibilityReason[] = []\n if (!constituentsReady) reasons.push('constituent_not_ready')\n if (\n pair.outcome.missingTaskIds.length > 0 ||\n pair.outcome.invalidTaskIds.length > 0 ||\n pair.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('pair_incomplete')\n }\n if (pair.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n if (interferenceTaskIds.length > 0) reasons.push('interference')\n const betterComparison = comparisons.find(\n (comparison) => comparison.comparatorCandidateId === betterSingle.candidate.candidateId,\n )!\n if (betterComparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n appendPairEvidenceReasons(\n reasons,\n firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendPairEvidenceReasons(\n reasons,\n effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, pair, baseline)) reasons.push('cost_limit_exceeded')\n return {\n compatible: reasons.length === 0,\n reasons: unique(reasons),\n betterSingleCandidateId: betterSingle.candidate.candidateId,\n }\n}\n\nfunction appendPairEvidenceReasons(\n reasons: CrossSurfacePairIncompatibilityReason[],\n evidence: CrossSurfacePairEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfacePairIncompatibilityReason,\n unobservedReason: CrossSurfacePairIncompatibilityReason,\n): void {\n const leftObserved = evidence.bothTaskIds.length + evidence.leftOnlyTaskIds.length\n const rightObserved = evidence.bothTaskIds.length + evidence.rightOnlyTaskIds.length\n if (leftObserved < minimum || rightObserved < minimum) reasons.push(belowReason)\n if (requireObserved && evidence.unobservedTaskIds.length > 0) reasons.push(unobservedReason)\n}\n\nfunction interactionEffect<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n baseline: CrossSurfaceCandidate,\n singles: CrossSurfaceCandidate[],\n composition: CrossSurfaceCandidate,\n): CrossSurfaceInteractionEffect {\n const perTask = context.input.taskOrder.map((taskId) => {\n const baselineRow = rowFor(context, baseline.candidateId, taskId)\n const singleRows = singles.map((single) => rowFor(context, single.candidateId, taskId))\n const compositionRow = rowFor(context, composition.candidateId, taskId)\n const rows = [baselineRow, ...singleRows, compositionRow]\n if (!rows.every((row) => row.completeness === 'complete')) {\n return { taskId, passInteraction: null, scoreInteraction: null }\n }\n const additivePass =\n singleRows.reduce((sum, row) => sum + Number(row.pass), 0) -\n (singles.length - 1) * Number(baselineRow.pass)\n const additiveScore =\n singleRows.reduce((sum, row) => sum + (row.score as number), 0) -\n (singles.length - 1) * (baselineRow.score as number)\n return {\n taskId,\n passInteraction: Number(compositionRow.pass) - additivePass,\n scoreInteraction: (compositionRow.score as number) - additiveScore,\n }\n })\n const complete = perTask.filter(\n (row): row is { taskId: string; passInteraction: number; scoreInteraction: number } =>\n row.passInteraction !== null && row.scoreInteraction !== null,\n )\n const passInteractions = complete.map((row) => row.passInteraction)\n const scoreInteractions = complete.map((row) => row.scoreInteraction)\n return {\n perTask,\n n: complete.length,\n nMissing: perTask.length - complete.length,\n meanPassInteraction: meanOrNull(passInteractions),\n meanScoreInteraction: meanOrNull(scoreInteractions),\n passBootstrap: bootstrapInteraction(passInteractions, context),\n scoreBootstrap: bootstrapInteraction(scoreInteractions, context),\n }\n}\n\nfunction bootstrapInteraction<TRow extends CrossSurfaceTaskRow>(\n interactions: number[],\n context: AnalysisContext<TRow>,\n) {\n if (interactions.length === 0) return null\n return pairedBootstrap(new Array(interactions.length).fill(0), interactions, {\n ...context.input.bootstrap,\n statistic: 'mean',\n })\n}\n\nfunction selectCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceSelections {\n const bestSingleRanking = eligibleSingles.filter((summary) => {\n const componentId = summary.candidate.componentIds[0]!\n return context.componentById.get(componentId)!.bestSingleEligible\n })\n const ranking: CrossSurfaceRankedSingle[] = bestSingleRanking.map((summary, index) => ({\n rank: index + 1,\n candidateId: summary.candidate.candidateId,\n componentId: summary.candidate.componentIds[0]!,\n }))\n const best = bestSingleRanking[0]\n const bestSingle = best\n ? {\n candidateId: best.candidate.candidateId,\n componentId: best.candidate.componentIds[0]!,\n ranking,\n }\n : null\n const naiveStack = selectNaiveStack(context, eligibleSingles)\n const interactionAware = selectInteractionAware(\n context,\n summaryById,\n interactionReadySingles,\n pairwise,\n )\n return { bestSingle, naiveStack, interactionAware }\n}\n\nfunction selectNaiveStack<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n eligibleSingles: CrossSurfaceCandidateSummary[],\n): CrossSurfaceNaiveStackSelection | null {\n if (eligibleSingles.length === 0) return null\n const componentIds = eligibleSingles\n .map((summary) => summary.candidate.componentIds[0]!)\n .sort((left, right) => context.componentIndex.get(left)! - context.componentIndex.get(right)!)\n const candidate = context.candidateByComponents.get(componentSetKey(componentIds))\n if (!candidate) {\n throw new ValidationError(\n `analyzeCrossSurfaceInteractions: naive stack [${componentIds.join(', ')}] was not evaluated`,\n )\n }\n return { candidateId: candidate.candidateId, componentIds }\n}\n\nfunction selectInteractionAware<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairwise: CrossSurfacePairwiseEntry[],\n): CrossSurfaceInteractionAwareSelection | null {\n const baseline = summaryById.get(context.input.baselineCandidateId)!\n const pairByComponents = new Map(\n pairwise.map((entry) => [componentSetKey(entry.componentIds), entry]),\n )\n const paths = pairwise\n .filter((entry) => entry.compatibility.compatible)\n .map((entry) =>\n growInteractionPath(\n context,\n summaryById,\n interactionReadySingles,\n pairByComponents,\n baseline,\n summaryById.get(entry.compositionCandidateId)!,\n ),\n )\n if (paths.length === 0) return null\n\n const qualified = paths\n .filter((path) => path.qualified)\n .sort((left, right) => compareInteractionPaths(context, summaryById, left, right))\n const winning =\n qualified[0] ??\n [...paths].sort((left, right) => compareInteractionPaths(context, summaryById, left, right))[0]!\n return {\n seedCandidateId: winning.seedCandidateId,\n terminalCandidateId: winning.terminalCandidateId,\n terminalComponentIds: [...winning.terminalComponentIds],\n selectedCandidateId: qualified.length > 0 ? winning.terminalCandidateId : null,\n qualified: qualified.length > 0,\n evaluatedPaths: paths,\n steps: winning.steps,\n }\n}\n\nfunction growInteractionPath<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n interactionReadySingles: CrossSurfaceCandidateSummary[],\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n seed: CrossSurfaceCandidateSummary,\n): CrossSurfaceInteractionPath {\n let current = seed\n let retained = [...seed.candidate.componentIds]\n let remaining = interactionReadySingles.filter(\n (summary) => !retained.includes(summary.candidate.componentIds[0]!),\n )\n const steps: CrossSurfaceCompositionStep[] = []\n\n while (remaining.length > 0) {\n const decisions = remaining.map((addition) =>\n evaluateAddition(\n context,\n summaryById,\n pairByComponents,\n baseline,\n current,\n retained,\n addition,\n ),\n )\n const eligible = decisions\n .filter((decision) => decision.eligible)\n .sort((left, right) => compareAdditionDecisions(context, summaryById, left, right))\n const selected = eligible[0]\n if (selected) selected.selected = true\n steps.push({\n fromCandidateId: current.candidate.candidateId,\n retainedComponentIds: [...retained],\n considered: decisions.sort(\n (left, right) =>\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!,\n ),\n selectedCandidateId: selected?.bundleCandidateId ?? null,\n })\n if (!selected?.bundleCandidateId) break\n current = summaryById.get(selected.bundleCandidateId)!\n retained = [...current.candidate.componentIds]\n remaining = remaining.filter(\n (summary) => summary.candidate.candidateId !== selected.additionCandidateId,\n )\n }\n\n const qualified = retained.length >= context.input.selection.minimumBundleComponents\n return {\n seedCandidateId: seed.candidate.candidateId,\n terminalCandidateId: current.candidate.candidateId,\n terminalComponentIds: retained,\n qualified,\n steps,\n }\n}\n\nfunction compareInteractionPaths<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceInteractionPath,\n right: CrossSurfaceInteractionPath,\n): number {\n const leftSummary = summaryById.get(left.terminalCandidateId)!\n const rightSummary = summaryById.get(right.terminalCandidateId)!\n const byNetBenefit = rightSummary.outcome.netBenefit - leftSummary.outcome.netBenefit\n if (byNetBenefit !== 0) return byNetBenefit\n const byBenefit =\n rightSummary.outcome.benefitTaskIds.length - leftSummary.outcome.benefitTaskIds.length\n if (byBenefit !== 0) return byBenefit\n const byRegression =\n leftSummary.outcome.regressionTaskIds.length - rightSummary.outcome.regressionTaskIds.length\n if (byRegression !== 0) return byRegression\n for (const metric of context.input.costMetricOrder) {\n const byCost = leftSummary.costs[metric]!.median - rightSummary.costs[metric]!.median\n if (byCost !== 0) return byCost\n }\n const byBytes = leftSummary.candidate.artifactBytes - rightSummary.candidate.artifactBytes\n if (byBytes !== 0) return byBytes\n const byCandidateOrder =\n context.candidateIndex.get(left.terminalCandidateId)! -\n context.candidateIndex.get(right.terminalCandidateId)!\n if (byCandidateOrder !== 0) return byCandidateOrder\n return (\n context.candidateIndex.get(left.seedCandidateId)! -\n context.candidateIndex.get(right.seedCandidateId)!\n )\n}\n\nfunction evaluateAddition<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n pairByComponents: Map<string, CrossSurfacePairwiseEntry>,\n baseline: CrossSurfaceCandidateSummary,\n current: CrossSurfaceCandidateSummary,\n retained: string[],\n addition: CrossSurfaceCandidateSummary,\n): CrossSurfaceAdditionDecision {\n const additionComponentId = addition.candidate.componentIds[0]!\n const reasons: CrossSurfaceAdditionRejectionReason[] = []\n for (const retainedComponentId of retained) {\n const pair = pairByComponents.get(\n componentSetKey(canonicalComponents(context, [retainedComponentId, additionComponentId])),\n )\n if (!pair?.compatibility.compatible) reasons.push('pair_incompatible')\n }\n const bundleComponents = canonicalComponents(context, [...retained, additionComponentId])\n const bundle = context.candidateByComponents.get(componentSetKey(bundleComponents))\n if (!bundle) {\n reasons.push('full_bundle_not_evaluated')\n return emptyAdditionDecision(addition, additionComponentId, reasons)\n }\n const bundleSummary = summaryById.get(bundle.candidateId)!\n if (\n bundleSummary.outcome.missingTaskIds.length > 0 ||\n bundleSummary.outcome.invalidTaskIds.length > 0 ||\n bundleSummary.outcome.comparisonMissingTaskIds.length > 0\n ) {\n reasons.push('bundle_incomplete')\n }\n if (bundleSummary.outcome.regressionTaskIds.length > 0) reasons.push('baseline_regression')\n const comparison = compareCandidates(\n context,\n summaryById,\n current.candidate.candidateId,\n bundle.candidateId,\n )\n if (comparison.winsTaskIds.length === 0) reasons.push('no_incremental_resolution')\n if (comparison.regressionTaskIds.length > 0) reasons.push('incremental_regression')\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.firing,\n context.input.selection.minimumFiringTasks,\n context.input.selection.requireObservedFiring,\n 'firing_below_minimum',\n 'firing_unobserved',\n )\n appendBundleEvidenceReasons(\n reasons,\n bundleSummary.effect,\n context.input.selection.minimumEffectTasks,\n context.input.selection.requireObservedEffect,\n 'effect_below_minimum',\n 'effect_unobserved',\n )\n if (!withinCostLimits(context, bundleSummary, baseline)) reasons.push('cost_limit_exceeded')\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: bundle.candidateId,\n incrementalResolutionTaskIds: comparison.winsTaskIds,\n incrementalRegressionTaskIds: comparison.regressionTaskIds,\n incrementalMedianCost: Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [\n metric,\n bundleSummary.costs[metric]!.median - current.costs[metric]!.median,\n ]),\n ),\n eligible: reasons.length === 0,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction emptyAdditionDecision(\n addition: CrossSurfaceCandidateSummary,\n additionComponentId: string,\n reasons: CrossSurfaceAdditionRejectionReason[],\n): CrossSurfaceAdditionDecision {\n return {\n additionCandidateId: addition.candidate.candidateId,\n additionComponentId,\n bundleCandidateId: null,\n incrementalResolutionTaskIds: [],\n incrementalRegressionTaskIds: [],\n incrementalMedianCost: null,\n eligible: false,\n selected: false,\n reasons: unique(reasons),\n }\n}\n\nfunction appendBundleEvidenceReasons(\n reasons: CrossSurfaceAdditionRejectionReason[],\n evidence: CrossSurfaceCandidateEvidence,\n minimum: number,\n requireObserved: boolean,\n belowReason: CrossSurfaceAdditionRejectionReason,\n unobservedReason: CrossSurfaceAdditionRejectionReason,\n): void {\n if (evidence.byComponent.some((component) => component.observedTaskIds.length < minimum)) {\n reasons.push(belowReason)\n }\n if (\n requireObserved &&\n evidence.byComponent.some((component) => component.unobservedTaskIds.length > 0)\n ) {\n reasons.push(unobservedReason)\n }\n}\n\nfunction compareAdditionDecisions<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n left: CrossSurfaceAdditionDecision,\n right: CrossSurfaceAdditionDecision,\n): number {\n const byWins =\n right.incrementalResolutionTaskIds.length - left.incrementalResolutionTaskIds.length\n if (byWins !== 0) return byWins\n for (const metric of context.input.costMetricOrder) {\n const byCost = left.incrementalMedianCost![metric]! - right.incrementalMedianCost![metric]!\n if (byCost !== 0) return byCost\n }\n const leftBytes = summaryById.get(left.additionCandidateId)!.candidate.artifactBytes\n const rightBytes = summaryById.get(right.additionCandidateId)!.candidate.artifactBytes\n const byBytes = leftBytes - rightBytes\n if (byBytes !== 0) return byBytes\n return (\n context.candidateIndex.get(left.additionCandidateId)! -\n context.candidateIndex.get(right.additionCandidateId)!\n )\n}\n\nfunction compareCandidates<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n summaryById: Map<string, CrossSurfaceCandidateSummary>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): CrossSurfaceCandidateComparison {\n const winsTaskIds: string[] = []\n const regressionTaskIds: string[] = []\n const missingTaskIds: string[] = []\n for (const taskId of context.input.taskOrder) {\n const comparator = rowFor(context, comparatorCandidateId, taskId)\n const treatment = rowFor(context, treatmentCandidateId, taskId)\n if (comparator.completeness !== 'complete' || treatment.completeness !== 'complete') {\n missingTaskIds.push(taskId)\n } else if (treatment.pass && !comparator.pass) winsTaskIds.push(taskId)\n else if (!treatment.pass && comparator.pass) regressionTaskIds.push(taskId)\n }\n return {\n comparatorCandidateId,\n treatmentCandidateId,\n winsTaskIds,\n regressionTaskIds,\n missingTaskIds,\n paired: pairedComparison(context, comparatorCandidateId, treatmentCandidateId),\n relativeCost: relativeCosts(\n context,\n summaryById.get(treatmentCandidateId)!,\n summaryById.get(comparatorCandidateId)!,\n ),\n }\n}\n\nfunction pairedComparison<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n comparatorCandidateId: string,\n treatmentCandidateId: string,\n): PairedArmsComparison {\n const rows: PairedArmRow[] = []\n for (const taskId of context.input.taskOrder) {\n rows.push(toPairedArmRow(context, rowFor(context, comparatorCandidateId, taskId)))\n rows.push(toPairedArmRow(context, rowFor(context, treatmentCandidateId, taskId)))\n }\n return comparePairedArms(rows, {\n baselineArm: comparatorCandidateId,\n treatmentArm: treatmentCandidateId,\n metricNames: ['score', ...context.input.costMetricOrder],\n bootstrap: { ...context.input.bootstrap, statistic: 'mean' },\n })\n}\n\nfunction toPairedArmRow<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n row: TRow,\n): PairedArmRow {\n const metrics: Record<string, number> = Object.fromEntries(\n context.input.costMetricOrder.map((metric) => [metric, row.cost[metric] as number]),\n )\n if (row.completeness === 'complete') metrics.score = row.score as number\n return {\n pairKey: row.taskId,\n arm: row.candidateId,\n ...(row.completeness === 'complete' ? { pass: row.pass as boolean } : {}),\n metrics,\n }\n}\n\nfunction summarizePairEvidence<TRow extends CrossSurfaceTaskRow>(\n rows: TRow[],\n leftComponentId: string,\n rightComponentId: string,\n field: 'fired' | 'effectObserved',\n): CrossSurfacePairEvidence {\n const bothTaskIds: string[] = []\n const leftOnlyTaskIds: string[] = []\n const rightOnlyTaskIds: string[] = []\n const neitherTaskIds: string[] = []\n const unobservedTaskIds: string[] = []\n for (const row of rows) {\n const left = evidenceValue(row, leftComponentId, field)\n const right = evidenceValue(row, rightComponentId, field)\n if (left === null || right === null) unobservedTaskIds.push(row.taskId)\n else if (left && right) bothTaskIds.push(row.taskId)\n else if (left) leftOnlyTaskIds.push(row.taskId)\n else if (right) rightOnlyTaskIds.push(row.taskId)\n else neitherTaskIds.push(row.taskId)\n }\n return {\n bothTaskIds,\n leftOnlyTaskIds,\n rightOnlyTaskIds,\n neitherTaskIds,\n unobservedTaskIds,\n }\n}\n\nfunction relativeCosts<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n comparator: CrossSurfaceCandidateSummary,\n): Record<string, CrossSurfaceRelativeCost> {\n return Object.fromEntries(\n context.input.costMetricOrder.map((metric) => {\n const treatmentMedian = treatment.costs[metric]!.median\n const comparatorMedian = comparator.costs[metric]!.median\n return [\n metric,\n {\n treatmentMedian,\n comparatorMedian,\n medianDelta: treatmentMedian - comparatorMedian,\n medianRatio:\n comparatorMedian === 0\n ? treatmentMedian === 0\n ? 1\n : null\n : treatmentMedian / comparatorMedian,\n },\n ]\n }),\n )\n}\n\nfunction withinCostLimits<TRow extends CrossSurfaceTaskRow>(\n context: AnalysisContext<TRow>,\n treatment: CrossSurfaceCandidateSummary,\n baseline: CrossSurfaceCandidateSummary,\n): boolean {\n const relative = relativeCosts(context, treatment, baseline)\n return Object.entries(context.input.selection.maximumMedianCostRatioToBaseline).every(\n ([metric, limit]) => {\n const ratio = relative[metric]!.medianRatio\n return ratio !== null && ratio <= limit\n },\n )\n}\n\nfunction distribution(values: number[]): CrossSurfaceDistribution {\n const sorted = [...values].sort((left, right) => left - right)\n const total = sorted.reduce((sum, value) => sum + value, 0)\n const middle = Math.floor(sorted.length / 2)\n const median =\n sorted.length % 2 === 1 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2\n return {\n n: sorted.length,\n min: sorted[0]!,\n median,\n mean: total / sorted.length,\n max: sorted[sorted.length - 1]!,\n total,\n }\n}\n\nfunction evidenceValue(\n row: CrossSurfaceTaskRow,\n componentId: string,\n field: 'fired' | 'effectObserved',\n): boolean | null {\n return row.componentEvidence.find((evidence) => evidence.componentId === componentId)![field]\n}\n\nfunction meanOrNull(values: number[]): number | null {\n return values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve } from 'node:path'\nimport { contentHash } from '../verdict-cache'\nimport { type CampaignRunPlan, type PlanCampaignRunOptions, planCampaignRun } from './run-campaign'\nimport type { CampaignStorage } from './storage'\nimport type { JudgeConfig, Scenario } from './types'\n\nexport type EvalFixtureValidationMode = 'vitest' | 'none'\n\nexport interface EvalFixtureFile {\n path: string\n sha256: string\n bytes: number\n}\n\nexport interface EvalFixture {\n name: string\n path: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n files: EvalFixtureFile[]\n fingerprint: string\n}\n\nexport interface EvalFixtureScenario extends Scenario {\n kind: 'eval-fixture'\n fixtureName: string\n fixturePath: string\n promptPath: string\n evalPath?: string\n packageJsonPath?: string\n prompt: string\n fingerprint: string\n}\n\nexport interface EvalFixtureLoadOptions {\n /** `vitest` requires EVAL.ts/EVAL.tsx and package.json type=module. `none` only requires PROMPT.md. */\n validation?: EvalFixtureValidationMode\n /** Extra caller-owned knobs that affect fixture behavior, folded into the fingerprint. */\n fingerprintConfig?: unknown\n}\n\nexport interface LoadEvalFixtureScenariosOptions extends EvalFixtureLoadOptions {\n names?: string[]\n}\n\nexport interface PlanEvalFixtureRunOptions<TArtifact = unknown>\n extends Pick<\n PlanCampaignRunOptions<EvalFixtureScenario, TArtifact>,\n 'dispatchRef' | 'judges' | 'seed' | 'reps' | 'resumable' | 'runDir'\n > {\n evalsDir: string\n validation?: EvalFixtureValidationMode\n fingerprintConfig?: unknown\n names?: string[]\n storage?: CampaignStorage\n}\n\nexport type EvalFixtureRunPlan = CampaignRunPlan & {\n fixtures: Array<Pick<EvalFixtureScenario, 'fixtureName' | 'fixturePath' | 'fingerprint'>>\n}\n\n/** Walk `evalsDir` and return the relative name of every fixture directory (one containing an exact-case `PROMPT.md`). */\nexport function discoverEvalFixtures(evalsDir: string): string[] {\n const root = resolve(evalsDir)\n if (!existsSync(root)) throw new Error(`discoverEvalFixtures: evalsDir not found: ${root}`)\n\n const fixtures: string[] = []\n const walk = (dir: string, base = '') => {\n for (const entry of readdirSync(dir).sort()) {\n if (entry.startsWith('.') || entry === 'node_modules') continue\n const fullPath = join(dir, entry)\n if (!statSync(fullPath).isDirectory()) continue\n\n const name = base ? `${base}/${entry}` : entry\n if (existsWithExactCase(fullPath, 'PROMPT.md')) {\n fixtures.push(name)\n } else {\n walk(fullPath, name)\n }\n }\n }\n\n walk(root)\n return fixtures\n}\n\n/**\n * Load ONE fixture by name: reads `PROMPT.md` (plus `EVAL.ts`/`EVAL.tsx` and `package.json` under\n * `vitest` validation) and content-fingerprints the full file set for cache identity.\n */\nexport function loadEvalFixture(\n evalsDir: string,\n name: string,\n options: EvalFixtureLoadOptions = {},\n): EvalFixture {\n const validation = options.validation ?? 'vitest'\n const root = resolve(evalsDir)\n const fixturePath = resolve(root, name)\n assertInside(root, fixturePath, name)\n\n if (!existsSync(fixturePath) || !statSync(fixturePath).isDirectory()) {\n throw new Error(`loadEvalFixture: fixture not found: ${name}`)\n }\n if (!existsWithExactCase(fixturePath, 'PROMPT.md')) {\n throw new Error(`loadEvalFixture: ${name} is missing exact-case PROMPT.md`)\n }\n\n const promptPath = join(fixturePath, 'PROMPT.md')\n const evalPath = resolveEvalPath(fixturePath)\n const packageJsonPath = existsWithExactCase(fixturePath, 'package.json')\n ? join(fixturePath, 'package.json')\n : undefined\n\n if (validation !== 'none') {\n if (!evalPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case EVAL.ts or EVAL.tsx`)\n if (!packageJsonPath)\n throw new Error(`loadEvalFixture: ${name} is missing exact-case package.json`)\n assertModulePackage(packageJsonPath, name)\n }\n\n const files = collectFixtureFiles(fixturePath)\n return {\n name,\n path: fixturePath,\n promptPath,\n evalPath,\n packageJsonPath,\n prompt: readFileSync(promptPath, 'utf8'),\n files,\n fingerprint: contentHash({\n files,\n config: options.fingerprintConfig ?? null,\n }),\n }\n}\n\n/** Load fixtures (all discovered, or just `names`) as campaign `Scenario`s tagged `eval-fixture`. */\nexport function loadEvalFixtureScenarios(\n evalsDir: string,\n options: LoadEvalFixtureScenariosOptions = {},\n): EvalFixtureScenario[] {\n const names = options.names ?? discoverEvalFixtures(evalsDir)\n return names.map((name) => {\n const fixture = loadEvalFixture(evalsDir, name, options)\n return {\n id: fixture.name,\n kind: 'eval-fixture',\n tags: ['eval-fixture'],\n fixtureName: fixture.name,\n fixturePath: fixture.path,\n promptPath: fixture.promptPath,\n evalPath: fixture.evalPath,\n packageJsonPath: fixture.packageJsonPath,\n prompt: fixture.prompt,\n fingerprint: fixture.fingerprint,\n }\n })\n}\n\n/**\n * Dry-run planner for a fixture campaign: loads the scenarios, delegates to `planCampaignRun`,\n * and returns the plan plus each fixture's name/path/fingerprint.\n */\nexport function planEvalFixtureRun<TArtifact = unknown>(\n options: PlanEvalFixtureRunOptions<TArtifact>,\n): EvalFixtureRunPlan {\n const scenarios = loadEvalFixtureScenarios(options.evalsDir, {\n names: options.names,\n validation: options.validation,\n fingerprintConfig: options.fingerprintConfig,\n })\n const plan = planCampaignRun<EvalFixtureScenario, TArtifact>({\n scenarios,\n dispatchRef: options.dispatchRef ?? 'eval-fixture-dispatch',\n judges: options.judges as JudgeConfig<TArtifact, EvalFixtureScenario>[] | undefined,\n seed: options.seed,\n reps: options.reps,\n resumable: options.resumable,\n runDir: options.runDir,\n storage: options.storage,\n })\n\n return {\n ...plan,\n fixtures: scenarios.map((scenario) => ({\n fixtureName: scenario.fixtureName,\n fixturePath: scenario.fixturePath,\n fingerprint: scenario.fingerprint,\n })),\n }\n}\n\nfunction existsWithExactCase(dirPath: string, fileName: string): boolean {\n try {\n return readdirSync(dirPath).includes(fileName)\n } catch {\n return false\n }\n}\n\nfunction resolveEvalPath(fixturePath: string): string | undefined {\n if (existsWithExactCase(fixturePath, 'EVAL.ts')) return join(fixturePath, 'EVAL.ts')\n if (existsWithExactCase(fixturePath, 'EVAL.tsx')) return join(fixturePath, 'EVAL.tsx')\n return undefined\n}\n\nfunction assertModulePackage(packageJsonPath: string, name: string): void {\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(packageJsonPath, 'utf8'))\n } catch (err) {\n throw new Error(\n `loadEvalFixture: ${name} package.json is invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n (parsed as { type?: unknown }).type !== 'module'\n ) {\n throw new Error(`loadEvalFixture: ${name} package.json must set \"type\": \"module\"`)\n }\n}\n\nfunction collectFixtureFiles(fixturePath: string, base = ''): EvalFixtureFile[] {\n const files: EvalFixtureFile[] = []\n for (const entry of readdirSync(join(fixturePath, base)).sort()) {\n if (entry === 'node_modules' || entry === '.git') continue\n const relativePath = base ? `${base}/${entry}` : entry\n const fullPath = join(fixturePath, relativePath)\n const stat = statSync(fullPath)\n if (stat.isDirectory()) {\n files.push(...collectFixtureFiles(fixturePath, relativePath))\n continue\n }\n const bytes = readFileSync(fullPath)\n files.push({\n path: relativePath,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n bytes: bytes.byteLength,\n })\n }\n return files\n}\n\nfunction assertInside(root: string, target: string, label: string): void {\n const rel = relative(root, target)\n if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) return\n throw new Error(`loadEvalFixture: fixture path escapes evalsDir: ${label}`)\n}\n","/**\n * @module\n * Composable placebo / neutralization promotion gate.\n *\n * A held-out gate proves a candidate beat baseline. It CANNOT prove the lift came\n * from the candidate's CONTENT rather than from the prompt/mount FOOTPRINT the\n * content happened to add (more bytes, a longer prompt). This gate closes that\n * hole: it compares the candidate's held-out lift against the lift of a\n * FOOTPRINT-MATCHED neutralized variant (same layout + length, zero content, via\n * `neutralizeText`). If the neutralized variant reproduces more than\n * `maxDecorativeFraction` of the candidate's lift, the lift is decorative — it\n * survives blanking the content — and the candidate is HELD regardless of how\n * large or significant its raw lift is.\n *\n * Compose it AFTER the significance gate — significance says the lift is real,\n * this says the lift is CAUSED BY THE CONTENT:\n * composeGate(heldOutGate({ ... }), neutralizationGate({ ... }))\n *\n * Requires `ctx.neutralizedJudgeScores`, populated by `runImprovementLoop` when it\n * is given a `neutralize` function. A gate composed without that wiring fails\n * loud rather than silently passing an unproven candidate.\n */\n\nimport type { Gate, GateContext, GateResult, Scenario } from '../types'\nimport { pairHoldout } from './statistical-heldout'\n\nexport interface NeutralizationGateOptions<TScenario extends Scenario = Scenario> {\n scenarios: TScenario[]\n /** Reject when the neutralized (content-blanked, footprint-matched) variant\n * reproduces at least this fraction of the candidate's held-out lift. Default\n * 0.5 — if blanking the content keeps half the lift, the content is decorative.\n * Equality rejects: a neutralized lift == threshold·candidateLift is decorative. */\n maxDecorativeFraction?: number\n}\n\n/** Mean of a numeric array; 0 for an empty array (callers guard n separately). */\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\n/** Paired mean held-out lift of `arm` over baseline, on the in-scope cells. */\nfunction pairedLift(\n arm: Map<string, Record<string, { composite: number }>>,\n baseline: Map<string, Record<string, { composite: number }>>,\n scenarioIds: Set<string>,\n): { lift: number; n: number } {\n const paired = pairHoldout(arm as never, baseline as never, scenarioIds, (s) => s.composite)\n const deltas = paired.after.map((a, i) => a - (paired.before[i] ?? 0))\n return { lift: mean(deltas), n: deltas.length }\n}\n\n/**\n * Composable placebo gate: ships only when the candidate's held-out lift is NOT\n * mostly reproduced by a footprint-matched neutralized variant.\n */\nexport function neutralizationGate<TArtifact, TScenario extends Scenario>(\n options: NeutralizationGateOptions<TScenario>,\n): Gate<TArtifact, TScenario> {\n const maxDecorativeFraction = options.maxDecorativeFraction ?? 0.5\n return {\n name: 'neutralizationGate',\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.baselineJudgeScores is required — the placebo control measures lift OVER baseline.',\n )\n }\n if (!ctx.neutralizedJudgeScores) {\n throw new Error(\n 'neutralizationGate: ctx.neutralizedJudgeScores is required. It is populated by runImprovementLoop only when a `neutralize` function is supplied — composing this gate without that wiring would pass an unproven candidate.',\n )\n }\n const scenarioIds = new Set(options.scenarios.map((s) => s.id))\n const cand = pairedLift(\n ctx.judgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n const neut = pairedLift(\n ctx.neutralizedJudgeScores as never,\n ctx.baselineJudgeScores as never,\n scenarioIds,\n )\n\n // No positive candidate lift → nothing to attribute. Fail closed: the\n // placebo control has no basis to clear the candidate (the significance\n // gate is what judges lift magnitude; this one only judges its CAUSE).\n if (cand.lift <= 0) {\n return {\n decision: 'hold',\n reasons: [\n `neutralization: candidate held-out lift ${cand.lift.toFixed(3)} ≤ 0 — no positive lift to attribute to content`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n passed: false,\n detail: { candidateLift: cand.lift, neutralizedLift: neut.lift, n: cand.n },\n },\n ],\n delta: cand.lift,\n }\n }\n\n const decorativeFraction = neut.lift / cand.lift\n const passed = decorativeFraction < maxDecorativeFraction\n const pct = (decorativeFraction * 100).toFixed(0)\n return {\n decision: passed ? 'ship' : 'hold',\n reasons: passed\n ? [\n `neutralization: content is causal — blanked variant reproduces ${pct}% of the lift (< ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ]\n : [\n `neutralization: lift is DECORATIVE — blanking the content (footprint-matched) reproduces ${pct}% of the lift (≥ ${(maxDecorativeFraction * 100).toFixed(0)}%); candidate Δ ${cand.lift.toFixed(3)}, neutralized Δ ${neut.lift.toFixed(3)}`,\n ],\n contributingGates: [\n {\n name: 'neutralizationGate',\n passed,\n detail: {\n candidateLift: cand.lift,\n neutralizedLift: neut.lift,\n decorativeFraction,\n maxDecorativeFraction,\n n: cand.n,\n },\n },\n ],\n delta: cand.lift,\n }\n },\n }\n}\n","/**\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 { createHash } from 'node:crypto'\nimport { canonicalize, 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}\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. */\n state(): EProcessState & { decision: SequentialDecision }\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` — same `sha256-content` scheme\n * (sha256 over the canonicalized manifest minus contentHash/algo), via\n * node:crypto so gate construction can stay synchronous and fail loud\n * before any observation is consumed. */\nfunction verifyManifestSync(m: SignedManifest): boolean {\n if (m.algo !== undefined && m.algo !== 'sha256-content') {\n throw new Error(`sequentialPairedGate: unrecognized manifest hash algo '${m.algo}'`)\n }\n const { contentHash, algo: _algo, ...rest } = m\n void _algo\n const bytes = JSON.stringify(canonicalize(rest))\n const hash = createHash('sha256').update(bytes, 'utf8').digest('hex')\n return hash === 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(): EProcessState & { decision: SequentialDecision }\n}\n\nfunction makeStream(cfg: ResolvedConfig): SequentialStream {\n const proc = eProcess({ alpha: cfg.alpha, maxBet: cfg.maxBet, nullMean: cfg.nullMean })\n const threshold = 1 / cfg.alpha\n let terminal: SequentialDecision | undefined\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)\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 preRegisteredId: manifest?.id,\n 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, passed: false, 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: [{ name, passed: decision === 'ship', detail }],\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, c) => (c.composite > best.composite ? c : best))\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","/**\n * Evidence grounding for reflective optimizers (GEPA-style revise loops).\n *\n * Two failure modes recur when an LLM revises an artifact from raw rollout\n * traces (first measured in agent-lab R358, where naive reflection REGRESSED\n * the score 0.375 -> 0.125 before these helpers fixed it):\n *\n * 1. The environment often hides WHY a rollout failed - a tool call can\n * succeed while an invisible downstream check fails - so the reviser\n * cannot see the cause in the transcript. The only reliable signal is the\n * field-level difference between what passing and failing rollouts did.\n * `rolloutArgumentDiff` computes that difference deterministically so the\n * reviser is handed the diff instead of being trusted to derive it.\n *\n * 2. Revisers invent plausible-but-wrong literal values (\"use 'new'\",\n * \"use 'sent'\") that no passing rollout ever used, turning every rollout\n * into a failure. `classifyUngroundedLiterals` mechanically detects them,\n * separating HARMFUL literals (ones failing rollouts actually used -\n * proven damage) from benign illustrations (e.g. a name example like\n * 'Doe'), so callers can hard-reject the former and merely log the latter.\n * Rejecting every ungrounded quoted word is too blunt: it killed a run\n * over a surname illustration before the severity split existed.\n *\n * Pure data in, data out: no LLM calls, no filesystem, no domain knowledge.\n */\n\n/** One tool/action call observed in a rollout: a name plus its arguments. */\nexport interface RolloutCall {\n readonly name: string\n readonly args: Readonly<Record<string, unknown>>\n}\n\n/** A scored rollout: its calls plus the scalar outcome used to split pass/fail. */\nexport interface ScoredRollout {\n /** Caller-meaningful identifier (task id, cell id) used only for reporting. */\n readonly id: string\n /** Scalar outcome in [0, 1]; `passThreshold` splits passing from failing. */\n readonly score: number\n readonly calls: readonly RolloutCall[]\n}\n\nexport interface RolloutArgumentDiffOptions {\n /** Rollouts with `score >= passThreshold` count as passing. Default 1. */\n readonly passThreshold?: number\n /** Max distinct values listed per field per side in the rendered text. Default 4. */\n readonly maxValuesPerField?: number\n}\n\nexport interface RolloutArgumentDiff {\n /** Human/LLM-readable per-field diff, one line per field. */\n readonly text: string\n /** Lowercased stringified argument values seen in passing rollouts. */\n readonly passingValues: ReadonlySet<string>\n /** Lowercased stringified argument values seen in failing rollouts. */\n readonly failingValues: ReadonlySet<string>\n}\n\n/**\n * Deterministic per-field diff of call arguments between passing and failing\n * rollouts. A field set by failing rollouts but left unset by passing ones is\n * the classic poison-input signature; a field whose values differ across the\n * split points at the correct value. Feed `text` to the reviser verbatim.\n */\nexport function rolloutArgumentDiff(\n rollouts: readonly ScoredRollout[],\n opts: RolloutArgumentDiffOptions = {},\n): RolloutArgumentDiff {\n const passThreshold = opts.passThreshold ?? 1\n const maxValues = opts.maxValuesPerField ?? 4\n const collect = (pass: boolean): Map<string, Set<string>> => {\n const byField = new Map<string, Set<string>>()\n for (const r of rollouts) {\n if (pass !== r.score >= passThreshold) continue\n for (const c of r.calls) {\n for (const [k, v] of Object.entries(c.args)) {\n const set = byField.get(k) ?? new Set<string>()\n set.add(String(v))\n byField.set(k, set)\n }\n }\n }\n return byField\n }\n const passing = collect(true)\n const failing = collect(false)\n const lines: string[] = []\n for (const field of new Set([...passing.keys(), ...failing.keys()])) {\n const pv = [...(passing.get(field) ?? [])].slice(0, maxValues)\n const fv = [...(failing.get(field) ?? [])].slice(0, maxValues)\n const render = (vals: string[]) => (vals.length ? JSON.stringify(vals) : 'NOT SET (omitted)')\n lines.push(` ${field}: passing runs -> ${render(pv)} | failing runs -> ${render(fv)}`)\n }\n const lower = (m: Map<string, Set<string>>): Set<string> => {\n const out = new Set<string>()\n for (const vals of m.values()) for (const v of vals) out.add(v.toLowerCase())\n return out\n }\n return {\n text: lines.join('\\n') || ' (no calls observed)',\n passingValues: lower(passing),\n failingValues: lower(failing),\n }\n}\n\nexport interface UngroundedLiteralReport {\n /** Quoted single-word literals in the text that no passing rollout used. */\n readonly ungrounded: readonly string[]\n /** The subset failing rollouts actually used - prescribing these is proven harmful. */\n readonly harmful: readonly string[]\n}\n\n/**\n * Scan revised artifact text for single-quoted single-word literals (the\n * \"use exactly 'new'\" pattern) that appear in no passing rollout's argument\n * values. Multi-word quotes pass (they are prose, not prescriptions).\n * Callers should reject on `harmful` (with a bounded retry) and at most log\n * `ungrounded` - see the module header for why the severities differ.\n */\nexport function classifyUngroundedLiterals(\n text: string,\n diff: Pick<RolloutArgumentDiff, 'passingValues' | 'failingValues'>,\n): UngroundedLiteralReport {\n const ungrounded = new Set<string>()\n for (const m of text.matchAll(/'([a-z][a-z_-]{1,19})'/gi)) {\n const w = (m[1] as string).toLowerCase()\n if (!diff.passingValues.has(w)) ungrounded.add(w)\n }\n const all = [...ungrounded]\n return {\n ungrounded: all,\n harmful: all.filter((w) => diff.failingValues.has(w)),\n }\n}\n","/**\n * Filesystem `LabeledScenarioStore` adapter. The default capture sink for\n * traces + eval artifacts. Production deployments typically swap for a\n * Turso/SQLite adapter (same interface).\n *\n * Records land as one JSONL file per source under `<root>/<source>.jsonl`.\n * Each line is a `LabeledScenarioRecord`. Append-only — no in-place edits.\n *\n * Safety properties enforced at write-time:\n *\n * - **Provenance required**: writes without `source`, `sourceVersionHash`,\n * `capturedAt`, `redactionStatus` are rejected. Closes the alignment\n * reviewer's data-poisoning gap.\n * - **Per-source rate limits**: optional `rateLimitBucket` + `maxWritesPerMinute`\n * stops a single tenant/source from flooding the store.\n *\n * Safety properties enforced at sample-time:\n *\n * - **Required split + capturedBefore**: substrate refuses to sample without\n * an explicit `split` ('train' | 'test') AND a temporal cutoff. Eliminates\n * accidental train/test contamination.\n * - **Default training-source filter**: when the store is sampled with\n * `split: 'train'`, production-trace records are EXCLUDED unless the\n * caller passes `filter.source: 'production-trace'` explicitly. Closes\n * the contamination-by-default gap flagged by the senior eval engineer.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type {\n LabeledScenarioRecord,\n LabeledScenarioSampleArgs,\n LabeledScenarioSource,\n LabeledScenarioStore,\n LabeledScenarioWrite,\n LabelTrust,\n} from '../types'\nimport { labelTrustRank } from '../types'\n\nexport interface FsLabeledScenarioStoreOptions {\n /** Root directory for JSONL files. Created if missing. */\n root: string\n /** Per-source rate limit. When set, writes exceeding the cap are rejected\n * with a typed error. Default: no limit. */\n maxWritesPerMinutePerBucket?: number\n /** Test seam — override `Date.now()` for deterministic tests. */\n now?: () => number\n}\n\n/** Typed rejection from a labeled-scenario store (bad provenance, rate limit, invalid sample args) — carries a stable string `code`. */\nexport class LabeledScenarioStoreError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message)\n this.name = 'LabeledScenarioStoreError'\n }\n}\n\ninterface RateLimitState {\n bucket: string\n windowStartMs: number\n count: number\n}\n\n/**\n * Filesystem `LabeledScenarioStore`: appends one JSONL file per source with provenance and\n * rate-limit guards. For tests, local dev, and small workloads — high-throughput lands in Turso.\n */\nexport class FsLabeledScenarioStore implements LabeledScenarioStore {\n private readonly now: () => number\n private readonly rateLimits = new Map<string, RateLimitState>()\n\n constructor(private readonly options: FsLabeledScenarioStoreOptions) {\n if (!existsSync(options.root)) mkdirSync(options.root, { recursive: true })\n this.now = options.now ?? Date.now\n }\n\n async observe(write: LabeledScenarioWrite): Promise<void> {\n this.assertProvenance(write)\n this.assertRateLimit(write)\n const record = this.toRecord(write)\n const path = this.pathForSource(write.source)\n const line = `${JSON.stringify(record)}\\n`\n // Append atomically. For high-throughput a writev-friendly buffered\n // implementation lands in the Turso adapter; FS adapter is for tests +\n // local dev + small workloads.\n appendLine(path, line)\n }\n\n async sample(args: LabeledScenarioSampleArgs): Promise<LabeledScenarioRecord[]> {\n if (!args.split) {\n throw new LabeledScenarioStoreError(\n 'split_required',\n 'sample() requires an explicit `split` (train | test) — substrate refuses ambiguous reads',\n )\n }\n if (!args.capturedBefore) {\n throw new LabeledScenarioStoreError(\n 'capturedBefore_required',\n 'sample() requires an explicit `capturedBefore` timestamp for temporal-split discipline',\n )\n }\n\n const all: LabeledScenarioRecord[] = []\n for (const source of ALL_SOURCES) {\n // Default training-source filter: when sampling train, EXCLUDE\n // production-trace records unless the caller asks for them.\n if (args.split === 'train' && source === 'production-trace') {\n const explicit = sourceFilterContains(args.filter?.source, 'production-trace')\n if (!explicit) continue\n }\n const path = this.pathForSource(source)\n if (!existsSync(path)) continue\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n for (const line of lines) {\n let record: LabeledScenarioRecord\n try {\n record = JSON.parse(line) as LabeledScenarioRecord\n } catch {\n continue\n }\n if (!matchesFilter(record, args, source)) continue\n all.push(record)\n }\n }\n\n // Deterministic order: by capturedAt ascending, then recordHash.\n all.sort((a, b) => {\n if (a.capturedAt !== b.capturedAt) return a.capturedAt.localeCompare(b.capturedAt)\n return a.recordHash.localeCompare(b.recordHash)\n })\n\n return all.slice(0, args.count)\n }\n\n async size(): Promise<{\n train: number\n test: number\n bySource: Record<string, number>\n byTrust: Record<LabelTrust, number>\n }> {\n const bySource: Record<string, number> = {}\n const byTrust: Record<LabelTrust, number> = {\n unverified: 0,\n 'verified-signal': 0,\n 'human-rated': 0,\n }\n let total = 0\n for (const source of ALL_SOURCES) {\n const path = this.pathForSource(source)\n if (!existsSync(path)) {\n bySource[source] = 0\n continue\n }\n const lines = readFileSync(path, 'utf8').split('\\n').filter(Boolean)\n bySource[source] = lines.length\n total += lines.length\n for (const line of lines) {\n let trust: LabelTrust = 'unverified'\n try {\n trust = (JSON.parse(line) as LabeledScenarioRecord).labelTrust ?? 'unverified'\n } catch {\n // A malformed line counts as unverified — never silently gold.\n }\n byTrust[trust] += 1\n }\n }\n // FS adapter doesn't track split assignments per-record (split is\n // computed at sample-time based on `capturedBefore`). For size(), we\n // report `train`+`test` as the same total — split is a sampling concept.\n return { train: total, test: total, bySource, byTrust }\n }\n\n private assertProvenance(write: LabeledScenarioWrite): void {\n if (!write.source) {\n throw new LabeledScenarioStoreError(\n 'missing_source',\n 'LabeledScenarioWrite requires `source`',\n )\n }\n if (!write.sourceVersionHash || write.sourceVersionHash.length === 0) {\n throw new LabeledScenarioStoreError(\n 'missing_source_version',\n 'LabeledScenarioWrite requires `sourceVersionHash` (git sha or substrate version)',\n )\n }\n if (!write.capturedAt) {\n throw new LabeledScenarioStoreError(\n 'missing_captured_at',\n 'LabeledScenarioWrite requires `capturedAt` ISO timestamp',\n )\n }\n if (!write.redactionStatus) {\n throw new LabeledScenarioStoreError(\n 'missing_redaction_status',\n 'LabeledScenarioWrite requires explicit `redactionStatus` — raw / redacted-pii / redacted-secrets / fully-redacted',\n )\n }\n if (!ALL_SOURCES.includes(write.source)) {\n throw new LabeledScenarioStoreError(\n 'unknown_source',\n `LabeledScenarioWrite.source must be one of: ${ALL_SOURCES.join(', ')}`,\n )\n }\n }\n\n private assertRateLimit(write: LabeledScenarioWrite): void {\n const cap = this.options.maxWritesPerMinutePerBucket\n if (!cap || !write.rateLimitBucket) return\n const now = this.now()\n const windowMs = 60_000\n let state = this.rateLimits.get(write.rateLimitBucket)\n if (!state || now - state.windowStartMs >= windowMs) {\n state = { bucket: write.rateLimitBucket, windowStartMs: now, count: 0 }\n this.rateLimits.set(write.rateLimitBucket, state)\n }\n if (state.count >= cap) {\n throw new LabeledScenarioStoreError(\n 'rate_limit_exceeded',\n `LabeledScenarioStore: bucket ${write.rateLimitBucket} exceeded ${cap} writes/min`,\n )\n }\n state.count += 1\n }\n\n private toRecord(write: LabeledScenarioWrite): LabeledScenarioRecord {\n const recordHash = sha256(\n JSON.stringify({\n id: write.scenario.id,\n src: write.source,\n at: write.capturedAt,\n ver: write.sourceVersionHash,\n }),\n )\n // FS adapter assigns split at sample-time, but we cache a hint here\n // based on capturedAt vs the world's \"now\" — sampler overrides this.\n return {\n ...write,\n recordHash,\n split: 'train',\n }\n }\n\n private pathForSource(source: string): string {\n return join(this.options.root, `${source}.jsonl`)\n }\n}\n\nconst ALL_SOURCES: LabeledScenarioWrite['source'][] = [\n 'production-trace',\n 'eval-run',\n 'manual',\n 'red-team',\n 'synthetic',\n]\n\nfunction sourceFilterContains(\n filter: LabeledScenarioSource | LabeledScenarioSource[] | undefined,\n needle: LabeledScenarioSource,\n): boolean {\n if (!filter) return false\n if (Array.isArray(filter)) return filter.includes(needle)\n return filter === needle\n}\n\nfunction matchesFilter(\n record: LabeledScenarioRecord,\n args: LabeledScenarioSampleArgs,\n source: string,\n): boolean {\n // Temporal cutoff — train must be capturedAt < capturedBefore.\n if (args.split === 'train' && record.capturedAt >= args.capturedBefore) return false\n if (args.split === 'test' && record.capturedAt < args.capturedBefore) return false\n\n const f = args.filter\n if (!f) return true\n if (f.kind && record.scenario.kind !== f.kind) return false\n if (f.source) {\n const sources = Array.isArray(f.source) ? f.source : [f.source]\n if (!sources.includes(source as never)) return false\n }\n if (f.minComposite !== undefined || f.maxComposite !== undefined) {\n const composites = Object.values(record.judgeScores).map((s) => s.composite)\n const max = composites.length === 0 ? 0 : Math.max(...composites)\n if (f.minComposite !== undefined && max < f.minComposite) return false\n if (f.maxComposite !== undefined && max > f.maxComposite) return false\n }\n if (f.minTrust !== undefined && labelTrustRank(record.labelTrust) < labelTrustRank(f.minTrust)) {\n return false\n }\n return true\n}\n\nfunction sha256(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 16)\n}\n\nfunction appendLine(path: string, line: string): void {\n if (existsSync(path)) {\n const existing = readFileSync(path, 'utf8')\n writeFileSync(path, existing + line)\n } else {\n writeFileSync(path, line)\n }\n}\n","/**\n * @module\n * Footprint-matched neutralization — the placebo control for content-vs-footprint\n * attribution in a promotion gate.\n *\n * A promoted surface can raise a held-out score two different ways:\n * 1. its CONTENT is informative (the thing we want to promote), or\n * 2. it merely added prompt/mount FOOTPRINT — more bytes, more lines, a longer\n * more authoritative-looking prompt — that the model spends attention on\n * regardless of what the bytes say.\n *\n * A held-out gate proves the candidate beat baseline; it cannot separate (1) from\n * (2). `neutralizeText` produces a variant that keeps the input's layout and\n * length while carrying ZERO information, so scoring it isolates the footprint\n * contribution (2). Feed the neutralized variant's scores to `neutralizationGate`:\n * any lift it still holds over baseline is decorative, and a candidate whose lift\n * survives neutralization is rejected however large its raw lift.\n */\n\n/** Filler for blanked content. A single ASCII byte, so a run of it preserves an\n * ASCII source's exact byte length; for multibyte sources it preserves CHARACTER\n * count and layout (what the tokenizer footprint tracks), not raw byte count. */\nconst FILLER = '#'\n\n/**\n * Blank every non-whitespace character to a 1-byte filler while preserving all\n * whitespace. Line count, indentation, and word/line lengths are unchanged — so\n * the neutralized variant has the same layout and (for ASCII) the same byte\n * footprint as the input, but no readable content. Whitespace is preserved\n * deliberately: collapsing it would change the token structure and stop the\n * variant from being a true footprint match.\n */\nexport function neutralizeText(content: string): string {\n return content.replace(/\\S/g, FILLER)\n}\n","/**\n * FAPO (Fully Autonomous Prompt Optimization) is an orchestration policy, not\n * a new prompt mutation primitive. The paper's loop evaluates an inspectable\n * workflow, attributes failures to an edit level, proposes ONE scoped change,\n * reviews it, measures it, and escalates from prompt -> parameters -> structure\n * only when prompt-level search is exhausted and attribution supports the\n * higher-cost edit.\n *\n * This substrate proposer encodes that policy while keeping the edit generators\n * pluggable:\n * - prompt: usually `gepaProposer`, `skillOptProposer`, or a runtime reflective proposer\n * - parameter: `parameterSweepProposer` or a caller-supplied config proposer\n * - structural: a caller-supplied code/worktree proposer from agent-runtime\n *\n * It deliberately does not import Claude Code, LangGraph, or Cisco's tenant\n * runtime. agent-eval owns measurement and proposer contracts; runtime-shaped\n * code generation stays downstream.\n *\n * Grounded sources:\n * - Kassianik et al., \"FAPO: Fully Autonomous Prompt Optimization of\n * Multi-Step LLM Pipelines\", arXiv:2606.19605v1.\n * - cisco-foundation-ai/fully-automated-prompt-optimization at\n * 376b50c57d5e2423e5a5de46e0d315a761d272d8.\n */\n\nimport type {\n GenerationCandidate,\n GenerationRecord,\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '../types'\nimport { isProposedCandidate } from '../types'\n\nexport type FapoOptimizationLevel = 'prompt' | 'parameter' | 'structural'\n\nconst FAPO_LEVELS: readonly FapoOptimizationLevel[] = ['prompt', 'parameter', 'structural']\nconst MAX_FINDING_DEPTH = 16\nconst UNSAFE_JSON_KEYS = new Set(['__proto__', 'prototype', 'constructor'])\n\nexport interface FapoScopeContract {\n /** Levels the tenant/playbook allows. Defaults to the levels with proposers. */\n allowedLevels?: readonly FapoOptimizationLevel[]\n /** Explicitly forbidden levels; wins over `allowedLevels`. */\n forbiddenLevels?: readonly FapoOptimizationLevel[]\n}\n\nexport interface FapoFailureCluster {\n label: string\n level: FapoOptimizationLevel\n count: number\n confidence?: 'high' | 'medium' | 'low'\n suggestedFix?: string\n caseIds?: string[]\n}\n\nexport interface FapoAttributionSignals {\n counts: Record<FapoOptimizationLevel, number>\n clusters: FapoFailureCluster[]\n}\n\nexport interface FapoReviewIssue {\n checkName: string\n severity: 'block' | 'warn'\n description: string\n location?: string\n}\n\nexport interface FapoReviewResult {\n verdict: 'pass' | 'warn' | 'fail'\n issues?: FapoReviewIssue[]\n suggestions?: string[]\n}\n\nexport interface FapoReviewInput<TFindings = unknown> {\n level: FapoOptimizationLevel\n candidate: ProposedCandidate\n context: ProposeContext<TFindings>\n reason: string\n}\n\nexport interface FapoProposerOptions<TFindings = unknown> {\n /** Level-specific candidate proposers. At least one is required. */\n proposers?: Partial<Record<FapoOptimizationLevel, SurfaceProposer<TFindings>>>\n /** Convenience aliases for `proposers.<level>`. */\n promptProposer?: SurfaceProposer<TFindings>\n parameterProposer?: SurfaceProposer<TFindings>\n structuralProposer?: SurfaceProposer<TFindings>\n /** Tenant/playbook-derived allowed and forbidden edit levels. */\n scope?: FapoScopeContract\n /**\n * Independent reviewer hook. Return `fail` to block a candidate before eval,\n * mirroring FAPO's variant-reviewer phase.\n */\n reviewCandidate?: (input: FapoReviewInput<TFindings>) => Promise<FapoReviewResult>\n /**\n * FAPO proposes one scoped change per cycle. Keep this at 1 unless you are\n * intentionally relaxing the paper loop for a batch experiment.\n */\n proposalsPerCycle?: number\n /** Consecutive non-improving variants required before a level is exhausted. Default 3. */\n plateauWindow?: number\n /** Distinct strategies required before declaring a plateau. Default 3. */\n minDistinctStrategies?: number\n /** Candidate score delta needed to count as an improvement. Default 0. */\n minImprovement?: number\n /** Paper-faithful default: try prompt edits before escalating. */\n promptFirst?: boolean\n /** Paper-faithful default: try parameter/config edits before structural code edits. */\n parameterBeforeStructural?: boolean\n}\n\ninterface FapoAttempt {\n level: FapoOptimizationLevel\n composite: number\n strategy: string\n}\n\ninterface FapoPolicyState {\n attempts: FapoAttempt[]\n exhausted: Record<FapoOptimizationLevel, boolean>\n signals: FapoAttributionSignals\n}\n\n/** Build a FAPO policy proposer from level-specific candidate generators. */\nexport function fapoProposer<TFindings = unknown>(\n opts: FapoProposerOptions<TFindings>,\n): SurfaceProposer<TFindings> {\n const proposers = levelProposers(opts)\n const allowed = allowedLevels(opts, proposers)\n const plateauWindow = opts.plateauWindow ?? 3\n const minDistinctStrategies = opts.minDistinctStrategies ?? 3\n const minImprovement = opts.minImprovement ?? 0\n const proposalsPerCycle = opts.proposalsPerCycle ?? 1\n\n if (allowed.length === 0) {\n throw new Error('fapoProposer: at least one allowed level must have a proposer')\n }\n if (plateauWindow < 1) throw new Error('fapoProposer: plateauWindow must be >= 1')\n if (minDistinctStrategies < 1) {\n throw new Error('fapoProposer: minDistinctStrategies must be >= 1')\n }\n if (proposalsPerCycle < 1) throw new Error('fapoProposer: proposalsPerCycle must be >= 1')\n\n return {\n kind: 'fapo',\n async propose(ctx: ProposeContext<TFindings>): Promise<ProposedCandidate[]> {\n const state = policyState(ctx.history, ctx.findings, {\n plateauWindow,\n minDistinctStrategies,\n minImprovement,\n })\n const decision = chooseLevel({\n allowed,\n available: allowed.filter((level) => !state.exhausted[level]),\n proposers,\n state,\n promptFirst: opts.promptFirst ?? true,\n parameterBeforeStructural: opts.parameterBeforeStructural ?? true,\n })\n if (!decision) return []\n\n const proposer = proposers[decision.level]\n if (!proposer) {\n throw new Error(`fapoProposer: selected ${decision.level} but no proposer is configured`)\n }\n\n const requested = Math.min(ctx.populationSize, proposalsPerCycle)\n const raw = await proposer.propose({ ...ctx, populationSize: requested })\n const wrapped = raw\n .map((candidate) => normalizeProposal(candidate))\n .map((candidate) => wrapProposal(candidate, decision.level, decision.reason))\n\n const reviewed: ProposedCandidate[] = []\n for (const candidate of wrapped) {\n const review = opts.reviewCandidate\n ? await opts.reviewCandidate({\n level: decision.level,\n candidate,\n context: ctx,\n reason: decision.reason,\n })\n : { verdict: 'pass' as const }\n if (review.verdict === 'fail') continue\n const warn = review.verdict === 'warn' ? renderReviewWarnings(review) : ''\n reviewed.push(\n warn ? { ...candidate, rationale: `${candidate.rationale}\\n${warn}` } : candidate,\n )\n }\n\n if (wrapped.length > 0 && reviewed.length === 0) {\n throw new Error(\n `fapoProposer: reviewer blocked every ${decision.level} candidate; refusing to evaluate an unreviewed variant`,\n )\n }\n return reviewed\n },\n decide({ history }) {\n const last = history[history.length - 1]\n if (last && last.candidates.length === 0) {\n return { stop: true, reason: 'FAPO produced no scoped candidate in the prior generation' }\n }\n const state = policyState(history, [], {\n plateauWindow,\n minDistinctStrategies,\n minImprovement,\n })\n const everyAllowedLevelExhausted = allowed.every((level) => state.exhausted[level])\n return everyAllowedLevelExhausted\n ? { stop: true, reason: `all FAPO levels exhausted (${allowed.join(', ')})` }\n : { stop: false }\n },\n }\n}\n\nfunction levelProposers<TFindings>(\n opts: FapoProposerOptions<TFindings>,\n): Partial<Record<FapoOptimizationLevel, SurfaceProposer<TFindings>>> {\n return {\n ...(opts.proposers ?? {}),\n ...(opts.promptProposer ? { prompt: opts.promptProposer } : {}),\n ...(opts.parameterProposer ? { parameter: opts.parameterProposer } : {}),\n ...(opts.structuralProposer ? { structural: opts.structuralProposer } : {}),\n }\n}\n\nfunction allowedLevels<TFindings>(\n opts: FapoProposerOptions<TFindings>,\n proposers: Partial<Record<FapoOptimizationLevel, SurfaceProposer<TFindings>>>,\n): FapoOptimizationLevel[] {\n const explicit = opts.scope?.allowedLevels\n const forbidden = new Set(opts.scope?.forbiddenLevels ?? [])\n return FAPO_LEVELS.filter((level) => {\n if (!proposers[level]) return false\n if (forbidden.has(level)) return false\n return explicit ? explicit.includes(level) : true\n })\n}\n\nfunction policyState(\n history: readonly GenerationRecord[],\n findings: readonly unknown[],\n opts: { plateauWindow: number; minDistinctStrategies: number; minImprovement: number },\n): FapoPolicyState {\n const attempts = extractAttempts(history)\n return {\n attempts,\n exhausted: {\n prompt: isLevelExhausted('prompt', attempts, opts),\n parameter: isLevelExhausted('parameter', attempts, opts),\n structural: isLevelExhausted('structural', attempts, opts),\n },\n signals: extractFapoAttributionSignals(findings),\n }\n}\n\nfunction extractAttempts(history: readonly GenerationRecord[]): FapoAttempt[] {\n const attempts: FapoAttempt[] = []\n for (const generation of history) {\n for (const candidate of generation.candidates) {\n const level = candidateLevel(candidate)\n if (!level) continue\n attempts.push({\n level,\n composite: candidate.composite,\n strategy: candidateStrategy(candidate),\n })\n }\n }\n return attempts\n}\n\nfunction candidateLevel(candidate: GenerationCandidate): FapoOptimizationLevel | null {\n const label = candidate.label ?? ''\n const rationale = candidate.rationale ?? ''\n return parseLevel(label) ?? parseLevel(rationale)\n}\n\nfunction parseLevel(text: string): FapoOptimizationLevel | null {\n const match = /\\bfapo:(prompt|parameter|structural)\\b/.exec(text)\n return match ? (match[1] as FapoOptimizationLevel) : null\n}\n\nfunction candidateStrategy(candidate: GenerationCandidate): string {\n const label = candidate.label ?? candidate.rationale ?? candidate.surfaceHash\n return (\n label.replace(/\\bfapo:(prompt|parameter|structural):?/g, '').trim() || candidate.surfaceHash\n )\n}\n\nfunction isLevelExhausted(\n level: FapoOptimizationLevel,\n attempts: readonly FapoAttempt[],\n opts: { plateauWindow: number; minDistinctStrategies: number; minImprovement: number },\n): boolean {\n const own = attempts.filter((attempt) => attempt.level === level)\n if (own.length < opts.plateauWindow) return false\n const distinctStrategies = new Set(own.map((attempt) => attempt.strategy)).size\n if (distinctStrategies < opts.minDistinctStrategies) return false\n\n let best = Number.NEGATIVE_INFINITY\n let nonImproving = 0\n for (const attempt of own) {\n if (attempt.composite > best + opts.minImprovement) {\n best = attempt.composite\n nonImproving = 0\n } else {\n nonImproving += 1\n }\n }\n return nonImproving >= opts.plateauWindow\n}\n\nfunction chooseLevel<TFindings>(args: {\n allowed: readonly FapoOptimizationLevel[]\n available: readonly FapoOptimizationLevel[]\n proposers: Partial<Record<FapoOptimizationLevel, SurfaceProposer<TFindings>>>\n state: FapoPolicyState\n promptFirst: boolean\n parameterBeforeStructural: boolean\n}): { level: FapoOptimizationLevel; reason: string } | null {\n const { available, state } = args\n if (available.length === 0) return null\n\n const triedPrompt = state.attempts.some((attempt) => attempt.level === 'prompt')\n if (args.promptFirst && available.includes('prompt') && !triedPrompt) {\n return {\n level: 'prompt',\n reason: 'prompt-first policy: no prompt-level variant has been tried yet',\n }\n }\n\n const supported = available.filter((level) => state.signals.counts[level] > 0)\n if (supported.includes('prompt')) {\n return {\n level: 'prompt',\n reason: `attribution has ${state.signals.counts.prompt} prompt-addressable failure(s)`,\n }\n }\n\n const strongest = supported.sort(\n (a, b) => state.signals.counts[b] - state.signals.counts[a] || levelRank(a) - levelRank(b),\n )[0]\n if (strongest) {\n if (\n strongest === 'structural' &&\n args.parameterBeforeStructural &&\n available.includes('parameter') &&\n args.proposers.parameter\n ) {\n return {\n level: 'parameter',\n reason:\n 'attribution indicates a non-prompt bottleneck; trying parameter/config edits before structural edits',\n }\n }\n return {\n level: strongest,\n reason: `attribution has ${state.signals.counts[strongest]} ${strongest}-addressable failure(s)`,\n }\n }\n\n // No usable attribution yet. FAPO can still start at the cheapest allowed\n // level, but it should not silently jump to structure after prompt exhausts.\n if (state.attempts.length === 0) {\n const first = available.slice().sort((a, b) => levelRank(a) - levelRank(b))[0]!\n return { level: first, reason: 'no attribution yet; starting at the cheapest allowed level' }\n }\n return null\n}\n\nfunction levelRank(level: FapoOptimizationLevel): number {\n return level === 'prompt' ? 0 : level === 'parameter' ? 1 : 2\n}\n\nfunction normalizeProposal(value: MutableSurface | ProposedCandidate): ProposedCandidate {\n return isProposedCandidate(value)\n ? value\n : { surface: value, label: 'candidate', rationale: 'bare candidate from level proposer' }\n}\n\nfunction wrapProposal(\n candidate: ProposedCandidate,\n level: FapoOptimizationLevel,\n reason: string,\n): ProposedCandidate {\n const label = candidate.label ? `fapo:${level}:${candidate.label}` : `fapo:${level}`\n return {\n ...candidate,\n label,\n rationale: [\n `fapo:${level} selected by reviewed escalation policy`,\n `Reason: ${reason}`,\n candidate.rationale ? `Level proposer rationale: ${candidate.rationale}` : '',\n ]\n .filter(Boolean)\n .join('\\n'),\n }\n}\n\nfunction renderReviewWarnings(review: FapoReviewResult): string {\n const issues = review.issues?.filter((issue) => issue.severity === 'warn') ?? []\n if (issues.length === 0) return ''\n return `Reviewer warnings:\\n${issues.map((issue) => `- ${issue.checkName}: ${issue.description}`).join('\\n')}`\n}\n\n/**\n * Scan a findings array and extract FAPO attribution signals — per-level counts and failure clusters used to decide which optimization level to escalate to next.\n */\nexport function extractFapoAttributionSignals(\n findings: readonly unknown[],\n): FapoAttributionSignals {\n const signals: FapoAttributionSignals = {\n counts: { prompt: 0, parameter: 0, structural: 0 },\n clusters: [],\n }\n const seen = new WeakSet<object>()\n for (const finding of findings) {\n collectFinding(signals, finding, seen, 0)\n }\n return signals\n}\n\nfunction collectFinding(\n signals: FapoAttributionSignals,\n finding: unknown,\n seen: WeakSet<object>,\n depth: number,\n): void {\n if (depth > MAX_FINDING_DEPTH) return\n if (!finding) return\n if (typeof finding === 'string') {\n const level = inferLevelFromText(finding)\n if (level) addCluster(signals, { label: finding, level, count: 1 })\n return\n }\n if (Array.isArray(finding)) {\n if (seen.has(finding)) return\n seen.add(finding)\n for (const item of finding) collectFinding(signals, item, seen, depth + 1)\n return\n }\n if (typeof finding !== 'object') return\n if (seen.has(finding)) return\n seen.add(finding)\n const obj = finding as Record<string, unknown>\n\n collectLevelPartition(signals, obj.level_partition ?? obj.levelPartition, seen, depth + 1)\n collectCounts(signals, obj)\n collectClusters(signals, obj.clusters, true, seen, depth + 1)\n\n const explicit = parseFindingLevel(obj.level ?? obj.optimization_level ?? obj.optimizationLevel)\n const text = textFields(obj)\n const inferred = explicit ?? inferLevelFromText(text)\n if (inferred) {\n addCluster(signals, {\n label: text || inferred,\n level: inferred,\n count: numberField(obj.count) ?? 1,\n confidence: confidenceField(obj.confidence),\n suggestedFix: stringField(obj.suggested_fix ?? obj.suggestedFix ?? obj.recommended_action),\n caseIds: stringArrayField(obj.case_ids ?? obj.caseIds),\n })\n }\n}\n\nfunction collectLevelPartition(\n signals: FapoAttributionSignals,\n raw: unknown,\n seen: WeakSet<object>,\n depth: number,\n): void {\n if (!raw || typeof raw !== 'object') return\n if (seen.has(raw)) return\n seen.add(raw)\n const partition = raw as Record<string, unknown>\n for (const level of FAPO_LEVELS) {\n const bucket = partition[level]\n if (!bucket || typeof bucket !== 'object') continue\n const obj = bucket as Record<string, unknown>\n const count = numberField(obj.count) ?? 0\n if (count > 0) signals.counts[level] += count\n collectClusters(signals, obj.clusters, false, seen, depth + 1)\n }\n}\n\nfunction collectCounts(signals: FapoAttributionSignals, obj: Record<string, unknown>): void {\n const prompt = numberField(obj.prompt_addressable ?? obj.promptAddressable)\n const structural = numberField(obj.structural_addressable ?? obj.structuralAddressable)\n const tool = numberField(obj.tool_addressable ?? obj.toolAddressable)\n if (prompt) signals.counts.prompt += prompt\n if (structural) signals.counts.structural += structural\n if (tool) signals.counts.structural += tool\n}\n\nfunction collectClusters(\n signals: FapoAttributionSignals,\n raw: unknown,\n countClusters: boolean,\n seen: WeakSet<object>,\n depth: number,\n): void {\n if (!Array.isArray(raw)) return\n if (seen.has(raw)) return\n seen.add(raw)\n for (const item of raw) {\n if (countClusters) {\n collectFinding(signals, item, seen, depth + 1)\n continue\n }\n const cluster = parseCluster(item)\n if (cluster) signals.clusters.push(cluster)\n }\n}\n\nfunction addCluster(signals: FapoAttributionSignals, cluster: FapoFailureCluster): void {\n signals.counts[cluster.level] += Math.max(1, cluster.count)\n signals.clusters.push(cluster)\n}\n\nfunction parseCluster(raw: unknown): FapoFailureCluster | null {\n if (!raw || typeof raw !== 'object') return null\n const obj = raw as Record<string, unknown>\n const text = textFields(obj)\n const level =\n parseFindingLevel(obj.level ?? obj.optimization_level ?? obj.optimizationLevel) ??\n inferLevelFromText(text)\n if (!level) return null\n return {\n label: text || level,\n level,\n count: numberField(obj.count) ?? 1,\n confidence: confidenceField(obj.confidence),\n suggestedFix: stringField(obj.suggested_fix ?? obj.suggestedFix ?? obj.recommended_action),\n caseIds: stringArrayField(obj.case_ids ?? obj.caseIds),\n }\n}\n\nfunction parseFindingLevel(raw: unknown): FapoOptimizationLevel | null {\n if (typeof raw !== 'string') return null\n const lower = raw.toLowerCase()\n if (lower === 'prompt' || lower === 'parameter' || lower === 'structural') return lower\n if (lower === 'chain' || lower === 'tool' || lower === 'code') return 'structural'\n if (lower === 'config' || lower === 'params') return 'parameter'\n return null\n}\n\nfunction inferLevelFromText(text: string): FapoOptimizationLevel | null {\n const lower = text.toLowerCase()\n if (\n /\\b(retrieval_k|temperature|top_p|max_tokens|max_completion_tokens|reasoning_effort|config|parameter)\\b/.test(\n lower,\n )\n ) {\n return 'parameter'\n }\n if (\n /\\b(retriev\\w*|search\\w*|bm25|hop|evidence|cascade|tool|node|chain|state|structur\\w*|topology|import)\\b/.test(\n lower,\n )\n ) {\n return 'structural'\n }\n if (\n /\\b(format\\w*|verbose|brevity|abstain\\w*|reasoning|instruction|prompt|output|answer)\\b/.test(\n lower,\n )\n ) {\n return 'prompt'\n }\n return null\n}\n\nfunction textFields(obj: Record<string, unknown>): string {\n return [\n obj.label,\n obj.claim,\n obj.recommended_action,\n obj.suggested_fix,\n obj.suggestedFix,\n obj.message,\n obj.text,\n obj.heuristic,\n obj.area,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n}\n\nfunction numberField(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction confidenceField(value: unknown): FapoFailureCluster['confidence'] {\n return value === 'high' || value === 'medium' || value === 'low' ? value : undefined\n}\n\nfunction stringArrayField(value: unknown): string[] | undefined {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : undefined\n}\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }\n\nexport interface ParameterChange {\n path: string | readonly string[]\n value: JsonValue\n}\n\nexport interface ParameterCandidate {\n label: string\n rationale: string\n /** Deep-merged into the current JSON surface. */\n patch?: Record<string, JsonValue>\n /** Dot-path writes, e.g. `{ path: 'retrieval.k', value: 10 }`. */\n changes?: readonly ParameterChange[]\n}\n\nexport interface ParameterSweepProposerOptions {\n candidates: readonly ParameterCandidate[]\n /** Optional parser for non-JSON config surface strings. */\n parse?: (surface: string) => Record<string, JsonValue>\n /** Optional serializer for non-JSON config surface strings. */\n stringify?: (config: Record<string, JsonValue>) => string\n}\n\n/** Config/parameter-level proposer for FAPO's middle escalation level. */\nexport function parameterSweepProposer(opts: ParameterSweepProposerOptions): SurfaceProposer {\n if (opts.candidates.length === 0) {\n throw new Error('parameterSweepProposer: candidates must not be empty')\n }\n return {\n kind: 'parameter-sweep',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n if (typeof ctx.currentSurface !== 'string') {\n throw new Error(\n 'parameterSweepProposer: currentSurface must be a JSON string config surface',\n )\n }\n const parse = opts.parse ?? parseJsonObject\n const stringify =\n opts.stringify ?? ((config: Record<string, JsonValue>) => JSON.stringify(config, null, 2))\n const current = parse(ctx.currentSurface)\n const currentCanonical = canonicalJson(current)\n const tried = triedLabels(ctx.history)\n const out: ProposedCandidate[] = []\n for (const candidate of opts.candidates) {\n if (tried.has(candidate.label)) continue\n const next = applyParameterCandidate(current, candidate)\n const surface = stringify(next)\n if (surface === ctx.currentSurface || canonicalJson(next) === currentCanonical) continue\n out.push({ surface, label: candidate.label, rationale: candidate.rationale })\n if (out.length >= ctx.populationSize) break\n }\n return out\n },\n }\n}\n\nfunction parseJsonObject(surface: string): Record<string, JsonValue> {\n let parsed: unknown\n try {\n parsed = JSON.parse(surface)\n } catch (error) {\n throw new Error(\n `parameterSweepProposer: currentSurface must be valid JSON object config (${error instanceof Error ? error.message : String(error)})`,\n )\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('parameterSweepProposer: JSON surface must parse to an object')\n }\n return parsed as Record<string, JsonValue>\n}\n\nfunction triedLabels(history: readonly GenerationRecord[]): Set<string> {\n const tried = new Set<string>()\n for (const generation of history) {\n for (const candidate of generation.candidates) {\n if (!candidate.label) continue\n tried.add(candidate.label)\n tried.add(candidateStrategy(candidate))\n }\n }\n return tried\n}\n\nfunction applyParameterCandidate(\n current: Record<string, JsonValue>,\n candidate: ParameterCandidate,\n): Record<string, JsonValue> {\n const next = cloneJsonObject(current)\n if (candidate.patch) deepMerge(next, candidate.patch)\n for (const change of candidate.changes ?? []) {\n setPath(\n next,\n typeof change.path === 'string' ? change.path.split('.') : [...change.path],\n change.value,\n )\n }\n return next\n}\n\nfunction cloneJsonObject(value: Record<string, JsonValue>): Record<string, JsonValue> {\n return JSON.parse(JSON.stringify(value)) as Record<string, JsonValue>\n}\n\nfunction deepMerge(target: Record<string, JsonValue>, patch: Record<string, JsonValue>): void {\n for (const [key, value] of Object.entries(patch)) {\n assertSafeJsonKey(key)\n if (isPlainObject(value) && isPlainObject(target[key])) {\n deepMerge(target[key] as Record<string, JsonValue>, value as Record<string, JsonValue>)\n } else {\n target[key] = value\n }\n }\n}\n\nfunction setPath(target: Record<string, JsonValue>, path: string[], value: JsonValue): void {\n if (path.length === 0) throw new Error('parameterSweepProposer: change path must not be empty')\n for (const part of path) assertSafeJsonKey(part)\n let cursor: Record<string, JsonValue> = target\n for (const part of path.slice(0, -1)) {\n const existing = cursor[part]\n if (!isPlainObject(existing)) {\n cursor[part] = {}\n }\n cursor = cursor[part] as Record<string, JsonValue>\n }\n cursor[path[path.length - 1]!] = value\n}\n\nfunction assertSafeJsonKey(key: string): void {\n if (!key.trim()) throw new Error('parameterSweepProposer: change path contains an empty key')\n if (UNSAFE_JSON_KEYS.has(key)) {\n throw new Error(`parameterSweepProposer: unsafe JSON key \"${key}\" is not allowed`)\n }\n}\n\nfunction canonicalJson(value: JsonValue | Record<string, JsonValue>): string {\n if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`\n if (isPlainObject(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key]!)}`)\n .join(',')}}`\n }\n return JSON.stringify(value)\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, JsonValue> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n","/**\n * SkillOpt patch primitives (Microsoft, arXiv:2605.23904 — \"Executive\n * Strategy for Self-Evolving Agent Skills\"). Where GEPA regenerates a surface\n * by reflection, SkillOpt emits BOUNDED, anchored edits to ONE skill document\n * — add / delete / replace — and accepts an edit only if it strictly improves\n * a held-out score. Bounded edits are the \"textual learning rate\": small,\n * reversible, and cheap to accept/reject, so a good rule introduced earlier is\n * not overwritten by a later sweeping rewrite.\n *\n * This module applies a patch deterministically and reports, per op, what\n * applied and what could not (a missing anchor is a rejected op, never a\n * silently dropped one). Pure, no I/O.\n */\n\n/** A single bounded edit against a skill surface.\n * - `add` — insert `text` after the first line containing `after`\n * (append to the end when `after` is absent/empty).\n * - `delete` — remove the first line containing `anchor`.\n * - `replace` — replace the first line containing `anchor` with `text`.\n * `text` may be multi-line; it is spliced in as multiple lines. Anchors match\n * the FIRST line that contains the substring (deterministic; SkillOpt is\n * expected to anchor on unique text). */\nexport type SkillPatchOp =\n | { op: 'add'; after?: string; text: string }\n | { op: 'delete'; anchor: string }\n | { op: 'replace'; anchor: string; text: string }\n\n/** A named, attributable bundle of ops the optimizer proposes as one edit. */\nexport interface SkillPatch {\n label: string\n rationale: string\n ops: SkillPatchOp[]\n}\n\nexport interface SkillPatchRejection {\n op: SkillPatchOp\n reason: string\n}\n\nexport interface ApplySkillPatchResult {\n surface: string\n /** Count of ops that mutated the surface. */\n applied: number\n /** Ops that could not apply (unanchored / empty), with the reason. The\n * surface still reflects every APPLIED op — partial application is honest,\n * and the caller decides whether a partial patch is worth scoring. */\n rejected: SkillPatchRejection[]\n}\n\n/**\n * Apply a SkillOpt patch to a text surface. Ops apply in array order against\n * the evolving line buffer (an `add after X` followed by a `delete X` sees the\n * inserted lines). A missing anchor rejects only that op; the rest still apply.\n */\nexport function applySkillPatch(surface: string, patch: SkillPatch): ApplySkillPatchResult {\n let lines = surface.split('\\n')\n let applied = 0\n const rejected: SkillPatchRejection[] = []\n const findLine = (anchor: string): number => lines.findIndex((l) => l.includes(anchor))\n\n for (const op of patch.ops) {\n if (op.op === 'add') {\n if (typeof op.text !== 'string' || op.text.trim() === '') {\n rejected.push({ op, reason: 'empty add text' })\n continue\n }\n const insert = op.text.split('\\n')\n if (op.after === undefined || op.after === '') {\n lines = [...lines, ...insert]\n applied++\n continue\n }\n const idx = findLine(op.after)\n if (idx === -1) {\n rejected.push({ op, reason: `add anchor not found: ${truncate(op.after)}` })\n continue\n }\n lines = [...lines.slice(0, idx + 1), ...insert, ...lines.slice(idx + 1)]\n applied++\n } else if (op.op === 'delete') {\n const idx = findLine(op.anchor)\n if (idx === -1) {\n rejected.push({ op, reason: `delete anchor not found: ${truncate(op.anchor)}` })\n continue\n }\n lines = [...lines.slice(0, idx), ...lines.slice(idx + 1)]\n applied++\n } else {\n // replace\n const idx = findLine(op.anchor)\n if (idx === -1) {\n rejected.push({ op, reason: `replace anchor not found: ${truncate(op.anchor)}` })\n continue\n }\n if (typeof op.text !== 'string') {\n rejected.push({ op, reason: 'replace text missing' })\n continue\n }\n lines = [...lines.slice(0, idx), ...op.text.split('\\n'), ...lines.slice(idx + 1)]\n applied++\n }\n }\n\n return { surface: lines.join('\\n'), applied, rejected }\n}\n\n/** Total ops in a patch — the edit-budget axis (SkillOpt's \"textual learning\n * rate\" caps this per epoch). */\nexport function patchEditCount(patch: SkillPatch): number {\n return patch.ops.length\n}\n\nfunction truncate(s: string, max = 48): string {\n return s.length <= max ? s : `${s.slice(0, max)}…`\n}\n","/**\n * `skillOptProposer` — a patch-mode `SurfaceProposer` implementing SkillOpt\n * (Microsoft, arXiv:2605.23904). Where `gepaProposer` regenerates the whole\n * surface by reflection, SkillOpt proposes BOUNDED, anchored edits\n * (add/delete/replace) to ONE skill document, so a good rule introduced\n * earlier is not clobbered by a later sweeping rewrite. The edit budget is the\n * paper's \"textual learning rate\"; a rejected-edit buffer + a slow-update\n * meta-note steer the optimizer away from dead ends.\n *\n * This module is the PROPOSER — the LLM call that turns evidence into\n * structured patches. The accept-only-if-held-out-improves loop, the budget\n * annealing, and the rejected buffer live in the `runSkillOpt` preset, which\n * owns the epoch hill-climb. The proposer also conforms to `SurfaceProposer`\n * (`propose` applies its patches to the current surface and returns the\n * candidate surfaces) so it is a drop-in for `runOptimization` and a fair\n * entrant in `compareProposers`.\n */\n\nimport { CostLedger, type CostLedgerHandle } from '../../cost-ledger'\nimport {\n callLlm,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from '../../llm-client'\nimport { renderAnalystEvidence } from '../../reflective-mutation'\nimport { applySkillPatch, type SkillPatch, type SkillPatchOp } from '../skill-patch'\nimport type { ProposeContext, ProposedCandidate, SurfaceProposer } from '../types'\n\nconst SKILLOPT_SYSTEM =\n 'You are a SkillOpt optimizer. You improve ONE skill document by proposing ' +\n 'BOUNDED, anchored edits — never a full rewrite. Output ONLY a JSON object of ' +\n 'shape {\"patches\":[{\"label\":string,\"rationale\":string,\"ops\":[op,...]}]} where ' +\n 'each op is one of: {\"op\":\"add\",\"after\":<exact substring of an existing line, ' +\n 'or omit to append>,\"text\":<new line(s)>}, {\"op\":\"delete\",\"anchor\":<exact ' +\n 'substring of the line to remove>}, {\"op\":\"replace\",\"anchor\":<exact substring ' +\n 'of the line to replace>,\"text\":<replacement line(s)>}. Anchors MUST be ' +\n 'verbatim substrings of lines that exist in the document. No prose outside JSON.'\n\n/** Evidence the optimizer reflects on: where the current surface is weakest.\n * Computed by the caller (the preset uses a TRAIN campaign so proposals never\n * see the held-out split; the generic loop derives it from history). */\nexport interface SkillOptEvidence {\n /** Lowest-scoring scenarios (drives WHICH behavior to patch). */\n weakScenarios: Array<{ scenarioId: string; composite: number }>\n /** Lowest-scoring judge dimensions (drives WHAT to patch for). */\n weakDimensions: Array<{ dimension: string; score: number }>\n}\n\n/** A patch that was tried and not accepted — fed back to the model so it does\n * not re-propose a dead end (SkillOpt's rejected-edit buffer). */\nexport interface RejectedEdit {\n label: string\n rationale: string\n reason: string\n}\n\nexport interface ProposePatchesArgs {\n surface: string\n evidence: SkillOptEvidence\n /** Max ops per patch this round (the annealed textual learning rate). */\n editBudget: number\n rejectedBuffer: RejectedEdit[]\n /** Slow-update meta guidance accumulated across epochs. */\n metaNote?: string\n /** Analyst findings + research report rendered as a prompt block so a patch\n * targets a NAMED diagnosed root cause. Built by\n * the proposer from `ctx.findings`/`ctx.report`; the patch-native `runSkillOpt`\n * path may also supply it. */\n findingsNote?: string\n /** How many candidate patches to propose. */\n count: number\n signal: AbortSignal\n costLedger?: CostLedgerHandle\n costPhase?: string\n}\n\nexport interface SkillOptProposerOptions {\n llm: LlmClientOptions\n model: string\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n /** What the skill document governs — orients the prompt. */\n target: string\n /** Default ops-per-patch cap when used as a bare `SurfaceProposer`. The\n * `runSkillOpt` preset overrides this per epoch as it anneals. Default 3. */\n editBudget?: number\n temperature?: number\n maxTokens?: number\n /** Top-K weak scenarios/dimensions surfaced as evidence. Default 3. */\n evidenceK?: number\n}\n\nexport interface SkillOptProposer extends SurfaceProposer {\n /** Patch-native path used by `runSkillOpt` (the SkillOpt epoch loop owns\n * acceptance/budget/buffer). Returns structured patches, NOT surfaces. */\n proposePatches(args: ProposePatchesArgs): Promise<SkillPatch[]>\n}\n\n/**\n * SkillOpt proposer: proposes bounded, anchored patch operations (add/delete/replace) on a skill document, conforming to both the patch-native `SkillOptProposer` and the generic `SurfaceProposer` interfaces.\n */\nexport function skillOptProposer(opts: SkillOptProposerOptions): SkillOptProposer {\n const evidenceK = opts.evidenceK ?? 3\n const defaultBudget = opts.editBudget ?? 3\n const directCostLedger = opts.costLedger ?? new CostLedger()\n\n async function proposePatches(args: ProposePatchesArgs): Promise<SkillPatch[]> {\n const userPrompt = buildPatchPrompt({\n target: opts.target,\n surface: args.surface,\n evidence: args.evidence,\n editBudget: args.editBudget,\n rejectedBuffer: args.rejectedBuffer,\n metaNote: args.metaNote,\n findingsNote: args.findingsNote,\n count: args.count,\n })\n const request: LlmCallRequest = {\n model: opts.model,\n messages: [\n { role: 'system', content: SKILLOPT_SYSTEM },\n { role: 'user', content: userPrompt },\n ],\n jsonMode: true,\n temperature: opts.temperature ?? 0.6,\n maxTokens: opts.maxTokens ?? 4000,\n }\n const paid = await (args.costLedger ?? directCostLedger).runPaidCall({\n channel: 'driver',\n phase: args.costPhase ?? 'search.proposal',\n actor: 'skill-opt.propose',\n model: opts.model,\n maximumCharge: maximumChargeForLlmRequest(request, opts.llm),\n signal: args.signal,\n execute: (signal, callId) =>\n callLlm(request, { ...opts.llm, signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const result = paid.value\n return parseSkillPatchResponse(result.content, args.count, args.editBudget)\n }\n\n return {\n kind: 'skill-opt',\n proposePatches,\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n if (typeof ctx.currentSurface !== 'string') {\n throw new Error(\n 'skillOptProposer: surface must be a string skill document (got a CodeSurface). SkillOpt patches text.',\n )\n }\n const surface = ctx.currentSurface\n const patches = await proposePatches({\n surface,\n evidence: evidenceFromHistory(ctx, evidenceK),\n editBudget: defaultBudget,\n rejectedBuffer: [],\n findingsNote: renderAnalystEvidence(ctx.findings, ctx.report) ?? undefined,\n count: ctx.populationSize,\n signal: ctx.signal,\n costLedger: ctx.costLedger ?? directCostLedger,\n costPhase: ctx.costPhase ?? 'search.proposal',\n })\n const out: ProposedCandidate[] = []\n const seen = new Set<string>()\n for (const patch of patches) {\n const { surface: candidate, applied } = applySkillPatch(surface, patch)\n if (applied === 0 || candidate === surface || seen.has(candidate)) continue\n seen.add(candidate)\n out.push({ surface: candidate, label: patch.label, rationale: patch.rationale })\n if (out.length >= ctx.populationSize) break\n }\n return out\n },\n }\n}\n\n/** Derive evidence from the loop's generation history (generic-proposer path):\n * the prior best candidate's worst scenarios + weakest dimensions. Empty on\n * generation 0. */\nfunction evidenceFromHistory(ctx: ProposeContext, k: number): SkillOptEvidence {\n const last = ctx.history.at(-1)\n if (!last || last.candidates.length === 0) return { weakScenarios: [], weakDimensions: [] }\n const best = [...last.candidates].sort((a, b) => b.composite - a.composite)[0]\n if (!best) return { weakScenarios: [], weakDimensions: [] }\n const weakScenarios = [...best.scenarios].sort((a, b) => a.composite - b.composite).slice(0, k)\n const weakDimensions = Object.entries(best.dimensions)\n .sort((a, b) => a[1] - b[1])\n .slice(0, k)\n .map(([dimension, score]) => ({ dimension, score }))\n return { weakScenarios, weakDimensions }\n}\n\nfunction buildPatchPrompt(args: {\n target: string\n surface: string\n evidence: SkillOptEvidence\n editBudget: number\n rejectedBuffer: RejectedEdit[]\n metaNote?: string\n findingsNote?: string\n count: number\n}): string {\n const lines: string[] = [\n `Skill document governs: ${args.target}.`,\n '',\n 'Current skill document:',\n '```',\n args.surface,\n '```',\n '',\n `Propose ${args.count} candidate patch(es). Each patch is a SMALL bundle of`,\n `at most ${args.editBudget} op(s). Anchors must be verbatim substrings of`,\n 'existing lines. Prefer adding a specific missing rule or sharpening a vague',\n 'one over deleting; never rewrite the whole document.',\n ]\n if (args.evidence.weakScenarios.length > 0) {\n lines.push(\n '',\n 'Weakest scenarios (patch to fix these):',\n ...args.evidence.weakScenarios.map((s) => `- ${s.scenarioId} (${s.composite.toFixed(2)})`),\n )\n }\n if (args.evidence.weakDimensions.length > 0) {\n lines.push(\n '',\n 'Weakest dimensions (what to improve):',\n ...args.evidence.weakDimensions.map((d) => `- ${d.dimension} (${d.score.toFixed(2)})`),\n )\n }\n if (args.rejectedBuffer.length > 0) {\n lines.push(\n '',\n 'Already tried and REJECTED (do not repeat or restate these edits):',\n ...args.rejectedBuffer.map((e) => `- ${e.label}: ${e.rationale} — ${e.reason}`),\n )\n }\n if (args.findingsNote) {\n lines.push('', args.findingsNote)\n }\n if (args.metaNote) {\n lines.push('', `Strategy note from prior epochs: ${args.metaNote}`)\n }\n return lines.join('\\n')\n}\n\n/** Parse + validate the patch response. Throws `SkillPatchParseError` when the\n * response is not valid JSON at all (a router/model failure the caller must\n * see — never a silent no-op epoch). Returns `[]` only for the legitimate\n * \"valid JSON, zero usable patches\" case. Malformed ops within a patch are\n * dropped (not silently mutated); each patch is truncated to the edit budget. */\nexport class SkillPatchParseError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SkillPatchParseError'\n }\n}\n\n/**\n * Parse a SkillOpt LLM response into validated `SkillPatch` objects, throwing `SkillPatchParseError` on malformed JSON and silently dropping ops that violate the edit budget.\n */\nexport function parseSkillPatchResponse(\n raw: string,\n maxPatches: number,\n editBudget: number,\n): SkillPatch[] {\n let text = raw.trim()\n if (text.startsWith('```')) text = text.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '')\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start < 0 || end <= start) {\n throw new SkillPatchParseError(\n `parseSkillPatchResponse: response was not valid JSON (no object found): ${snippet(raw)}`,\n )\n }\n let parsed: { patches?: unknown }\n try {\n parsed = JSON.parse(text.slice(start, end + 1))\n } catch (err) {\n throw new SkillPatchParseError(\n `parseSkillPatchResponse: response was not valid JSON (${\n err instanceof Error ? err.message : String(err)\n }): ${snippet(raw)}`,\n )\n }\n const rawPatches = Array.isArray(parsed.patches) ? parsed.patches : []\n const out: SkillPatch[] = []\n for (const rp of rawPatches) {\n if (typeof rp !== 'object' || rp === null) continue\n const obj = rp as Record<string, unknown>\n const ops = Array.isArray(obj.ops) ? obj.ops.map(normalizeOp).filter(isOp) : []\n if (ops.length === 0) continue\n out.push({\n label: typeof obj.label === 'string' ? obj.label : 'patch',\n rationale: typeof obj.rationale === 'string' ? obj.rationale : '',\n ops: ops.slice(0, editBudget),\n })\n if (out.length >= maxPatches) break\n }\n return out\n}\n\nfunction normalizeOp(raw: unknown): SkillPatchOp | null {\n if (typeof raw !== 'object' || raw === null) return null\n const o = raw as Record<string, unknown>\n if (o.op === 'add') {\n if (typeof o.text !== 'string') return null\n const op: SkillPatchOp = { op: 'add', text: o.text }\n if (typeof o.after === 'string') op.after = o.after\n return op\n }\n if (o.op === 'delete') {\n if (typeof o.anchor !== 'string') return null\n return { op: 'delete', anchor: o.anchor }\n }\n if (o.op === 'replace') {\n if (typeof o.anchor !== 'string' || typeof o.text !== 'string') return null\n return { op: 'replace', anchor: o.anchor, text: o.text }\n }\n return null\n}\n\nfunction isOp(op: SkillPatchOp | null): op is SkillPatchOp {\n return op !== null\n}\n\nfunction snippet(s: string, max = 120): string {\n const t = s.trim().replace(/\\s+/g, ' ')\n return t.length <= max ? t : `${t.slice(0, max)}…`\n}\n","/**\n * `runSkillOpt` — the SkillOpt epoch hill-climb (Microsoft, arXiv:2605.23904).\n * Unlike `runOptimization`'s population search around one global incumbent,\n * SkillOpt is a sequential, held-out-gated hill-climb on ONE skill document:\n *\n * each epoch:\n * 1. reflect on the CURRENT surface's weakest TRAIN scenarios/dimensions\n * (never the held-out split — proposals must not see the acceptance axis)\n * 2. propose ≤ `patchesPerEpoch` bounded patches (≤ `editBudget` ops each)\n * 3. apply each; score the candidate on the HELD-OUT split\n * 4. ACCEPT the first patch that STRICTLY improves the held-out composite;\n * otherwise push it to the rejected-edit buffer (fed back so the model\n * does not re-propose dead ends)\n * 5. anneal the edit budget down after consecutive rejections (the\n * \"textual learning rate\" decay); refresh the slow-update meta note\n * 6. stop at `maxEpochs` or after `patience` epochs with no acceptance\n *\n * The accept-only-if-held-out-improves rule is the same discipline as\n * `HeldOutGate`/`defaultProductionGate`, applied per edit instead of once at\n * the end — which is why the held-out composite is monotonically\n * non-decreasing and a regression can never ship. `runCampaign` is the\n * measurement; `applySkillPatch` applies the edits; `skillOptProposer` proposes\n * them.\n */\n\nimport type { CostLedgerHandle, CostLedgerSummary } from '../../cost-ledger'\nimport type { RejectedEdit, SkillOptEvidence, SkillOptProposer } from '../proposers/skill-opt'\nimport { type RunCampaignOptions, runCampaign } from '../run-campaign'\nimport { resolveRunDir } from '../run-dir'\nimport { campaignBreakdown, campaignMeanComposite } from '../score-utils'\nimport { applySkillPatch } from '../skill-patch'\nimport { createRunCostLedger, fsCampaignStorage } from '../storage'\nimport type { CampaignResult, DispatchContext, Scenario } from '../types'\n\nexport interface RunSkillOptOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'scenarios'> {\n /** The skill document being optimized. */\n baselineSurface: string\n /** Dispatcher taking the CURRENT skill surface + scenario → artifact. */\n dispatchWithSurface: (\n surface: string,\n scenario: TScenario,\n ctx: DispatchContext,\n ) => Promise<TArtifact>\n proposer: SkillOptProposer\n /** Scenarios the optimizer reflects on for evidence. MUST be disjoint from\n * `holdoutScenarios` — proposals never see the acceptance axis. */\n trainScenarios: TScenario[]\n /** Held-out scenarios. An edit is accepted ONLY if it strictly improves the\n * mean composite here. */\n holdoutScenarios: TScenario[]\n maxEpochs: number\n /** Candidate patches proposed per epoch. Default 2. */\n patchesPerEpoch?: number\n /** Initial ops-per-patch cap (the textual learning rate). Default 3. */\n editBudget?: number\n /** Strict acceptance margin: accept iff the held-out composite improves by\n * MORE than this. Default 0 (any strict improvement). */\n minImprovement?: number\n /** Stop after this many consecutive epochs with no acceptance. Default =\n * `maxEpochs` (never early-stop). */\n patience?: number\n /** Shrink the edit budget by 1 after 2 consecutive rejected epochs (min 1).\n * Default true. */\n budgetAnneal?: boolean\n /** Cap on the rejected-edit buffer (most-recent kept). Default 12. */\n rejectedBufferSize?: number\n /** Refresh the slow-update meta note every N epochs. Default 2. 0 disables. */\n slowMetaEvery?: number\n /** Top-K weak scenarios/dimensions surfaced as evidence each epoch. Default 3. */\n evidenceK?: number\n /** Abort signal forwarded to the patch-proposing LLM calls. */\n signal?: AbortSignal\n}\n\nexport interface AcceptedEdit {\n epoch: number\n label: string\n rationale: string\n /** Held-out composite improvement vs the surface before this edit. */\n holdoutDelta: number\n}\n\nexport interface SkillOptEpochRecord {\n epoch: number\n editBudget: number\n proposed: number\n /** The accepted edit this epoch, or null if every proposal was rejected. */\n accepted: AcceptedEdit | null\n rejected: RejectedEdit[]\n /** Held-out composite of the CURRENT surface at the END of the epoch. */\n holdoutComposite: number\n}\n\nexport interface RunSkillOptResult {\n winnerSurface: string\n baselineHoldoutComposite: number\n winnerHoldoutComposite: number\n /** `winnerHoldoutComposite - baselineHoldoutComposite` — monotonically ≥ 0\n * by construction (only strictly-improving edits are accepted). */\n lift: number\n acceptedEdits: AcceptedEdit[]\n rejectedEdits: RejectedEdit[]\n epochsRun: number\n history: SkillOptEpochRecord[]\n /** Total cost across every scoring campaign (train evidence + holdout\n * acceptance) the hill-climb ran. */\n totalCostUsd: number\n /** Run-wide spend, including scoring, proposals, and judges. */\n cost: CostLedgerSummary\n}\n\n/**\n * SkillOpt sequential hill-climb: each epoch reflects on train-scenario weaknesses, proposes bounded patches, accepts the first patch that strictly improves the held-out composite, and anneals the edit budget on consecutive rejections.\n */\nexport async function runSkillOpt<TScenario extends Scenario, TArtifact>(\n opts: RunSkillOptOptions<TScenario, TArtifact>,\n): Promise<RunSkillOptResult> {\n if (opts.trainScenarios.length === 0) throw new Error('runSkillOpt: trainScenarios is empty')\n if (opts.holdoutScenarios.length === 0) throw new Error('runSkillOpt: holdoutScenarios is empty')\n if (!opts.judges || opts.judges.length === 0) {\n throw new Error(\n 'runSkillOpt: at least one judge is required — scoring (and therefore acceptance) is meaningless without one, and would report a silent zero lift.',\n )\n }\n // train ∩ holdout must be empty: proposals reflect on TRAIN evidence, so any\n // overlap leaks the acceptance axis into the proposal (held-out contamination).\n const holdoutIds = new Set(opts.holdoutScenarios.map((s) => s.id))\n const overlap = opts.trainScenarios.filter((s) => holdoutIds.has(s.id)).map((s) => s.id)\n if (overlap.length > 0) {\n throw new Error(\n `runSkillOpt: trainScenarios and holdoutScenarios must be disjoint (overlap: [${overlap.join(\n ', ',\n )}]) — a shared scenario leaks the held-out acceptance axis into the proposal evidence.`,\n )\n }\n\n const patchesPerEpoch = opts.patchesPerEpoch ?? 2\n const initialBudget = opts.editBudget ?? 3\n const minImprovement = opts.minImprovement ?? 0\n if (minImprovement < 0) {\n throw new Error(\n 'runSkillOpt: minImprovement must be >= 0 — a negative threshold would accept held-out regressions, breaking the monotonic-lift contract.',\n )\n }\n const patience = opts.patience ?? opts.maxEpochs\n const budgetAnneal = opts.budgetAnneal ?? true\n const rejectedBufferSize = opts.rejectedBufferSize ?? 12\n const slowMetaEvery = opts.slowMetaEvery ?? 2\n opts.runDir = resolveRunDir(opts.runDir, opts.repo)\n const storage = opts.storage ?? fsCampaignStorage()\n const costLedger =\n opts.costLedger ??\n createRunCostLedger({\n storage,\n runDir: opts.runDir,\n costCeilingUsd: opts.costCeiling,\n })\n\n const scoreHoldout = async (surface: string, tag: string): Promise<number> => {\n const campaign = await runScoringCampaign(opts, opts.holdoutScenarios, surface, tag, costLedger)\n return campaignMeanComposite(campaign)\n }\n const evidenceK = opts.evidenceK ?? 3\n const trainEvidence = async (surface: string, tag: string): Promise<SkillOptEvidence> => {\n const campaign = await runScoringCampaign(opts, opts.trainScenarios, surface, tag, costLedger)\n return toEvidence(campaign, evidenceK)\n }\n\n let current = opts.baselineSurface\n let currentEvidence = await trainEvidence(current, 'baseline-train')\n const baselineHoldout = await scoreHoldout(current, 'baseline-holdout')\n let currentHoldout = baselineHoldout\n\n const buffer: RejectedEdit[] = []\n const acceptedEdits: AcceptedEdit[] = []\n const rejectedAll: RejectedEdit[] = []\n const history: SkillOptEpochRecord[] = []\n let budget = initialBudget\n let sinceAccept = 0\n let metaNote: string | undefined\n let epochsRun = 0\n\n for (let epoch = 0; epoch < opts.maxEpochs; epoch++) {\n epochsRun++\n const patches = await opts.proposer.proposePatches({\n surface: current,\n evidence: currentEvidence,\n editBudget: budget,\n rejectedBuffer: buffer,\n metaNote,\n count: patchesPerEpoch,\n signal: opts.signal ?? new AbortController().signal,\n costLedger,\n costPhase: 'skill-opt.proposal',\n })\n\n let accepted: AcceptedEdit | null = null\n const rejectedThisEpoch: RejectedEdit[] = []\n for (let i = 0; i < patches.length; i++) {\n const patch = patches[i]!\n const { surface: candidate, applied } = applySkillPatch(current, patch)\n if (applied === 0 || candidate === current) {\n rejectedThisEpoch.push({\n label: patch.label,\n rationale: patch.rationale,\n reason: 'no-op (unanchored or zero-change)',\n })\n continue\n }\n const candidateHoldout = await scoreHoldout(candidate, `epoch-${epoch}-cand-${i}-holdout`)\n if (candidateHoldout > currentHoldout + minImprovement) {\n accepted = {\n epoch,\n label: patch.label,\n rationale: patch.rationale,\n holdoutDelta: candidateHoldout - currentHoldout,\n }\n current = candidate\n currentHoldout = candidateHoldout\n // The surface changed — recompute evidence for the next epoch from it.\n currentEvidence = await trainEvidence(current, `epoch-${epoch}-train`)\n break // greedy: take the first strictly-improving edit\n }\n rejectedThisEpoch.push({\n label: patch.label,\n rationale: patch.rationale,\n reason: `held-out ${candidateHoldout.toFixed(3)} ≤ current ${currentHoldout.toFixed(3)}`,\n })\n }\n\n if (accepted) {\n acceptedEdits.push(accepted)\n sinceAccept = 0\n } else {\n sinceAccept++\n if (budgetAnneal && sinceAccept >= 2 && budget > 1) budget--\n }\n // Maintain the bounded rejected-edit buffer (steers the proposer away from\n // dead ends; capped so the prompt stays bounded).\n for (const r of rejectedThisEpoch) {\n buffer.push(r)\n rejectedAll.push(r)\n }\n while (buffer.length > rejectedBufferSize) buffer.shift()\n\n // Slow-update meta note: a cross-epoch digest refreshed on a slow cadence.\n if (slowMetaEvery > 0 && (epoch + 1) % slowMetaEvery === 0) {\n metaNote = buildMetaNote(acceptedEdits, buffer)\n }\n\n history.push({\n epoch,\n editBudget: budget,\n proposed: patches.length,\n accepted,\n rejected: rejectedThisEpoch,\n holdoutComposite: currentHoldout,\n })\n\n if (sinceAccept >= patience) break\n }\n\n const cost = costLedger.summary()\n return {\n winnerSurface: current,\n baselineHoldoutComposite: baselineHoldout,\n winnerHoldoutComposite: currentHoldout,\n lift: currentHoldout - baselineHoldout,\n acceptedEdits,\n rejectedEdits: rejectedAll,\n epochsRun,\n history,\n totalCostUsd: cost.totalCostUsd,\n cost,\n }\n}\n\nfunction runScoringCampaign<TScenario extends Scenario, TArtifact>(\n opts: RunSkillOptOptions<TScenario, TArtifact>,\n scenarios: TScenario[],\n surface: string,\n tag: string,\n costLedger: CostLedgerHandle,\n): Promise<CampaignResult<TArtifact, TScenario>> {\n return runCampaign<TScenario, TArtifact>({\n ...opts,\n costLedger,\n scenarios,\n dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),\n runDir: `${opts.runDir}/${tag}`,\n })\n}\n\nfunction toEvidence<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n k: number,\n): SkillOptEvidence {\n const { dimensions, scenarios } = campaignBreakdown(campaign)\n const weakScenarios = [...scenarios].sort((a, b) => a.composite - b.composite).slice(0, k)\n const weakDimensions = Object.entries(dimensions)\n .sort((a, b) => a[1] - b[1])\n .slice(0, k)\n .map(([dimension, score]) => ({ dimension, score }))\n return { weakScenarios, weakDimensions }\n}\n\nfunction buildMetaNote(accepted: AcceptedEdit[], rejected: RejectedEdit[]): string {\n const parts: string[] = []\n if (accepted.length > 0) {\n parts.push(\n `Edits that improved held-out so far: ${accepted\n .map((a) => `\"${a.label}\" (+${a.holdoutDelta.toFixed(3)})`)\n .join('; ')}. Build on these.`,\n )\n }\n if (rejected.length > 0) {\n const labels = [...new Set(rejected.map((r) => r.label))].slice(0, 5)\n parts.push(`Dead ends to avoid: ${labels.join(', ')}. Try a different anchor or rule.`)\n }\n parts.push('Keep edits small and anchored to existing lines.')\n return parts.join(' ')\n}\n","/**\n * `compareProposers` — a head-to-head lift benchmark across surface proposers\n * on ONE corpus. This is the forcing function: optimizer quality (GEPA\n * reflection vs GEPA+Pareto vs SkillOpt) becomes a NUMBER with a confidence\n * interval, so a proposer regression — or shipping a simplified proposer and\n * calling it the real one — turns a build red instead of going\n * measurement-invisible.\n *\n * Every entrant is scored the SAME way: each proposer returns the surface it\n * promoted, then the benchmark scores the baseline + every winner on the\n * SAME held-out scenarios with the SAME judges. Apples-to-apples by\n * construction — the comparison never depends on how a proposer measured itself.\n * The per-scenario held-out composites feed a paired bootstrap (`statistics.ts`)\n * for each proposer's lift CI and for the pairwise \"which proposer wins\" CI.\n */\n\nimport type { LlmClientOptions } from '../../llm-client'\nimport { pairedBootstrap } from '../../statistics'\nimport { defaultProductionGate } from '../gates/default-production-gate'\nimport {\n type FapoProposerOptions,\n fapoProposer,\n type ParameterCandidate,\n parameterSweepProposer,\n} from '../proposers/fapo'\nimport { gepaProposer } from '../proposers/gepa'\nimport { skillOptProposer } from '../proposers/skill-opt'\nimport { type RunCampaignOptions, runCampaign } from '../run-campaign'\nimport { campaignBreakdown } from '../score-utils'\nimport type {\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n MutableSurface,\n Scenario,\n SurfaceProposer,\n} from '../types'\nimport { type RunImprovementLoopOptions, runImprovementLoop } from './run-improvement-loop'\nimport { runSkillOpt } from './run-skill-opt'\n\n/** What an optimizer produced: the surface it promoted + what it cost to get\n * there. The comparison does the held-out scoring itself, so an entry only\n * needs to run its loop and hand back the winner. */\nexport interface ProposerEntry {\n name: string\n optimize: () => Promise<{ winnerSurface: MutableSurface; costUsd: number; durationMs?: number }>\n}\n\nexport interface ProposerScore {\n name: string\n /** Mean held-out composite of the baseline (identical across proposers). */\n baselineComposite: number\n /** Mean held-out composite of this proposer's promoted surface. */\n winnerComposite: number\n /** Mean per-scenario held-out lift (winner − baseline). */\n lift: number\n /** Paired-bootstrap CI of the per-scenario lift. `low > 0` ⇒ a real gain. */\n liftCi: { low: number; high: number }\n costUsd: number\n durationMs?: number\n winnerSurface: MutableSurface\n /** 1-based, by descending lift. */\n rank: number\n}\n\nexport interface ProposerPairwise {\n /** Higher-ranked proposer. */\n a: string\n b: string\n /** Mean per-scenario held-out delta (a − b). */\n deltaMean: number\n low: number\n high: number\n /** `a` if the CI clears 0, `b` if it is entirely negative, else `'tie'`. */\n favored: string\n}\n\nexport interface ProposerComparison {\n /** Sorted by descending lift; `rank` set accordingly. */\n scores: ProposerScore[]\n best: ProposerScore\n /** Best vs each other proposer, paired-bootstrap on the held-out winners. */\n pairwise: ProposerPairwise[]\n holdoutScenarioIds: string[]\n}\n\nexport interface CompareProposersOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'dispatch' | 'scenarios'> {\n proposers: ProposerEntry[]\n baselineSurface: MutableSurface\n /** The held-out scenarios every winner is scored on. */\n holdoutScenarios: TScenario[]\n /** Scores a surface on a scenario — the same dispatcher the proposers used. */\n dispatchWithSurface: (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n ) => Promise<TArtifact>\n /** Bootstrap resamples for the lift CIs. Default 2000. */\n resamples?: number\n /** CI confidence. Default 0.95. */\n confidence?: number\n}\n\n/**\n * Run a head-to-head lift benchmark across surface proposers on a shared holdout, returning per-proposer lift CIs and pairwise \"who wins\" verdicts.\n */\nexport async function compareProposers<TScenario extends Scenario, TArtifact>(\n opts: CompareProposersOptions<TScenario, TArtifact>,\n): Promise<ProposerComparison> {\n return compareProposerEntries(opts)\n}\n\nasync function compareProposerEntries<TScenario extends Scenario, TArtifact>(\n opts: CompareProposersOptions<TScenario, TArtifact>,\n): Promise<ProposerComparison> {\n if (opts.proposers.length === 0) throw new Error('compareProposers: no proposers to compare')\n const seed = opts.seed ?? 42\n const resamples = opts.resamples ?? 2000\n const confidence = opts.confidence ?? 0.95\n\n const scoreOnHoldout = async (\n surface: MutableSurface,\n tag: string,\n ): Promise<Record<string, number>> => {\n const campaign: CampaignResult<TArtifact, TScenario> = await runCampaign<TScenario, TArtifact>({\n ...opts,\n scenarios: opts.holdoutScenarios,\n dispatch: (scenario, ctx) => opts.dispatchWithSurface(surface, scenario, ctx),\n runDir: `${opts.runDir}/${tag}`,\n })\n const byScenario: Record<string, number> = {}\n for (const { scenarioId, composite } of campaignBreakdown(campaign).scenarios) {\n byScenario[scenarioId] = composite\n }\n return byScenario\n }\n\n // The comparison axis is the DESIGNED held-out set, not whatever a campaign\n // happened to score. Align every score vector to it and FAIL LOUD if a\n // surface is missing any scenario (an errored cell / a judge that returned no\n // score). Fabricating a 0 there would silently penalize that surface and\n // corrupt the paired-bootstrap lift CI — the exact \"no silent zeros\" trap.\n const scenarioIds = [...new Set(opts.holdoutScenarios.map((s) => s.id))].sort()\n if (scenarioIds.length === 0) throw new Error('compareProposers: holdoutScenarios is empty')\n const align = (byScenario: Record<string, number>, label: string): number[] => {\n const missing = scenarioIds.filter((id) => !(id in byScenario))\n if (missing.length > 0) {\n throw new Error(\n `compareProposers: ${label} produced no held-out score for scenario(s) [${missing.join(\n ', ',\n )}] — a cell errored or its judges returned nothing. Refusing to fabricate a 0 (it would corrupt the lift comparison). Fix the dispatch/judge or drop the scenario.`,\n )\n }\n return scenarioIds.map((id) => byScenario[id]!)\n }\n\n const baselineArr = align(\n await scoreOnHoldout(opts.baselineSurface, 'compare-baseline'),\n 'baseline',\n )\n\n // Run + uniformly re-score every entrant on the SAME held-out axis.\n const winners: Array<{\n name: string\n winnerSurface: MutableSurface\n costUsd: number\n durationMs?: number\n arr: number[]\n }> = []\n for (const proposer of opts.proposers) {\n const out = await proposer.optimize()\n const byScenario = await scoreOnHoldout(out.winnerSurface, `compare-${slug(proposer.name)}`)\n winners.push({\n name: proposer.name,\n winnerSurface: out.winnerSurface,\n costUsd: out.costUsd,\n durationMs: out.durationMs,\n arr: align(byScenario, `proposer \"${proposer.name}\"`),\n })\n }\n\n const scores: ProposerScore[] = winners.map((w) => {\n const boot = pairedBootstrap(baselineArr, w.arr, {\n seed,\n resamples,\n confidence,\n statistic: 'mean',\n })\n const score: ProposerScore = {\n name: w.name,\n baselineComposite: mean(baselineArr),\n winnerComposite: mean(w.arr),\n lift: boot.mean,\n liftCi: { low: boot.low, high: boot.high },\n costUsd: w.costUsd,\n winnerSurface: w.winnerSurface,\n rank: 0,\n }\n if (w.durationMs !== undefined) score.durationMs = w.durationMs\n return score\n })\n // Sort by lift; tie-break by lower cost (cheaper wins a tie).\n scores.sort((a, b) => b.lift - a.lift || a.costUsd - b.costUsd)\n scores.forEach((s, i) => {\n s.rank = i + 1\n })\n const best = scores[0]!\n\n const byName = new Map(winners.map((w) => [w.name, w]))\n const bestArr = byName.get(best.name)!.arr\n const pairwise: ProposerPairwise[] = scores.slice(1).map((other) => {\n const otherArr = byName.get(other.name)!.arr\n // before = other, after = best ⇒ delta = best − other on the held-out set.\n const boot = pairedBootstrap(otherArr, bestArr, {\n seed,\n resamples,\n confidence,\n statistic: 'mean',\n })\n const favored = boot.low > 0 ? best.name : boot.high < 0 ? other.name : 'tie'\n return {\n a: best.name,\n b: other.name,\n deltaMean: boot.mean,\n low: boot.low,\n high: boot.high,\n favored,\n }\n })\n\n return { scores, best, pairwise, holdoutScenarioIds: scenarioIds }\n}\n\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\nfunction slug(name: string): string {\n return name.replace(/[^a-z0-9]+/gi, '-').toLowerCase()\n}\n\n// ── Built-in entries — wire the real optimizers for a live comparison ───────\n\n/** Shared corpus + transport for the three built-in optimizer entries. */\nexport interface OptimizerEntryConfig<TScenario extends Scenario, TArtifact> {\n baselineSurface: string\n /** Training scenarios the proposers reflect on. */\n trainScenarios: TScenario[]\n /** Held-out scenarios (the gate axis + the benchmark scoring axis). */\n holdoutScenarios: TScenario[]\n dispatchWithSurface: (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n ) => Promise<TArtifact>\n judges: JudgeConfig<TArtifact, TScenario>[]\n llm: LlmClientOptions\n model: string\n target: string\n runDir: string\n seed?: number\n /** GEPA population per generation. Default 2. */\n populationSize?: number\n /** GEPA generations. Default 3. */\n maxGenerations?: number\n /** SkillOpt epochs. Default 6. */\n maxEpochs?: number\n mutationPrimitives?: string[]\n /** Static findings seed forwarded to each GEPA proposer's `propose()` as\n * `ctx.findings`. Forwarded by `gepaReflectionEntry` / `gepaParetoEntry`;\n * `skillOptEntry` runs without findings (see its doc). */\n findings?: unknown[]\n /** Per-generation findings producer: after each generation scores, this\n * re-diagnoses and REPLACES `ctx.findings` for the\n * next generation's `propose()`. Reuses the `runOptimization` field type so\n * it cannot drift. GEPA entries only. */\n analyzeGeneration?: RunImprovementLoopOptions<TScenario, TArtifact>['analyzeGeneration']\n /** Optional analysis report forwarded to `propose()` as `ctx.report`. */\n report?: unknown\n}\n\n/** GEPA, reflection-only (single-parent, no Pareto combine). */\nexport function gepaReflectionEntry<TScenario extends Scenario, TArtifact>(\n config: OptimizerEntryConfig<TScenario, TArtifact>,\n name = 'gepa-reflection',\n): ProposerEntry {\n return gepaEntry(config, false, name)\n}\n\n/** GEPA with the Pareto frontier + combine-complementary-lessons. */\nexport function gepaParetoEntry<TScenario extends Scenario, TArtifact>(\n config: OptimizerEntryConfig<TScenario, TArtifact>,\n name = 'gepa-pareto',\n): ProposerEntry {\n return gepaEntry(config, true, name)\n}\n\nfunction gepaEntry<TScenario extends Scenario, TArtifact>(\n config: OptimizerEntryConfig<TScenario, TArtifact>,\n combineParents: boolean,\n name: string,\n): ProposerEntry {\n return {\n name,\n async optimize() {\n const started = Date.now()\n const proposer = gepaProposer({\n llm: config.llm,\n model: config.model,\n target: config.target,\n combineParents,\n ...(config.mutationPrimitives ? { mutationPrimitives: config.mutationPrimitives } : {}),\n })\n const result = await runImprovementLoop<TScenario, TArtifact>({\n scenarios: config.trainScenarios,\n holdoutScenarios: config.holdoutScenarios,\n baselineSurface: config.baselineSurface,\n dispatchWithSurface: config.dispatchWithSurface,\n judges: config.judges,\n proposer,\n populationSize: config.populationSize ?? 2,\n maxGenerations: config.maxGenerations ?? 3,\n gate: defaultProductionGate<TArtifact, TScenario>({\n holdoutScenarios: config.holdoutScenarios,\n deltaThreshold: 0,\n }),\n autoOnPromote: 'none',\n runDir: `${config.runDir}/${slug(name)}-loop`,\n ...(config.seed !== undefined ? { seed: config.seed } : {}),\n // Flow findings to the proposer's propose(). These reach runOptimization\n // unchanged (runImprovementLoop extends RunOptimizationOptions and\n // forwards {...opts}); ctx.findings/report/analyzeGeneration are consumed there.\n ...(config.findings !== undefined ? { findings: config.findings } : {}),\n ...(config.analyzeGeneration ? { analyzeGeneration: config.analyzeGeneration } : {}),\n ...(config.report !== undefined ? { report: config.report } : {}),\n })\n return {\n winnerSurface: result.winnerSurface,\n costUsd: result.cost.totalCostUsd,\n durationMs: Date.now() - started,\n }\n },\n }\n}\n\n/** SkillOpt patch-mode hill-climb. Runs findings-BLIND: `runSkillOpt` owns its\n * own epoch acceptance/budget loop and does not thread `analyzeGeneration`, so\n * `config.findings` is intentionally NOT forwarded here. In a findings-fed\n * comparison this entry is the blind control — do not read its result as\n * findings-fed. (Threading findings into the SkillOpt epoch loop is a separate\n * refactor, deferred not faked.) */\nexport function skillOptEntry<TScenario extends Scenario, TArtifact>(\n config: OptimizerEntryConfig<TScenario, TArtifact>,\n name = 'skill-opt',\n): ProposerEntry {\n return {\n name,\n async optimize() {\n const started = Date.now()\n const proposer = skillOptProposer({\n llm: config.llm,\n model: config.model,\n target: config.target,\n })\n const result = await runSkillOpt<TScenario, TArtifact>({\n baselineSurface: config.baselineSurface,\n dispatchWithSurface: config.dispatchWithSurface,\n judges: config.judges,\n proposer,\n trainScenarios: config.trainScenarios,\n holdoutScenarios: config.holdoutScenarios,\n maxEpochs: config.maxEpochs ?? 6,\n runDir: `${config.runDir}/${slug(name)}-loop`,\n ...(config.seed !== undefined ? { seed: config.seed } : {}),\n })\n return {\n winnerSurface: result.winnerSurface,\n costUsd: result.totalCostUsd,\n durationMs: Date.now() - started,\n }\n },\n }\n}\n\n/** FAPO reviewed-escalation policy. This is an orchestration layer over\n * level-specific proposers, not a new mutation operator:\n * prompt -> parameter -> structural, with scope + reviewer + plateau rules in\n * `fapoProposer`. The prompt proposer defaults to GEPA+Pareto because that is\n * the package's strongest prompt-tier proposer; parameter/structural proposers\n * are opt-in so we do not fake code-generation inside agent-eval. */\nexport interface FapoEntryConfig<TScenario extends Scenario, TArtifact>\n extends OptimizerEntryConfig<TScenario, TArtifact> {\n /** Override the prompt-level proposer. Default: `gepaProposer({ combineParents: true })`. */\n promptProposer?: SurfaceProposer\n /** Parameter/config-level proposer. If omitted, `parameterCandidates` builds one. */\n parameterProposer?: SurfaceProposer\n /** Structural/code-level proposer, typically supplied by agent-runtime. */\n structuralProposer?: SurfaceProposer\n /** Convenience: build a `parameterSweepProposer` from these candidates. */\n parameterCandidates?: readonly ParameterCandidate[]\n /** FAPO policy knobs: scope, reviewer, plateau thresholds. */\n fapo?: Omit<\n FapoProposerOptions,\n 'proposers' | 'promptProposer' | 'parameterProposer' | 'structuralProposer'\n >\n}\n\n/**\n * Build a `ProposerEntry` that runs the full FAPO escalation policy (prompt → parameter → structural) as a single comparable optimizer entry.\n */\nexport function fapoEscalationEntry<TScenario extends Scenario, TArtifact>(\n config: FapoEntryConfig<TScenario, TArtifact>,\n name = 'fapo-escalation',\n): ProposerEntry {\n return {\n name,\n async optimize() {\n const started = Date.now()\n const promptProposer =\n config.promptProposer ??\n gepaProposer({\n llm: config.llm,\n model: config.model,\n target: config.target,\n combineParents: true,\n ...(config.mutationPrimitives ? { mutationPrimitives: config.mutationPrimitives } : {}),\n })\n const parameterProposer =\n config.parameterProposer ??\n (config.parameterCandidates\n ? parameterSweepProposer({ candidates: config.parameterCandidates })\n : undefined)\n const structuralProposer = config.structuralProposer\n const proposer = fapoProposer({\n ...(config.fapo ?? {}),\n promptProposer,\n ...(parameterProposer ? { parameterProposer } : {}),\n ...(structuralProposer ? { structuralProposer } : {}),\n })\n const result = await runImprovementLoop<TScenario, TArtifact>({\n scenarios: config.trainScenarios,\n holdoutScenarios: config.holdoutScenarios,\n baselineSurface: config.baselineSurface,\n dispatchWithSurface: config.dispatchWithSurface,\n judges: config.judges,\n proposer,\n populationSize: config.populationSize ?? 2,\n maxGenerations: config.maxGenerations ?? 3,\n gate: defaultProductionGate<TArtifact, TScenario>({\n holdoutScenarios: config.holdoutScenarios,\n deltaThreshold: 0,\n }),\n autoOnPromote: 'none',\n runDir: `${config.runDir}/${slug(name)}-loop`,\n ...(config.seed !== undefined ? { seed: config.seed } : {}),\n ...(config.findings !== undefined ? { findings: config.findings } : {}),\n ...(config.analyzeGeneration ? { analyzeGeneration: config.analyzeGeneration } : {}),\n ...(config.report !== undefined ? { report: config.report } : {}),\n })\n return {\n winnerSurface: result.winnerSurface,\n costUsd: result.cost.totalCostUsd,\n durationMs: Date.now() - started,\n }\n },\n }\n}\n","/**\n * Completion verifier — the task-completion oracle.\n *\n * Answers the only eval question that is not a proxy: did the agent actually\n * COMPLETE the task — produce every required deliverable, persisted and\n * correct — rather than describe what should be done. A fluent transcript\n * that never produces the artifact scores zero here.\n *\n * Per requirement, a two-stage check:\n * 1. Structural — a produced item (vault artifact / approved proposal /\n * tool call) of the right kind is matched against the requirement and\n * carries non-empty content. Deterministic; no LLM.\n * 2. Correctness — only if structurally present AND the matched item\n * carries content, one targeted check decides whether that item\n * actually fulfils the requirement. A hallucinated artifact fails here;\n * an absent one already failed stage 1.\n *\n * `completionRate` is satisfied / MEASURABLE requirements (unmeasured rows —\n * checker failures — are excluded from the denominator, never scored as\n * zeros). Quality dimensions are meaningless on an incomplete task — callers\n * gate on `fullyComplete` / `completionRate` before scoring quality.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TCloud } from '@tangle-network/tcloud'\nimport type { Artifact } from './artifact-validator'\nimport { CostLedger, type CostLedgerHandle, type CostReceiptInput } from './cost-ledger'\nimport { recoverTruncatedJson } from './json-recovery'\nimport { JudgeParseError } from './judges'\nimport type { LlmCallRequest } from './llm-client'\nimport { costReceiptFromTCloud, maximumChargeForTCloudRequest } from './tcloud-cost'\nimport type { RawProviderEvent, RawProviderSink } from './trace/raw-provider-sink'\nimport type { DefaultVerdict } from './verdict'\n\n/** What kind of produced state can satisfy a requirement structurally. */\nexport type SatisfiedBy = 'artifact' | 'proposal' | 'tool-call' | 'any'\n\nexport interface CompletionRequirement {\n /** Stable id from the task gold (e.g. a persona's `expected_requirements[].req_id`). */\n reqId: string\n /** Human-readable description of the required deliverable. */\n title: string\n /** Optional kind/category hint, matched against a produced item's kind. */\n category?: string\n /** What produced state satisfies this requirement. Defaults to 'any'. */\n satisfiedBy?: SatisfiedBy\n}\n\nexport interface TaskGold {\n taskId: string\n requirements: CompletionRequirement[]\n}\n\nexport interface ProducedProposal {\n id: string\n title: string\n status: 'pending' | 'approved' | 'rejected'\n /** Optional persisted body — when present, enables a correctness check. */\n content?: string\n}\n\n/** Everything observable about what a run actually produced. */\nexport interface ProducedState {\n /** Persisted vault artifacts. Reuses the shared `Artifact` shape. */\n artifacts: Artifact[]\n /** Proposals / filings the agent created. */\n proposals: ProducedProposal[]\n /** Names of tools the agent invoked. */\n toolCalls: string[]\n}\n\nexport interface RequirementCheck {\n reqId: string\n title: string\n /** A produced item of the right kind matched the requirement, non-empty. */\n structurallyPresent: boolean\n /**\n * Whether the matched item actually fulfils the requirement. `null` when\n * not structurally present, when the matched item carries no content\n * to assess, or when the correctness check itself failed (`unmeasured`).\n */\n correct: boolean | null\n /** structurallyPresent && !unmeasured && correct !== false. */\n satisfied: boolean\n /**\n * Set when the correctness check itself errored (LLM call failure or an\n * unparseable response after retry). The requirement's fulfilment is\n * UNKNOWN — `correct` stays null, `satisfied` is false, and\n * `completionVerdict` excludes the row from `completionRate`'s\n * denominator. Never folded into a zero: a synthetic zero is\n * indistinguishable from a real failure (see `JudgeParseError`).\n */\n unmeasured?: true\n /** Why the correctness check could not be measured (present iff `unmeasured`). */\n unmeasuredReason?: string\n /** Human-readable evidence for the verdict. */\n evidence: string[]\n}\n\n/** Extends the substrate verdict spine: `valid` = `fullyComplete` and\n * `score` = `completionRate` — derived in `completionVerdict()`, the one\n * place those equalities hold by construction. */\nexport interface CompletionVerdict extends DefaultVerdict {\n taskId: string\n requirements: RequirementCheck[]\n /** satisfied / MEASURABLE requirements (unmeasured rows leave the denominator). */\n completionRate: number\n /** Every measurable requirement satisfied (false when anything is unmeasured). */\n fullyComplete: boolean\n /** Requirements whose correctness check errored — reported, never scored as zero. */\n unmeasuredCount: number\n}\n\n/**\n * Construct a `CompletionVerdict` from the per-requirement checks, deriving\n * `completionRate` / `fullyComplete` and the spine fields (`valid` =\n * `fullyComplete`, `score` = `completionRate`) in one place. Throws on zero\n * requirements — a verdict over nothing is a misconfiguration, mirroring\n * `verifyCompletion`'s gold-spec guard.\n */\nexport function completionVerdict(input: {\n taskId: string\n requirements: RequirementCheck[]\n}): CompletionVerdict {\n if (input.requirements.length === 0) {\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no requirement checks — nothing to derive a verdict from`,\n )\n }\n const measurable = input.requirements.filter((r) => !r.unmeasured)\n const unmeasuredCount = input.requirements.length - measurable.length\n if (measurable.length === 0) {\n // Every check errored: this is an infrastructure failure, not a scored\n // run. A 0-rate verdict here would be a fabricated measurement.\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no measurable requirements — all ${input.requirements.length} correctness checks failed (${input.requirements[0]?.unmeasuredReason ?? 'unknown reason'})`,\n )\n }\n const satisfiedCount = measurable.filter((r) => r.satisfied).length\n const completionRate = satisfiedCount / measurable.length\n // A run with unmeasured rows can still report a rate over what WAS\n // measured, but must not claim full completion.\n const fullyComplete = unmeasuredCount === 0 && satisfiedCount === measurable.length\n return {\n taskId: input.taskId,\n requirements: input.requirements,\n completionRate,\n fullyComplete,\n unmeasuredCount,\n valid: fullyComplete,\n score: completionRate,\n }\n}\n\n/**\n * Decides whether a produced item's content actually fulfils a requirement.\n * Injected so the structural verifier stays pure and unit-testable; the\n * production implementation is `createLlmCorrectnessChecker`.\n */\nexport type CorrectnessChecker = (\n requirement: CompletionRequirement,\n content: string,\n) => Promise<{ correct: boolean; reason: string }>\n\nconst STOPWORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'for',\n 'and',\n 'or',\n 'to',\n 'in',\n 'on',\n 'with',\n 'by',\n])\n\n// Deliverable-FORM vocabulary — words that name the SHAPE of an output, not its\n// domain content. A correct \"swap-comparison view persisted as a ui/** artifact\"\n// is an OpenUI JSON whose body says nothing about \"artifact\" / \"persisted\" /\n// \"view\"; the discriminative tokens are the domain nouns (swap, comparison).\n// Stripped from the REQUIREMENT side of structural recall so a deliverable is\n// matched on what it IS about, not on the boilerplate describing its form. The\n// correctness checker strips the same class via TITLE_STOPWORDS. Anti-game holds:\n// the distinctive domain tokens remain, so an off-topic item still fails.\nconst REQUIREMENT_FORM_STOPWORDS = new Set([\n 'generated',\n 'generate',\n 'view',\n 'render',\n 'rendered',\n 'persisted',\n 'persist',\n 'artifact',\n 'file',\n 'document',\n 'note',\n 'proposal',\n 'deliverable',\n 'output',\n 'created',\n 'create',\n 'produce',\n 'produced',\n 'flag',\n])\n\nconst MATCH_THRESHOLD = 0.5\nconst MIN_CONTENT_CHARS = 50\n\nfunction tokens(s: string, extraStop?: Set<string>): Set<string> {\n return new Set(\n s\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t) && !extraStop?.has(t)),\n )\n}\n\n/**\n * Recall of the requirement's tokens within a candidate's identifying text.\n * Recall, not Jaccard — a candidate's path/id legitimately carries extra\n * tokens the requirement does not name. The requirement side drops\n * deliverable-FORM vocabulary so recall keys on the distinctive domain tokens.\n */\nfunction tokenRecall(requirementText: string, candidateText: string): number {\n const req = tokens(requirementText, REQUIREMENT_FORM_STOPWORDS)\n if (req.size === 0) return 0\n const cand = tokens(candidateText)\n let hit = 0\n for (const t of req) if (cand.has(t)) hit++\n return hit / req.size\n}\n\ninterface Candidate {\n reqIndex: number\n /** Unique key for a produced item — each item satisfies at most one requirement. */\n itemKey: string\n score: number\n evidence: string\n /** Content to correctness-check, or null when the matched item has none. */\n content: string | null\n}\n\nfunction artifactCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n artifacts: Artifact[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n artifacts.forEach((a, i) => {\n if ((a.content ?? '').trim().length < MIN_CONTENT_CHARS) return\n // Match against the artifact CONTENT too, not just its path + kind — a\n // generated view / note whose path is generic still satisfies a requirement\n // when its body covers it (e.g. an OpenUI comparison grounded in the on-file\n // figures). Bounded slice keeps the recall text cheap; MATCH_THRESHOLD holds.\n let score = tokenRecall(\n reqText,\n `${a.path ?? ''} ${a.kind} ${(a.content ?? '').slice(0, 4000)}`,\n )\n if (req.category && a.kind && req.category.toLowerCase() === a.kind.toLowerCase()) {\n score = Math.max(score, 1)\n }\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `artifact:${i}`,\n score,\n evidence: `artifact '${a.path ?? a.kind}' matched (token recall ${score.toFixed(2)})`,\n content: a.content ?? null,\n })\n })\n return out\n}\n\nfunction proposalCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n proposals: ProducedProposal[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n for (const p of proposals) {\n // Pending or rejected work is not a completed deliverable.\n if (p.status !== 'approved') continue\n // A proposal needs an assessable BODY to be a deliverable. A bare title is\n // not completion: correctness cannot be judged on it, so a title-only match\n // would auto-pass the oracle (structurallyPresent && correct===null →\n // satisfied) with no verifiable content. Tool calls are the only\n // legitimately content-less deliverable (`toolCallCandidates`).\n const body = (p.content ?? '').trim()\n if (body.length < MIN_CONTENT_CHARS) continue\n // Match against the body as well as the (often short) title — a refusal /\n // flag / analysis proposal whose title is a label still satisfies a\n // descriptively-worded requirement when its content covers it. MATCH_THRESHOLD\n // + the requirement's distinctive tokens keep an off-topic proposal out;\n // correctness (a SEMANTIC checker, NOT this lexical pass) then judges\n // polarity/fulfilment, so a negation that merely contains the tokens fails.\n // Structural and correctness must use different evidence or the two-stage\n // check collapses to one lexical gate.\n const score = tokenRecall(reqText, `${p.title} ${body}`)\n if (score < MATCH_THRESHOLD) continue\n out.push({\n reqIndex,\n itemKey: `proposal:${p.id}`,\n score,\n evidence: `approved proposal '${p.title}' matched (token recall ${score.toFixed(2)})`,\n content: body,\n })\n }\n return out\n}\n\nfunction toolCallCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n toolCalls: string[],\n): Candidate[] {\n const out: Candidate[] = []\n toolCalls.forEach((name, i) => {\n const score = tokenRecall(req.title, name)\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `tool:${i}`,\n score,\n evidence: `tool call '${name}' matched (token recall ${score.toFixed(2)})`,\n content: null,\n })\n })\n return out\n}\n\n/**\n * Verify whether a run completed the task. `checkCorrectness` is injected —\n * `createLlmCorrectnessChecker` for production, a deterministic stub in tests.\n *\n * Throws on a gold spec with no requirements: an eval task that requires\n * nothing is a misconfiguration, not a vacuously-complete task.\n */\nexport async function verifyCompletion(\n gold: TaskGold,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<CompletionVerdict> {\n if (gold.requirements.length === 0) {\n throw new Error(\n `verifyCompletion: task '${gold.taskId}' has no requirements — malformed gold spec`,\n )\n }\n\n // Collect every above-threshold (requirement, produced-item) candidate, then\n // assign greedily by descending score: each requirement and each produced\n // item is used at most once. One deliverable fulfils one requirement.\n const candidates: Candidate[] = []\n gold.requirements.forEach((req, i) => {\n const by = req.satisfiedBy ?? 'any'\n if (by === 'artifact' || by === 'any') {\n candidates.push(...artifactCandidates(req, i, state.artifacts))\n }\n if (by === 'proposal' || by === 'any') {\n candidates.push(...proposalCandidates(req, i, state.proposals))\n }\n if (by === 'tool-call' || by === 'any') {\n candidates.push(...toolCallCandidates(req, i, state.toolCalls))\n }\n })\n candidates.sort((a, b) => b.score - a.score)\n\n const assigned = new Map<number, Candidate>()\n const itemTaken = new Set<string>()\n for (const c of candidates) {\n if (assigned.has(c.reqIndex) || itemTaken.has(c.itemKey)) continue\n assigned.set(c.reqIndex, c)\n itemTaken.add(c.itemKey)\n }\n\n const requirements: RequirementCheck[] = []\n for (let i = 0; i < gold.requirements.length; i++) {\n const req = gold.requirements[i]!\n const match = assigned.get(i)\n const evidence: string[] = []\n let correct: boolean | null = null\n let unmeasuredReason: string | undefined\n\n if (match) {\n evidence.push(match.evidence)\n if (match.content !== null) {\n try {\n const r = await checkCorrectness(req, match.content)\n correct = r.correct\n evidence.push(`correctness: ${r.correct ? 'pass' : 'fail'} — ${r.reason}`)\n } catch (err) {\n // The CHECKER failed, not the requirement. Recording this as a\n // zero would fabricate a model failure out of an infrastructure\n // one; the requirement is unmeasured and leaves the denominator.\n unmeasuredReason =\n err instanceof JudgeParseError\n ? `checker response unparseable after retry: ${err.raw.slice(0, 200)}`\n : `checker call failed: ${err instanceof Error ? err.message : String(err)}`\n evidence.push(`correctness: UNMEASURED — ${unmeasuredReason}`)\n }\n } else {\n evidence.push('correctness: not assessed — matched item carries no content')\n }\n } else {\n const by = req.satisfiedBy ?? 'any'\n const kind = by === 'any' ? 'artifact/proposal/tool-call' : by\n evidence.push(`no produced ${kind} matched this requirement`)\n }\n\n const structurallyPresent = match !== undefined\n const unmeasured = unmeasuredReason !== undefined\n const satisfied = structurallyPresent && !unmeasured && correct !== false\n requirements.push({\n reqId: req.reqId,\n title: req.title,\n structurallyPresent,\n correct,\n satisfied,\n ...(unmeasured ? { unmeasured: true as const, unmeasuredReason } : {}),\n evidence,\n })\n }\n\n return completionVerdict({ taskId: gold.taskId, requirements })\n}\n\nexport interface LlmCorrectnessCheckerOpts {\n model?: string\n /** Optional ledger for direct use. */\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /** Exact maximum provider attempts configured on the supplied TCloud client. */\n tcloudMaximumAttempts?: number\n /** Usage/cost retained by a failed provider response; enables a safe retry. */\n receiptFromError?: (error: Error, attempt: number) => CostReceiptInput | undefined\n /** Max chars of artifact content sent to the checker. */\n maxContentChars?: number\n /**\n * Checker LLM calls per requirement before giving up (parse failures and\n * call errors both consume attempts). The failure then surfaces as an\n * `unmeasured` requirement, never a zero.\n */\n maxAttempts?: number\n /**\n * Forensic capture of every checker request/response/error — without it a\n * checker failure is unauditable (the agent-turn raws never contain the\n * checker's own calls). Same sink contract as `LlmClient`.\n */\n rawSink?: RawProviderSink\n}\n\n/**\n * Parse the correctness checker's model response. Tolerates a response\n * truncated mid-JSON (max_tokens cap) by auto-closing the prefix — the\n * verdict boolean usually lands in the first few tokens, so a recovered\n * prefix with a boolean `correct` is a real measurement, not a guess.\n * Fails loud (JudgeParseError) when no boolean verdict is recoverable.\n */\nexport function parseCorrectnessResponse(raw: string): { correct: boolean; reason: string } {\n const readVerdict = (candidate: unknown): { correct: boolean; reason: string } | null => {\n if (candidate === null || typeof candidate !== 'object') return null\n const { correct, reason } = candidate as { correct?: unknown; reason?: unknown }\n if (typeof correct !== 'boolean') return null\n return { correct, reason: typeof reason === 'string' ? reason : '' }\n }\n\n const match = raw.match(/\\{[\\s\\S]*\\}/)\n if (match) {\n try {\n const strict = readVerdict(JSON.parse(match[0]))\n if (strict) return strict\n } catch {\n // fall through to truncation recovery\n }\n }\n // The strict path needs a closing `}`; a cap-hit response has none. Take\n // everything from the first `{` and auto-close it.\n const start = raw.indexOf('{')\n if (start !== -1) {\n const recovered = readVerdict(recoverTruncatedJson(raw.slice(start)))\n if (recovered) return recovered\n }\n throw new JudgeParseError('correctness-checker', raw)\n}\n\n/**\n * Production `CorrectnessChecker` — one LLM call per matched artifact,\n * deterministic (temperature 0), structured JSON out. Judges fulfilment\n * only: a plan, a gesture, or a description of what should be done does not\n * fulfil a requirement — the artifact must BE the deliverable.\n */\nexport function createLlmCorrectnessChecker(\n tc: TCloud,\n opts: LlmCorrectnessCheckerOpts = {},\n): CorrectnessChecker {\n const model = opts.model ?? 'claude-sonnet-4-6'\n const maxContentChars = opts.maxContentChars ?? 8000\n const maxAttempts = opts.maxAttempts ?? 2\n const costLedger = opts.costLedger ?? new CostLedger()\n const sink = opts.rawSink\n const record = async (event: RawProviderEvent): Promise<void> => {\n // Forensic capture is best-effort; the verdict is the system of record.\n try {\n await sink?.record(event)\n } catch {\n // Intentionally swallowed.\n }\n }\n return async (requirement, content) => {\n const request = {\n model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You verify whether a produced work artifact actually fulfils a stated requirement. Judge fulfilment only — is the deliverable substantively present and on-point — not polish. A plan to do it later, a vague gesture, or a description of what should be done does NOT fulfil a requirement; the artifact must BE the deliverable. Respond with a single JSON object: {\"correct\": boolean, \"reason\": string (<= 30 words)}.',\n },\n {\n role: 'user' as const,\n content: `Requirement: ${requirement.title}\\n${\n requirement.category ? `Category: ${requirement.category}\\n` : ''\n }\\nProduced artifact:\\n${content.slice(0, maxContentChars)}`,\n },\n ],\n temperature: 0,\n maxTokens: 200,\n } satisfies LlmCallRequest\n let lastErr: unknown\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const started = Date.now()\n await record({\n eventId: randomUUID(),\n provider: 'correctness-checker',\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'request',\n timestamp: started,\n requestBody: request,\n redactedFields: [],\n })\n try {\n const paid = await costLedger.runPaidCall({\n channel: 'verifier',\n phase: opts.costPhase ?? 'completion.correctness',\n actor: 'correctness-checker',\n model,\n maximumCharge: maximumChargeForTCloudRequest(request, opts.tcloudMaximumAttempts),\n tags: {\n ...opts.costTags,\n requirementId: requirement.reqId,\n attempt: String(attempt),\n },\n signal: opts.signal,\n execute: () => tc.chat(request),\n receipt: (response) => costReceiptFromTCloud(response, model),\n receiptFromError: (error) => opts.receiptFromError?.(error, attempt),\n })\n if (!paid.succeeded) throw paid.error\n const resp = paid.value\n const raw =\n (resp as { choices?: { message?: { content?: string } }[] }).choices?.[0]?.message\n ?.content ?? ''\n await record({\n eventId: randomUUID(),\n provider: 'correctness-checker',\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n responseBody: resp,\n redactedFields: [],\n })\n return parseCorrectnessResponse(raw)\n } catch (err) {\n lastErr = err\n await record({\n eventId: randomUUID(),\n provider: 'correctness-checker',\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n }\n}\n\n/** Stopwords for requirement-title tokenization — drops the imperative verbs\n * ('review', 'update', …) common to deliverable titles so recall keys on the\n * substantive nouns, not the boilerplate ask. */\nconst TITLE_STOPWORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'for',\n 'to',\n 'of',\n 'in',\n 'on',\n 'with',\n 'review',\n 'update',\n 'new',\n 'proposed',\n])\n\n/**\n * Deterministic `CorrectnessChecker` — the no-LLM counterpart to\n * `createLlmCorrectnessChecker`. A produced item fulfils a requirement when its\n * content is substantive (≥ `minContentLength` chars) AND recalls ≥ `minRecall`\n * of the requirement title's significant tokens. No network.\n *\n * Polarity-blind: token recall credits a negation that contains the\n * requirement's tokens (\"I will NOT produce the comparison\" recalls every token\n * of \"produce the comparison\"). The structural match stage is ALSO lexical, so\n * pairing the two collapses to a single gameable gate. Use this only as an\n * opt-in structural pre-filter or for tasks whose requirements have no polarity\n * to invert; for produced-state grading the correctness checker MUST be semantic\n * (`createLlmCorrectnessChecker`). See the anti-game fixtures in the test suite.\n */\nexport function createTokenRecallChecker(\n opts: { minRecall?: number; minContentLength?: number } = {},\n): CorrectnessChecker {\n const minRecall = opts.minRecall ?? 0.5\n const minLen = opts.minContentLength ?? 120\n return async (requirement, content) => {\n const body = content.trim()\n if (body.length < minLen)\n return {\n correct: false,\n reason: `content too thin (${body.length} chars) to be the deliverable`,\n }\n const titleTokens = requirement.title\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 2 && !TITLE_STOPWORDS.has(t))\n if (titleTokens.length === 0)\n return {\n correct: true,\n reason: 'requirement title has no significant tokens — structural match accepted',\n }\n const lower = body.toLowerCase()\n const hits = titleTokens.filter((t) => lower.includes(t)).length\n const recall = hits / titleTokens.length\n return recall >= minRecall\n ? {\n correct: true,\n reason: `content recalls ${hits}/${titleTokens.length} requirement tokens`,\n }\n : {\n correct: false,\n reason: `content recalls only ${hits}/${titleTokens.length} requirement tokens`,\n }\n }\n}\n","/**\n * Produced-state extraction — normalize a run's runtime event stream into the\n * typed `ProducedState` the completion oracle consumes.\n *\n * `ProducedState` answers \"what did the agent actually produce\" — vault\n * artifacts, proposals, tool calls. The runtime emits these as a stream of\n * events; this module is the single normalization point from that stream to\n * the shape `verifyCompletion` expects.\n *\n * Input is structurally typed (`RuntimeEventLike`) so this module does not\n * depend on agent-runtime — agent-runtime's `RuntimeStreamEvent` satisfies it\n * structurally. The `content` on `ArtifactEventLike` and the whole\n * `proposal_created` variant are the runtime-side enrichments this contract\n * requires; the runtime emits them, this module consumes them.\n */\n\nimport type { Artifact } from './artifact-validator'\nimport type { ProducedProposal, ProducedState } from './completion-verifier'\n\n/** A tool the agent invoked. */\nexport interface ToolCallEventLike {\n type: 'tool_call'\n toolName: string\n}\n\n/**\n * An artifact the agent produced. `content` is the enriched field — the\n * runtime's base `artifact` event carries only metadata; the completion\n * oracle needs the body to verify the deliverable, so the runtime emits it.\n */\nexport interface ArtifactEventLike {\n type: 'artifact'\n artifactId: string\n name?: string\n mimeType?: string\n uri?: string\n content?: string\n}\n\n/** A proposal / filing the agent created. */\nexport interface ProposalEventLike {\n type: 'proposal_created'\n proposalId: string\n title: string\n status?: 'pending' | 'approved' | 'rejected'\n // body of the proposal (e.g. a submit_proposal `description`). When present,\n // the completion oracle correctness-checks it like artifact content; absent,\n // the proposal is graded presence-only.\n content?: string\n}\n\n/**\n * The subset of runtime stream events `extractProducedState` consumes.\n * agent-runtime's full `RuntimeStreamEvent` union satisfies this structurally;\n * the `{ type: string }` catch-all keeps the input permissive so callers can\n * pass the whole unfiltered telemetry stream — unrecognized events are skipped.\n */\nexport type RuntimeEventLike =\n | ToolCallEventLike\n | ArtifactEventLike\n | ProposalEventLike\n | { type: string }\n\nfunction artifactKind(mimeType: string | undefined): string {\n if (!mimeType) return 'file'\n if (mimeType.includes('json')) return 'json'\n if (mimeType.startsWith('text/')) return 'text'\n return 'file'\n}\n\n/**\n * Normalize a run's runtime event stream into `ProducedState`.\n *\n * Pure and total — unrecognized event types are skipped. `toolCalls` is\n * deduplicated by name in first-seen order (completion cares about a tool's\n * presence, not its call count). An artifact with neither a name nor a uri\n * still yields an entry keyed by its `artifactId` so it is never silently\n * dropped; an artifact with no `content` yields empty content, which the\n * completion oracle's structural check then rejects on its own.\n */\nexport function extractProducedState(events: readonly RuntimeEventLike[]): ProducedState {\n const artifacts: Artifact[] = []\n const proposals: ProducedProposal[] = []\n const toolCalls: string[] = []\n const seenTools = new Set<string>()\n\n for (const ev of events) {\n if (ev.type === 'tool_call') {\n const name = (ev as ToolCallEventLike).toolName\n if (name && !seenTools.has(name)) {\n seenTools.add(name)\n toolCalls.push(name)\n }\n } else if (ev.type === 'artifact') {\n const a = ev as ArtifactEventLike\n artifacts.push({\n kind: artifactKind(a.mimeType),\n path: a.name ?? a.uri ?? a.artifactId,\n content: a.content ?? '',\n })\n } else if (ev.type === 'proposal_created') {\n const p = ev as ProposalEventLike\n proposals.push({\n id: p.proposalId,\n title: p.title,\n status: p.status ?? 'pending',\n ...(p.content !== undefined ? { content: p.content } : {}),\n })\n }\n }\n\n return { artifacts, proposals, toolCalls }\n}\n","/**\n * Product-flow playback — drive the REAL product through a user story and\n * score the produced state per requirement (the launch \"Jira tick-off\").\n *\n * This is the substrate adapter + contract only. It plugs a `PlaybackDriver`\n * into the existing `runProfileMatrix` dispatch seam: a driver drives the real\n * product (a Playwright UI session or a sandbox workspace) and returns the\n * runtime event stream; `extractProducedState` + `verifyCompletion` then score\n * each requirement PASS/FAIL. The concrete drivers live in consumers — they\n * depend on browser / runtime infra the substrate must not import — so\n * agent-eval owns the seam, the `UserStory` contract, and the scoreboard.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n type CompletionRequirement,\n type CompletionVerdict,\n type CorrectnessChecker,\n type ProducedState,\n verifyCompletion,\n} from '../../completion-verifier'\nimport { extractProducedState, type RuntimeEventLike } from '../../produced-state'\nimport type { DispatchContext, Scenario } from '../types'\nimport type { ProfileDispatchFn } from './run-profile-matrix'\n\n/** One step of a user story — what the user does. The driver interprets\n * `payload` (a Playwright selector + action, or a sandbox chat turn). */\nexport interface PlaybackStep {\n /** Human-readable action, captured verbatim in the UX narrative. */\n action: string\n /** Driver-specific payload (e.g. `{ selector, fill }` or `{ turn }`). */\n payload?: Record<string, unknown>\n}\n\n/**\n * A user story = a runnable product journey plus the requirements that define\n * \"this story works\". Each requirement is one Jira ticket line. Extends\n * `Scenario` so a catalog drops straight into `runProfileMatrix({ scenarios })`.\n */\nexport interface UserStory extends Scenario {\n /** Human-readable story title (the ticket headline). */\n title: string\n /** Ordered steps the driver executes. */\n steps: PlaybackStep[]\n /** What must hold in the produced state for the story to pass. */\n requirements: CompletionRequirement[]\n}\n\n/** Dispatch context plus the profile under test (which cheap model, etc.). */\nexport interface PlaybackContext extends DispatchContext {\n profile: AgentProfile\n}\n\n/**\n * Drives the real product through a story and returns the runtime event stream\n * `extractProducedState` consumes. Implemented by CONSUMERS —\n * `SandboxPlaybackDriver` (real API / sandbox workspace) and\n * `PlaywrightPlaybackDriver` (real UI) — because they depend on runtime /\n * browser infra the substrate must not import. The driver MUST report LLM\n * usage through `ctx.cost.runPaidCall` so the backend-integrity check sees real\n * tokens (a run that never reports tokens reads as a stub).\n */\nexport interface PlaybackDriver<TStory extends UserStory = UserStory> {\n run(story: TStory, ctx: PlaybackContext): Promise<readonly RuntimeEventLike[]>\n}\n\n/**\n * Adapt a `PlaybackDriver` into a `runProfileMatrix` dispatch. The artifact the\n * matrix scores is the `ProducedState` extracted from the driver's event\n * stream — grade it with `scoreUserStory` (or a judge wrapping it).\n */\nexport function makePlaybackDispatch<TStory extends UserStory>(\n driver: PlaybackDriver<TStory>,\n): ProfileDispatchFn<TStory, ProducedState> {\n return async (profile, scenario, ctx) => {\n const events = await driver.run(scenario, { ...ctx, profile })\n return extractProducedState(events)\n }\n}\n\n/** A scored user story — the completion verdict plus its human title. */\nexport interface UserStoryVerdict extends CompletionVerdict {\n title: string\n}\n\n/**\n * Score one story's produced state against its requirements. Thin wrapper over\n * `verifyCompletion` that builds the gold from the story and returns a\n * per-requirement PASS/FAIL verdict. `checkCorrectness` is injected — a\n * deterministic stub in tests, `createLlmCorrectnessChecker` in production.\n */\nexport async function scoreUserStory(\n story: UserStory,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<UserStoryVerdict> {\n const verdict = await verifyCompletion(\n { taskId: story.id, requirements: story.requirements },\n state,\n checkCorrectness,\n )\n return { ...verdict, title: story.title }\n}\n\n/** One row of the launch scoreboard — story × requirement → PASS/FAIL. */\nexport interface ScoreboardRow {\n storyId: string\n storyTitle: string\n reqId: string\n reqTitle: string\n status: 'PASS' | 'FAIL'\n evidence: string[]\n}\n\n/**\n * Flatten story verdicts into the per-requirement scoreboard — the literal\n * Jira tick-off: one row per (story, requirement) with PASS/FAIL and the\n * evidence behind the verdict.\n */\nexport function userStoryScoreboard(verdicts: readonly UserStoryVerdict[]): ScoreboardRow[] {\n const rows: ScoreboardRow[] = []\n for (const v of verdicts) {\n for (const r of v.requirements) {\n rows.push({\n storyId: v.taskId,\n storyTitle: v.title,\n reqId: r.reqId,\n reqTitle: r.title,\n status: r.satisfied ? 'PASS' : 'FAIL',\n evidence: r.evidence,\n })\n }\n }\n return rows\n}\n\n/** Launch-readiness headline counts rolled up from the per-requirement rows. */\nexport interface ScoreboardSummary {\n /** Distinct user stories on the board. */\n stories: number\n /** Stories whose every requirement passed. */\n storiesFullyComplete: number\n /** Total (story, requirement) rows. */\n requirements: number\n /** Rows with status PASS. */\n passed: number\n /** Rows with status FAIL. */\n failed: number\n /** passed / requirements; 0 when there are no rows. */\n passRate: number\n}\n\n/** Roll the per-requirement rows up into the launch headline counts. */\nexport function scoreboardSummary(rows: readonly ScoreboardRow[]): ScoreboardSummary {\n const byStory = new Map<string, { total: number; passed: number }>()\n let passed = 0\n for (const r of rows) {\n const s = byStory.get(r.storyId) ?? { total: 0, passed: 0 }\n s.total++\n if (r.status === 'PASS') {\n s.passed++\n passed++\n }\n byStory.set(r.storyId, s)\n }\n let storiesFullyComplete = 0\n for (const s of byStory.values()) if (s.total > 0 && s.passed === s.total) storiesFullyComplete++\n return {\n stories: byStory.size,\n storiesFullyComplete,\n requirements: rows.length,\n passed,\n failed: rows.length - passed,\n passRate: rows.length === 0 ? 0 : passed / rows.length,\n }\n}\n\nexport interface ScoreboardRenderOptions {\n /** Document H1. Defaults to a generic playback title. */\n title?: string\n /** Key/value run metadata rendered under the headline (runId, backend, model, date). */\n meta?: Record<string, string>\n /** Max chars of joined evidence shown per row. Default 160. */\n maxEvidenceChars?: number\n}\n\nfunction escapeCell(s: string): string {\n return s.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}…`\n}\n\n/**\n * Render the scoreboard as a launch-readiness Markdown document — the literal\n * \"tick off every user story\" artifact: a headline roll-up, the open tickets\n * (FAIL rows) up top as the launch blockers, then a per-story table of\n * requirement → PASS/FAIL with the evidence behind each verdict. Pure: same\n * rows in, same bytes out (no clock/random), so it is safe to snapshot.\n */\nexport function renderScoreboardMarkdown(\n rows: readonly ScoreboardRow[],\n opts: ScoreboardRenderOptions = {},\n): string {\n const maxEv = opts.maxEvidenceChars ?? 160\n const sum = scoreboardSummary(rows)\n const pct = (n: number) => `${Math.round(n * 100)}%`\n const ev = (e: string[]) => escapeCell(truncate(e.join('; '), maxEv)) || '—'\n const out: string[] = [`# ${opts.title ?? 'Product-flow playback scoreboard'}`, '']\n if (opts.meta) {\n for (const [k, v] of Object.entries(opts.meta)) out.push(`- **${k}:** ${v}`)\n out.push('')\n }\n out.push(\n `**${sum.storiesFullyComplete}/${sum.stories}** user stories fully shipped · ` +\n `**${sum.passed}/${sum.requirements}** requirements passing (${pct(sum.passRate)}) · ` +\n `**${sum.failed}** open`,\n '',\n )\n const fails = rows.filter((r) => r.status === 'FAIL')\n if (fails.length > 0) {\n out.push('## Open tickets', '', '| Story | Requirement | Evidence |', '| --- | --- | --- |')\n for (const r of fails) {\n out.push(`| ${escapeCell(r.storyTitle)} | ${escapeCell(r.reqTitle)} | ${ev(r.evidence)} |`)\n }\n out.push('')\n } else {\n out.push('_All requirements passing — no open tickets._', '')\n }\n out.push('## Per-story tick-off', '')\n for (const storyId of [...new Set(rows.map((r) => r.storyId))]) {\n const storyRows = rows.filter((r) => r.storyId === storyId)\n const passed = storyRows.filter((r) => r.status === 'PASS').length\n const mark = passed === storyRows.length ? '✅' : '⚠️'\n out.push(\n `### ${escapeCell(storyRows[0]!.storyTitle)} — ${passed}/${storyRows.length} ${mark}`,\n '',\n '| Requirement | Status | Evidence |',\n '| --- | --- | --- |',\n )\n for (const r of storyRows) {\n out.push(\n `| ${escapeCell(r.reqTitle)} | ${r.status === 'PASS' ? '✅ PASS' : '❌ FAIL'} | ${ev(r.evidence)} |`,\n )\n }\n out.push('')\n }\n return out.join('\\n')\n}\n","/**\n * `runLineageLoop` — the live adapter that wires the {@link runLineage} DAG's\n * two abstract seams (`step`, `merge`) to the REAL improvement machinery, so the\n * multi-track, multi-parent improvement DAG can run against a real proposer +\n * real measurement.\n *\n * INTEGRATION CHOICE (smallest correct integration):\n * - `step` = ONE `SurfaceProposer.propose` from the track tip (a single GEPA\n * reflective generation, small population) + one scoring campaign\n * per candidate. The best-scoring candidate (elitist: the tip is\n * kept in the pool so a step never regresses below its parent)\n * becomes the new DAG node.\n * - `merge` = the SAME proposer driven with `ctx.paretoParents` set to the\n * 2+ parent surfaces, which fires `gepaProposer`'s GEPA\n * combine-complementary-lessons CROSSOVER, then one scoring\n * campaign on the merged surface.\n *\n * We deliberately do NOT run a full {@link runImprovementLoop} (baseline\n * campaign + optimization + two holdout campaigns + gate + optional PR) per DAG\n * step — that is the OUTER gated-promotion shell for a single lineage, far too\n * heavy to fire once per node. The DAG {@link Governor} controls BREADTH across\n * steps (extend / branch / merge / prune); the inner step is intentionally one\n * small generation. This mirrors the task's guidance: \"Keep the improvement\n * budget per step SMALL (1 generation, small population).\"\n *\n * Both machinery halves are injectable seams so the loop is unit-testable\n * without a live model or a sandbox:\n * - `proposer` — defaults to {@link gepaProposer} (needs `llm` + `model`).\n * A test injects a pure stub `SurfaceProposer`.\n * - `scoreSurface` — defaults to a {@link runCampaign} pass over\n * `holdoutScenarios ?? scenarios` (the \"agent\" =\n * `dispatchWithSurface`, the judges = `judges`). A test\n * injects a deterministic function of the surface string,\n * or supplies a stub `dispatchWithSurface` + `judges` and\n * exercises the real `runCampaign` path.\n *\n * Additive: no changes to `lineage.ts`, `run-optimization.ts`, or `gepa.ts`.\n */\n\nimport type { LlmClientOptions } from '../../llm-client'\nimport {\n type Governor,\n heuristicGovernor,\n type Lineage,\n type LineageNode,\n type LineageStore,\n type RunLineageSeed,\n runLineage,\n} from '../lineage'\nimport { gepaProposer } from '../proposers/gepa'\nimport { type RunCampaignOptions, runCampaign } from '../run-campaign'\nimport { campaignBreakdown, campaignMeanComposite } from '../score-utils'\nimport type { CampaignStorage } from '../storage'\nimport {\n isProposedCandidate,\n type JudgeConfig,\n type MutableSurface,\n type ParetoParent,\n type ProposedCandidate,\n type Scenario,\n type SurfaceProposer,\n} from '../types'\nimport { surfaceHash } from './run-optimization'\n\n/** A seed track: the initial surface + track identity. Unlike\n * {@link RunLineageSeed} there is NO `score` — `runLineageLoop` scores each\n * seed surface in an initial pass so seed fitness is measured, not asserted. */\nexport interface RunLineageLoopSeed {\n surface: MutableSurface\n track: string\n /** Human label for the strategy driving this track (e.g. `solve`,\n * `outside-the-box`, `contrarian`). */\n vision?: string\n /** Proposer label recorded on the seed node (e.g. `gepa`, `seed`). */\n proposer: string\n}\n\n/** The measured fitness of one surface — the value recorded on a DAG node. */\nexport interface SurfaceScore {\n score: number\n /** Per-objective vector (per-scenario composite) for Pareto dominance across\n * track tips. Omitted ⇒ the DAG uses the scalar `score`. */\n scoreVector?: number[]\n}\n\nexport interface RunLineageLoopOptions<TScenario extends Scenario, TArtifact> {\n /** The visioned tracks to seed the DAG with. Each is scored once up front. */\n seeds: RunLineageLoopSeed[]\n\n // ── Scoring machinery (default `scoreSurface` = a runCampaign pass) ────────\n /** Scenarios the candidate surfaces are proposed against + scored on. */\n scenarios: TScenario[]\n /** Held-out scenarios used to SCORE each DAG node's fitness. Defaults to\n * `scenarios` when omitted. Scored the same way for seeds, steps, and merges\n * so every node's `score` is comparable. */\n holdoutScenarios?: TScenario[]\n /** Judges for the scoring campaign. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** The \"agent\" seam: run the CURRENT surface on a scenario → artifact. Same\n * shape as `runOptimization`'s `dispatchWithSurface`. Required UNLESS a\n * custom `scoreSurface` is injected. */\n dispatchWithSurface?: (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: Parameters<RunCampaignOptions<TScenario, TArtifact>['dispatch']>[1],\n ) => Promise<TArtifact>\n /** Where scoring campaigns write. Required UNLESS `scoreSurface` is injected. */\n runDir?: string\n\n // ── Proposer machinery (default = gepaProposer) ───────────────────────────\n /** Router transport for the default `gepaProposer`. Required UNLESS a custom\n * `proposer` is injected. */\n llm?: LlmClientOptions\n /** Model for the default `gepaProposer`. Required UNLESS a custom `proposer`\n * is injected. */\n model?: string\n /** What is being optimized — appears in the GEPA reflection/combine prompts.\n * Default `'agent surface'`. */\n target?: string\n /** Candidates proposed per extend/branch step (BREADTH within one step).\n * Default 4. The merge always proposes a single crossover. */\n populationSize?: number\n\n // ── DAG control ───────────────────────────────────────────────────────────\n /** Agent-managed decision layer. Default {@link heuristicGovernor}. */\n governor?: Governor\n budget: { maxSteps: number }\n store?: LineageStore\n\n // ── Injectable seams (unit-testable without a live model) ─────────────────\n /** Override the per-step proposer. Default {@link gepaProposer}. Inject a\n * pure stub to unit-test without an LLM. */\n proposer?: SurfaceProposer\n /** Override how a surface is scored into a DAG-node fitness. Default is a\n * {@link runCampaign} pass over `holdoutScenarios ?? scenarios`. Inject a\n * deterministic function to unit-test without a campaign. */\n scoreSurface?: (surface: MutableSurface) => Promise<SurfaceScore>\n\n // ── runCampaign passthroughs (consumed by the default `scoreSurface`) ─────\n seed?: number\n reps?: number\n storage?: CampaignStorage\n tracing?: 'on' | 'off'\n expectUsage?: 'assert' | 'warn' | 'off'\n maxConcurrency?: number\n dispatchTimeoutMs?: number\n /** Test seam — deterministic wall clock forwarded to `runCampaign`. */\n now?: () => Date\n\n log?: (msg: string, fields?: Record<string, unknown>) => void\n}\n\nexport interface RunLineageLoopResult {\n lineage: Lineage\n best: LineageNode | undefined\n steps: number\n}\n\n/** Normalize a proposer output (bare surface OR `ProposedCandidate`) to its\n * surface + optional rationale. */\nfunction toCandidate(p: MutableSurface | ProposedCandidate): {\n surface: MutableSurface\n rationale?: string\n} {\n return isProposedCandidate(p)\n ? { surface: p.surface, ...(p.rationale ? { rationale: p.rationale } : {}) }\n : { surface: p }\n}\n\n/**\n * Wire the {@link runLineage} DAG's `step`/`merge` seams to a real\n * `SurfaceProposer` + a real scoring campaign and run the multi-track improvement\n * DAG live under a {@link Governor}.\n */\nexport async function runLineageLoop<TScenario extends Scenario, TArtifact>(\n opts: RunLineageLoopOptions<TScenario, TArtifact>,\n): Promise<RunLineageLoopResult> {\n const governor = opts.governor ?? heuristicGovernor()\n const populationSize = opts.populationSize ?? 4\n if (populationSize < 1) {\n throw new Error('runLineageLoop: populationSize must be >= 1')\n }\n\n // ── Resolve the proposer seam ─────────────────────────────────────────────\n let proposer = opts.proposer\n if (!proposer) {\n if (!opts.llm || !opts.model) {\n throw new Error(\n 'runLineageLoop: a proposer is required — either inject `proposer`, or provide `llm` + `model` for the default gepaProposer.',\n )\n }\n proposer = gepaProposer({\n llm: opts.llm,\n model: opts.model,\n target: opts.target ?? 'agent surface',\n // GEPA combine-complementary-lessons is what the `merge` seam relies on.\n combineParents: true,\n })\n }\n\n // ── Resolve the scoreSurface seam ─────────────────────────────────────────\n const scoringScenarios = opts.holdoutScenarios ?? opts.scenarios\n let scoreSurface = opts.scoreSurface\n if (!scoreSurface) {\n const dispatchWithSurface = opts.dispatchWithSurface\n const runDir = opts.runDir\n if (!dispatchWithSurface || !runDir) {\n throw new Error(\n 'runLineageLoop: scoring is required — either inject `scoreSurface`, or provide `dispatchWithSurface` (the agent) + `runDir` for the default runCampaign scorer.',\n )\n }\n if (scoringScenarios.length === 0) {\n throw new Error(\n 'runLineageLoop: the default scorer needs at least one scenario (holdoutScenarios ?? scenarios is empty).',\n )\n }\n scoreSurface = async (surface: MutableSurface): Promise<SurfaceScore> => {\n const campaign = await runCampaign<TScenario, TArtifact>({\n scenarios: scoringScenarios,\n dispatch: (scenario, ctx) => dispatchWithSurface(surface, scenario, ctx),\n dispatchRef: `lineage-loop:${surfaceHash(surface)}`,\n runDir: `${runDir}/score/${surfaceHash(surface)}`,\n ...(opts.judges ? { judges: opts.judges } : {}),\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.reps !== undefined ? { reps: opts.reps } : {}),\n ...(opts.storage ? { storage: opts.storage } : {}),\n ...(opts.tracing ? { tracing: opts.tracing } : {}),\n ...(opts.expectUsage ? { expectUsage: opts.expectUsage } : {}),\n ...(opts.maxConcurrency !== undefined ? { maxConcurrency: opts.maxConcurrency } : {}),\n ...(opts.dispatchTimeoutMs !== undefined\n ? { dispatchTimeoutMs: opts.dispatchTimeoutMs }\n : {}),\n ...(opts.now ? { now: opts.now } : {}),\n })\n const score = campaignMeanComposite(campaign)\n // Build the objective vector in a STABLE order (scoringScenarios order) so\n // component i is the same scenario across every scored surface — a\n // prerequisite for the DAG's Pareto dominance across track tips.\n const byId = new Map(\n campaignBreakdown(campaign).scenarios.map((s) => [s.scenarioId, s.composite]),\n )\n const scoreVector = scoringScenarios.map((s) => byId.get(s.id) ?? 0)\n return { score, scoreVector }\n }\n }\n\n // Build the per-parent objective map GEPA's combine prompt reads: per-scenario\n // composite when a scoreVector is present, else the scalar score. Aligned to\n // `scoringScenarios` order (the same order `scoreSurface` builds the vector in).\n const objectivesOf = (node: LineageNode): Record<string, number> => {\n const objectives: Record<string, number> = {}\n if (node.scoreVector && node.scoreVector.length > 0) {\n scoringScenarios.forEach((s, i) => {\n objectives[s.id] = node.scoreVector![i] ?? 0\n })\n if (Object.keys(objectives).length > 0) return objectives\n }\n objectives.composite = node.score\n return objectives\n }\n\n // ── (1) Score every seed surface → RunLineageSeed[] ───────────────────────\n const scoredSeeds: RunLineageSeed[] = []\n for (const seed of opts.seeds) {\n const measured = await scoreSurface(seed.surface)\n scoredSeeds.push({\n surface: seed.surface as string,\n track: seed.track,\n proposer: seed.proposer,\n score: measured.score,\n ...(seed.vision !== undefined ? { vision: seed.vision } : {}),\n ...(measured.scoreVector !== undefined ? { scoreVector: measured.scoreVector } : {}),\n })\n }\n\n // ── (2) The live `step` seam: propose from the tip, score, pick the best ──\n const step = async (args: {\n tip: LineageNode\n }): Promise<SurfaceScore & { surface: string; rationale?: string }> => {\n const proposed = await proposer!.propose({\n currentSurface: args.tip.surface,\n history: [],\n findings: [],\n populationSize,\n generation: 0,\n signal: new AbortController().signal,\n paretoParents: [],\n })\n\n // Elitism: keep the tip in the pool so a step never regresses below its\n // parent — mirrors runOptimization keeping the winner as the baseline when\n // no candidate beats it. A tie resolves to the earliest pool entry (the tip\n // first, then proposer order) → deterministic.\n type PoolEntry = {\n surface: MutableSurface\n score: number\n scoreVector?: number[]\n rationale?: string\n }\n const pool: PoolEntry[] = [\n {\n surface: args.tip.surface,\n score: args.tip.score,\n ...(args.tip.scoreVector !== undefined ? { scoreVector: args.tip.scoreVector } : {}),\n ...(args.tip.rationale !== undefined ? { rationale: args.tip.rationale } : {}),\n },\n ]\n for (const p of proposed) {\n const { surface, rationale } = toCandidate(p)\n const measured = await scoreSurface!(surface)\n pool.push({\n surface,\n score: measured.score,\n ...(measured.scoreVector !== undefined ? { scoreVector: measured.scoreVector } : {}),\n ...(rationale !== undefined ? { rationale } : {}),\n })\n }\n\n let best = pool[0]!\n for (const entry of pool) {\n if (entry.score > best.score) best = entry\n }\n return {\n surface: best.surface as string,\n score: best.score,\n ...(best.scoreVector !== undefined ? { scoreVector: best.scoreVector } : {}),\n ...(best.rationale !== undefined ? { rationale: best.rationale } : {}),\n }\n }\n\n // ── (3) The live `merge` seam: GEPA crossover of the parents, then score ──\n const merge = async (args: {\n parents: LineageNode[]\n }): Promise<SurfaceScore & { surface: string; rationale?: string }> => {\n // Order parents best-first; the strongest surface is the reflection base and\n // GEPA reads each parent's per-scenario objectives to combine strengths.\n const ordered = [...args.parents].sort((a, b) => b.score - a.score)\n const paretoParents: ParetoParent[] = ordered.map((node) => ({\n surface: node.surface,\n surfaceHash: surfaceHash(node.surface),\n objectives: objectivesOf(node),\n composite: node.score,\n generation: node.generation,\n }))\n\n const proposed = await proposer!.propose({\n currentSurface: ordered[0]!.surface,\n history: [],\n findings: [],\n // A merge is a single crossover; combineParents fires because\n // paretoParents has > 1 string member.\n populationSize: 1,\n // generation >= 1 keeps the combine slot semantically a \"merge\" step.\n generation: 1,\n signal: new AbortController().signal,\n paretoParents,\n })\n\n const first = proposed[0]\n // Fall back to the best parent surface if the proposer returned nothing\n // mergeable (a degenerate proposer) — never fabricate a surface.\n const merged = first ? toCandidate(first) : { surface: ordered[0]!.surface as string }\n const measured = await scoreSurface!(merged.surface)\n return {\n surface: merged.surface as string,\n score: measured.score,\n ...(measured.scoreVector !== undefined ? { scoreVector: measured.scoreVector } : {}),\n ...(merged.rationale !== undefined ? { rationale: merged.rationale } : {}),\n }\n }\n\n // ── (4) Run the DAG under the governor ────────────────────────────────────\n const result = await runLineage({\n seeds: scoredSeeds,\n step,\n merge,\n governor,\n budget: opts.budget,\n ...(opts.store ? { store: opts.store } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n })\n\n return { lineage: result.lineage, best: result.best, steps: result.steps }\n}\n","/**\n * `runProfileMatrix` — the missing keystone between `runAgentMatrix` and the\n * backend-integrity guard.\n *\n * The gap it closes: `runAgentMatrix` is a topology-opaque scheduler whose\n * cells return a bare `{ output, verdict, costUsd }` — no `tokenUsage`, not a\n * `RunRecord`. `assertRealBackend` / `summarizeBackendIntegrity` key on\n * `RunRecord.tokenUsage`, so they cannot run on a raw matrix result. Every\n * consumer therefore hand-writes the same bridge: fan a profile × scenario\n * cartesian, call dispatch, fabricate a `RunRecord` with token usage, thread it\n * back, run the integrity guard. That hand-rolled bridge is exactly the pile of\n * bespoke `eval:*` scripts the adoption skills keep trying (and failing) to\n * forbid.\n *\n * `runProfileMatrix` IS that bridge, once:\n *\n * - axis 3 (PROFILE) = `profiles: AgentProfile[]`\n * - axis 1 (PERSONA/SCENARIO) = `scenarios: Scenario[]` (each scenario carries\n * its persona; `personaOf` groups them for the `byPersona` pivot)\n * - the scoring axis = `judges`\n *\n * It runs `runCampaign` once per profile (reusing its seeds, reps, bootstrap\n * CIs, resumability, and the `LabeledScenarioStore` capture flywheel), maps\n * every cell to a validated `RunRecord` carrying the real `tokenUsage` the\n * dispatch committed via `ctx.cost.runPaidCall`, and runs `assertRealBackend`\n * BY CONSTRUCTION before returning — so a stub-backend run fails loudly instead\n * of reporting a clean 0/N leaderboard.\n *\n * Dispatch contract: a dispatch that calls an LLM MUST report usage via\n * `ctx.cost.runPaidCall({ execute, receipt })`.\n * A dispatch that reports zero tokens is indistinguishable from a stub and the\n * integrity guard treats it as one.\n */\n\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileHash,\n agentProfileId,\n agentProfileModelId,\n HARNESS_NATIVE_MODEL,\n harnessAxisOf,\n} from '../../agent-profile'\nimport { type AgentProfileCell, buildAgentProfileCell } from '../../agent-profile-cell'\nimport { AgentEvalError } from '../../errors'\nimport {\n assertRealBackend,\n type BackendIntegrityReport,\n summarizeBackendIntegrity,\n} from '../../integrity/backend-integrity'\nimport {\n modelHasSnapshot,\n type RunOutcome,\n type RunRecord,\n type RunSplitTag,\n validateRunRecord,\n} from '../../run-record'\nimport { runCampaign } from '../run-campaign'\nimport type { CampaignStorage } from '../storage'\nimport type {\n CampaignCellResult,\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n LabeledScenarioSource,\n LabeledScenarioStore,\n Scenario,\n} from '../types'\n\n/** Thrown when the matrix is misconfigured (no profiles, a profile whose model\n * lacks a snapshot version, etc.). Distinct from `BackendIntegrityError`,\n * which signals a stub backend at run time. */\nexport class ProfileMatrixError extends AgentEvalError {\n constructor(message: string) {\n super('profile_matrix', message)\n }\n}\n\n/** Dispatch for one cell: render `profile` against `scenario`, returning the\n * artifact the judges score. Run LLM work through `ctx.cost.runPaidCall` —\n * the integrity check depends on its receipt. */\nexport type ProfileDispatchFn<TScenario extends Scenario, TArtifact> = (\n profile: AgentProfile,\n scenario: TScenario,\n ctx: DispatchContext,\n) => Promise<TArtifact>\n\nexport interface RunProfileMatrixOptions<TScenario extends Scenario, TArtifact> {\n /** Axis 3 — the agent-under-test configurations. Each is one column. */\n profiles: AgentProfile[]\n /** Axis 1 — the persona/scenario corpus, run against every profile. */\n scenarios: TScenario[]\n /** Renders one (profile, scenario) cell. */\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n /** The scoring axis. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Where each profile's campaign writes artifacts/traces. One subdir per\n * profile. */\n runDir: string\n /** Git SHA the harness ran from — stamped onto every RunRecord (mandatory\n * for paper-grade records). */\n commitSha: string\n /** Logical experiment id shared across the whole matrix so the promotion\n * gate can pair profiles on matched scenarios. Default: a hash of the\n * profile + scenario ids. */\n experimentId?: string\n /** Which split these runs belong to. Default `'search'`. */\n splitTag?: RunSplitTag\n /** Replicates per (profile, scenario) cell for CI bands. Default 1. */\n reps?: number\n /** Campaign seed (per profile). Default 42. */\n seed?: number\n /**\n * Backend-integrity posture, enforced AFTER the matrix completes:\n * - `'assert'` (default) — throw `BackendIntegrityError` if the run was a\n * stub (and, with `allowMixed:false`, if it was mixed).\n * - `'warn'` — log the verdict but never throw.\n * - `'off'` — skip the guard entirely (only for offline/replay analysis).\n */\n integrity?: 'assert' | 'warn' | 'off'\n /** Forwarded to `assertRealBackend`. Default true (tolerate partial 429\n * cascades); set false for strict CI gates. */\n allowMixed?: boolean\n /** Max concurrent cells WITHIN each profile's campaign. Default 2.\n * Profiles run sequentially so the cost ceiling is honored deterministically. */\n maxConcurrency?: number\n /** Cumulative USD cap per profile campaign. */\n costCeiling?: number\n /** Capture flywheel — forwarded to each campaign. */\n labeledStore?: LabeledScenarioStore | 'off'\n captureSource?: LabeledScenarioSource\n /** Storage backend. Default `fsCampaignStorage`. Pass\n * `inMemoryCampaignStorage()` for edge/CF-Worker/test runs. */\n storage?: CampaignStorage\n /** Test seam — override the wall clock. */\n now?: () => Date\n /** Optional persona key per scenario — drives the `byPersona` pivot. When\n * unset, `byPersona` is omitted. */\n personaOf?: (scenario: TScenario) => string\n /** Validate every produced RunRecord with `validateRunRecord` (fail-loud).\n * Default true — catches bad model snapshots and non-finite judge dims at\n * the boundary instead of letting them poison downstream analysis. */\n validate?: boolean\n /** Corpus-by-default: derive the trajectory text (`prompt` + `completion`)\n * for each cell from its artifact + scenario. When set, every produced\n * record carries `prompt`/`completion` (a `CorpusRecord`) so the run's\n * graded trajectories can be appended to the durable RL corpus with no\n * side-channel — `appendToCorpus(result.records, path)`. Fail-soft: a\n * throwing or undefined-returning extractor just omits the text. */\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n}\n\nexport interface ProfileSummary {\n profileId: string\n profileHash: string\n model: string\n /** RunRecords produced for this profile (= scenarios × reps). */\n records: number\n /** Mean composite across this profile's records. */\n meanComposite: number\n totalCostUsd: number\n /** Per-profile integrity verdict — surfaces a single profile that ran stub\n * even when the matrix as a whole looks real. */\n integrity: BackendIntegrityReport\n}\n\nexport interface ScenarioRollup {\n meanComposite: number\n n: number\n}\n\nexport interface RunProfileMatrixResult<TArtifact, TScenario extends Scenario> {\n matrixId: string\n experimentId: string\n /** One RunRecord per (profile, scenario, rep) cell — the integrity-checked,\n * paper-grade output. Feed straight into `analyzeRuns`, `HeldOutGate`,\n * scorecards, the hosted wire format. */\n records: RunRecord[]\n byProfile: Record<string, ProfileSummary>\n byScenario: Record<string, ScenarioRollup>\n /** Present only when `personaOf` was supplied. */\n byPersona?: Record<string, ScenarioRollup>\n /** Whole-matrix integrity report (the one `integrity:'assert'` enforces). */\n integrity: BackendIntegrityReport\n /** The raw per-profile campaign results, keyed by profile id. */\n campaigns: Record<string, CampaignResult<TArtifact, TScenario>>\n}\n\nfunction sanitize(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction sha(input: unknown): string {\n return createHash('sha256').update(JSON.stringify(input)).digest('hex')\n}\n\nfunction mean(xs: number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\nfunction cellComposite(cell: CampaignCellResult<unknown>): number {\n const composites = Object.values(cell.judgeScores).map((s) => s.composite)\n return composites.length === 0 ? 0 : mean(composites)\n}\n\ninterface BuildRecordArgs<TScenario extends Scenario, TArtifact> {\n cell: CampaignCellResult<TArtifact>\n profile: AgentProfile\n profileHash: string\n configHash: string\n experimentId: string\n splitTag: RunSplitTag\n commitSha: string\n matrixId: string\n /** The (profile, harness, model, dimensions) identity of this cell — attached to\n * every record so results group by the canonical `groupRunsByAgentProfileCell`\n * (harness/model aware) instead of profileId alone. */\n agentProfileCell?: AgentProfileCell\n scenario?: TScenario\n corpusText?: (\n artifact: TArtifact,\n scenario: TScenario,\n ) => { prompt: string; completion: string } | undefined\n}\n\n/**\n * Resolve the concrete, snapshot-bearing model for a cell whose profile\n * declared the `HARNESS_NATIVE_MODEL` sentinel (a vendor-locked harness that\n * resolves its model at runtime). The dispatch must have reported it via\n * the model in a paid-call receipt — surfaced as `cell.resolvedModel`. Throws when it is\n * missing or lacks a snapshot, so a provenance-broken row can never be\n * recorded as the bare sentinel.\n */\nfunction requireResolvedModel(cell: CampaignCellResult<unknown>, profileId: string): string {\n const resolved = cell.resolvedModel?.trim()\n if (!resolved) {\n throw new ProfileMatrixError(\n `profile '${profileId}' declared the '${HARNESS_NATIVE_MODEL}' runtime-resolved model but its dispatch reported no resolved model for cell '${cell.cellId}' — return it in the ctx.cost.runPaidCall receipt so the RunRecord pins the real model (never records '${HARNESS_NATIVE_MODEL}')`,\n )\n }\n if (!modelHasSnapshot(resolved)) {\n throw new ProfileMatrixError(\n `profile '${profileId}' resolved to model '${resolved}' for cell '${cell.cellId}', which lacks a snapshot version — pin it (name@YYYY-MM-DD or name-YYYYMMDD) in the paid-call receipt`,\n )\n }\n return resolved\n}\n\nfunction buildRunRecord<TScenario extends Scenario, TArtifact>(\n args: BuildRecordArgs<TScenario, TArtifact>,\n): RunRecord {\n const { cell, profile, profileHash, configHash, experimentId, splitTag, commitSha, matrixId } =\n args\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n // Provenance guarantee: every recorded cell pins a real, snapshot-bearing\n // model. A profile that declared the `HARNESS_NATIVE_MODEL` sentinel resolved\n // its model at runtime — the dispatch commits it in the paid-call receipt,\n // surfaced here as `cell.resolvedModel`. Substitute it (and require a\n // snapshot). If the dispatch reported no resolved model, or an unpinned one,\n // FAIL LOUD — never silently record the sentinel, which would erase which\n // model actually produced the row.\n const model =\n declaredModel === HARNESS_NATIVE_MODEL ? requireResolvedModel(cell, profileId) : declaredModel\n const composite = cellComposite(cell)\n\n // Flatten judge dimensions (judge-prefixed to avoid collisions) into raw.\n const raw: Record<string, number> = { composite }\n const perJudge: Record<string, Record<string, number>> = {}\n const dimAccum: Record<string, number[]> = {}\n const notes: string[] = []\n for (const [judgeName, js] of Object.entries(cell.judgeScores)) {\n perJudge[judgeName] = { ...js.dimensions }\n for (const [dim, value] of Object.entries(js.dimensions)) {\n raw[`${judgeName}.${dim}`] = value\n dimAccum[dim] ??= []\n dimAccum[dim]!.push(value)\n }\n if (js.notes) notes.push(`${judgeName}: ${js.notes}`)\n }\n const perDimMean: Record<string, number> = {}\n for (const [dim, values] of Object.entries(dimAccum)) perDimMean[dim] = mean(values)\n\n // Cost / efficiency guardrail dimensions — RAW-ONLY. The composite stays the\n // judge objective (anti-Goodhart); these are tracked + dashboarded + carried\n // into the dataset, never optimized. Makes every run multi-dimensional by\n // construction (the cost/tokens/latency the cell already reports). Computed\n // ratios are guarded so a zero-cost stub or zero-quality cell never writes a\n // non-finite value into the raw bag.\n //\n const costUsd = cell.costUsd\n raw.cost_usd = costUsd\n raw.cost_estimated = cell.costEstimated ? 1 : 0\n raw.tokens_input = cell.tokenUsage.input\n raw.tokens_output = cell.tokenUsage.output\n if (typeof cell.tokenUsage.cached === 'number') raw.tokens_cached = cell.tokenUsage.cached\n raw.latency_ms = cell.durationMs\n if (costUsd > 0) {\n raw.tokens_per_dollar = (cell.tokenUsage.input + cell.tokenUsage.output) / costUsd\n }\n if (composite > 0.01) raw.cost_per_quality = costUsd / composite\n\n const outcome: RunOutcome =\n splitTag === 'holdout' ? { holdoutScore: composite, raw } : { searchScore: composite, raw }\n if (Object.keys(perJudge).length > 0) {\n outcome.judgeScores = {\n perJudge,\n perDimMean,\n composite,\n ...(notes.length > 0 ? { notes: notes.join(' | ') } : {}),\n }\n }\n\n const record: RunRecord & { prompt?: string; completion?: string } = {\n runId: `${matrixId}:${profileId}:${cell.cellId}`,\n experimentId,\n candidateId: profileId,\n seed: cell.seed,\n model,\n promptHash: profileHash,\n configHash,\n commitSha,\n wallMs: cell.durationMs,\n costUsd,\n tokenUsage: cell.tokenUsage,\n outcome,\n splitTag,\n scenarioId: cell.scenarioId,\n ...(args.agentProfileCell ? { agentProfile: args.agentProfileCell } : {}),\n ...(cell.error ? { failureMode: cell.error } : {}),\n }\n\n // Corpus-by-default: stamp the trajectory text onto the record (CorpusRecord\n // shape — the validator ignores the extra keys) so the run is dataset-able\n // with no side-channel. Fail-soft: a bad extractor never fails the run.\n if (args.corpusText && args.scenario) {\n try {\n const text = args.corpusText(cell.artifact, args.scenario)\n if (text && typeof text.prompt === 'string' && typeof text.completion === 'string') {\n record.prompt = text.prompt\n record.completion = text.completion\n }\n } catch {\n // extractor threw — omit trajectory text, keep the graded record.\n }\n }\n return record\n}\n\n/**\n * Profile × scenario matrix runner: fan N agent profiles across M scenarios, project each cell to a validated `RunRecord` with real token usage, and enforce the backend-integrity guard before returning.\n */\nexport async function runProfileMatrix<TScenario extends Scenario, TArtifact>(\n opts: RunProfileMatrixOptions<TScenario, TArtifact>,\n): Promise<RunProfileMatrixResult<TArtifact, TScenario>> {\n if (opts.profiles.length === 0) throw new ProfileMatrixError('profiles must not be empty')\n if (opts.scenarios.length === 0) throw new ProfileMatrixError('scenarios must not be empty')\n\n const splitTag = opts.splitTag ?? 'search'\n const seed = opts.seed ?? 42\n const validate = opts.validate ?? true\n const integrityMode = opts.integrity ?? 'assert'\n const profileIds = opts.profiles.map(agentProfileId)\n const experimentId =\n opts.experimentId ??\n `pm_${sha({ profileIds, scenarios: opts.scenarios.map((s) => s.id) }).slice(0, 16)}`\n const matrixId = `mtx_${sha({ experimentId, profileIds, seed, splitTag }).slice(0, 16)}`\n // Scenario lookup for the corpus-text extractor (records carry trajectory text).\n const scenarioById = new Map(opts.scenarios.map((s) => [s.id, s]))\n\n // Preflight: every profile must hash (non-empty model) AND its model must\n // carry a snapshot version, BEFORE any LLM spend. A probe record run through\n // validateRunRecord catches both in the exact place they'd otherwise surface\n // far downstream.\n //\n // Exception: a vendor-locked harness that snapped to `HARNESS_NATIVE_MODEL`\n // declares no concrete model up front — the backend resolves it at runtime.\n // Its declared model deliberately carries no snapshot, so probing it verbatim\n // would fail the snapshot assertion for a profile that IS recordable (the\n // resolved model, committed in the paid-call receipt, pins the RunRecord).\n // Probe such a profile with a snapshot-bearing placeholder so the OTHER\n // recordability checks still run, without asserting a snapshot the sentinel\n // can't have. `buildRunRecord` enforces the real snapshot from the resolved\n // model — never records the sentinel.\n for (const profile of opts.profiles) {\n const profileHash = agentProfileHash(profile)\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n const model =\n declaredModel === HARNESS_NATIVE_MODEL\n ? `${HARNESS_NATIVE_MODEL}@runtime-resolved`\n : declaredModel\n try {\n validateRunRecord({\n runId: `${matrixId}:${profileId}:probe`,\n experimentId,\n candidateId: profileId,\n seed,\n model,\n promptHash: profileHash,\n configHash: profileHash,\n commitSha: opts.commitSha,\n wallMs: 0,\n costUsd: 0,\n tokenUsage: { input: 0, output: 0 },\n outcome:\n splitTag === 'holdout' ? { holdoutScore: 0, raw: {} } : { searchScore: 0, raw: {} },\n splitTag,\n })\n } catch (err) {\n throw new ProfileMatrixError(\n `profile '${profileId}' is not recordable: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n const records: RunRecord[] = []\n const campaigns: Record<string, CampaignResult<TArtifact, TScenario>> = {}\n const byProfile: Record<string, ProfileSummary> = {}\n\n for (const profile of opts.profiles) {\n const profileHash = agentProfileHash(profile)\n const profileId = agentProfileId(profile)\n const declaredModel = agentProfileModelId(profile)\n const configHash = sha({\n profile: profileHash,\n judges: (opts.judges ?? []).map((j) => j.name),\n seed,\n splitTag,\n })\n\n // Bind the profile into a campaign dispatch. Name it so the campaign's\n // manifest hash is stable + distinct per profile.\n const dispatch = (scenario: TScenario, ctx: DispatchContext): Promise<TArtifact> =>\n opts.dispatch(profile, scenario, ctx)\n Object.defineProperty(dispatch, 'name', { value: `profile_${sanitize(profileId)}` })\n\n const campaign = await runCampaign<TScenario, TArtifact>({\n scenarios: opts.scenarios,\n dispatch,\n judges: opts.judges,\n seed,\n reps: opts.reps,\n maxConcurrency: opts.maxConcurrency,\n costCeiling: opts.costCeiling,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n storage: opts.storage,\n now: opts.now,\n runDir: join(opts.runDir, sanitize(profileId)),\n })\n\n // The canonical (profile, harness, model) identity for every record in this\n // column, so results group by `groupRunsByAgentProfileCell` (harness/model\n // aware). Harness comes from the axis stamp `expandProfileAxes` left on the\n // profile; a profile that wasn't axis-expanded simply has no harness in its\n // cell (unchanged grouping). The `model` is the profile's declared model\n // UNLESS it snapped to the `HARNESS_NATIVE_MODEL` sentinel — then the cell\n // identity must carry the RUNTIME-RESOLVED model per cell (surfaced via\n // `cell.resolvedModel`), so the pivot groups by the real Kimi/etc. model and\n // the cell identity matches the RunRecord's pinned model.\n const axis = harnessAxisOf(profile)\n const buildCellIdentity = (cellModel: string): Promise<AgentProfileCell> =>\n buildAgentProfileCell({\n profileId,\n sourceProfile: { kind: 'agent-interface-profile', hash: profileHash },\n model: cellModel,\n ...(axis ? { harness: { id: axis.harness } } : {}),\n })\n // A profile with a concrete declared model builds its cell identity once and\n // shares it; the sentinel path builds one per cell after resolution.\n const sharedCellIdentity =\n declaredModel === HARNESS_NATIVE_MODEL ? undefined : await buildCellIdentity(declaredModel)\n\n const profileRecords: RunRecord[] = []\n for (const cell of campaign.cells) {\n const agentProfileCell =\n sharedCellIdentity ?? (await buildCellIdentity(requireResolvedModel(cell, profileId)))\n const record = buildRunRecord({\n cell,\n profile,\n profileHash,\n configHash,\n experimentId,\n splitTag,\n commitSha: opts.commitSha,\n matrixId,\n agentProfileCell,\n scenario: scenarioById.get(cell.scenarioId),\n corpusText: opts.corpusText,\n })\n if (validate) validateRunRecord(record)\n profileRecords.push(record)\n records.push(record)\n }\n\n const totalCostUsd = campaign.aggregates.totalCostUsd\n campaigns[profileId] = campaign\n\n byProfile[profileId] = {\n profileId,\n profileHash,\n // The declared model, unless it snapped to the sentinel — then the\n // resolved model the cells actually ran on (all cells of a profile share\n // one harness, so the first record's model is representative).\n model:\n declaredModel === HARNESS_NATIVE_MODEL\n ? (profileRecords[0]?.model ?? declaredModel)\n : declaredModel,\n records: profileRecords.length,\n meanComposite: mean(profileRecords.map(compositeOf)),\n totalCostUsd,\n integrity: summarizeBackendIntegrity(profileRecords),\n }\n }\n\n // Integrity by construction — the whole point of the primitive.\n const integrity = summarizeBackendIntegrity(records)\n if (integrityMode === 'assert') {\n assertRealBackend(records, { allowMixed: opts.allowMixed ?? true })\n } else if (integrityMode === 'warn' && integrity.verdict !== 'real') {\n // eslint-disable-next-line no-console\n console.warn(\n `[runProfileMatrix] backend integrity: ${integrity.verdict} — ${integrity.diagnosis}`,\n )\n }\n\n // Pivots.\n const byScenario = rollup(records, (r) => r.scenarioId)\n const byPersona = opts.personaOf\n ? rollupByPersona(records, opts.scenarios, opts.personaOf)\n : undefined\n\n return { matrixId, experimentId, records, byProfile, byScenario, byPersona, integrity, campaigns }\n}\n\n/** Composite for a produced RunRecord (the split score it carries). */\nfunction compositeOf(r: RunRecord): number {\n return r.outcome.holdoutScore ?? r.outcome.searchScore ?? 0\n}\n\nfunction rollup(\n records: RunRecord[],\n keyOf: (r: RunRecord) => string | undefined,\n): Record<string, ScenarioRollup> {\n const groups = new Map<string, number[]>()\n for (const r of records) {\n const key = keyOf(r)\n if (key === undefined) continue\n const arr = groups.get(key) ?? []\n arr.push(compositeOf(r))\n groups.set(key, arr)\n }\n const out: Record<string, ScenarioRollup> = {}\n for (const [key, xs] of groups) out[key] = { meanComposite: mean(xs), n: xs.length }\n return out\n}\n\nfunction rollupByPersona<TScenario extends Scenario>(\n records: RunRecord[],\n scenarios: TScenario[],\n personaOf: (s: TScenario) => string,\n): Record<string, ScenarioRollup> {\n const personaByScenarioId = new Map<string, string>()\n for (const s of scenarios) personaByScenarioId.set(s.id, personaOf(s))\n return rollup(records, (r) => (r.scenarioId ? personaByScenarioId.get(r.scenarioId) : undefined))\n}\n","import { createHash } from 'node:crypto'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { type HarnessType, harnessSupportsModel } from '@tangle-network/agent-interface'\nimport { ValidationError } from './errors'\nimport { canonicalize } from './pre-registration'\n\nexport type { AgentProfile, HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * The agentic coding harnesses an eval sweeps by default — the ones we care about\n * ranking. This is the SINGLE source of that list; consumers import it instead of\n * re-declaring their own (a re-declared list is how the fleet drifts). Pass an\n * explicit `harnesses` (e.g. `harnessTypeSchema.options` for literally every known\n * harness) to widen beyond these.\n */\nexport const CODING_HARNESSES: readonly HarnessType[] = [\n 'opencode',\n 'claude-code',\n 'codex',\n 'kimi-code',\n]\n\nexport interface ProfileAxisSpec {\n /** The domain profile to sweep. Its prompt/tools/skills are held fixed; only the\n * harness and model vary. `model.default` is the fallback model. */\n base: AgentProfile\n /** Harnesses to cross. Default: {@link CODING_HARNESSES}. */\n harnesses?: readonly HarnessType[]\n /** Models to cross. Default: `[base.model.default]` — one model, i.e. today's\n * single-model behaviour, so omitting this never changes an existing run. */\n models?: readonly string[]\n /** Force every (harness, model) pair verbatim, even ones the harness can't run —\n * for deliberately testing failure modes. Default (false): SNAP instead — a\n * vendor-locked harness runs only the swept models in its family, or its native\n * default when it supports none, so no harness is dropped and none gets a\n * guaranteed-failing foreign-model cell. */\n keepIncompatible?: boolean\n}\n\n/** Model sentinel for a vendor-locked harness that supports none of the swept models:\n * it carries no provider prefix, so `harnessSupportsModel` accepts it and the harness\n * resolves it to its own native default model at runtime (e.g. kimi-code → its Kimi\n * model). Lets `expandProfileAxes` snap-instead-of-drop without a per-harness flagship\n * table that would rot as router catalogs change. */\nexport const HARNESS_NATIVE_MODEL = 'default'\n\n/**\n * Expand a base profile across the harness × model matrix into the `AgentProfile[]`\n * that `runProfileMatrix` / `selfImprove` score — the ONE place \"which harnesses ×\n * which models do we evaluate\" lives, so no product hand-rolls its own harness list\n * or column→profile mapping (the pattern that let those copies drift and silently\n * break the harness pivot).\n *\n * Each cell clones `base`, sets `model.default`, and stamps `metadata.harness` +\n * `metadata.harnessModel` (both hash-bearing, so every cell gets a distinct\n * `agentProfileId` row and results join back by harness/model via {@link harnessAxisOf}\n * with no hand-recomputed key). A vendor-locked harness snaps to its family's swept\n * models — or its native default ({@link HARNESS_NATIVE_MODEL}) when it supports none —\n * so every requested harness runs; `keepIncompatible` forces every pair verbatim.\n *\n * Omit `harnesses`/`models` to sweep the full default set — the \"turn it on for\n * everything we care about\" switch, identical in shape whether one harness or all.\n */\nexport function expandProfileAxes(spec: ProfileAxisSpec): AgentProfile[] {\n const harnesses = spec.harnesses ?? CODING_HARNESSES\n if (harnesses.length === 0) throw new ValidationError('expandProfileAxes: no harnesses to sweep')\n const baseModel = spec.base.model?.default\n const models = spec.models ?? (baseModel ? [baseModel] : [])\n if (models.length === 0) {\n throw new ValidationError(\n 'expandProfileAxes: no models to sweep — base profile has no model.default and none were supplied',\n )\n }\n const out: AgentProfile[] = []\n const seen = new Set<string>()\n for (const harness of harnesses) {\n // A universal (router-backed) harness — opencode/pi/claudish — runs every swept\n // model. A vendor-locked harness — codex/claude-code/kimi-code — runs only the\n // swept models in its own family; when it supports NONE of them it snaps to its\n // native default (the `HARNESS_NATIVE_MODEL` sentinel it resolves at runtime)\n // rather than being dropped, so every requested harness still appears in the\n // sweep on a model it can actually run — e.g. sweeping `deepseek/x` puts opencode\n // on deepseek and kimi-code on its own Kimi model, a real head-to-head.\n // `keepIncompatible` forces every (harness, model) pair verbatim (failure-mode runs).\n const supported = spec.keepIncompatible\n ? models\n : models.filter((model) => harnessSupportsModel(harness, model))\n const effective = supported.length > 0 ? supported : [HARNESS_NATIVE_MODEL]\n for (const model of effective) {\n const profile: AgentProfile = {\n ...spec.base,\n name: `${spec.base.name ?? 'agent'}/${harness}/${model}`,\n model: { ...spec.base.model, default: model },\n metadata: { ...(spec.base.metadata ?? {}), harness, harnessModel: model },\n }\n const id = agentProfileId(profile)\n if (seen.has(id)) continue\n seen.add(id)\n out.push(profile)\n }\n }\n if (out.length === 0) {\n // Unreachable in normal use — snapping guarantees ≥1 cell per harness — but keep a\n // fail-closed guard so a future refactor can't silently produce an empty sweep.\n throw new ValidationError(\n `expandProfileAxes: produced no profiles (harnesses=[${harnesses.join(', ')}], models=[${models.join(', ')}]).`,\n )\n }\n return out\n}\n\n/**\n * Read the (harness, model) a matrix cell ran under, off a profile or a result row's\n * profile — the join-back for a `byHarness` pivot. Returns undefined when the profile\n * wasn't produced by {@link expandProfileAxes}. Callers group `result.byProfile` by\n * this instead of recomputing an id (recomputing the wrong key is what broke the pivot\n * in the hand-rolled copies).\n */\nexport function harnessAxisOf(\n profile: Pick<AgentProfile, 'metadata'>,\n): { harness: HarnessType; model: string } | undefined {\n const m = profile.metadata as Record<string, unknown> | undefined\n const harness = m?.harness\n const model = m?.harnessModel\n if (typeof harness === 'string' && typeof model === 'string') {\n return { harness: harness as HarnessType, model }\n }\n return undefined\n}\n\n/**\n * Collision-resistant, path-safe, human-readable profile id for eval artifacts.\n * Scorecard joins still use `agentProfileHash`; this id is for run ids, matrix\n * keys, and directory names where two profiles must not collapse onto one row.\n * The suffix is the first 64 bits of the behaviour hash, enough for ordinary\n * eval matrices while keeping filenames readable.\n */\nexport function agentProfileId(profile: AgentProfile): string {\n const label = pathSafeProfileLabel(agentProfileDisplayLabel(profile)) ?? 'profile'\n return `${label}-${agentProfileHash(profile).slice(0, 16)}`\n}\n\n/**\n * Model snapshot used for `RunRecord.model`. Eval surfaces require a concrete\n * model id because run records reject bare/missing model aliases.\n */\nexport function agentProfileModelId(profile: AgentProfile): string {\n const model = profile.model?.default?.trim()\n if (!model) {\n const label = agentProfileDisplayLabel(profile) ?? 'unnamed profile'\n throw new ValidationError(\n `AgentProfile \"${label}\" has no model.default — cannot record eval run`,\n )\n }\n return model\n}\n\nfunction agentProfileDisplayLabel(profile: AgentProfile): string | undefined {\n return profile.name?.trim() || profile.version?.trim() || undefined\n}\n\nfunction pathSafeProfileLabel(label: string | undefined): string | undefined {\n const safe = label\n ?.trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '')\n return safe || undefined\n}\n\nfunction compact<T extends Record<string, unknown>>(input: T): Partial<T> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input)) {\n if (value !== undefined) out[key] = value\n }\n return out as Partial<T>\n}\n\n/**\n * Deterministic behaviour identity for the canonical\n * `@tangle-network/agent-interface` AgentProfile.\n *\n * `name` and `description` are labels and do not affect the hash. Profile\n * `version`, prompt, model hints, tools, resources, hooks, modes, permissions,\n * and extensions do affect the hash. Resource array order is hash-bearing\n * because mount order can change agent behaviour. Undefined fields are treated\n * as absent; explicit `null` fields remain hash-bearing.\n */\nexport function agentProfileHash(profile: AgentProfile): string {\n const model = agentProfileModelId(profile)\n const behaviour = {\n ...profile,\n name: undefined,\n description: undefined,\n tags: profile.tags ? [...profile.tags].sort() : undefined,\n model: compact({ ...profile.model, default: model }),\n }\n return createHash('sha256')\n .update(JSON.stringify(canonicalize(behaviour)))\n .digest('hex')\n}\n","/**\n * Shared finding→text helpers for the curator-style proposers (`memoryCurationProposer`\n * dedup-and-replace, `aceProposer` append-mostly). One copy so the two proposers\n * extract lessons + normalize keys identically and cannot drift apart.\n */\n\nimport type { MutableSurface } from '../types'\n\n/** A finding can be a raw string or a structured analyst finding. Pulls the\n * most actionable text (recommended_action > claim > lesson > text > message). */\nexport function findingToLesson(f: unknown): string | null {\n if (typeof f === 'string') return f.trim() || null\n if (f && typeof f === 'object') {\n const o = f as Record<string, unknown>\n const cand = o.recommended_action ?? o.claim ?? o.lesson ?? o.text ?? o.message\n if (typeof cand === 'string' && cand.trim()) return cand.trim()\n }\n return null\n}\n\n/** Normalize for dedup/idempotency: lowercase, collapse whitespace, strip\n * trailing punctuation. */\nexport function normKey(s: string): string {\n return s\n .toLowerCase()\n .replace(/\\s+/g, ' ')\n .replace(/[.;:!?\\s]+$/, '')\n .trim()\n}\n\n/** Curator proposers are prompt-tier — they manage a text block in the surface.\n * A code-tier surface has no prompt to append to; fail loud rather than\n * silently coercing. */\nexport function surfaceToText(surface: MutableSurface): string {\n if (typeof surface === 'string') return surface\n throw new Error(\n `curator proposer: surface must be a string prompt, got a ${surface.kind}-tier surface (${surface.worktreeRef}) — curation is prompt-tier`,\n )\n}\n\n// ── Delimited-block IO (the part ace + memory curators share) ──────────\n// Both manage a marker-delimited block in the surface; only the bullet\n// format + retention policy differ. One copy of the read/strip so they\n// cannot drift on how they find or remove the block.\n\n/** Body text strictly between `startMarker` and `endMarker`; '' if absent. */\nexport function extractBlockBody(text: string, startMarker: string, endMarker: string): string {\n const start = text.indexOf(startMarker)\n const end = text.indexOf(endMarker)\n if (start === -1 || end === -1 || end < start) return ''\n return text.slice(start + startMarker.length, end)\n}\n\n/** Remove the delimited block (and surrounding trailing whitespace), trimmed,\n * so the caller can re-emit a fresh block. */\nexport function stripBlock(text: string, startMarker: string, endMarker: string): string {\n const start = text.indexOf(startMarker)\n const end = text.indexOf(endMarker)\n if (start === -1 || end === -1 || end < start) return text.trimEnd()\n return (text.slice(0, start) + text.slice(end + endMarker.length)).trimEnd()\n}\n","/**\n * `aceProposer` — Agentic Context Engineering: an APPEND-MOSTLY curator, the\n * deliberate contrast to `memoryCurationProposer`'s dedup-and-replace. ACE's\n * thesis (arXiv:2510.04618) is that aggressively deduping/rewriting a context\n * causes \"context collapse\" — hard-won specific lessons get summarized away. So\n * the playbook GROWS by appending each generation's new lessons as provenance-\n * tagged delta bullets; existing bullets are preserved verbatim, never merged.\n *\n * Each generation it:\n * 1. reads the playbook block already in the parent surface (verbatim);\n * 2. turns this generation's `findings` into lessons, keeping only the ones not\n * already present (idempotency — a recurring finding is not re-appended, but\n * a genuinely NEW lesson always is, even if similar to an old one);\n * 3. appends the new lessons as `- [gN] <lesson>` deltas and re-emits the block.\n *\n * Bounded WITHOUT collapse: when the playbook exceeds `maxEntries`, the OLDEST\n * deltas are evicted (FIFO) — recency is kept, but no two distinct lessons are\n * ever merged into one. Deterministic (no LLM) so a lift is attributable to the\n * accumulated lessons, not a rewrite's model noise.\n *\n * Fail-loud: with no new lesson this generation it returns NO candidate (the\n * playbook is unchanged — nothing to propose), never a fabricated bullet.\n */\n\nimport type { ProposeContext, ProposedCandidate, SurfaceProposer } from '../types'\nimport {\n extractBlockBody,\n findingToLesson,\n normKey,\n stripBlock,\n surfaceToText,\n} from './_findings-text'\n\nconst BLOCK_START = '<!-- BEGIN ace-playbook (auto-managed by aceProposer) -->'\nconst BLOCK_END = '<!-- END ace-playbook -->'\nconst DEFAULT_HEADING = '## Playbook (accumulated lessons — append-only)'\n\nexport interface AceProposerOptions {\n /** Max delta bullets retained in the playbook. On overflow the OLDEST are\n * evicted (FIFO) — never merged. Default 50 (ACE keeps a long context). */\n maxEntries?: number\n /** Heading rendered above the bullets inside the block. */\n sectionHeading?: string\n}\n\ninterface Bullet {\n /** Generation tag the lesson was first appended at. */\n gen: number\n text: string\n}\n\n/** Parse the existing playbook block into bullets, preserving order + tags. A\n * bullet line is `- [gN] <text>`; an untagged `- <text>` is tolerated (gen -1). */\nfunction parsePlaybook(surface: string): Bullet[] {\n const body = extractBlockBody(surface, BLOCK_START, BLOCK_END)\n const out: Bullet[] = []\n for (const raw of body.split('\\n')) {\n const line = raw.trim()\n if (!line.startsWith('- ')) continue\n const item = line.slice(2).trim()\n const tag = /^\\[g(-?\\d+)\\]\\s*(.*)$/.exec(item)\n if (tag) out.push({ gen: Number(tag[1]), text: tag[2]!.trim() })\n else out.push({ gen: -1, text: item })\n }\n return out\n}\n\n/**\n * Append-only context engineering proposer: grows a skill playbook by appending generation-tagged lessons without merging or overwriting prior entries.\n */\nexport function aceProposer(opts: AceProposerOptions = {}): SurfaceProposer {\n const maxEntries = opts.maxEntries ?? 50\n if (maxEntries < 1) throw new Error('aceProposer: maxEntries must be >= 1')\n const heading = opts.sectionHeading ?? DEFAULT_HEADING\n\n return {\n kind: 'ace',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const parent = surfaceToText(ctx.currentSurface)\n const existing = parsePlaybook(parent)\n const seen = new Set(existing.map((b) => normKey(b.text)))\n\n // New lessons from this generation's findings — only those not already in\n // the playbook (idempotent; a recurring finding never duplicates a bullet).\n const fresh: Bullet[] = []\n for (const f of ctx.findings ?? []) {\n const lesson = findingToLesson(f)\n if (!lesson) continue\n const k = normKey(lesson)\n if (!k || seen.has(k)) continue\n seen.add(k)\n fresh.push({ gen: ctx.generation, text: lesson })\n }\n\n // Nothing genuinely new ⇒ the playbook is unchanged ⇒ no candidate.\n if (fresh.length === 0) return []\n\n // Append (preserving existing verbatim), then FIFO-evict the oldest on\n // overflow — recency kept, distinct lessons never merged.\n const all = [...existing, ...fresh].slice(-maxEntries)\n const block = [\n BLOCK_START,\n heading,\n ...all.map((b) => `- [g${b.gen}] ${b.text}`),\n BLOCK_END,\n ].join('\\n')\n const base = stripBlock(parent, BLOCK_START, BLOCK_END)\n const surface = base ? `${base}\\n\\n${block}` : block\n\n return [\n {\n surface,\n label: `ace-playbook +${fresh.length}`,\n rationale: `appended ${fresh.length} new lesson(s) from gen ${ctx.generation} findings (playbook now ${all.length} bullet(s), append-only)`,\n },\n ]\n },\n }\n}\n","/**\n * `compositeProposer` — run N proposers TOGETHER on the same surface.\n *\n * The question this answers (\"why can't we combine GEPA + skillOpt + ACE + a\n * trace-analyst?\"): nothing in the loop cares where candidates come from — the\n * generation's population is one pool and the Pareto frontier / promotion logic\n * evaluates every candidate identically. The only missing piece was a proposer\n * that fans the population budget out across members and merges their proposals.\n * This is that piece.\n *\n * Semantics:\n * - Budget: each member is asked for a share of `populationSize`\n * (near-equal split by default, or explicit `weights`). Members may return\n * fewer; the pool is topped up round-robin from members that can offer more\n * is NOT attempted — proposers are not obligated to be re-entrant.\n * - Provenance: every candidate's `label` is prefixed with its member's kind\n * (`gepa:...`, `skill-opt:...`) so generation records and the promotion\n * provenance attribute each winner to the proposer family that made it —\n * the cheap, honest version of proposer-level credit assignment.\n * - Dedup: identical surfaces from different members collapse to the first.\n * - Failure isolation: one member throwing does not sink the generation; its\n * error is logged into the surviving candidates' generation via a warning\n * and the pool proceeds (a generation with zero candidates from all members\n * failing still throws — that is a real failure).\n * - Early stop: the composite stops only when EVERY member with a `decide`\n * votes stop (a member without `decide` never votes stop).\n *\n * This is deliberately NOT joint multi-surface mutation: every member mutates\n * the SAME `MutableSurface`. Joint profile-patch surfaces (prompt+skills+tools\n * in one candidate) require the composite-surface contract and measured\n * component attribution — see the experiment-optimal research brief.\n */\n\nimport { surfaceContentHash } from '../surface-identity'\nimport type {\n GenerationRecord,\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '../types'\n\nexport interface CompositeProposerOptions<TFindings = unknown> {\n /** Member proposers, in priority order (earlier members get the larger share\n * of an uneven split). At least one required. */\n proposers: Array<SurfaceProposer<TFindings>>\n /** Optional population-share weights, same length as `proposers`. Need not\n * sum to anything; shares are proportional. Default: equal. */\n weights?: number[]\n}\n\n/** Fan the population budget across N proposers and merge their candidates into\n * one generation pool, with per-member provenance labels. */\nexport function compositeProposer<TFindings = unknown>(\n opts: CompositeProposerOptions<TFindings>,\n): SurfaceProposer<TFindings> {\n const members = opts.proposers\n if (members.length === 0)\n throw new Error('compositeProposer: at least one member proposer required')\n const weights = opts.weights ?? members.map(() => 1)\n if (weights.length !== members.length || weights.some((w) => !(w > 0))) {\n throw new Error('compositeProposer: weights must match proposers length and be positive')\n }\n\n return {\n kind: `composite(${members.map((m) => m.kind).join('+')})`,\n\n async propose(\n ctx: ProposeContext<TFindings>,\n ): Promise<Array<MutableSurface | ProposedCandidate>> {\n const totalWeight = weights.reduce((a, b) => a + b, 0)\n // Largest-remainder split so shares sum exactly to populationSize and\n // every member with positive weight gets at least the floor of its share.\n const exact = weights.map((w) => (ctx.populationSize * w) / totalWeight)\n const shares = exact.map((e) => Math.floor(e))\n let remaining = ctx.populationSize - shares.reduce((a, b) => a + b, 0)\n const byRemainder = exact\n .map((e, i) => ({ i, rem: e - Math.floor(e) }))\n .sort((a, b) => b.rem - a.rem)\n for (const { i } of byRemainder) {\n if (remaining <= 0) break\n shares[i] = (shares[i] ?? 0) + 1\n remaining -= 1\n }\n\n const pool: ProposedCandidate[] = []\n const seen = new Set<string>()\n const errors: string[] = []\n for (let i = 0; i < members.length; i += 1) {\n const member = members[i]\n const share = shares[i] ?? 0\n if (!member || share === 0 || ctx.signal.aborted) continue\n try {\n const proposals = await member.propose({ ...ctx, populationSize: share })\n for (const proposal of proposals) {\n const isCandidate =\n typeof proposal === 'object' && proposal !== null && 'surface' in proposal\n const surface = isCandidate\n ? (proposal as ProposedCandidate).surface\n : (proposal as MutableSurface)\n const label = isCandidate ? (proposal as ProposedCandidate).label : 'candidate'\n const rationale = isCandidate ? (proposal as ProposedCandidate).rationale : ''\n const candidateRecord = isCandidate\n ? (proposal as ProposedCandidate).candidateRecord\n : undefined\n const key = surfaceContentHash(surface)\n if (seen.has(key)) continue\n seen.add(key)\n pool.push({\n surface,\n label: `${member.kind}:${label}`,\n rationale,\n ...(candidateRecord ? { candidateRecord } : {}),\n })\n }\n } catch (err) {\n errors.push(`${member.kind}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n if (pool.length === 0) {\n throw new Error(\n `compositeProposer: every member failed or proposed nothing${errors.length ? ` — ${errors.join('; ')}` : ''}`,\n )\n }\n if (errors.length > 0) {\n console.warn(\n `[compositeProposer] ${errors.length} member(s) failed this generation: ${errors.join('; ')}`,\n )\n }\n return pool.slice(0, ctx.populationSize)\n },\n\n decide(args: { history: GenerationRecord[] }): { stop: boolean; reason?: string } {\n const votes = members\n .filter((m) => typeof m.decide === 'function')\n .map((m) => (m.decide as NonNullable<SurfaceProposer<TFindings>['decide']>)(args))\n if (votes.length === 0) return { stop: false }\n const allStop = votes.every((v) => v.stop)\n return allStop\n ? {\n stop: true,\n reason:\n votes\n .map((v) => v.reason)\n .filter(Boolean)\n .join('; ') || 'all members converged',\n }\n : { stop: false }\n },\n }\n}\n","/**\n * `haloProposer` — wraps the REAL halo-engine (Inference.net's hierarchical\n * agentic trace analyzer, `pip install halo-engine`, repo context-labs/halo)\n * as an agent-eval `SurfaceProposer`, so HALO competes head-to-head with\n * `gepaProposer` — and with our own `traceAnalystProposer` — inside `compareProposers`\n * on identical traces / scenarios / held-out scoring.\n *\n * It PRESERVES halo's actual working usage — `analyze` shells out to the\n * published CLI (`halo <traces.jsonl> -p <prompt> -m <model>`) and uses its real\n * RLM findings verbatim. We do NOT reimplement its analysis; that would make the\n * benchmark meaningless. The materialize/apply pipeline is the shared\n * `analysisEditProposer` — identical to `traceAnalystProposer`, which is what makes\n * the comparison apples-to-apples.\n *\n * Fail-loud: no traces → throw; halo errors → throw; empty findings → throw.\n */\n\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport type { CostLedgerHandle, CostReceiptInput, MaximumCharge } from '../../cost-ledger'\nimport type { LlmClientOptions } from '../../llm-client'\nimport type { ProposeContext, SurfaceProposer } from '../types'\nimport { analysisEditProposer } from './analysis-edit'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface HaloProposerOptions {\n /** OpenAI-compatible base URL for BOTH halo's RLM analysis and the apply\n * step (e.g. the Tangle router `https://router.tangle.tools/v1`). */\n baseUrl: string\n /** Bearer key (else relies on OPENAI_API_KEY in the env halo inherits). */\n apiKey?: string\n /** Model for halo's `--model` (its RLM). Default 'gpt-5.4-mini' (halo's own default). */\n model?: string\n /** Model used to APPLY halo's findings to the prompt surface. Default = `model`. */\n applyModel?: string\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n analysisMaximumCharge?: MaximumCharge\n analysisReceipt?: (report: string) => CostReceiptInput\n applyMaxTokens?: number\n /** The real halo binary. Default 'halo' (from `pip install halo-engine`). */\n haloBin?: string\n /** Resolve the OTLP traces (JSONL string) halo should analyze for THIS\n * generation. Returning empty throws (halo has nothing to analyze). */\n resolveTraces: (ctx: ProposeContext) => string | Promise<string>\n /** halo's analysis prompt (`-p`). Default targets the failure taxonomy. */\n analysisPrompt?: string\n /** halo `--max-depth` / `--max-turns` passthrough. */\n maxDepth?: number\n maxTurns?: number\n /** Test seam: inject a fetch for the apply-step callLlm (no network in unit tests). */\n fetchImpl?: LlmClientOptions['fetch']\n}\n\nconst DEFAULT_ANALYSIS_PROMPT =\n 'Diagnose the failures in these agent execution traces — hallucinated tool calls, redundant tool arguments, refusal loops, and semantic-correctness errors — and suggest concrete, generalizable fixes to the agent instructions.'\n\n/** Wrap the real halo-engine CLI as a SurfaceProposer (prompt-tier). */\nexport function haloProposer(opts: HaloProposerOptions): SurfaceProposer {\n const haloBin = opts.haloBin ?? 'halo'\n const model = opts.model ?? 'gpt-5.4-mini'\n return analysisEditProposer({\n kind: 'halo',\n label: 'halo',\n baseUrl: opts.baseUrl,\n apiKey: opts.apiKey,\n analysisModel: model,\n applyModel: opts.applyModel ?? model,\n costLedger: opts.costLedger,\n analysisMaximumCharge: opts.analysisMaximumCharge,\n analysisReceipt: opts.analysisReceipt,\n applyMaxTokens: opts.applyMaxTokens,\n fetchImpl: opts.fetchImpl,\n resolveTraces: opts.resolveTraces,\n noTracesError:\n 'haloProposer: resolveTraces returned no OTLP traces — the halo engine has nothing to analyze',\n // HALO's real findings are preserved verbatim in the rationale (attribution).\n rationale: (findings) => `halo-engine findings:\\n${findings.slice(0, 800)}`,\n analyze: async (tracePath, ctx) => {\n // The published halo-engine reads the base URL + key from the env\n // (OPENAI_BASE_URL / OPENAI_API_KEY) — it has no --base-url/--api-key flags.\n const args = [\n tracePath,\n '-p',\n opts.analysisPrompt ?? DEFAULT_ANALYSIS_PROMPT,\n '-m',\n model,\n ...(opts.maxDepth !== undefined ? ['--max-depth', String(opts.maxDepth)] : []),\n ...(opts.maxTurns !== undefined ? ['--max-turns', String(opts.maxTurns)] : []),\n ]\n let findings: string\n try {\n const { stdout } = await execFileAsync(haloBin, args, {\n maxBuffer: 64 * 1024 * 1024,\n signal: ctx.signal,\n env: {\n ...process.env,\n ...(opts.apiKey ? { OPENAI_API_KEY: opts.apiKey } : {}),\n OPENAI_BASE_URL: opts.baseUrl,\n },\n })\n findings = stdout.trim()\n } catch (e) {\n throw new Error(\n `haloProposer: halo-engine ('${haloBin}') failed — ${e instanceof Error ? e.message : String(e)}`,\n )\n }\n if (!findings) throw new Error('haloProposer: halo-engine produced no findings')\n return findings\n },\n })\n}\n","/**\n * Shared core for prompt-tier \"analysis → one LLM edit\" proposers. `haloProposer`\n * and `traceAnalystProposer` differ ONLY in who produces the findings; the\n * materialize-traces → apply-via-`APPLY_SYSTEM` → candidate pipeline is\n * identical. Keeping it in one place IS the fairness contract their head-to-head\n * (`compareProposers`) depends on — the apply step can no longer drift between the\n * two engines being compared.\n */\n\nimport { mkdtempSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport {\n CostAccountingIncompleteError,\n CostLedger,\n type CostLedgerHandle,\n type CostReceiptInput,\n type MaximumCharge,\n} from '../../cost-ledger'\nimport {\n callLlm,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from '../../llm-client'\nimport type { ProposeContext, ProposedCandidate, SurfaceProposer } from '../types'\n\nexport const APPLY_SYSTEM =\n 'You apply a trace-analysis report to an agent instruction prompt. Output ONLY the full revised prompt — no preamble, no commentary, no code fences. Make the minimal edits that address the report findings; preserve everything else verbatim.'\n\n/** Serialize a surface (string or structured) into prompt text. */\nexport function surfaceToPromptText(surface: unknown): string {\n return typeof surface === 'string' ? surface : JSON.stringify(surface)\n}\n\nexport interface AnalysisEditProposerOptions {\n kind: string\n label: string\n baseUrl: string\n apiKey?: string\n analysisModel: string\n applyModel: string\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n /** Required for each external step when the shared ledger has a dollar cap. */\n analysisMaximumCharge?: MaximumCharge\n /** Convert the external analyzer's result into measured usage/cost. */\n analysisReceipt?: (report: string) => CostReceiptInput\n applyMaxTokens?: number\n fetchImpl?: LlmClientOptions['fetch']\n /** Resolve the OTLP traces (JSONL) for THIS generation. Empty → `noTracesError`. */\n resolveTraces: (ctx: ProposeContext) => string | Promise<string>\n /** Produce the analysis REPORT string from the materialized trace file. Owns\n * its engine-specific failure + no-findings throws. */\n analyze: (tracePath: string, ctx: ProposeContext) => Promise<string>\n noTracesError: string\n rationale: (report: string) => string\n}\n\n/** Build a `SurfaceProposer` that runs `analyze` over the generation's OTLP\n * traces and applies the report to the surface via one identical LLM edit. */\nexport function analysisEditProposer(opts: AnalysisEditProposerOptions): SurfaceProposer {\n const directCostLedger = opts.costLedger ?? new CostLedger()\n return {\n kind: opts.kind,\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const parent = surfaceToPromptText(ctx.currentSurface)\n const costLedger = ctx.costLedger ?? directCostLedger\n const phase = ctx.costPhase ?? 'search.proposal'\n\n const traces = (await opts.resolveTraces(ctx)) ?? ''\n if (!traces.trim()) throw new Error(opts.noTracesError)\n const dir = mkdtempSync(join(tmpdir(), `${opts.kind}-proposer-`))\n const tracePath = join(dir, 'traces.jsonl')\n writeFileSync(tracePath, traces.endsWith('\\n') ? traces : `${traces}\\n`)\n\n if (costLedger.costCeilingUsd !== undefined && !opts.analysisReceipt) {\n throw new CostAccountingIncompleteError(\n `${opts.kind}: capped analysis requires analysisReceipt before external execution`,\n )\n }\n\n const analysis = await costLedger.runPaidCall({\n channel: 'analyst',\n phase,\n actor: `${opts.kind}.analyze`,\n model: opts.analysisModel,\n maximumCharge: opts.analysisMaximumCharge,\n tags: { generation: String(ctx.generation) },\n signal: ctx.signal,\n execute: (signal) => opts.analyze(tracePath, { ...ctx, signal }),\n receipt: (report) =>\n opts.analysisReceipt?.(report) ?? {\n model: opts.analysisModel,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n },\n })\n if (!analysis.succeeded) throw analysis.error\n const report = analysis.value\n\n const request: LlmCallRequest = {\n model: opts.applyModel,\n messages: [\n { role: 'system', content: APPLY_SYSTEM },\n {\n role: 'user',\n content: `CURRENT PROMPT:\\n${parent}\\n\\nTRACE-ANALYSIS REPORT:\\n${report}\\n\\nReturn the full revised prompt.`,\n },\n ],\n maxTokens: opts.applyMaxTokens ?? 6000,\n }\n const llm: LlmClientOptions = {\n baseUrl: opts.baseUrl,\n apiKey: opts.apiKey,\n fetch: opts.fetchImpl,\n }\n const apply = await costLedger.runPaidCall({\n channel: 'driver',\n phase,\n actor: `${opts.kind}.apply`,\n model: opts.applyModel,\n maximumCharge: maximumChargeForLlmRequest(request, llm),\n tags: { generation: String(ctx.generation) },\n signal: ctx.signal,\n execute: (signal, callId) => callLlm(request, { ...llm, signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!apply.succeeded) throw apply.error\n const applied = apply.value\n const text = applied.content.trim()\n if (!text || text === parent) return []\n return [{ surface: text, label: opts.label, rationale: opts.rationale(report) }]\n },\n }\n}\n","import { z } from 'zod'\nimport type { AgentProfileJson } from '../../agent-profile-cell'\nimport {\n makePolicyEdit,\n POLICY_EDIT_AXES,\n POLICY_EDIT_TARGET_SURFACES,\n type PolicyEdit,\n type PolicyEditAdmission,\n type PolicyEditAdmissionOptions,\n type PolicyEditCandidateRecord,\n type PolicyEditExpectedGain,\n type PolicyEditInit,\n validatePolicyEditCandidateRecord,\n} from '../../analyst/policy-edit'\nimport { assertNoJudgeVerdict } from '../../analyst/steer-firewall'\nimport type { AnalystFinding, EvidenceRef } from '../../analyst/types'\nimport { CostLedger, type CostLedgerHandle } from '../../cost-ledger'\nimport {\n callLlmJson,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from '../../llm-client'\nimport type {\n GenerationCandidate,\n GenerationRecord,\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n ScoredSurfaceOutcome,\n SurfaceProposer,\n} from '../types'\nimport { policyEditProposer } from './policy-edit'\nimport {\n assertPolicyEditAuthorContextBudget,\n selectPolicyEditAuthorRows,\n} from './policy-edit-author-context'\n\nconst JSON_POLICY_EDIT_TARGET_SURFACES = [\n 'prompt',\n 'tool-contract',\n 'runtime-config',\n 'memory',\n 'agent-profile',\n] as const satisfies readonly (typeof POLICY_EDIT_TARGET_SURFACES)[number][]\n\nexport type JsonPolicyEditTargetSurface = (typeof JSON_POLICY_EDIT_TARGET_SURFACES)[number]\n\nconst NonEmptyStringSchema = z.string().trim().min(1)\n\nconst JsonValueSchema: z.ZodType<AgentProfileJson> = z.lazy(() =>\n z.union([\n z.string(),\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(JsonValueSchema),\n z.record(NonEmptyStringSchema, JsonValueSchema),\n ]),\n)\n\nconst AuthoredJsonChangeSchema = z.discriminatedUnion('mode', [\n z\n .object({\n kind: z.literal('json'),\n mode: z.literal('set'),\n path: NonEmptyStringSchema,\n value: JsonValueSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('json'),\n mode: z.literal('merge'),\n path: NonEmptyStringSchema,\n value: JsonValueSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('json'),\n mode: z.literal('remove'),\n path: NonEmptyStringSchema,\n })\n .strict(),\n])\n\nconst AuthoredPolicyEditSchema = z\n .object({\n axis: z.enum(POLICY_EDIT_AXES),\n target: z\n .object({\n surface: z.enum(POLICY_EDIT_TARGET_SURFACES),\n path: NonEmptyStringSchema,\n label: NonEmptyStringSchema.max(200).nullable(),\n })\n .strict(),\n change: AuthoredJsonChangeSchema,\n claim: NonEmptyStringSchema.max(2_000),\n expectedGain: z\n .object({\n metric: NonEmptyStringSchema.max(400),\n direction: z.enum(['increase', 'decrease']),\n amount: z.number().finite().positive(),\n unit: z.enum(['absolute', 'relative', 'percent', 'score']).nullable(),\n rationale: NonEmptyStringSchema.max(2_000).nullable(),\n })\n .strict(),\n confidence: z.number().finite().min(0).max(1),\n risk: z.enum(['low', 'medium', 'high', 'unknown']),\n source: z\n .object({\n findingKeys: z\n .array(NonEmptyStringSchema)\n .min(1)\n .refine((ids) => new Set(ids).size === ids.length, 'findingKeys must be unique'),\n })\n .strict(),\n rationale: NonEmptyStringSchema.max(4_000).nullable(),\n validationPlan: NonEmptyStringSchema.max(2_000).nullable(),\n })\n .strict()\n\nconst PolicyEditAuthorResponseSchema = z\n .object({\n edits: z.array(AuthoredPolicyEditSchema),\n })\n .strict()\n\ntype AuthoredPolicyEdit = z.infer<typeof AuthoredPolicyEditSchema>\n\nconst POLICY_EDIT_AUTHOR_JSON_SCHEMA: Record<string, unknown> = {\n type: 'object',\n additionalProperties: false,\n required: ['edits'],\n properties: {\n edits: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: [\n 'axis',\n 'target',\n 'change',\n 'claim',\n 'expectedGain',\n 'confidence',\n 'risk',\n 'source',\n 'rationale',\n 'validationPlan',\n ],\n properties: {\n axis: { type: 'string', enum: [...POLICY_EDIT_AXES] },\n target: {\n type: 'object',\n additionalProperties: false,\n required: ['surface', 'path', 'label'],\n properties: {\n surface: { type: 'string', enum: [...POLICY_EDIT_TARGET_SURFACES] },\n path: { type: 'string', minLength: 1 },\n label: { type: ['string', 'null'], maxLength: 200 },\n },\n },\n change: {\n anyOf: [\n {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'mode', 'path', 'value'],\n properties: {\n kind: { const: 'json' },\n mode: { const: 'set' },\n path: { type: 'string', minLength: 1 },\n value: {},\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'mode', 'path', 'value'],\n properties: {\n kind: { const: 'json' },\n mode: { const: 'merge' },\n path: { type: 'string', minLength: 1 },\n value: {},\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'mode', 'path'],\n properties: {\n kind: { const: 'json' },\n mode: { const: 'remove' },\n path: { type: 'string', minLength: 1 },\n },\n },\n ],\n },\n claim: { type: 'string', minLength: 1, maxLength: 2_000 },\n expectedGain: {\n type: 'object',\n additionalProperties: false,\n required: ['metric', 'direction', 'amount', 'unit', 'rationale'],\n properties: {\n metric: { type: 'string', minLength: 1, maxLength: 400 },\n direction: { type: 'string', enum: ['increase', 'decrease'] },\n amount: { type: 'number', exclusiveMinimum: 0 },\n unit: {\n type: ['string', 'null'],\n enum: ['absolute', 'relative', 'percent', 'score', null],\n },\n rationale: { type: ['string', 'null'], maxLength: 2_000 },\n },\n },\n confidence: { type: 'number', minimum: 0, maximum: 1 },\n risk: { type: 'string', enum: ['low', 'medium', 'high', 'unknown'] },\n source: {\n type: 'object',\n additionalProperties: false,\n required: ['findingKeys'],\n properties: {\n findingKeys: {\n type: 'array',\n minItems: 1,\n uniqueItems: true,\n items: { type: 'string', minLength: 1 },\n },\n },\n },\n rationale: { type: ['string', 'null'], maxLength: 4_000 },\n validationPlan: { type: ['string', 'null'], maxLength: 2_000 },\n },\n },\n },\n },\n}\n\nfunction policyEditAuthorJsonSchema(\n maxItems: number,\n targetSurface: JsonPolicyEditTargetSurface,\n allowedJsonPaths: readonly string[],\n objectives: readonly PolicyEditObjective[],\n): Record<string, unknown> {\n const schema = JSON.parse(JSON.stringify(POLICY_EDIT_AUTHOR_JSON_SCHEMA)) as Record<\n string,\n unknown\n >\n const properties = schema.properties as Record<string, unknown>\n const edits = properties.edits as Record<string, unknown>\n edits.maxItems = maxItems\n const item = edits.items as Record<string, unknown>\n const itemProperties = item.properties as Record<string, unknown>\n const target = itemProperties.target as Record<string, unknown>\n const targetProperties = target.properties as Record<string, unknown>\n targetProperties.surface = { type: 'string', enum: [targetSurface] }\n targetProperties.path = { type: 'string', enum: [...allowedJsonPaths] }\n const change = itemProperties.change as { anyOf: Array<Record<string, unknown>> }\n for (const variant of change.anyOf) {\n const variantProperties = variant.properties as Record<string, unknown>\n variantProperties.path = { type: 'string', enum: [...allowedJsonPaths] }\n }\n const expectedGain = itemProperties.expectedGain as Record<string, unknown>\n const gainProperties = expectedGain.properties as Record<string, unknown>\n gainProperties.metric = { type: 'string', enum: objectives.map((objective) => objective.key) }\n gainProperties.direction = {\n type: 'string',\n enum: [...new Set(objectives.map((objective) => objective.direction))],\n }\n gainProperties.unit = {\n type: 'string',\n enum: [...new Set(objectives.map((objective) => objective.unit))],\n }\n return schema\n}\n\nexport const DEFAULT_POLICY_EDIT_HISTORY_LIMITS = Object.freeze({\n generations: 4,\n candidatesPerGeneration: 16,\n scenariosPerCandidate: 12,\n findings: 32,\n authorContextChars: 200_000,\n})\n\nexport interface PolicyEditObjective {\n /** Stable objective key cited by forecasts, for example `search.composite`. */\n key: string\n /** Steering objectives are search-only; fresh-task results never enter author context. */\n split: 'search'\n /** Search promotes only larger composite scores. */\n direction: 'increase'\n scale: { min: number; max: number }\n /** Forecast amounts are absolute deltas on the declared score scale. */\n unit: 'score'\n}\n\nexport type PolicyEditFindingSource =\n | { kind: 'surface'; surfaceHash: string; generation: number }\n | { kind: 'global'; label: string }\n\n/** Trace-derived findings must name the measured profile that produced them.\n * Cross-run doctrine can be explicitly global; an unwrapped finding is rejected. */\nexport interface PolicyEditFindingInput {\n finding: AnalystFinding\n source: PolicyEditFindingSource\n}\n\nexport interface PolicyEditHistoryProjectionOptions {\n /** Number of most recent generations retained. Default: 4. */\n maxGenerations?: number\n /** Number of candidates retained per generation. Default: 16. */\n maxCandidatesPerGeneration?: number\n /** Scored tasks retained per candidate/outcome after deterministic extreme selection. */\n maxScenariosPerCandidate?: number\n /** Optional pseudonymizer applied before scenario IDs enter author text. */\n scenarioIdTransform?: (scenarioId: string) => string\n /** Objectives used to compute forecast residuals from measured composite deltas. */\n objectives?: readonly PolicyEditObjective[]\n}\n\nexport interface PolicyEditCandidateSummary {\n editId: string\n axis: PolicyEdit['axis']\n target: PolicyEdit['target']\n change: PolicyEdit['change']\n claim: string\n expectedGain: PolicyEdit['expectedGain']\n confidence: number\n risk: PolicyEdit['risk']\n sourceFindingIds: string[]\n rationale: string | null\n validationPlan: string | null\n}\n\nexport interface PolicyEditHistoryCandidateContext {\n surfaceHash: string\n parentSurfaceHash: string | null\n parentComposite: number | null\n label: string | null\n rationale: string | null\n composite: number\n observedDeltaFromParent: number | null\n eligibleForPromotion: boolean | null\n coverage: {\n expectedCells: number\n scorableCells: number\n unscorableCells: Array<{ reason: string }>\n } | null\n dimensions: Record<string, number>\n scenarios: Array<{ scenarioId: string; composite: number; notes: string | null }>\n candidateEdit: PolicyEditCandidateSummary | null\n forecastCalibration: {\n objectiveKey: string\n predictedDelta: number\n observedDelta: number\n residual: number\n } | null\n}\n\nexport interface PolicyEditOutcomeContext {\n split: 'search'\n generation: number\n surfaceHash: string\n composite: number\n dimensions: Record<string, number>\n scenarios: Array<{ scenarioId: string; composite: number; notes: string | null }>\n coverage: { expectedCells: number; scorableCells: number }\n}\n\nexport interface PolicyEditHistoryGenerationContext {\n generationIndex: number\n promoted: string[]\n candidates: PolicyEditHistoryCandidateContext[]\n}\n\nconst POLICY_EDIT_AUTHOR_SYSTEM = [\n 'You author strictly typed PolicyEdit candidates over one JSON surface.',\n 'Return exactly one JSON object with shape {\"edits\":[...]}; emit an empty edits array when no evidence supports a change.',\n `axis must be one of: ${POLICY_EDIT_AXES.join(', ')}.`,\n `target.surface must be one of: ${POLICY_EDIT_TARGET_SURFACES.join(', ')}.`,\n 'target.path and change.path must be the same caller-allowed JSON path.',\n 'change must be exactly one operation: {\"kind\":\"json\",\"mode\":\"set\",\"path\":string,\"value\":json}, {\"kind\":\"json\",\"mode\":\"merge\",\"path\":string,\"value\":json}, or {\"kind\":\"json\",\"mode\":\"remove\",\"path\":string}.',\n 'Nullable fields required by the response schema must be null when they do not apply.',\n 'Every edit must cite one or more supplied finding keys in source.findingKeys. Do not emit persistent finding IDs, analyst IDs, or evidence references; the caller binds those from the cited findings.',\n 'Treat expectedGain and confidence as forecasts, never as measured evidence. Learn from baselineOutcome, incumbentOutcome, and observedDeltaFromParent.',\n 'Do not invent a finding, path, field, score, or task fact. Do not include schemaVersion, editId, metadata, prose, or undeclared keys.',\n].join('\\n')\n\nexport interface LlmPolicyEditProposerOptions {\n llm: LlmClientOptions\n model: string\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n /** Plain-language description of the JSON surface being improved. */\n target: string\n /** PolicyEdit target surface every authored edit must retain. */\n targetSurface: JsonPolicyEditTargetSurface\n /** Exact JSON paths the author may change. Prefix or fuzzy matches are not accepted. */\n allowedJsonPaths: readonly string[]\n /** Exact search objectives forecasts may name. Unknown keys or mismatched directions fail. */\n objectives: readonly PolicyEditObjective[]\n /** Default: evidence-only, so uncertain edits are measured rather than\n * suppressed by their own model-authored predictions. */\n admissionMode?: 'evidence-only' | 'strict'\n /** Readiness thresholds used only when admissionMode is explicitly strict. */\n admission?: PolicyEditAdmissionOptions\n maxCandidates?: number\n temperature?: number\n maxTokens?: number\n timeoutMs?: number\n /** Number of most recent scored generations sent to the author. Default: 4. */\n maxHistoryGenerations?: number\n /** Candidates retained per admitted generation. Default: 16. */\n maxHistoryCandidatesPerGeneration?: number\n /** Scored tasks retained per candidate/outcome after deterministic extreme selection. */\n maxScenariosPerCandidate?: number\n /** Evidence-bearing findings retained after deterministic severity/confidence ordering. */\n maxFindings?: number\n /** Hard character limit over system + schema + serialized author context. */\n maxAuthorContextChars?: number\n /** Optional one-to-one pseudonymizer applied to every author-visible evidence field. */\n scenarioIdTransform?: (scenarioId: string) => string\n onAdmission?: (admission: PolicyEditAdmission) => void\n}\n\n/**\n * LLM-backed PolicyEdit author. It reads only the current JSON surface,\n * evidence-bearing analyst findings, and scored generation history. Model output\n * is validated and rebound to exact finding evidence before the deterministic\n * policyEditProposer applies, admits, and deduplicates candidates.\n */\nexport function llmPolicyEditProposer(\n opts: LlmPolicyEditProposerOptions,\n): SurfaceProposer<PolicyEditFindingInput> {\n const allowedJsonPaths = validateAllowedJsonPaths(opts.allowedJsonPaths)\n const allowedPathSet = new Set(allowedJsonPaths)\n const objectives = validateObjectives(opts.objectives)\n const objectiveByKey = new Map(objectives.map((objective) => [objective.key, objective]))\n requireNonEmpty(opts.model, 'model')\n requireNonEmpty(opts.target, 'target')\n if (!(JSON_POLICY_EDIT_TARGET_SURFACES as readonly string[]).includes(opts.targetSurface)) {\n throw new Error(\n `llmPolicyEditProposer: targetSurface '${opts.targetSurface}' is not a JSON-backed surface`,\n )\n }\n if (\n opts.maxCandidates !== undefined &&\n (!Number.isSafeInteger(opts.maxCandidates) || opts.maxCandidates < 0)\n ) {\n throw new Error('llmPolicyEditProposer: maxCandidates must be a non-negative safe integer')\n }\n const admissionMode = opts.admissionMode ?? 'evidence-only'\n if (admissionMode !== 'evidence-only' && admissionMode !== 'strict') {\n throw new Error(\"llmPolicyEditProposer: admissionMode must be 'evidence-only' or 'strict'\")\n }\n if (opts.admission && admissionMode !== 'strict') {\n throw new Error(\"llmPolicyEditProposer: admission thresholds require admissionMode: 'strict'\")\n }\n const historyLimits = validateHistoryLimits({\n ...(opts.maxHistoryGenerations === undefined\n ? {}\n : { maxGenerations: opts.maxHistoryGenerations }),\n ...(opts.maxHistoryCandidatesPerGeneration === undefined\n ? {}\n : { maxCandidatesPerGeneration: opts.maxHistoryCandidatesPerGeneration }),\n ...(opts.maxScenariosPerCandidate === undefined\n ? {}\n : { maxScenariosPerCandidate: opts.maxScenariosPerCandidate }),\n ...(opts.scenarioIdTransform === undefined\n ? {}\n : { scenarioIdTransform: opts.scenarioIdTransform }),\n })\n const maxFindings = positiveLimit(\n opts.maxFindings ?? DEFAULT_POLICY_EDIT_HISTORY_LIMITS.findings,\n 'maxFindings',\n )\n const maxAuthorContextChars = positiveLimit(\n opts.maxAuthorContextChars ?? DEFAULT_POLICY_EDIT_HISTORY_LIMITS.authorContextChars,\n 'maxAuthorContextChars',\n )\n const directCostLedger = opts.costLedger ?? new CostLedger()\n\n return {\n kind: 'llm-policy-edit',\n async propose(\n ctx: ProposeContext<PolicyEditFindingInput>,\n ): Promise<Array<MutableSurface | ProposedCandidate>> {\n const limit = Math.min(ctx.populationSize, opts.maxCandidates ?? ctx.populationSize)\n if (limit <= 0) return []\n\n const currentSurface = parseJsonSurface(ctx.currentSurface)\n assertSearchOutcome(ctx.baselineOutcome, 'baselineOutcome')\n assertSearchOutcome(ctx.incumbentOutcome, 'incumbentOutcome')\n assertMeasuredCompositesInScale(ctx, objectives[0]!)\n const scenarioIds = createScenarioIdProjector(historyLimits.scenarioIdTransform)\n registerOutcomeScenarioIds(ctx.baselineOutcome, scenarioIds)\n registerOutcomeScenarioIds(ctx.incumbentOutcome, scenarioIds)\n registerHistoryScenarioIds(ctx.history.slice(-historyLimits.maxGenerations), scenarioIds)\n assertSurfaceIsTaskAgnostic(\n { currentSurface, allowedJsonPaths, objectives, targetSurface: opts.targetSurface },\n scenarioIds,\n )\n const measuredSources = measuredSourceMeasurements(ctx)\n const findings = citableFindings(ctx.findings, measuredSources, maxFindings)\n const findingByKey = new Map(\n findings.map((finding, index) => [`finding-${index + 1}`, finding]),\n )\n const authorContext = {\n target: scenarioIds.sanitize(opts.target),\n targetSurface: opts.targetSurface,\n allowedJsonPaths,\n objectives,\n candidateCount: limit,\n generation: ctx.generation,\n currentSurface,\n findings: findings.map((finding, index) =>\n renderFinding(finding, `finding-${index + 1}`, scenarioIds, measuredSources),\n ),\n baselineOutcome: projectOutcome(\n ctx.baselineOutcome,\n scenarioIds,\n historyLimits.maxScenariosPerCandidate,\n ),\n incumbentOutcome: projectOutcome(\n ctx.incumbentOutcome,\n scenarioIds,\n historyLimits.maxScenariosPerCandidate,\n ctx.baselineOutcome,\n ),\n history: projectPolicyEditHistoryWithProjector(\n ctx.history,\n historyLimits,\n scenarioIds,\n objectiveByKey,\n ),\n }\n const responseSchema = policyEditAuthorJsonSchema(\n limit,\n opts.targetSurface,\n allowedJsonPaths,\n objectives,\n )\n assertPolicyEditAuthorContextBudget(\n { system: POLICY_EDIT_AUTHOR_SYSTEM, authorContext, responseSchema },\n maxAuthorContextChars,\n )\n const userContent = JSON.stringify(authorContext)\n const request: LlmCallRequest = {\n model: opts.model,\n messages: [\n { role: 'system', content: POLICY_EDIT_AUTHOR_SYSTEM },\n { role: 'user', content: userContent },\n ],\n jsonSchema: {\n name: 'policy_edit_author',\n schema: responseSchema,\n },\n temperature: opts.temperature ?? 0.2,\n maxTokens: opts.maxTokens ?? 6_000,\n timeoutMs: opts.timeoutMs,\n }\n const paid = await (ctx.costLedger ?? directCostLedger).runPaidCall({\n channel: 'driver',\n phase: ctx.costPhase ?? 'search.proposal',\n actor: 'llm-policy-edit.author',\n model: opts.model,\n maximumCharge: maximumChargeForLlmRequest(request, opts.llm),\n tags: { generation: String(ctx.generation) },\n signal: ctx.signal,\n execute: (signal, callId) =>\n callLlmJson<unknown>(request, { ...opts.llm, signal, idempotencyKey: callId }),\n receipt: ({ result }) => costReceiptFromLlm(result),\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const { value } = paid.value\n const response = parseAuthorResponse(value)\n if (response.edits.length > limit) {\n throw new Error(\n `llmPolicyEditProposer: author returned ${response.edits.length} edits for ${limit} candidate slots`,\n )\n }\n const edits = response.edits.map((draft) =>\n bindAuthoredEdit(\n draft,\n findingByKey,\n opts.targetSurface,\n allowedPathSet,\n objectiveByKey,\n ctx.incumbentOutcome?.composite ?? ctx.baselineOutcome?.composite,\n ),\n )\n return policyEditProposer({\n edits,\n admission:\n admissionMode === 'strict'\n ? opts.admission\n : {\n minScore: 0,\n minExpectedGain: 0,\n allowHighRisk: true,\n requireEvidence: true,\n },\n maxCandidates: limit,\n onAdmission: opts.onAdmission,\n }).propose(ctx)\n },\n }\n}\n\n/**\n * Projects scored history into the only fields a policy author may consume.\n * It admits recent generations and a bounded candidate count, while retaining\n * every dimension and scenario score for each admitted candidate.\n */\nexport function projectPolicyEditHistory(\n history: readonly GenerationRecord[],\n options: PolicyEditHistoryProjectionOptions = {},\n): PolicyEditHistoryGenerationContext[] {\n const limits = validateHistoryLimits(options)\n const objectiveByKey = new Map(\n (options.objectives ? validateObjectives(options.objectives) : []).map((objective) => [\n objective.key,\n objective,\n ]),\n )\n const scenarioIds = createScenarioIdProjector(limits.scenarioIdTransform)\n registerHistoryScenarioIds(history.slice(-limits.maxGenerations), scenarioIds)\n return projectPolicyEditHistoryWithProjector(history, limits, scenarioIds, objectiveByKey)\n}\n\nfunction projectPolicyEditHistoryWithProjector(\n history: readonly GenerationRecord[],\n limits: ReturnType<typeof validateHistoryLimits>,\n scenarioIds: ScenarioIdProjector,\n objectiveByKey: ReadonlyMap<string, PolicyEditObjective>,\n): PolicyEditHistoryGenerationContext[] {\n const retainedHistory = history.slice(-limits.maxGenerations)\n const candidateByHash = new Map(\n retainedHistory.flatMap((record) =>\n record.candidates.map((candidate) => [candidate.surfaceHash, candidate] as const),\n ),\n )\n return retainedHistory.map((record) => {\n const candidates = selectHistoryCandidates(record, limits.maxCandidatesPerGeneration)\n const hashes = new Set(candidates.map((candidate) => candidate.surfaceHash))\n return {\n generationIndex: record.generationIndex,\n promoted: record.promoted\n .filter((hash) => hashes.has(hash))\n .map((hash) => scenarioIds.sanitize(hash)),\n candidates: candidates.map((candidate) =>\n projectHistoryCandidate(\n candidate,\n scenarioIds,\n limits.maxScenariosPerCandidate,\n candidate.parentSurfaceHash\n ? candidateByHash.get(candidate.parentSurfaceHash)?.scenarios\n : undefined,\n objectiveByKey,\n ),\n ),\n }\n })\n}\n\nfunction selectHistoryCandidates(record: GenerationRecord, limit: number): GenerationCandidate[] {\n const promotionOrder = new Map(record.promoted.map((hash, index) => [hash, index]))\n const promoted = [...record.candidates]\n .filter((candidate) => promotionOrder.has(candidate.surfaceHash))\n .sort((a, b) => promotionOrder.get(a.surfaceHash)! - promotionOrder.get(b.surfaceHash)!)\n const selected = promoted.slice(0, limit)\n const selectedHashes = new Set(selected.map((candidate) => candidate.surfaceHash))\n const remaining = [...record.candidates]\n .filter((candidate) => !promotionOrder.has(candidate.surfaceHash))\n .sort((a, b) => b.composite - a.composite || a.surfaceHash.localeCompare(b.surfaceHash))\n let high = 0\n let low = remaining.length - 1\n let takeLow = selected.length > 0\n while (selected.length < limit && high <= low) {\n const candidate = takeLow ? remaining[low--] : remaining[high++]\n takeLow = !takeLow\n if (!candidate || selectedHashes.has(candidate.surfaceHash)) continue\n selected.push(candidate)\n selectedHashes.add(candidate.surfaceHash)\n }\n return selected\n}\n\nfunction projectHistoryCandidate(\n candidate: GenerationCandidate,\n scenarioIds: ScenarioIdProjector,\n maxScenarios: number,\n parentScenarios: GenerationCandidate['scenarios'] | undefined,\n objectiveByKey: ReadonlyMap<string, PolicyEditObjective>,\n): PolicyEditHistoryCandidateContext {\n const referenceByScenario = parentScenarios\n ? new Map(parentScenarios.map((scenario) => [scenario.scenarioId, scenario.composite]))\n : undefined\n const selectedScenarios = selectPolicyEditAuthorRows(candidate.scenarios, {\n limit: maxScenarios,\n ...(referenceByScenario ? { referenceByScenario } : {}),\n })\n const validatedRecord = candidate.candidateRecord\n ? validatePolicyEditCandidateRecord(candidate.candidateRecord)\n : undefined\n return {\n surfaceHash: scenarioIds.sanitize(candidate.surfaceHash),\n parentSurfaceHash: candidate.parentSurfaceHash\n ? scenarioIds.sanitize(candidate.parentSurfaceHash)\n : null,\n parentComposite: candidate.parentComposite ?? null,\n label: candidate.label ? scenarioIds.sanitize(candidate.label) : null,\n rationale: candidate.rationale ? scenarioIds.sanitize(candidate.rationale) : null,\n composite: candidate.composite,\n observedDeltaFromParent: candidate.observedDeltaFromParent ?? null,\n eligibleForPromotion: candidate.eligibleForPromotion ?? null,\n coverage: candidate.coverage\n ? {\n expectedCells: candidate.coverage.expectedCells,\n scorableCells: candidate.coverage.scorableCells,\n // `cellId` embeds the raw scenario ID. The aggregate reason is useful\n // for search, but the identifier must not bypass scenarioIdTransform.\n unscorableCells: [...candidate.coverage.unscorableCells]\n .sort((a, b) => a.cellId.localeCompare(b.cellId))\n .slice(0, maxScenarios)\n .map((cell) => ({ reason: scenarioIds.sanitize(cell.reason) })),\n }\n : null,\n // GenerationCandidate.ci95 is currently a placeholder [composite, composite],\n // not a measured interval. Keep it out of author context until it is real.\n dimensions: sanitizeDimensions(candidate.dimensions, scenarioIds),\n scenarios: selectedScenarios.map((scenario) => {\n return {\n scenarioId: scenarioIds.project(scenario.scenarioId),\n composite: scenario.composite,\n notes: scenario.notes ? scenarioIds.sanitize(scenario.notes) : null,\n }\n }),\n candidateEdit: validatedRecord ? summarizeCandidateEdit(validatedRecord, scenarioIds) : null,\n forecastCalibration: forecastCalibration(candidate, validatedRecord, objectiveByKey),\n }\n}\n\nfunction projectOutcome(\n outcome: ScoredSurfaceOutcome | undefined,\n scenarioIds: ScenarioIdProjector,\n maxScenarios: number,\n reference: ScoredSurfaceOutcome | undefined = undefined,\n): PolicyEditOutcomeContext | null {\n if (!outcome) return null\n const referenceByScenario = reference\n ? new Map(reference.scenarios.map((scenario) => [scenario.scenarioId, scenario.composite]))\n : undefined\n const selectedScenarios = selectPolicyEditAuthorRows(outcome.scenarios, {\n limit: maxScenarios,\n ...(referenceByScenario ? { referenceByScenario } : {}),\n })\n return {\n split: 'search',\n generation: outcome.generation,\n surfaceHash: scenarioIds.sanitize(outcome.surfaceHash),\n composite: outcome.composite,\n dimensions: sanitizeDimensions(outcome.dimensions, scenarioIds),\n scenarios: selectedScenarios.map((scenario) => {\n return {\n scenarioId: scenarioIds.project(scenario.scenarioId),\n composite: scenario.composite,\n notes: scenario.notes ? scenarioIds.sanitize(scenario.notes) : null,\n }\n }),\n coverage: { ...outcome.coverage },\n }\n}\n\ninterface ScenarioIdProjector {\n project(scenarioId: string): string\n sanitize(text: string): string\n}\n\nfunction createScenarioIdProjector(transform: (scenarioId: string) => string): ScenarioIdProjector {\n const aliases = new Map<string, string>()\n const originals = new Map<string, string>()\n return {\n project(scenarioId) {\n const known = aliases.get(scenarioId)\n if (known) return known\n const alias = transform(scenarioId)\n if (!alias || alias.trim() !== alias) {\n throw new Error(\n 'llmPolicyEditProposer: scenarioIdTransform must return a trimmed non-empty string',\n )\n }\n const collision = originals.get(alias)\n if (collision && collision !== scenarioId) {\n throw new Error(\n `llmPolicyEditProposer: scenarioIdTransform collision for '${collision}' and '${scenarioId}'`,\n )\n }\n const aliasIsAnotherOriginal = aliases.has(alias) && alias !== scenarioId\n const originalIsAnotherAlias =\n originals.has(scenarioId) && originals.get(scenarioId) !== scenarioId\n if (aliasIsAnotherOriginal || originalIsAnotherAlias) {\n throw new Error(\n 'llmPolicyEditProposer: scenarioIdTransform aliases overlap raw scenario IDs',\n )\n }\n aliases.set(scenarioId, alias)\n originals.set(alias, scenarioId)\n return alias\n },\n sanitize(text) {\n const originalsByLength = [...aliases.keys()].sort((a, b) => b.length - a.length)\n if (originalsByLength.length === 0) return text\n const pattern = new RegExp(\n `(^|[^A-Za-z0-9_-])(${originalsByLength.map(escapeRegExp).join('|')})(?=$|[^A-Za-z0-9_-])`,\n 'g',\n )\n return text.replace(\n pattern,\n (_match, prefix: string, original: string) =>\n `${prefix}${aliases.get(original) ?? original}`,\n )\n },\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\ninterface PolicyEditFindingMeasurement {\n surfaceHash: string\n generation: number\n composite: number\n parentComposite: number | null\n observedDeltaFromParent: number | null\n eligibleForPromotion: boolean\n coverage: { expectedCells: number; scorableCells: number }\n}\n\nfunction sourceKey(surfaceHash: string, generation: number): string {\n return `${surfaceHash}@${generation}`\n}\n\nfunction measuredSourceMeasurements(\n ctx: ProposeContext<PolicyEditFindingInput>,\n): Map<string, PolicyEditFindingMeasurement> {\n const measurements = new Map<string, PolicyEditFindingMeasurement>()\n const add = (measurement: PolicyEditFindingMeasurement) => {\n measurements.set(sourceKey(measurement.surfaceHash, measurement.generation), measurement)\n }\n if (ctx.baselineOutcome) {\n add({\n surfaceHash: ctx.baselineOutcome.surfaceHash,\n generation: ctx.baselineOutcome.generation,\n composite: ctx.baselineOutcome.composite,\n parentComposite: null,\n observedDeltaFromParent: null,\n eligibleForPromotion: true,\n coverage: { ...ctx.baselineOutcome.coverage },\n })\n }\n for (const record of ctx.history) {\n for (const candidate of record.candidates) {\n add({\n surfaceHash: candidate.surfaceHash,\n generation: record.generationIndex,\n composite: candidate.composite,\n parentComposite: candidate.parentComposite ?? null,\n observedDeltaFromParent: candidate.observedDeltaFromParent ?? null,\n eligibleForPromotion: candidate.eligibleForPromotion === true,\n coverage: candidate.coverage\n ? {\n expectedCells: candidate.coverage.expectedCells,\n scorableCells: candidate.coverage.scorableCells,\n }\n : { expectedCells: 0, scorableCells: 0 },\n })\n }\n }\n if (ctx.incumbentOutcome) {\n const generation = ctx.incumbentOutcome.generation\n const key = sourceKey(ctx.incumbentOutcome.surfaceHash, generation)\n if (!measurements.has(key)) {\n add({\n surfaceHash: ctx.incumbentOutcome.surfaceHash,\n generation,\n composite: ctx.incumbentOutcome.composite,\n parentComposite: null,\n observedDeltaFromParent: null,\n eligibleForPromotion: true,\n coverage: { ...ctx.incumbentOutcome.coverage },\n })\n }\n }\n return measurements\n}\n\nfunction validateFindingSource(\n source: PolicyEditFindingSource,\n measured: ReadonlyMap<string, PolicyEditFindingMeasurement>,\n): void {\n if (source.kind === 'global') {\n requireNonEmpty(source.label, 'global finding source label')\n return\n }\n if (!measured.has(sourceKey(source.surfaceHash, source.generation))) {\n throw new Error(\n `llmPolicyEditProposer: finding source ${source.surfaceHash}@${source.generation} is not a measured surface`,\n )\n }\n}\n\nfunction sameFindingSource(a: PolicyEditFindingSource, b: PolicyEditFindingSource): boolean {\n if (a.kind !== b.kind) return false\n return a.kind === 'surface' && b.kind === 'surface'\n ? a.surfaceHash === b.surfaceHash && a.generation === b.generation\n : a.kind === 'global' && b.kind === 'global' && a.label === b.label\n}\n\nfunction summarizeCandidateEdit(\n record: PolicyEditCandidateRecord,\n scenarioIds: ScenarioIdProjector,\n): PolicyEditCandidateSummary {\n const edit = record.policyEdit\n return {\n editId: edit.editId,\n axis: edit.axis,\n target: sanitizeAuthorValue(edit.target, scenarioIds) as PolicyEdit['target'],\n change: sanitizeAuthorValue(edit.change, scenarioIds) as PolicyEdit['change'],\n claim: scenarioIds.sanitize(edit.claim),\n expectedGain: sanitizeAuthorValue(edit.expectedGain, scenarioIds) as PolicyEdit['expectedGain'],\n confidence: edit.confidence,\n risk: edit.risk,\n sourceFindingIds: edit.source.findingIds.map((id) => scenarioIds.sanitize(id)),\n rationale: edit.rationale ? scenarioIds.sanitize(edit.rationale) : null,\n validationPlan: edit.validationPlan ? scenarioIds.sanitize(edit.validationPlan) : null,\n }\n}\n\nfunction sanitizeAuthorValue(value: unknown, scenarioIds: ScenarioIdProjector): unknown {\n if (typeof value === 'string') return scenarioIds.sanitize(value)\n if (Array.isArray(value)) return value.map((item) => sanitizeAuthorValue(item, scenarioIds))\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n scenarioIds.sanitize(key),\n sanitizeAuthorValue(child, scenarioIds),\n ]),\n )\n }\n return value\n}\n\nfunction sanitizeDimensions(\n dimensions: Readonly<Record<string, number>>,\n scenarioIds: ScenarioIdProjector,\n): Record<string, number> {\n const sanitized = new Map<string, { original: string; value: number }>()\n for (const [key, value] of Object.entries(dimensions)) {\n const projected = scenarioIds.sanitize(key)\n const prior = sanitized.get(projected)\n if (prior && prior.original !== key) {\n throw new Error(\n `llmPolicyEditProposer: pseudonymized dimension key collision for '${prior.original}' and '${key}'`,\n )\n }\n sanitized.set(projected, { original: key, value })\n }\n return Object.fromEntries([...sanitized].map(([key, entry]) => [key, entry.value]))\n}\n\nfunction forecastCalibration(\n candidate: GenerationCandidate,\n record: PolicyEditCandidateRecord | undefined,\n objectiveByKey: ReadonlyMap<string, PolicyEditObjective>,\n): PolicyEditHistoryCandidateContext['forecastCalibration'] {\n if (!record || candidate.observedDeltaFromParent === undefined) return null\n const forecast = record.policyEdit.expectedGain\n const objective = objectiveByKey.get(forecast.metric)\n if (!objective || objective.key !== 'search.composite') return null\n if (forecast.direction !== objective.direction || forecast.unit !== objective.unit) return null\n if (forecast.amount > objective.scale.max - objective.scale.min) return null\n const predictedDelta = forecast.amount\n return {\n objectiveKey: objective.key,\n predictedDelta,\n observedDelta: candidate.observedDeltaFromParent,\n residual: candidate.observedDeltaFromParent - predictedDelta,\n }\n}\n\nfunction assertSearchOutcome(outcome: ScoredSurfaceOutcome | undefined, field: string): void {\n if (outcome && (outcome as { split?: unknown }).split !== 'search') {\n throw new Error(`llmPolicyEditProposer: ${field} must be a search-split outcome`)\n }\n}\n\nfunction assertMeasuredCompositesInScale(\n ctx: ProposeContext<PolicyEditFindingInput>,\n objective: PolicyEditObjective,\n): void {\n const assertInScale = (value: number, field: string) => {\n if (!Number.isFinite(value) || value < objective.scale.min || value > objective.scale.max) {\n throw new Error(\n `llmPolicyEditProposer: ${field} ${value} is outside objective '${objective.key}' scale [${objective.scale.min}, ${objective.scale.max}]`,\n )\n }\n }\n const assertOutcome = (outcome: ScoredSurfaceOutcome | undefined, field: string) => {\n if (!outcome) return\n assertInScale(outcome.composite, `${field}.composite`)\n for (const [index, scenario] of outcome.scenarios.entries()) {\n assertInScale(scenario.composite, `${field}.scenarios[${index}].composite`)\n }\n }\n assertOutcome(ctx.baselineOutcome, 'baselineOutcome')\n assertOutcome(ctx.incumbentOutcome, 'incumbentOutcome')\n for (const [generationIndex, generation] of ctx.history.entries()) {\n for (const [candidateIndex, candidate] of generation.candidates.entries()) {\n const field = `history[${generationIndex}].candidates[${candidateIndex}]`\n assertInScale(candidate.composite, `${field}.composite`)\n if (candidate.parentComposite !== undefined) {\n assertInScale(candidate.parentComposite, `${field}.parentComposite`)\n }\n for (const [scenarioIndex, scenario] of candidate.scenarios.entries()) {\n assertInScale(scenario.composite, `${field}.scenarios[${scenarioIndex}].composite`)\n }\n }\n }\n}\n\nfunction assertSurfaceIsTaskAgnostic(value: unknown, scenarioIds: ScenarioIdProjector): void {\n const serialized = JSON.stringify(value)\n if (scenarioIds.sanitize(serialized) !== serialized) {\n throw new Error(\n 'llmPolicyEditProposer: current JSON surface or signature contains a raw scenario identifier',\n )\n }\n}\n\nfunction registerOutcomeScenarioIds(\n outcome: ScoredSurfaceOutcome | undefined,\n scenarioIds: ScenarioIdProjector,\n): void {\n for (const scenario of outcome?.scenarios ?? []) scenarioIds.project(scenario.scenarioId)\n}\n\nfunction registerHistoryScenarioIds(\n history: readonly GenerationRecord[],\n scenarioIds: ScenarioIdProjector,\n): void {\n for (const record of history) {\n for (const candidate of record.candidates) {\n for (const scenario of candidate.scenarios) scenarioIds.project(scenario.scenarioId)\n for (const cell of candidate.coverage?.unscorableCells ?? []) {\n const separator = cell.cellId.lastIndexOf(':')\n if (separator <= 0 || !/^\\d+$/.test(cell.cellId.slice(separator + 1))) continue\n scenarioIds.project(cell.cellId.slice(0, separator))\n }\n }\n }\n}\n\nfunction validateHistoryLimits(options: PolicyEditHistoryProjectionOptions): {\n maxGenerations: number\n maxCandidatesPerGeneration: number\n maxScenariosPerCandidate: number\n scenarioIdTransform: (scenarioId: string) => string\n} {\n const maxGenerations = options.maxGenerations ?? DEFAULT_POLICY_EDIT_HISTORY_LIMITS.generations\n const maxCandidatesPerGeneration =\n options.maxCandidatesPerGeneration ?? DEFAULT_POLICY_EDIT_HISTORY_LIMITS.candidatesPerGeneration\n const maxScenariosPerCandidate =\n options.maxScenariosPerCandidate ?? DEFAULT_POLICY_EDIT_HISTORY_LIMITS.scenariosPerCandidate\n if (!Number.isSafeInteger(maxGenerations) || maxGenerations <= 0) {\n throw new Error('llmPolicyEditProposer: maxHistoryGenerations must be a positive safe integer')\n }\n if (!Number.isSafeInteger(maxCandidatesPerGeneration) || maxCandidatesPerGeneration <= 0) {\n throw new Error(\n 'llmPolicyEditProposer: maxHistoryCandidatesPerGeneration must be a positive safe integer',\n )\n }\n if (!Number.isSafeInteger(maxScenariosPerCandidate) || maxScenariosPerCandidate <= 0) {\n throw new Error(\n 'llmPolicyEditProposer: maxScenariosPerCandidate must be a positive safe integer',\n )\n }\n return {\n maxGenerations,\n maxCandidatesPerGeneration,\n maxScenariosPerCandidate,\n scenarioIdTransform: options.scenarioIdTransform ?? ((scenarioId) => scenarioId),\n }\n}\n\nfunction validateObjectives(inputs: readonly PolicyEditObjective[]): PolicyEditObjective[] {\n if (inputs.length === 0) {\n throw new Error('llmPolicyEditProposer: objectives must not be empty')\n }\n const seen = new Set<string>()\n return inputs.map((input) => {\n requireNonEmpty(input.key, 'objective key')\n if (seen.has(input.key)) {\n throw new Error(`llmPolicyEditProposer: duplicate objective '${input.key}'`)\n }\n seen.add(input.key)\n if (input.split !== 'search') {\n throw new Error(`llmPolicyEditProposer: objective '${input.key}' must use the search split`)\n }\n if (input.key !== 'search.composite') {\n throw new Error(\n `llmPolicyEditProposer: objective '${input.key}' is not yet measurable; use 'search.composite'`,\n )\n }\n if (input.direction !== 'increase') {\n throw new Error(\n `llmPolicyEditProposer: objective '${input.key}' must increase because search promotes larger composite scores`,\n )\n }\n if (\n !Number.isFinite(input.scale.min) ||\n !Number.isFinite(input.scale.max) ||\n input.scale.max <= input.scale.min\n ) {\n throw new Error(`llmPolicyEditProposer: objective '${input.key}' has an invalid scale`)\n }\n if (input.unit !== 'score') {\n throw new Error(`llmPolicyEditProposer: objective '${input.key}' must use raw score deltas`)\n }\n return {\n key: input.key,\n split: 'search',\n direction: input.direction,\n scale: { ...input.scale },\n unit: input.unit,\n }\n })\n}\n\nfunction positiveLimit(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`llmPolicyEditProposer: ${field} must be a positive safe integer`)\n }\n return value\n}\n\nfunction parseAuthorResponse(value: unknown): z.infer<typeof PolicyEditAuthorResponseSchema> {\n const parsed = PolicyEditAuthorResponseSchema.safeParse(value)\n if (parsed.success) return parsed.data\n const issues = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ')\n throw new Error(`llmPolicyEditProposer: invalid PolicyEdit response: ${issues}`)\n}\n\nfunction bindAuthoredEdit(\n draft: AuthoredPolicyEdit,\n findingByKey: ReadonlyMap<string, CitableFinding>,\n targetSurface: JsonPolicyEditTargetSurface,\n allowedPaths: ReadonlySet<string>,\n objectiveByKey: ReadonlyMap<string, PolicyEditObjective>,\n currentComposite: number | undefined,\n): PolicyEdit {\n if (draft.target.surface !== targetSurface) {\n throw new Error(\n `llmPolicyEditProposer: target surface '${draft.target.surface}' does not match '${targetSurface}'`,\n )\n }\n if (draft.target.path !== draft.change.path) {\n throw new Error('llmPolicyEditProposer: target.path must equal change.path')\n }\n if (!allowedPaths.has(draft.change.path)) {\n throw new Error(\n `llmPolicyEditProposer: JSON path '${draft.change.path}' is outside allowedJsonPaths`,\n )\n }\n\n const cited = draft.source.findingKeys.map((findingKey) => {\n const finding = findingByKey.get(findingKey)\n if (!finding) {\n throw new Error(\n `llmPolicyEditProposer: edit cites unknown or uncitable finding key '${findingKey}'`,\n )\n }\n return finding\n })\n const evidenceRefs = uniqueEvidenceRefs(cited.flatMap((finding) => finding.evidenceRefs))\n if (evidenceRefs.length === 0) {\n throw new Error('llmPolicyEditProposer: authored edit has no cited evidence')\n }\n\n const objective = objectiveByKey.get(draft.expectedGain.metric)\n if (!objective) {\n throw new Error(\n `llmPolicyEditProposer: unknown forecast objective '${draft.expectedGain.metric}'`,\n )\n }\n if (draft.expectedGain.direction !== objective.direction) {\n throw new Error(\n `llmPolicyEditProposer: forecast direction for '${objective.key}' must be '${objective.direction}'`,\n )\n }\n if (draft.expectedGain.unit !== objective.unit) {\n throw new Error(\n `llmPolicyEditProposer: forecast unit for '${objective.key}' must be '${objective.unit}'`,\n )\n }\n const maxGain =\n currentComposite === undefined\n ? objective.scale.max - objective.scale.min\n : objective.scale.max - currentComposite\n if (draft.expectedGain.amount > maxGain) {\n throw new Error(\n `llmPolicyEditProposer: forecast amount for '${objective.key}' exceeds the available score headroom`,\n )\n }\n\n const expectedGain: PolicyEditExpectedGain = {\n metric: draft.expectedGain.metric,\n direction: draft.expectedGain.direction,\n amount: draft.expectedGain.amount,\n ...(draft.expectedGain.unit ? { unit: draft.expectedGain.unit } : {}),\n ...(draft.expectedGain.rationale ? { rationale: draft.expectedGain.rationale } : {}),\n }\n const init: PolicyEditInit = {\n axis: draft.axis,\n target: {\n surface: draft.target.surface,\n path: draft.target.path,\n ...(draft.target.label ? { label: draft.target.label } : {}),\n },\n change: draft.change,\n claim: draft.claim,\n expectedGain,\n confidence: draft.confidence,\n risk: draft.risk,\n source: {\n findingIds: [...new Set(cited.map((finding) => finding.finding.finding_id))],\n analystIds: [...new Set(cited.map((finding) => finding.finding.analyst_id))],\n evidenceRefs,\n },\n ...(draft.rationale ? { rationale: draft.rationale } : {}),\n ...(draft.validationPlan ? { validationPlan: draft.validationPlan } : {}),\n }\n return makePolicyEdit(init)\n}\n\nfunction parseJsonSurface(surface: MutableSurface): AgentProfileJson {\n if (typeof surface !== 'string') {\n throw new Error('llmPolicyEditProposer: currentSurface must be serialized JSON')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(surface)\n } catch {\n throw new Error('llmPolicyEditProposer: currentSurface must be valid JSON')\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('llmPolicyEditProposer: currentSurface JSON root must be an object')\n }\n return parsed as AgentProfileJson\n}\n\ninterface CitableFinding {\n finding: AnalystFinding\n sources: PolicyEditFindingSource[]\n evidenceRefs: EvidenceRef[]\n}\n\nfunction citableFindings(\n inputs: readonly PolicyEditFindingInput[],\n measuredSources: ReadonlyMap<string, PolicyEditFindingMeasurement>,\n limit: number,\n): CitableFinding[] {\n if (inputs.length === 0) {\n throw new Error('llmPolicyEditProposer: at least one analyst finding is required')\n }\n const findings: AnalystFinding[] = []\n for (const input of inputs) {\n if (!isPolicyEditFindingInput(input)) {\n throw new Error(\n 'llmPolicyEditProposer: ctx.findings must contain attributed PolicyEditFindingInput rows',\n )\n }\n findings.push(input.finding)\n }\n assertNoJudgeVerdict(findings, 'llmPolicyEditProposer')\n const grouped = new Map<string, CitableFinding>()\n for (const input of inputs) {\n validateFindingSource(input.source, measuredSources)\n if (input.finding.evidence_refs.length === 0) continue\n const existing = grouped.get(input.finding.finding_id)\n if (existing) {\n if (\n existing.finding.analyst_id !== input.finding.analyst_id ||\n existing.finding.area !== input.finding.area ||\n existing.finding.claim !== input.finding.claim ||\n existing.finding.subject !== input.finding.subject\n ) {\n throw new Error(\n `llmPolicyEditProposer: finding '${input.finding.finding_id}' has conflicting content`,\n )\n }\n if (!existing.sources.some((source) => sameFindingSource(source, input.source))) {\n existing.sources.push(input.source)\n }\n existing.evidenceRefs = uniqueEvidenceRefs([\n ...existing.evidenceRefs,\n ...input.finding.evidence_refs,\n ])\n continue\n }\n grouped.set(input.finding.finding_id, {\n finding: input.finding,\n sources: [input.source],\n evidenceRefs: uniqueEvidenceRefs(input.finding.evidence_refs),\n })\n }\n if (grouped.size === 0) {\n throw new Error('llmPolicyEditProposer: no evidence-bearing findings are available')\n }\n const severityRank: Record<AnalystFinding['severity'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n info: 4,\n }\n return [...grouped.values()]\n .sort(\n (a, b) =>\n severityRank[a.finding.severity] - severityRank[b.finding.severity] ||\n b.finding.confidence - a.finding.confidence ||\n a.finding.finding_id.localeCompare(b.finding.finding_id),\n )\n .slice(0, limit)\n}\n\nfunction isAnalystFindingLike(input: unknown): input is AnalystFinding {\n if (!input || typeof input !== 'object') return false\n const value = input as Partial<AnalystFinding>\n return (\n typeof value.finding_id === 'string' &&\n typeof value.analyst_id === 'string' &&\n typeof value.claim === 'string' &&\n Array.isArray(value.evidence_refs)\n )\n}\n\nfunction isPolicyEditFindingInput(input: unknown): input is PolicyEditFindingInput {\n if (!input || typeof input !== 'object') return false\n const value = input as Partial<PolicyEditFindingInput>\n return isAnalystFindingLike(value.finding) && isFindingSource(value.source)\n}\n\nfunction isFindingSource(input: unknown): input is PolicyEditFindingSource {\n if (!input || typeof input !== 'object') return false\n const value = input as Partial<PolicyEditFindingSource>\n if (value.kind === 'surface') {\n return typeof value.surfaceHash === 'string' && Number.isSafeInteger(value.generation)\n }\n return value.kind === 'global' && typeof value.label === 'string' && value.label.trim().length > 0\n}\n\nfunction renderFinding(\n context: CitableFinding,\n findingKey: string,\n scenarioIds: ScenarioIdProjector,\n measuredSources: ReadonlyMap<string, PolicyEditFindingMeasurement>,\n): Record<string, unknown> {\n const { finding } = context\n return {\n findingKey,\n sources: context.sources.map((source) =>\n source.kind === 'surface'\n ? {\n ...measuredSources.get(sourceKey(source.surfaceHash, source.generation))!,\n surfaceHash: scenarioIds.sanitize(source.surfaceHash),\n kind: 'surface',\n }\n : { kind: 'global', label: scenarioIds.sanitize(source.label) },\n ),\n analystId: scenarioIds.sanitize(finding.analyst_id),\n area: scenarioIds.sanitize(finding.area),\n severity: finding.severity,\n subject: finding.subject ? scenarioIds.sanitize(finding.subject) : null,\n claim: scenarioIds.sanitize(finding.claim),\n rationale: finding.rationale ? scenarioIds.sanitize(finding.rationale) : null,\n recommendedAction: finding.recommended_action\n ? scenarioIds.sanitize(finding.recommended_action)\n : null,\n validationPlan: finding.validation_plan ? scenarioIds.sanitize(finding.validation_plan) : null,\n confidence: finding.confidence,\n evidenceRefs: context.evidenceRefs.map((ref) => ({\n kind: ref.kind,\n uri: scenarioIds.sanitize(ref.uri),\n excerpt: ref.excerpt ? scenarioIds.sanitize(ref.excerpt) : null,\n })),\n }\n}\n\nfunction uniqueEvidenceRefs(refs: readonly EvidenceRef[]): EvidenceRef[] {\n const seen = new Set<string>()\n return refs.filter((ref) => {\n const key = JSON.stringify([ref.kind, ref.uri, ref.excerpt ?? null])\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\nfunction validateAllowedJsonPaths(paths: readonly string[]): string[] {\n if (paths.length === 0) {\n throw new Error('llmPolicyEditProposer: allowedJsonPaths must not be empty')\n }\n for (const path of paths) {\n if (!path || path.trim() !== path) {\n throw new Error(\n 'llmPolicyEditProposer: allowedJsonPaths must contain trimmed non-empty paths',\n )\n }\n }\n if (new Set(paths).size !== paths.length) {\n throw new Error('llmPolicyEditProposer: allowedJsonPaths must be unique')\n }\n return [...paths]\n}\n\nfunction requireNonEmpty(value: string, field: string): void {\n if (!value || value.trim() !== value) {\n throw new Error(`llmPolicyEditProposer: ${field} must be a trimmed non-empty string`)\n }\n}\n","/**\n * `policyEditProposer` turns typed analyst policy edits into measured candidate\n * surfaces. It is deliberately deterministic: analysts propose the edit, this\n * proposer only checks admission and applies it. The campaign/holdout loop still\n * decides whether the candidate actually wins.\n */\n\nimport {\n admitPolicyEdit,\n applyPolicyEditToSurface,\n type FindingToPolicyEditOptions,\n isPolicyEdit,\n makePolicyEditCandidateRecord,\n type PolicyEdit,\n type PolicyEditAdmission,\n type PolicyEditAdmissionOptions,\n policyEditsFromFindings,\n} from '../../analyst/policy-edit'\nimport type { AnalystFinding } from '../../analyst/types'\nimport { assertCodeSurfaceIdentity, surfaceContentHash } from '../surface-identity'\nimport type { MutableSurface, ProposeContext, ProposedCandidate, SurfaceProposer } from '../types'\n\nexport interface PolicyEditProposerOptions {\n /** Static edits, useful when an analyst has already emitted typed edits. When\n * omitted, the proposer reads `ctx.findings`. */\n edits?: ReadonlyArray<PolicyEdit>\n /** Adapter for legacy `AnalystFinding` rows. Findings without typed expected\n * gain are ignored rather than inflated with fake numbers. */\n findingOptions?: FindingToPolicyEditOptions\n /** Admission threshold. Defaults live in `admitPolicyEdit`. */\n admission?: PolicyEditAdmissionOptions\n /** Candidate cap. Default: `ctx.populationSize`. */\n maxCandidates?: number\n /** Optional callback for audit UIs/tests that need rejected edit reasons. */\n onAdmission?: (admission: PolicyEditAdmission) => void\n}\n\n/**\n * `SurfaceProposer` that admission-checks typed analyst `PolicyEdit`s and applies each\n * admitted edit to the current surface as one measured candidate.\n */\nexport function policyEditProposer(opts: PolicyEditProposerOptions = {}): SurfaceProposer {\n return {\n kind: 'policy-edit',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const edits = materializePolicyEdits(opts.edits ?? ctx.findings, opts.findingOptions)\n const limit = Math.max(\n 0,\n Math.min(opts.maxCandidates ?? ctx.populationSize, ctx.populationSize),\n )\n const out: ProposedCandidate[] = []\n const seen = new Set([surfaceContentHash(ctx.currentSurface)])\n if (limit === 0) return out\n\n for (const edit of edits) {\n const admission = admitPolicyEdit(edit, opts.admission)\n opts.onAdmission?.(admission)\n if (admission.decision !== 'admit') continue\n\n const surface = coerceCandidateSurface(applyPolicyEditToSurface(ctx.currentSurface, edit))\n const hash = surfaceContentHash(surface)\n if (seen.has(hash)) continue\n seen.add(hash)\n\n out.push({\n surface,\n label: `policy-edit:${edit.axis}`,\n rationale:\n `${edit.editId} expected ${edit.expectedGain.direction} ` +\n `${edit.expectedGain.metric} by ${edit.expectedGain.amount}; ` +\n `source findings [${edit.source.findingIds.join(', ')}]`,\n candidateRecord: makePolicyEditCandidateRecord(edit),\n })\n if (out.length >= limit) break\n }\n\n return out\n },\n }\n}\n\nfunction materializePolicyEdits(\n inputs: ReadonlyArray<unknown>,\n findingOptions: FindingToPolicyEditOptions | undefined,\n): PolicyEdit[] {\n const edits: PolicyEdit[] = []\n const findings: AnalystFinding[] = []\n\n for (const input of inputs) {\n if (isPolicyEdit(input)) {\n edits.push(input)\n } else if (isAnalystFindingLike(input)) {\n findings.push(input)\n }\n }\n\n if (findings.length > 0) edits.push(...policyEditsFromFindings(findings, findingOptions))\n return edits\n}\n\nfunction isAnalystFindingLike(input: unknown): input is AnalystFinding {\n if (!input || typeof input !== 'object') return false\n const obj = input as Record<string, unknown>\n return (\n typeof obj.finding_id === 'string' &&\n typeof obj.analyst_id === 'string' &&\n typeof obj.claim === 'string' &&\n Array.isArray(obj.evidence_refs)\n )\n}\n\nfunction coerceCandidateSurface(surface: unknown): MutableSurface {\n if (typeof surface === 'string') return surface\n if (surface && typeof surface === 'object') {\n const obj = surface as Record<string, unknown>\n if (obj.kind === 'code' && typeof obj.worktreeRef === 'string') {\n assertCodeSurfaceIdentity(surface)\n return surface\n }\n return JSON.stringify(surface, null, 2)\n }\n throw new Error('policyEditProposer: policy edit produced an unsupported surface')\n}\n","/** One measured scenario row eligible for PolicyEdit author context. */\nexport interface PolicyEditAuthorScenarioRow {\n scenarioId: string\n composite: number\n}\n\nexport interface SelectPolicyEditAuthorRowsOptions {\n /** Maximum returned rows. Must be a positive safe integer. */\n limit: number\n /** Optional score to compare against, keyed by scenario ID. */\n referenceByScenario?: ReadonlyMap<string, number>\n}\n\nexport interface SerializedJsonBudget {\n json: string\n actualChars: number\n maxChars: number\n}\n\ninterface RankedRow<T> {\n row: T\n delta: number | null\n}\n\n/**\n * Select a bounded, deterministic evidence slice for a PolicyEdit author.\n *\n * Rows are deduplicated by scenario ID, keeping the first measured row. The\n * result then interleaves three ranked views: hardest score, largest regression,\n * and largest improvement. A row selected by multiple views appears once.\n */\nexport function selectPolicyEditAuthorRows<T extends PolicyEditAuthorScenarioRow>(\n rows: readonly T[],\n options: SelectPolicyEditAuthorRowsOptions,\n): T[] {\n assertPositiveSafeInteger(options.limit, 'limit')\n\n const unique = new Map<string, RankedRow<T>>()\n for (const row of rows) {\n if (!row.scenarioId || row.scenarioId.trim() !== row.scenarioId) {\n throw new Error('selectPolicyEditAuthorRows: scenarioId must be trimmed and non-empty')\n }\n if (!Number.isFinite(row.composite)) {\n throw new Error(\n `selectPolicyEditAuthorRows: composite must be finite for '${row.scenarioId}'`,\n )\n }\n if (unique.has(row.scenarioId)) continue\n\n const reference = options.referenceByScenario?.get(row.scenarioId)\n if (reference !== undefined && !Number.isFinite(reference)) {\n throw new Error(\n `selectPolicyEditAuthorRows: reference must be finite for '${row.scenarioId}'`,\n )\n }\n unique.set(row.scenarioId, {\n row,\n delta: reference === undefined ? null : row.composite - reference,\n })\n }\n\n const hardest = [...unique.values()].sort(\n (a, b) => a.row.composite - b.row.composite || compareScenarioId(a.row, b.row),\n )\n const regressions = [...unique.values()]\n .filter((entry) => entry.delta !== null && entry.delta < 0)\n .sort((a, b) => a.delta! - b.delta! || compareScenarioId(a.row, b.row))\n const improvements = [...unique.values()]\n .filter((entry) => entry.delta !== null && entry.delta > 0)\n .sort((a, b) => b.delta! - a.delta! || compareScenarioId(a.row, b.row))\n const rankings = [hardest, regressions, improvements]\n const maxDepth = Math.max(...rankings.map((ranking) => ranking.length), 0)\n const selected: T[] = []\n const selectedIds = new Set<string>()\n\n for (let depth = 0; depth < maxDepth && selected.length < options.limit; depth += 1) {\n for (const ranking of rankings) {\n const entry = ranking[depth]\n if (!entry || selectedIds.has(entry.row.scenarioId)) continue\n selected.push(entry.row)\n selectedIds.add(entry.row.scenarioId)\n if (selected.length === options.limit) break\n }\n }\n return selected\n}\n\n/** Serialize once and fail before dispatch when author context exceeds its budget. */\nexport function assertPolicyEditAuthorContextBudget(\n value: unknown,\n maxChars: number,\n): SerializedJsonBudget {\n assertPositiveSafeInteger(maxChars, 'maxChars')\n const json = JSON.stringify(value)\n if (json === undefined) {\n throw new Error('assertPolicyEditAuthorContextBudget: value must serialize to JSON')\n }\n const actualChars = json.length\n if (actualChars > maxChars) {\n throw new Error(\n `assertPolicyEditAuthorContextBudget: serialized JSON exceeds budget (actualChars=${actualChars}, maxChars=${maxChars})`,\n )\n }\n return { json, actualChars, maxChars }\n}\n\nfunction compareScenarioId(a: PolicyEditAuthorScenarioRow, b: PolicyEditAuthorScenarioRow): number {\n return a.scenarioId < b.scenarioId ? -1 : a.scenarioId > b.scenarioId ? 1 : 0\n}\n\nfunction assertPositiveSafeInteger(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${name} must be a positive safe integer (got ${value})`)\n }\n}\n","/**\n * `memoryCurationProposer` — a CURATOR `SurfaceProposer`, the complement to the\n * OPTIMIZER proposers (`gepaProposer` rewrites the prompt; this one BUILDS a\n * searchable memory of what prior trajectories taught and grafts the most\n * relevant lessons onto the surface).\n *\n * Each generation it:\n * 1. collects lessons — this generation's trace-analyst `findings` PLUS the\n * memory already carried in the parent surface (so memory accumulates\n * across generations instead of resetting);\n * 2. curates them — normalizes, deduplicates near-identical lessons, and ranks\n * by recurrence (a lesson seen across many findings outranks a one-off);\n * 3. retrieves the top-K and writes them back as a single delimited memory\n * block in the surface (idempotent — the block is replaced, never stacked,\n * so the prompt does not grow without bound).\n *\n * This is the substrate behind the \"knowledge base of working trajectories\" the\n * agent searches: the curated block IS the retrieved memory the next run reads.\n * Curation is DETERMINISTIC (no LLM) so a lift it produces is attributable to\n * the lessons, not to model noise in a rewrite. An optional `distill` LLM step\n * can compress raw findings into crisp imperatives; default is verbatim.\n *\n * Fail-loud: never fabricates a lesson. With no findings and no prior memory it\n * returns no candidate (nothing learned yet — gen 0). It does not throw on an\n * empty generation because early generations legitimately have no findings.\n */\n\nimport { CostLedger, type CostLedgerHandle } from '../../cost-ledger'\nimport {\n callLlm,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from '../../llm-client'\nimport type { ProposeContext, ProposedCandidate, SurfaceProposer } from '../types'\nimport {\n extractBlockBody,\n findingToLesson,\n normKey,\n stripBlock,\n surfaceToText,\n} from './_findings-text'\n\nconst BLOCK_START = '<!-- BEGIN curated-memory (auto-managed by memoryCurationProposer) -->'\nconst BLOCK_END = '<!-- END curated-memory -->'\n\nexport interface MemoryCurationProposerOptions {\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n /** Top-K lessons retained in the surface memory block. Default 12. */\n maxEntries?: number\n /** Heading rendered above the lessons inside the block. Default below. */\n sectionHeading?: string\n /**\n * Optional LLM distillation: compress raw findings into crisp, generalizable\n * one-line imperatives before curating. Omit for verbatim (deterministic).\n */\n distill?: {\n baseUrl: string\n apiKey?: string\n model: string\n maxTokens?: number\n fetchImpl?: LlmClientOptions['fetch']\n }\n}\n\nconst DEFAULT_HEADING = '## Learned from prior runs (curated memory)'\n\nconst DISTILL_SYSTEM =\n 'You compress raw trace-analysis findings into crisp, generalizable agent guidance. ' +\n 'Output ONLY a JSON array of strings, each one imperative lesson the agent should follow ' +\n '(e.g. \"Always fetch a resource before mutating it\"). No prose outside the JSON. ' +\n 'Deduplicate; keep the most actionable and general; drop case-specific noise.'\n\n/** Pull the lessons already curated into the parent surface's memory block. */\nfunction extractExistingLessons(text: string): string[] {\n return extractBlockBody(text, BLOCK_START, BLOCK_END)\n .split('\\n')\n .map((l) => l.replace(/^\\s*-\\s+/, '').trim())\n .filter((l) => l && !l.startsWith('#'))\n}\n\nasync function distillLessons(\n raw: string[],\n distill: NonNullable<MemoryCurationProposerOptions['distill']>,\n ctx: ProposeContext,\n costLedger: CostLedgerHandle,\n): Promise<string[]> {\n const request: LlmCallRequest = {\n model: distill.model,\n messages: [\n { role: 'system', content: DISTILL_SYSTEM },\n { role: 'user', content: `Findings:\\n${raw.map((r) => `- ${r}`).join('\\n')}` },\n ],\n maxTokens: distill.maxTokens ?? 2000,\n }\n const llm: LlmClientOptions = {\n baseUrl: distill.baseUrl,\n apiKey: distill.apiKey,\n fetch: distill.fetchImpl,\n }\n const paid = await costLedger.runPaidCall({\n channel: 'driver',\n phase: ctx.costPhase ?? 'search.proposal',\n actor: 'memory-curation.distill',\n model: distill.model,\n maximumCharge: maximumChargeForLlmRequest(request, llm),\n tags: { generation: String(ctx.generation) },\n signal: ctx.signal,\n execute: (signal, callId) => callLlm(request, { ...llm, signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const res = paid.value\n try {\n const parsed = JSON.parse(res.content.trim())\n if (Array.isArray(parsed)) {\n const lessons = parsed.filter(\n (x): x is string => typeof x === 'string' && x.trim().length > 0,\n )\n if (lessons.length > 0) return lessons\n }\n } catch {\n // Distillation is a best-effort refinement; fall back to the verbatim\n // findings rather than dropping real lessons on a malformed LLM reply.\n }\n return raw\n}\n\n/** Build the CURATOR proposer. */\nexport function memoryCurationProposer(opts: MemoryCurationProposerOptions = {}): SurfaceProposer {\n const maxEntries = opts.maxEntries ?? 12\n const heading = opts.sectionHeading ?? DEFAULT_HEADING\n const directCostLedger = opts.costLedger ?? new CostLedger()\n return {\n kind: 'memory-curation',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const parent = surfaceToText(ctx.currentSurface)\n\n // (1) Collect lessons: this generation's findings + memory already in the\n // parent (accumulation across generations).\n const fresh: string[] = []\n for (const f of ctx.findings ?? []) {\n const l = findingToLesson(f)\n if (l) fresh.push(l)\n }\n const carried = extractExistingLessons(parent)\n if (fresh.length === 0 && carried.length === 0) return [] // nothing learned yet\n\n const distilled =\n opts.distill && fresh.length > 0\n ? await distillLessons(fresh, opts.distill, ctx, ctx.costLedger ?? directCostLedger)\n : fresh\n\n // (2) Curate: dedup by normalized key, rank by recurrence (carried lessons\n // start with a recurrence prior of 1; each fresh occurrence adds).\n const byKey = new Map<string, { text: string; count: number }>()\n for (const l of carried) {\n const k = normKey(l)\n if (k) byKey.set(k, { text: l, count: 1 })\n }\n for (const l of distilled) {\n const k = normKey(l)\n if (!k) continue\n const e = byKey.get(k)\n if (e) e.count += 1\n else byKey.set(k, { text: l, count: 1 })\n }\n\n // (3) Rank + top-K. Stable: by count desc, then lexicographic for determinism.\n const ranked = [...byKey.values()]\n .sort((a, b) => b.count - a.count || a.text.localeCompare(b.text))\n .slice(0, maxEntries)\n if (ranked.length === 0) return []\n\n const block = [BLOCK_START, heading, ...ranked.map((e) => `- ${e.text}`), BLOCK_END].join(\n '\\n',\n )\n const next = `${stripBlock(parent, BLOCK_START, BLOCK_END)}\\n\\n${block}\\n`\n if (next === parent) return [] // no change (same lessons already curated)\n\n return [\n {\n surface: next,\n label: 'memory-curation',\n rationale: `curated ${ranked.length} lessons (from ${fresh.length} new finding(s) + ${carried.length} carried)`,\n },\n ]\n },\n }\n}\n","/**\n * `traceAnalystProposer` — wraps agent-eval's OWN trace-analyst engine\n * (`AnalystRegistry` over the agentic OTLP reader) as a `SurfaceProposer`.\n * It is the symmetric opponent to `haloProposer`: both run the SAME shared\n * `analysisEditProposer` pipeline (materialize identical traces → apply via one\n * identical LLM edit), so a `compareProposers` lift delta isolates a single\n * variable — ANALYSIS QUALITY. The benchmark answers \"is our HALO clone as good\n * as the real HALO?\" as a held-out lift CI, not a vibe.\n *\n * Findings come from the REGISTRY (structured `AnalystFinding[]` carrying\n * area / severity / recommended_action), rendered into the report the shared\n * apply step consumes.\n *\n * Fail-loud: no traces → throw; analyst run errors → throw; zero findings →\n * throw. Never fabricate a candidate.\n */\n\nimport { ai } from '@ax-llm/ax'\nimport { createTraceAnalystKind, type TraceAnalystKindSpec } from '../../analyst/kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from '../../analyst/kinds'\nimport { AnalystRegistry } from '../../analyst/registry'\nimport type { AnalystFinding } from '../../analyst/types'\nimport type { CostLedgerHandle, CostReceiptInput, MaximumCharge } from '../../cost-ledger'\nimport type { LlmClientOptions } from '../../llm-client'\nimport { OtlpFileTraceStore } from '../../trace-analyst/store-otlp'\nimport type { ProposeContext, SurfaceProposer } from '../types'\nimport { analysisEditProposer } from './analysis-edit'\n\nexport interface TraceAnalystProposerOptions {\n /** OpenAI-compatible base URL for BOTH the analyst's agentic reads and the\n * apply step (e.g. `https://api.deepseek.com/v1` or the Tangle router). */\n baseUrl: string\n /** Bearer key. Required — the Ax AI service has no env fallback here. */\n apiKey: string\n /** Model the analyst kinds use for their agentic trace reads. */\n model: string\n /** Model used to APPLY findings to the prompt surface. Default = `model`.\n * Keep this EQUAL to haloProposer's `applyModel` for an apples-to-apples run. */\n applyModel?: string\n /** Optional ledger for direct proposer use. Campaign context takes precedence. */\n costLedger?: CostLedgerHandle\n analysisMaximumCharge?: MaximumCharge\n analysisReceipt?: (report: string) => CostReceiptInput\n applyMaxTokens?: number\n /** Ax provider name. Default 'openai' — works for any OpenAI-compatible base\n * via `apiURL`. Use 'deepseek' to hit DeepSeek's native provider. */\n provider?: string\n /** Which analyst kinds to run. Default = the full shipped suite. */\n kinds?: readonly TraceAnalystKindSpec[]\n /** Resolve the OTLP traces (JSONL string) the analyst should read for THIS\n * generation — identical contract to `haloProposer.resolveTraces`. */\n resolveTraces: (ctx: ProposeContext) => string | Promise<string>\n /** Override the findings producer. Default: the shipped `AnalystRegistry`\n * over `kinds`. The unit suite injects canned findings here. */\n analyze?: (tracePath: string, ctx: ProposeContext) => Promise<ReadonlyArray<AnalystFinding>>\n /** Test seam: inject a fetch for the apply-step `callLlm`. */\n fetchImpl?: LlmClientOptions['fetch']\n}\n\n/** Render structured findings into the report shape the shared apply step\n * consumes — so the application is identical across engines. */\nfunction renderFindings(findings: ReadonlyArray<AnalystFinding>): string {\n return findings\n .map((f, i) => {\n const action = f.recommended_action ? `\\n FIX: ${f.recommended_action}` : ''\n const subject = f.subject ? ` (${f.subject})` : ''\n return `${i + 1}. [${f.severity}/${f.area}]${subject} ${f.claim}${action}`\n })\n .join('\\n')\n}\n\n/** Wrap agent-eval's trace-analyst registry as a SurfaceProposer (prompt-tier). */\nexport function traceAnalystProposer(opts: TraceAnalystProposerOptions): SurfaceProposer {\n if (!opts.apiKey) throw new Error('traceAnalystProposer: apiKey is required')\n if (!opts.model) throw new Error('traceAnalystProposer: model is required')\n const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS\n\n const produceFindings =\n opts.analyze ??\n (async (path: string, c: ProposeContext): Promise<ReadonlyArray<AnalystFinding>> => {\n const aiService = ai({\n name: opts.provider ?? 'openai',\n apiKey: opts.apiKey,\n apiURL: opts.baseUrl,\n config: { model: opts.model },\n })\n const registry = new AnalystRegistry()\n for (const spec of kinds) {\n registry.register(createTraceAnalystKind(spec, { ai: aiService, model: opts.model }))\n }\n const result = await registry.run(\n `trace-analyst-gen-${c.generation}`,\n { traceStore: new OtlpFileTraceStore({ path }) },\n { signal: c.signal },\n )\n return result.findings\n })\n\n return analysisEditProposer({\n kind: 'trace-analyst',\n label: 'trace-analyst',\n baseUrl: opts.baseUrl,\n apiKey: opts.apiKey,\n analysisModel: opts.model,\n applyModel: opts.applyModel ?? opts.model,\n costLedger: opts.costLedger,\n analysisMaximumCharge: opts.analysisMaximumCharge,\n analysisReceipt: opts.analysisReceipt,\n applyMaxTokens: opts.applyMaxTokens,\n fetchImpl: opts.fetchImpl,\n resolveTraces: opts.resolveTraces,\n noTracesError:\n 'traceAnalystProposer: resolveTraces returned no OTLP traces — the analyst has nothing to read',\n rationale: (report) => `trace-analyst findings:\\n${report.slice(0, 800)}`,\n analyze: async (tracePath, ctx) => {\n let findings: ReadonlyArray<AnalystFinding>\n try {\n findings = await produceFindings(tracePath, ctx)\n } catch (e) {\n throw new Error(\n `traceAnalystProposer: analyst engine failed — ${e instanceof Error ? e.message : String(e)}`,\n )\n }\n if (findings.length === 0) {\n throw new Error('traceAnalystProposer: analyst engine produced no findings')\n }\n return renderFindings(findings)\n },\n })\n}\n","/**\n * Discriminative scenario selection (research claim E2).\n *\n * The OR benchmark is SATURATING: run 7 measured ~75% tied holdout cells — most\n * problems are solved optimally by the baseline AND every candidate, so those\n * paired cells carry zero signal. A random/balanced holdout split spends its\n * budget on scenarios that cannot separate candidates.\n *\n * This picks the holdout by DISCRIMINATION power instead: a scenario every\n * candidate scores identically (variance ~0) carries no signal; one where the\n * scores spread carries the most. We drop fully saturated ties so each paired\n * holdout cell is spent on a scenario that can actually move a verdict.\n */\n\n/** Per-scenario observation: the composite scores each candidate earned on it. */\nexport interface ScenarioSignal {\n scenarioId: string\n /** Per-candidate composite scores observed for this scenario (>=1 values). */\n scores: number[]\n}\n\nexport interface DiscriminationScore {\n scenarioId: string\n /** Higher = separates candidates more (spread of their scores). */\n discrimination: number\n /** Higher = easier / more-saturated (mean of candidate scores). */\n meanScore: number\n variance: number\n /** variance ~0 AND meanScore at/above the ceiling ⇒ a saturated tie, no signal. */\n tied: boolean\n}\n\nconst DEFAULT_SATURATION_CEILING = 0.999\n/** Variance below this is treated as \"every candidate scored the same\". */\nconst VARIANCE_EPSILON = 1e-9\n\ninterface Moments {\n meanScore: number\n variance: number\n}\n\n/** Population mean + variance of the candidate scores. Empty ⇒ zeros (a signal\n * with no observations cannot discriminate). */\nfunction moments(scores: number[]): Moments {\n const n = scores.length\n if (n === 0) return { meanScore: 0, variance: 0 }\n let sum = 0\n for (const s of scores) sum += s\n const meanScore = sum / n\n let sqDev = 0\n for (const s of scores) {\n const d = s - meanScore\n sqDev += d * d\n }\n return { meanScore, variance: sqDev / n }\n}\n\n/** Deterministic ordering: discrimination desc, then meanScore asc (more\n * headroom first), then scenarioId asc. */\nfunction compareDiscrimination(a: DiscriminationScore, b: DiscriminationScore): number {\n if (b.discrimination !== a.discrimination) return b.discrimination - a.discrimination\n if (a.meanScore !== b.meanScore) return a.meanScore - b.meanScore\n return a.scenarioId < b.scenarioId ? -1 : a.scenarioId > b.scenarioId ? 1 : 0\n}\n\n/**\n * Rank scenarios by how well they DISCRIMINATE candidates.\n *\n * `discrimination = variance` (spread of the candidate scores) — kept simple on\n * purpose; the headroom term (`saturationCeiling - meanScore`) only breaks ties\n * so that, among equally spread scenarios, the one with more room to improve\n * ranks first. Returned sorted by the deterministic order above.\n */\nexport function scoreDiscrimination(\n signals: ScenarioSignal[],\n opts?: { saturationCeiling?: number },\n): DiscriminationScore[] {\n const saturationCeiling = opts?.saturationCeiling ?? DEFAULT_SATURATION_CEILING\n const scored = signals.map((signal): DiscriminationScore => {\n const { meanScore, variance } = moments(signal.scores)\n const tied = variance < VARIANCE_EPSILON && meanScore >= saturationCeiling\n return {\n scenarioId: signal.scenarioId,\n discrimination: variance,\n meanScore,\n variance,\n tied,\n }\n })\n return scored.sort(compareDiscrimination)\n}\n\n/**\n * Select the top-`k` most discriminative scenario ids for a holdout, EXCLUDING\n * fully saturated ties when enough non-tied scenarios exist (a tie in the\n * holdout wastes a paired cell).\n *\n * Prefers non-tied scenarios; if fewer than `k` non-tied exist, fills with the\n * least-saturated tied ones (tied scenarios are already ordered least-saturated\n * first by `meanScore` asc). Deterministic. Throws if `k < 1`. If\n * `signals.length <= k`, returns all ids in discrimination order.\n */\nexport function selectDiscriminative(\n signals: ScenarioSignal[],\n k: number,\n opts?: { saturationCeiling?: number },\n): string[] {\n if (k < 1) throw new Error(`selectDiscriminative: k must be >= 1 (got ${k})`)\n const ranked = scoreDiscrimination(signals, opts)\n if (ranked.length <= k) return ranked.map((s) => s.scenarioId)\n const nonTied = ranked.filter((s) => !s.tied)\n if (nonTied.length >= k) return nonTied.slice(0, k).map((s) => s.scenarioId)\n const tied = ranked.filter((s) => s.tied)\n const fill = tied.slice(0, k - nonTied.length)\n return [...nonTied, ...fill].map((s) => s.scenarioId)\n}\n","/**\n * Durable append-only audit log for improvement searches.\n *\n * Existing campaign artifacts keep their own rich records: `RunRecord` owns a\n * measured run, `Lineage` owns the candidate graph, and `CostLedger` owns\n * per-call accounting. This ledger does not copy those structures. It binds\n * their immutable ids and receipts into one replayable event stream so a\n * search can answer, after a crash, exactly which candidates and task attempts\n * existed, which surfaces actually fired, what they cost, and why they were\n * selected or rejected.\n *\n * The file format is canonical JSONL with a SHA-256 hash chain. Every append is\n * serialized across processes, fsynced before acknowledgement, and idempotent\n * by `eventId`. A malformed, non-canonical, truncated, reordered, or conflicting\n * log fails loudly; the implementation never skips a bad row.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { z } from 'zod'\nimport { Mutex } from '../concurrency'\nimport { canonicalize } from '../pre-registration'\nimport { modelHasSnapshot } from '../run-record'\nimport {\n SearchLedgerConflictError,\n SearchLedgerError,\n SearchLedgerIntegrityError,\n} from './search-ledger-errors'\nimport { appendSearchLedgerLine, withSearchLedgerFileLock } from './search-ledger-file'\n\nexport { SearchLedgerConflictError, SearchLedgerError, SearchLedgerIntegrityError }\n\nexport const SEARCH_LEDGER_SCHEMA = 'tangle.search-ledger.v1' as const\n\nexport type SearchLedgerHash = `sha256:${string}`\n\nexport type SearchSurfaceKind =\n | 'prompt'\n | 'tool-contract'\n | 'runtime-config'\n | 'memory'\n | 'knowledge'\n | 'agent-profile'\n | 'code'\n | 'deployment'\n\n/** Content-addressed artifact or receipt. Mutable paths are locators only; the\n * digest and byte length bind the exact bytes used by the search. */\nexport interface SearchArtifactRef {\n role: string\n uri: string\n sha256: SearchLedgerHash\n byteLength: number\n}\n\n/** Repository, dataset, or package source pinned to an immutable commit or\n * content digest. Branches, tags, and bare package versions are rejected. */\nexport interface SearchSourceRef {\n uri: string\n revision: string\n}\n\nexport interface SearchModelIdentity {\n provider: string\n snapshot: string\n}\n\nexport interface SearchCandidateSurface {\n surfaceId: string\n kind: SearchSurfaceKind\n artifact: SearchArtifactRef\n}\n\nexport interface SearchCandidateLineage {\n /** Existing `LineageNode.id`; this ledger references rather than embeds it. */\n lineageNodeId: string\n parentCandidateIds: string[]\n generation: number\n proposer: string\n proposerSource: SearchSourceRef\n}\n\nexport type SearchOperationKind =\n | 'candidate-generation'\n | 'analysis'\n | 'selection'\n | 'judge'\n | 'other'\n\nexport interface SearchPlannedTask {\n taskId: string\n source: SearchSourceRef\n benchmark: SearchSourceRef\n /** Maximum transport attempts for this task and candidate. Only an explicit\n * passed/failed outcome satisfies the planned denominator. */\n maxAttempts: number\n}\n\nexport interface SearchPlannedOperation {\n operationId: string\n kind: SearchOperationKind\n}\n\nexport interface SearchCandidateSlot {\n slotId: string\n /** Planned candidate-generation call that must either produce this slot or\n * fail before the slot can be closed. Several slots may share one batched call. */\n generationOperationId: string\n}\n\nexport interface SearchPlan {\n /** Stable slots and their proposer calls are frozen before search begins. */\n candidateSlots: SearchCandidateSlot[]\n /** Every task applies to every successfully registered candidate. */\n tasks: SearchPlannedTask[]\n /** Non-task spend slots: proposal, analysis, selection, extra judges, etc. */\n operations: SearchPlannedOperation[]\n}\n\nexport type SearchTokenAccounting =\n | {\n status: 'known'\n inputTokens: number\n outputTokens: number\n cachedTokens: number\n }\n | {\n status: 'unknown'\n reason: string\n }\n\nexport type SearchCostAccounting =\n | {\n status: 'known'\n usd: number\n source: 'provider' | 'pricing-table' | 'free'\n }\n | {\n status: 'unknown'\n /** Known spend may still be a lower bound when one call was unpriced. */\n knownLowerBoundUsd: number\n reason: string\n }\n\nexport interface SearchAttemptAccounting {\n tokens: SearchTokenAccounting\n cost: SearchCostAccounting\n}\n\nexport interface SearchFailureReason {\n code: string\n message: string\n}\n\nexport type SearchTaskOutcome =\n | {\n status: 'passed'\n score: number\n metrics: Record<string, number>\n }\n | {\n status: 'failed'\n score: number\n metrics: Record<string, number>\n failure: SearchFailureReason\n }\n | {\n status: 'errored'\n metrics: Record<string, number>\n error: SearchFailureReason & { retryable: boolean }\n }\n\nexport type SearchSurfaceEffect =\n | {\n status: 'measured'\n metric: string\n baselineValue: number\n candidateValue: number\n delta: number\n }\n | {\n status: 'not-measured'\n reason: string\n }\n\n/** Per-attempt proof that a declared candidate surface was or was not active,\n * plus measured effect when the experiment supports attribution. */\nexport interface SearchSurfaceEvidence {\n surfaceId: string\n fired: boolean\n firingCount: number\n effect: SearchSurfaceEffect\n evidence: SearchArtifactRef[]\n}\n\ninterface SearchLedgerEventBase {\n eventId: string\n occurredAt: string\n artifacts: SearchArtifactRef[]\n}\n\nexport interface SearchPlannedEvent extends SearchLedgerEventBase {\n kind: 'search-planned'\n plan: SearchPlan\n}\n\nexport interface SearchCandidateRegisteredEvent extends SearchLedgerEventBase {\n kind: 'candidate-registered'\n slotId: string\n generationOperationId: string\n candidateId: string\n lineage: SearchCandidateLineage\n surfaces: SearchCandidateSurface[]\n}\n\nexport interface SearchCandidateSlotClosedEvent extends SearchLedgerEventBase {\n kind: 'candidate-slot-closed'\n slotId: string\n generationOperationId: string\n reason: SearchFailureReason\n}\n\nexport interface SearchTaskAttemptedEvent extends SearchLedgerEventBase {\n kind: 'task-attempted'\n candidateId: string\n runId: string\n attemptIndex: number\n task: {\n taskId: string\n source: SearchSourceRef\n }\n identity: {\n model: SearchModelIdentity\n agent: SearchSourceRef\n benchmark: SearchSourceRef\n }\n outcome: SearchTaskOutcome\n accounting: SearchAttemptAccounting\n surfaceEvidence: SearchSurfaceEvidence[]\n}\n\nexport interface SearchOperationRecordedEvent extends SearchLedgerEventBase {\n kind: 'search-operation-recorded'\n operationId: string\n operationKind: SearchOperationKind\n execution:\n | {\n kind: 'model'\n model: SearchModelIdentity\n source: SearchSourceRef\n }\n | {\n kind: 'deterministic'\n source: SearchSourceRef\n }\n outcome:\n | { status: 'completed' }\n | { status: 'partial'; failure: SearchFailureReason }\n | { status: 'failed'; failure: SearchFailureReason }\n accounting: SearchAttemptAccounting\n}\n\nexport interface SearchCandidateDecidedEvent extends SearchLedgerEventBase {\n kind: 'candidate-decided'\n candidateId: string\n decision:\n | { status: 'selected' }\n | {\n status: 'rejected'\n reason: SearchFailureReason\n }\n}\n\nexport interface SearchCompletedEvent extends SearchLedgerEventBase {\n kind: 'search-completed'\n result:\n | {\n status: 'selected'\n candidateId: string\n }\n | {\n status: 'all-rejected'\n reason: SearchFailureReason\n }\n}\n\nexport type SearchLedgerEvent =\n | SearchPlannedEvent\n | SearchCandidateRegisteredEvent\n | SearchCandidateSlotClosedEvent\n | SearchTaskAttemptedEvent\n | SearchOperationRecordedEvent\n | SearchCandidateDecidedEvent\n | SearchCompletedEvent\n\nexport interface SearchLedgerEntry {\n schema: typeof SEARCH_LEDGER_SCHEMA\n campaignId: string\n sequence: number\n previousHash: SearchLedgerHash | null\n event: SearchLedgerEvent\n entryHash: SearchLedgerHash\n}\n\nexport type SearchAccountingAudit =\n | {\n status: 'known'\n inputTokens: number\n outputTokens: number\n cachedTokens: number\n costUsd: number\n }\n | {\n status: 'partial'\n knownInputTokens: number\n knownOutputTokens: number\n knownCachedTokens: number\n knownCostUsd: number\n unknownTokenEventIds: string[]\n unknownCostEventIds: string[]\n }\n\nexport interface SearchLedgerAudit {\n campaignId: string\n eventCount: number\n candidateCount: number\n closedCandidateSlotCount: number\n attemptCount: number\n operationCount: number\n outcomes: { passed: number; failed: number; errored: number }\n operationOutcomes: { completed: number; partial: number; failed: number }\n decisions: { selected: number; rejected: number; pending: number }\n expected: {\n candidateSlots: number\n taskOutcomes: number\n operations: number\n missingCandidateSlots: string[]\n missingTaskOutcomes: string[]\n missingOperations: string[]\n }\n status: 'in-progress' | 'selected' | 'all-rejected'\n selectedCandidateId: string | null\n accounting: SearchAccountingAudit\n headHash: SearchLedgerHash | null\n}\n\nexport interface SearchLedgerReplay {\n entries: SearchLedgerEntry[]\n plan: SearchPlannedEvent | null\n candidates: SearchCandidateRegisteredEvent[]\n closedCandidateSlots: SearchCandidateSlotClosedEvent[]\n attempts: SearchTaskAttemptedEvent[]\n operations: SearchOperationRecordedEvent[]\n decisions: SearchCandidateDecidedEvent[]\n completion: SearchCompletedEvent | null\n audit: SearchLedgerAudit\n}\n\nexport interface SearchLedgerAppendResult {\n entry: SearchLedgerEntry\n /** False when the exact event was already durably present. */\n appended: boolean\n replay: SearchLedgerReplay\n}\n\nconst NON_EMPTY = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, 'must not contain surrounding whitespace')\nconst HASH = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst LINEAGE_NODE_ID = z.string().regex(/^[a-f0-9]{16}$/)\nconst IMMUTABLE_REVISION = z\n .string()\n .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64}|sha256:[a-f0-9]{64}|sha512:[A-Za-z0-9+/=]+)$/)\nconst ISO_TIMESTAMP = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$/)\n .refine((value) => Number.isFinite(Date.parse(value)), 'invalid timestamp')\nconst NON_NEGATIVE_INT = z.number().int().nonnegative().safe()\nconst FINITE_NUMBER = z.number().finite()\n\nconst ArtifactRefSchema = z\n .object({\n role: NON_EMPTY,\n uri: NON_EMPTY,\n sha256: HASH,\n byteLength: NON_NEGATIVE_INT,\n })\n .strict()\n\nconst SourceRefSchema = z\n .object({\n uri: NON_EMPTY,\n revision: IMMUTABLE_REVISION,\n })\n .strict()\n\nconst FailureReasonSchema = z\n .object({\n code: NON_EMPTY,\n message: NON_EMPTY,\n })\n .strict()\n\nconst EventBaseShape = {\n eventId: NON_EMPTY,\n occurredAt: ISO_TIMESTAMP,\n artifacts: z.array(ArtifactRefSchema).min(1),\n}\n\nconst OperationKindSchema = z.enum([\n 'candidate-generation',\n 'analysis',\n 'selection',\n 'judge',\n 'other',\n])\n\nconst SearchPlannedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('search-planned'),\n plan: z\n .object({\n candidateSlots: z\n .array(\n z\n .object({\n slotId: NON_EMPTY,\n generationOperationId: NON_EMPTY,\n })\n .strict(),\n )\n .min(1),\n tasks: z\n .array(\n z\n .object({\n taskId: NON_EMPTY,\n source: SourceRefSchema,\n benchmark: SourceRefSchema,\n maxAttempts: z.number().int().positive().safe(),\n })\n .strict(),\n )\n .min(1),\n operations: z\n .array(\n z\n .object({\n operationId: NON_EMPTY,\n kind: OperationKindSchema,\n })\n .strict(),\n )\n .min(1),\n })\n .strict(),\n })\n .strict()\n\nconst CandidateRegisteredSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('candidate-registered'),\n slotId: NON_EMPTY,\n generationOperationId: NON_EMPTY,\n candidateId: NON_EMPTY,\n lineage: z\n .object({\n lineageNodeId: LINEAGE_NODE_ID,\n parentCandidateIds: z.array(NON_EMPTY),\n generation: NON_NEGATIVE_INT,\n proposer: NON_EMPTY,\n proposerSource: SourceRefSchema,\n })\n .strict(),\n surfaces: z\n .array(\n z\n .object({\n surfaceId: NON_EMPTY,\n kind: z.enum([\n 'prompt',\n 'tool-contract',\n 'runtime-config',\n 'memory',\n 'knowledge',\n 'agent-profile',\n 'code',\n 'deployment',\n ]),\n artifact: ArtifactRefSchema,\n })\n .strict(),\n )\n .min(1),\n })\n .strict()\n\nconst CandidateSlotClosedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('candidate-slot-closed'),\n slotId: NON_EMPTY,\n generationOperationId: NON_EMPTY,\n reason: FailureReasonSchema,\n })\n .strict()\n\nconst KnownTokensSchema = z\n .object({\n status: z.literal('known'),\n inputTokens: NON_NEGATIVE_INT,\n outputTokens: NON_NEGATIVE_INT,\n cachedTokens: NON_NEGATIVE_INT,\n })\n .strict()\n\nconst UnknownSchema = z\n .object({\n status: z.literal('unknown'),\n reason: NON_EMPTY,\n })\n .strict()\n\nconst KnownCostSchema = z\n .object({\n status: z.literal('known'),\n usd: z.number().finite().nonnegative(),\n source: z.enum(['provider', 'pricing-table', 'free']),\n })\n .strict()\n .superRefine((cost, ctx) => {\n if (cost.source === 'free' && cost.usd !== 0) {\n ctx.addIssue({ code: 'custom', message: 'free cost source must have usd 0' })\n }\n })\n\nconst UnknownCostSchema = z\n .object({\n status: z.literal('unknown'),\n knownLowerBoundUsd: z.number().finite().nonnegative(),\n reason: NON_EMPTY,\n })\n .strict()\n\nconst AccountingSchema = z\n .object({\n tokens: z.discriminatedUnion('status', [KnownTokensSchema, UnknownSchema]),\n cost: z.discriminatedUnion('status', [KnownCostSchema, UnknownCostSchema]),\n })\n .strict()\n\nconst MetricsSchema = z.record(NON_EMPTY, FINITE_NUMBER).superRefine((metrics, ctx) => {\n for (const key of Object.keys(metrics)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n ctx.addIssue({ code: 'custom', message: `unsafe metric key ${key}` })\n }\n }\n})\n\nconst OutcomeSchema = z.discriminatedUnion('status', [\n z\n .object({\n status: z.literal('passed'),\n score: FINITE_NUMBER,\n metrics: MetricsSchema,\n })\n .strict(),\n z\n .object({\n status: z.literal('failed'),\n score: FINITE_NUMBER,\n metrics: MetricsSchema,\n failure: FailureReasonSchema,\n })\n .strict(),\n z\n .object({\n status: z.literal('errored'),\n metrics: MetricsSchema,\n error: FailureReasonSchema.extend({ retryable: z.boolean() }).strict(),\n })\n .strict(),\n])\n\nconst EffectSchema = z.discriminatedUnion('status', [\n z\n .object({\n status: z.literal('measured'),\n metric: NON_EMPTY,\n baselineValue: FINITE_NUMBER,\n candidateValue: FINITE_NUMBER,\n delta: FINITE_NUMBER,\n })\n .strict()\n .superRefine((effect, ctx) => {\n const expected = effect.candidateValue - effect.baselineValue\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(expected), Math.abs(effect.delta)) * 8\n if (Math.abs(effect.delta - expected) > tolerance) {\n ctx.addIssue({ code: 'custom', message: 'delta must equal candidateValue - baselineValue' })\n }\n }),\n z\n .object({\n status: z.literal('not-measured'),\n reason: NON_EMPTY,\n })\n .strict(),\n])\n\nconst SurfaceEvidenceSchema = z\n .object({\n surfaceId: NON_EMPTY,\n fired: z.boolean(),\n firingCount: NON_NEGATIVE_INT,\n effect: EffectSchema,\n evidence: z.array(ArtifactRefSchema).min(1),\n })\n .strict()\n .superRefine((evidence, ctx) => {\n if (evidence.fired && evidence.firingCount === 0) {\n ctx.addIssue({ code: 'custom', message: 'a fired surface must have firingCount >= 1' })\n }\n if (!evidence.fired && evidence.firingCount !== 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'a surface that did not fire must have firingCount 0',\n })\n }\n if (!evidence.fired && evidence.effect.status === 'measured' && evidence.effect.delta !== 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'a surface that did not fire cannot claim non-zero effect',\n })\n }\n })\n\nconst TaskAttemptedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('task-attempted'),\n candidateId: NON_EMPTY,\n runId: NON_EMPTY,\n attemptIndex: NON_NEGATIVE_INT,\n task: z.object({ taskId: NON_EMPTY, source: SourceRefSchema }).strict(),\n identity: z\n .object({\n model: z\n .object({\n provider: NON_EMPTY,\n snapshot: NON_EMPTY.refine(\n modelHasSnapshot,\n 'model must include an immutable snapshot',\n ),\n })\n .strict(),\n agent: SourceRefSchema,\n benchmark: SourceRefSchema,\n })\n .strict(),\n outcome: OutcomeSchema,\n accounting: AccountingSchema,\n surfaceEvidence: z.array(SurfaceEvidenceSchema).min(1),\n })\n .strict()\n\nconst SearchOperationRecordedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('search-operation-recorded'),\n operationId: NON_EMPTY,\n operationKind: OperationKindSchema,\n execution: z.discriminatedUnion('kind', [\n z\n .object({\n kind: z.literal('model'),\n model: z\n .object({\n provider: NON_EMPTY,\n snapshot: NON_EMPTY.refine(\n modelHasSnapshot,\n 'model must include an immutable snapshot',\n ),\n })\n .strict(),\n source: SourceRefSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('deterministic'),\n source: SourceRefSchema,\n })\n .strict(),\n ]),\n outcome: z.discriminatedUnion('status', [\n z.object({ status: z.literal('completed') }).strict(),\n z\n .object({\n status: z.literal('partial'),\n failure: FailureReasonSchema,\n })\n .strict(),\n z\n .object({\n status: z.literal('failed'),\n failure: FailureReasonSchema,\n })\n .strict(),\n ]),\n accounting: AccountingSchema,\n })\n .strict()\n\nconst CandidateDecidedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('candidate-decided'),\n candidateId: NON_EMPTY,\n decision: z.discriminatedUnion('status', [\n z.object({ status: z.literal('selected') }).strict(),\n z\n .object({\n status: z.literal('rejected'),\n reason: FailureReasonSchema,\n })\n .strict(),\n ]),\n })\n .strict()\n\nconst SearchCompletedSchema = z\n .object({\n ...EventBaseShape,\n kind: z.literal('search-completed'),\n result: z.discriminatedUnion('status', [\n z\n .object({\n status: z.literal('selected'),\n candidateId: NON_EMPTY,\n })\n .strict(),\n z\n .object({\n status: z.literal('all-rejected'),\n reason: FailureReasonSchema,\n })\n .strict(),\n ]),\n })\n .strict()\n\nconst EventSchema = z.discriminatedUnion('kind', [\n SearchPlannedSchema,\n CandidateRegisteredSchema,\n CandidateSlotClosedSchema,\n TaskAttemptedSchema,\n SearchOperationRecordedSchema,\n CandidateDecidedSchema,\n SearchCompletedSchema,\n])\n\nconst EntrySchema = z\n .object({\n schema: z.literal(SEARCH_LEDGER_SCHEMA),\n campaignId: NON_EMPTY,\n sequence: NON_NEGATIVE_INT,\n previousHash: z.union([HASH, z.null()]),\n event: EventSchema,\n entryHash: HASH,\n })\n .strict()\n\n/** Validate and return a canonical copy. Arrays whose order is not semantic are\n * sorted so retries from different processes produce byte-identical events. */\nexport function validateSearchLedgerEvent(input: unknown): SearchLedgerEvent {\n const parsed = EventSchema.safeParse(input)\n if (!parsed.success) {\n throw new SearchLedgerError(`invalid search ledger event: ${formatZodError(parsed.error)}`)\n }\n return normalizeEvent(parsed.data as SearchLedgerEvent)\n}\n\nexport interface OpenSearchLedgerOptions {\n path: string\n campaignId: string\n}\n\nexport interface SearchLedger {\n readonly path: string\n readonly campaignId: string\n append(event: SearchLedgerEvent): Promise<SearchLedgerAppendResult>\n replay(): Promise<SearchLedgerReplay>\n}\n\n/** Open a durable filesystem search ledger. Construction performs no I/O; the\n * first `append` or `replay` validates the complete existing file. */\nexport function openSearchLedger(options: OpenSearchLedgerOptions): SearchLedger {\n if (options.path.trim().length === 0) throw new SearchLedgerError('ledger path is empty')\n return new FileSearchLedger(options.path, options.campaignId)\n}\n\nconst ledgerMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = ledgerMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n ledgerMutexes.set(path, mutex)\n return mutex\n}\n\nexport class FileSearchLedger implements SearchLedger {\n readonly path: string\n readonly campaignId: string\n private readonly mutex: Mutex\n\n constructor(path: string, campaignId: string) {\n if (path.trim().length === 0) throw new SearchLedgerError('ledger path is empty')\n if (campaignId.length === 0) throw new SearchLedgerError('campaignId is empty')\n if (campaignId.trim() !== campaignId) {\n throw new SearchLedgerError('campaignId must not contain surrounding whitespace')\n }\n this.path = resolve(path)\n this.campaignId = campaignId\n this.mutex = mutexFor(this.path)\n }\n\n async replay(): Promise<SearchLedgerReplay> {\n return this.mutex.runExclusive(() =>\n withSearchLedgerFileLock(this.path, () => replayFile(this.path, this.campaignId)),\n )\n }\n\n async append(input: SearchLedgerEvent): Promise<SearchLedgerAppendResult> {\n const event = validateSearchLedgerEvent(input)\n return this.mutex.runExclusive(() =>\n withSearchLedgerFileLock(this.path, () => {\n const before = replayFile(this.path, this.campaignId)\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw new SearchLedgerConflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n return { entry: existing, appended: false, replay: before }\n }\n\n const previousHash = before.audit.headHash\n const material = {\n schema: SEARCH_LEDGER_SCHEMA,\n campaignId: this.campaignId,\n sequence: before.entries.length,\n previousHash,\n event,\n } as const\n const entry: SearchLedgerEntry = {\n ...material,\n entryHash: hashCanonical(material),\n }\n\n // Apply the state transition before spending an append. This catches\n // unknown parents, missing task attempts, duplicate decisions, and\n // invalid completion records without touching the durable file.\n const replay = replayEntries([...before.entries, entry], this.campaignId)\n appendSearchLedgerLine(this.path, `${canonicalString(entry)}\\n`)\n return { entry, appended: true, replay }\n }),\n )\n }\n}\n\nfunction replayFile(path: string, campaignId: string): SearchLedgerReplay {\n if (!existsSync(path)) return replayEntries([], campaignId)\n const text = readFileSync(path, 'utf8')\n if (text.length === 0) return replayEntries([], campaignId)\n if (!text.endsWith('\\n')) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: SearchLedgerEntry[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\n } catch (error) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n const parsed = EntrySchema.safeParse(raw)\n if (!parsed.success) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has a malformed entry at line ${index + 1}: ${formatZodError(parsed.error)}`,\n )\n }\n const entry = parsed.data as SearchLedgerEntry\n const normalizedEvent = validateSearchLedgerEvent(entry.event)\n if (canonicalString(normalizedEvent) !== canonicalString(entry.event)) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has non-canonical event ordering at line ${index + 1}`,\n )\n }\n if (line !== canonicalString(entry)) {\n throw new SearchLedgerIntegrityError(\n `search ledger ${path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return replayEntries(entries, campaignId)\n}\n\ninterface CandidateState {\n registered: SearchCandidateRegisteredEvent\n attempts: SearchTaskAttemptedEvent[]\n decision: SearchCandidateDecidedEvent | null\n}\n\nfunction replayEntries(entries: SearchLedgerEntry[], campaignId: string): SearchLedgerReplay {\n const candidates = new Map<string, CandidateState>()\n const candidateBySlot = new Map<string, string>()\n const closedSlots = new Map<string, SearchCandidateSlotClosedEvent>()\n const lineageNodes = new Map<string, string>()\n const eventIds = new Set<string>()\n const runIds = new Set<string>()\n const attemptKeys = new Set<string>()\n const candidateEvents: SearchCandidateRegisteredEvent[] = []\n const closedSlotEvents: SearchCandidateSlotClosedEvent[] = []\n const attempts: SearchTaskAttemptedEvent[] = []\n const operationEvents: SearchOperationRecordedEvent[] = []\n const operationsById = new Map<string, SearchOperationRecordedEvent>()\n const decisions: SearchCandidateDecidedEvent[] = []\n let planEvent: SearchPlannedEvent | null = null\n let completion: SearchCompletedEvent | null = null\n let expectedPrevious: SearchLedgerHash | null = null\n let previousOccurredAt = Number.NEGATIVE_INFINITY\n\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n if (entry.campaignId !== campaignId) {\n throw new SearchLedgerIntegrityError(\n `entry ${index} belongs to campaign ${entry.campaignId}, expected ${campaignId}`,\n )\n }\n if (entry.sequence !== index) {\n throw new SearchLedgerIntegrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw new SearchLedgerIntegrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw new SearchLedgerIntegrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n\n const event = entry.event\n if (eventIds.has(event.eventId)) {\n throw new SearchLedgerIntegrityError(`duplicate eventId ${event.eventId} in durable ledger`)\n }\n eventIds.add(event.eventId)\n if (completion) {\n throw new SearchLedgerIntegrityError(\n `event ${event.eventId} appears after terminal event ${completion.eventId}`,\n )\n }\n const occurredAt = Date.parse(event.occurredAt)\n if (occurredAt < previousOccurredAt) {\n throw new SearchLedgerIntegrityError(\n `event ${event.eventId} occurred before the preceding durable event`,\n )\n }\n previousOccurredAt = occurredAt\n assertUnique(event.artifacts.map(artifactKey), 'artifact receipt', event.eventId)\n\n if (event.kind === 'search-planned') {\n if (index !== 0 || planEvent) {\n throw new SearchLedgerIntegrityError('search plan must be the first and only plan event')\n }\n assertUnique(\n event.plan.candidateSlots.map((slot) => slot.slotId),\n 'candidate slot',\n event.eventId,\n )\n assertUnique(\n event.plan.tasks.map((task) => task.taskId),\n 'planned taskId',\n event.eventId,\n )\n assertUnique(\n event.plan.operations.map((operation) => operation.operationId),\n 'planned operationId',\n event.eventId,\n )\n for (const slot of event.plan.candidateSlots) {\n const generationOperation = event.plan.operations.find(\n (operation) => operation.operationId === slot.generationOperationId,\n )\n if (!generationOperation || generationOperation.kind !== 'candidate-generation') {\n throw new SearchLedgerIntegrityError(\n `candidate slot ${slot.slotId} references unplanned candidate-generation operation ${slot.generationOperationId}`,\n )\n }\n }\n planEvent = event\n continue\n }\n\n if (!planEvent) {\n throw new SearchLedgerIntegrityError(\n `event ${event.eventId} appears before the required search plan`,\n )\n }\n\n if (event.kind === 'candidate-registered') {\n if (candidates.has(event.candidateId)) {\n throw new SearchLedgerIntegrityError(`candidate ${event.candidateId} was registered twice`)\n }\n const plannedSlot = planEvent.plan.candidateSlots.find((slot) => slot.slotId === event.slotId)\n if (!plannedSlot) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} binds unknown slot ${event.slotId}`,\n )\n }\n if (candidateBySlot.has(event.slotId)) {\n throw new SearchLedgerIntegrityError(`candidate slot ${event.slotId} was bound twice`)\n }\n if (closedSlots.has(event.slotId)) {\n throw new SearchLedgerIntegrityError(`candidate slot ${event.slotId} was already closed`)\n }\n if (event.generationOperationId !== plannedSlot.generationOperationId) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} generation operation ${event.generationOperationId} does not match slot ${event.slotId} plan ${plannedSlot.generationOperationId}`,\n )\n }\n const generationOperation = operationsById.get(event.generationOperationId)\n if (!generationOperation) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} precedes generation operation ${event.generationOperationId}`,\n )\n }\n if (generationOperation.outcome.status === 'failed') {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} cannot bind failed generation operation ${event.generationOperationId}`,\n )\n }\n const previousCandidate = lineageNodes.get(event.lineage.lineageNodeId)\n if (previousCandidate) {\n throw new SearchLedgerIntegrityError(\n `lineage node ${event.lineage.lineageNodeId} is already bound to ${previousCandidate}`,\n )\n }\n assertUnique(event.lineage.parentCandidateIds, 'parentCandidateId', event.eventId)\n const parents = event.lineage.parentCandidateIds.map((id) => {\n const parent = candidates.get(id)\n if (!parent) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} references unknown parent ${id}`,\n )\n }\n return parent\n })\n const expectedGeneration =\n parents.length === 0\n ? 0\n : Math.max(...parents.map((parent) => parent.registered.lineage.generation)) + 1\n if (event.lineage.generation !== expectedGeneration) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} generation ${event.lineage.generation} does not follow its parents (expected ${expectedGeneration})`,\n )\n }\n assertUnique(\n event.surfaces.map((surface) => surface.surfaceId),\n 'surfaceId',\n event.eventId,\n )\n candidates.set(event.candidateId, { registered: event, attempts: [], decision: null })\n candidateBySlot.set(event.slotId, event.candidateId)\n lineageNodes.set(event.lineage.lineageNodeId, event.candidateId)\n candidateEvents.push(event)\n continue\n }\n\n if (event.kind === 'task-attempted') {\n const candidate = candidates.get(event.candidateId)\n if (!candidate) {\n throw new SearchLedgerIntegrityError(\n `attempt ${event.eventId} references unknown candidate ${event.candidateId}`,\n )\n }\n if (candidate.decision) {\n throw new SearchLedgerIntegrityError(\n `attempt ${event.eventId} appears after candidate ${event.candidateId} was decided`,\n )\n }\n const plannedTask = planEvent.plan.tasks.find((task) => task.taskId === event.task.taskId)\n if (!plannedTask) {\n throw new SearchLedgerIntegrityError(\n `attempt ${event.eventId} references unplanned task ${event.task.taskId}`,\n )\n }\n if (\n canonicalString(plannedTask.source) !== canonicalString(event.task.source) ||\n canonicalString(plannedTask.benchmark) !== canonicalString(event.identity.benchmark)\n ) {\n throw new SearchLedgerIntegrityError(\n `task ${event.task.taskId} does not match its planned source identity`,\n )\n }\n if (event.attemptIndex >= plannedTask.maxAttempts) {\n throw new SearchLedgerIntegrityError(\n `task ${event.task.taskId} attempt ${event.attemptIndex} exceeds planned maxAttempts ${plannedTask.maxAttempts}`,\n )\n }\n if (runIds.has(event.runId)) {\n throw new SearchLedgerIntegrityError(`runId ${event.runId} was recorded twice`)\n }\n runIds.add(event.runId)\n const attemptKey = canonicalString([event.candidateId, event.task.taskId, event.attemptIndex])\n if (attemptKeys.has(attemptKey)) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} task ${event.task.taskId} attempt ${event.attemptIndex} was recorded twice`,\n )\n }\n const expectedAttemptIndex = candidate.attempts.filter(\n (attempt) => attempt.task.taskId === event.task.taskId,\n ).length\n if (event.attemptIndex !== expectedAttemptIndex) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} task ${event.task.taskId} attempt index ${event.attemptIndex} is not contiguous (expected ${expectedAttemptIndex})`,\n )\n }\n const previousAttempt = candidate.attempts.find(\n (attempt) => attempt.task.taskId === event.task.taskId,\n )\n if (\n previousAttempt?.outcome.status !== undefined &&\n previousAttempt.outcome.status !== 'errored'\n ) {\n throw new SearchLedgerIntegrityError(\n `task ${event.task.taskId} was retried after a measured outcome`,\n )\n }\n if (\n previousAttempt &&\n canonicalString({ task: previousAttempt.task, identity: previousAttempt.identity }) !==\n canonicalString({ task: event.task, identity: event.identity })\n ) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} task ${event.task.taskId} changed immutable execution identity between attempts`,\n )\n }\n attemptKeys.add(attemptKey)\n\n const declared = candidate.registered.surfaces.map((surface) => surface.surfaceId).sort()\n const observed = event.surfaceEvidence.map((surface) => surface.surfaceId).sort()\n assertUnique(observed, 'surface evidence', event.eventId)\n for (const evidence of event.surfaceEvidence) {\n assertUnique(evidence.evidence.map(artifactKey), 'surface evidence receipt', event.eventId)\n }\n if (canonicalString(declared) !== canonicalString(observed)) {\n throw new SearchLedgerIntegrityError(\n `attempt ${event.eventId} surface evidence does not exactly cover candidate ${event.candidateId}`,\n )\n }\n candidate.attempts.push(event)\n attempts.push(event)\n continue\n }\n\n if (event.kind === 'search-operation-recorded') {\n const plannedOperation = planEvent.plan.operations.find(\n (operation) => operation.operationId === event.operationId,\n )\n if (!plannedOperation) {\n throw new SearchLedgerIntegrityError(\n `operation ${event.operationId} was not declared in the search plan`,\n )\n }\n if (plannedOperation.kind !== event.operationKind) {\n throw new SearchLedgerIntegrityError(\n `operation ${event.operationId} kind ${event.operationKind} does not match planned ${plannedOperation.kind}`,\n )\n }\n if (operationsById.has(event.operationId)) {\n throw new SearchLedgerIntegrityError(`operation ${event.operationId} was recorded twice`)\n }\n operationsById.set(event.operationId, event)\n operationEvents.push(event)\n continue\n }\n\n if (event.kind === 'candidate-slot-closed') {\n const plannedSlot = planEvent.plan.candidateSlots.find((slot) => slot.slotId === event.slotId)\n if (!plannedSlot) {\n throw new SearchLedgerIntegrityError(\n `candidate slot closure ${event.eventId} references unknown slot ${event.slotId}`,\n )\n }\n if (event.generationOperationId !== plannedSlot.generationOperationId) {\n throw new SearchLedgerIntegrityError(\n `candidate slot closure ${event.eventId} generation operation ${event.generationOperationId} does not match slot ${event.slotId} plan ${plannedSlot.generationOperationId}`,\n )\n }\n if (candidateBySlot.has(event.slotId)) {\n throw new SearchLedgerIntegrityError(\n `candidate slot ${event.slotId} was already bound to a candidate`,\n )\n }\n if (closedSlots.has(event.slotId)) {\n throw new SearchLedgerIntegrityError(`candidate slot ${event.slotId} was closed twice`)\n }\n const operation = operationsById.get(event.generationOperationId)\n if (!operation) {\n throw new SearchLedgerIntegrityError(\n `candidate slot closure ${event.eventId} precedes operation ${event.generationOperationId}`,\n )\n }\n if (operation.outcome.status === 'completed') {\n throw new SearchLedgerIntegrityError(\n `candidate slot ${event.slotId} cannot close from completed operation ${event.generationOperationId}`,\n )\n }\n closedSlots.set(event.slotId, event)\n closedSlotEvents.push(event)\n continue\n }\n\n if (event.kind === 'candidate-decided') {\n const candidate = candidates.get(event.candidateId)\n if (!candidate) {\n throw new SearchLedgerIntegrityError(\n `decision ${event.eventId} references unknown candidate ${event.candidateId}`,\n )\n }\n if (candidate.decision) {\n throw new SearchLedgerIntegrityError(`candidate ${event.candidateId} was decided twice`)\n }\n if (event.decision.status === 'selected') {\n if (!candidate.attempts.some((attempt) => attempt.outcome.status !== 'errored')) {\n throw new SearchLedgerIntegrityError(\n `candidate ${event.candidateId} cannot be selected without a measured task outcome`,\n )\n }\n if (decisions.some((decision) => decision.decision.status === 'selected')) {\n throw new SearchLedgerIntegrityError('more than one candidate was selected')\n }\n }\n candidate.decision = event\n decisions.push(event)\n continue\n }\n\n const missingCandidateSlots = planEvent.plan.candidateSlots\n .filter((slot) => !candidateBySlot.has(slot.slotId) && !closedSlots.has(slot.slotId))\n .map((slot) => slot.slotId)\n if (missingCandidateSlots.length > 0) {\n throw new SearchLedgerIntegrityError(\n `search completed with missing candidate slots: ${missingCandidateSlots.join(', ')}`,\n )\n }\n const missingTaskOutcomes = plannedTaskOutcomeKeys(planEvent, candidates)\n if (missingTaskOutcomes.length > 0) {\n throw new SearchLedgerIntegrityError(\n `search completed with missing task outcomes: ${missingTaskOutcomes.join(', ')}`,\n )\n }\n const missingOperations = planEvent.plan.operations\n .filter((operation) => !operationsById.has(operation.operationId))\n .map((operation) => operation.operationId)\n if (missingOperations.length > 0) {\n throw new SearchLedgerIntegrityError(\n `search completed with missing search operations: ${missingOperations.join(', ')}`,\n )\n }\n for (const operation of planEvent.plan.operations) {\n if (operation.kind !== 'candidate-generation') continue\n const generationOutcome = operationsById.get(operation.operationId)!.outcome.status\n const slots = planEvent.plan.candidateSlots.filter(\n (slot) => slot.generationOperationId === operation.operationId,\n )\n if (slots.length === 0) continue\n const registeredCount = slots.filter((slot) => candidateBySlot.has(slot.slotId)).length\n const closedCount = slots.filter((slot) => closedSlots.has(slot.slotId)).length\n if (generationOutcome === 'completed' && closedCount > 0) {\n throw new SearchLedgerIntegrityError(\n `completed generation operation ${operation.operationId} contains ${closedCount} closed slot(s)`,\n )\n }\n if (generationOutcome === 'failed' && registeredCount > 0) {\n throw new SearchLedgerIntegrityError(\n `failed generation operation ${operation.operationId} contains ${registeredCount} registered candidate(s)`,\n )\n }\n if (generationOutcome === 'partial' && (registeredCount === 0 || closedCount === 0)) {\n throw new SearchLedgerIntegrityError(\n `partial generation operation ${operation.operationId} must contain both a registered candidate and a closed slot`,\n )\n }\n }\n const pending = [...candidates.values()].filter((candidate) => candidate.decision === null)\n if (pending.length > 0) {\n throw new SearchLedgerIntegrityError(\n `search completed with ${pending.length} candidate decision(s) missing`,\n )\n }\n const selected = decisions.filter((decision) => decision.decision.status === 'selected')\n if (event.result.status === 'selected') {\n if (selected.length !== 1 || selected[0]!.candidateId !== event.result.candidateId) {\n throw new SearchLedgerIntegrityError(\n `search completion winner ${event.result.candidateId} does not match candidate decisions`,\n )\n }\n } else if (selected.length !== 0) {\n throw new SearchLedgerIntegrityError('all-rejected completion contains a selected candidate')\n }\n completion = event\n }\n\n const selectedDecisions = decisions.filter((decision) => decision.decision.status === 'selected')\n const rejectedDecisions = decisions.filter((decision) => decision.decision.status === 'rejected')\n const outcomeCounts = { passed: 0, failed: 0, errored: 0 }\n const operationOutcomeCounts = { completed: 0, partial: 0, failed: 0 }\n let inputTokens = 0\n let outputTokens = 0\n let cachedTokens = 0\n let costUsd = 0\n const unknownTokenEventIds: string[] = []\n const unknownCostEventIds: string[] = []\n for (const attempt of attempts) {\n outcomeCounts[attempt.outcome.status] += 1\n }\n for (const operation of operationEvents) {\n operationOutcomeCounts[operation.outcome.status] += 1\n }\n for (const costedEvent of [...attempts, ...operationEvents]) {\n if (costedEvent.accounting.tokens.status === 'known') {\n inputTokens += costedEvent.accounting.tokens.inputTokens\n outputTokens += costedEvent.accounting.tokens.outputTokens\n cachedTokens += costedEvent.accounting.tokens.cachedTokens\n } else {\n unknownTokenEventIds.push(costedEvent.eventId)\n }\n if (costedEvent.accounting.cost.status === 'known') {\n costUsd += costedEvent.accounting.cost.usd\n } else {\n costUsd += costedEvent.accounting.cost.knownLowerBoundUsd\n unknownCostEventIds.push(costedEvent.eventId)\n }\n }\n const accounting: SearchAccountingAudit =\n unknownTokenEventIds.length === 0 && unknownCostEventIds.length === 0\n ? {\n status: 'known',\n inputTokens,\n outputTokens,\n cachedTokens,\n costUsd,\n }\n : {\n status: 'partial',\n knownInputTokens: inputTokens,\n knownOutputTokens: outputTokens,\n knownCachedTokens: cachedTokens,\n knownCostUsd: costUsd,\n unknownTokenEventIds,\n unknownCostEventIds,\n }\n\n const selectedCandidateId =\n completion?.result.status === 'selected' ? completion.result.candidateId : null\n const status: SearchLedgerAudit['status'] =\n completion?.result.status === 'selected'\n ? 'selected'\n : completion?.result.status === 'all-rejected'\n ? 'all-rejected'\n : 'in-progress'\n const missingCandidateSlots =\n planEvent?.plan.candidateSlots\n .filter((slot) => !candidateBySlot.has(slot.slotId) && !closedSlots.has(slot.slotId))\n .map((slot) => slot.slotId) ?? []\n const missingTaskOutcomes = planEvent ? plannedTaskOutcomeKeys(planEvent, candidates) : []\n const missingOperations =\n planEvent?.plan.operations\n .filter((operation) => !operationsById.has(operation.operationId))\n .map((operation) => operation.operationId) ?? []\n return {\n entries: [...entries],\n plan: planEvent,\n candidates: candidateEvents,\n closedCandidateSlots: closedSlotEvents,\n attempts,\n operations: operationEvents,\n decisions,\n completion,\n audit: {\n campaignId,\n eventCount: entries.length,\n candidateCount: candidates.size,\n closedCandidateSlotCount: closedSlots.size,\n attemptCount: attempts.length,\n operationCount: operationEvents.length,\n outcomes: outcomeCounts,\n operationOutcomes: operationOutcomeCounts,\n decisions: {\n selected: selectedDecisions.length,\n rejected: rejectedDecisions.length,\n pending: candidates.size - decisions.length,\n },\n expected: {\n candidateSlots: planEvent?.plan.candidateSlots.length ?? 0,\n taskOutcomes: candidates.size * (planEvent?.plan.tasks.length ?? 0),\n operations: planEvent?.plan.operations.length ?? 0,\n missingCandidateSlots,\n missingTaskOutcomes,\n missingOperations,\n },\n status,\n selectedCandidateId,\n accounting,\n headHash: entries.at(-1)?.entryHash ?? null,\n },\n }\n}\n\nfunction plannedTaskOutcomeKeys(\n planEvent: SearchPlannedEvent,\n candidates: Map<string, CandidateState>,\n): string[] {\n const missing: string[] = []\n const registeredCandidates = [...candidates.values()].sort((a, b) =>\n compareStrings(a.registered.slotId, b.registered.slotId),\n )\n for (const candidate of registeredCandidates) {\n const slotId = candidate.registered.slotId\n for (const task of planEvent.plan.tasks) {\n const measured = candidate.attempts.some(\n (attempt) => attempt.task.taskId === task.taskId && attempt.outcome.status !== 'errored',\n )\n if (!measured) missing.push(`${slotId}/${task.taskId}`)\n }\n }\n return missing\n}\n\nfunction normalizeEvent(event: SearchLedgerEvent): SearchLedgerEvent {\n const artifacts = sortArtifacts(event.artifacts)\n if (event.kind === 'search-planned') {\n return {\n ...event,\n artifacts,\n plan: {\n candidateSlots: [...event.plan.candidateSlots].sort((a, b) =>\n compareStrings(a.slotId, b.slotId),\n ),\n tasks: [...event.plan.tasks].sort((a, b) => compareStrings(a.taskId, b.taskId)),\n operations: [...event.plan.operations].sort((a, b) =>\n compareStrings(a.operationId, b.operationId),\n ),\n },\n }\n }\n if (event.kind === 'candidate-registered') {\n return {\n ...event,\n artifacts,\n lineage: {\n ...event.lineage,\n parentCandidateIds: sortedStrings(event.lineage.parentCandidateIds),\n },\n surfaces: [...event.surfaces]\n .map((surface) => ({ ...surface, artifact: { ...surface.artifact } }))\n .sort((a, b) => compareStrings(a.surfaceId, b.surfaceId)),\n }\n }\n if (event.kind === 'task-attempted') {\n return {\n ...event,\n artifacts,\n surfaceEvidence: [...event.surfaceEvidence]\n .map((evidence) => ({ ...evidence, evidence: sortArtifacts(evidence.evidence) }))\n .sort((a, b) => compareStrings(a.surfaceId, b.surfaceId)),\n }\n }\n return { ...event, artifacts }\n}\n\nfunction sortArtifacts(artifacts: SearchArtifactRef[]): SearchArtifactRef[] {\n return [...artifacts]\n .map((artifact) => ({ ...artifact }))\n .sort((a, b) => compareStrings(artifactKey(a), artifactKey(b)))\n}\n\nfunction artifactKey(artifact: SearchArtifactRef): string {\n return canonicalString(artifact)\n}\n\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nfunction sortedStrings(values: string[]): string[] {\n return [...values].sort()\n}\n\nfunction assertUnique(values: string[], label: string, eventId: string): void {\n if (new Set(values).size !== values.length) {\n throw new SearchLedgerIntegrityError(`event ${eventId} contains duplicate ${label} values`)\n }\n}\n\nfunction canonicalString(value: unknown): string {\n return JSON.stringify(canonicalize(value))\n}\n\nfunction hashCanonical(value: unknown): SearchLedgerHash {\n return `sha256:${createHash('sha256').update(canonicalString(value)).digest('hex')}`\n}\n\nfunction formatZodError(error: z.ZodError): string {\n return error.issues\n .map((issue) => `${issue.path.length > 0 ? issue.path.join('.') : '<root>'}: ${issue.message}`)\n .join('; ')\n}\n","/**\n * Single-run lock for evaluations that share one mutable environment.\n *\n * Two concurrent runs against a shared stateful gym silently corrupt each\n * other: each resets/mutates environment state mid-cell of the other, and\n * every score from both becomes garbage that LOOKS like worker variance\n * (agent-lab R357 burned hours on flip-flopping scores before tracing them\n * to exactly this). The fix is a pid lockfile: refuse to start while a live\n * holder exists, reclaim stale locks whose pid is gone, release only if the\n * lock is still ours.\n *\n * `alsoCheck` exists because independent runners can guard the same shared\n * resource with differently named lockfiles; a runner must respect all of\n * them even though it writes only its own.\n */\n\nimport { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\n\nexport interface SingleRunLockOptions {\n /** Lockfile this runner writes (and checks). */\n readonly lockPath: string\n /** Other runners' lockfiles guarding the same resource; checked, never written. */\n readonly alsoCheck?: readonly string[]\n /** Install a process 'exit' hook that releases the lock. Default true. */\n readonly releaseOnExit?: boolean\n /** Owner pid recorded in the lockfile. Default process.pid. */\n readonly pid?: number\n}\n\nexport interface SingleRunLock {\n /** Remove the lockfile if this process still owns it. Idempotent. */\n release(): void\n}\n\nfunction liveHolder(path: string): number | null {\n if (!existsSync(path)) return null\n const holder = Number(readFileSync(path, 'utf8').trim())\n if (!Number.isFinite(holder) || holder <= 0) return null\n try {\n process.kill(holder, 0)\n return holder\n } catch {\n return null // stale: holder pid is gone; safe to reclaim\n }\n}\n\n/**\n * Acquire the lock or throw naming the live holder. A stale lock (holder pid\n * no longer running) is reclaimed silently.\n */\nexport function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock {\n const pid = opts.pid ?? process.pid\n for (const path of [opts.lockPath, ...(opts.alsoCheck ?? [])]) {\n const holder = liveHolder(path)\n if (holder !== null && holder !== pid) {\n throw new Error(\n `single-run lock held by live pid ${holder} (${path}); refusing a concurrent run on the shared resource`,\n )\n }\n }\n writeFileSync(opts.lockPath, String(pid))\n const release = (): void => {\n try {\n if (existsSync(opts.lockPath) && readFileSync(opts.lockPath, 'utf8').trim() === String(pid)) {\n unlinkSync(opts.lockPath)\n }\n } catch {\n // release is best-effort; a leftover stale lock is reclaimed on next acquire\n }\n }\n if (opts.releaseOnExit ?? true) process.on('exit', release)\n return { release }\n}\n","/**\n * Transient-transport-failure classification for dispatch retry policies.\n *\n * When an eval cell dies, the harness must decide: retry (the infrastructure\n * hiccuped - a 502 storm, an admission-queue rejection, a dropped stream) or\n * score it (the agent genuinely failed). Getting this wrong corrupts results\n * in both directions: scoring transport hiccups as failures buries real\n * effects under noise (agent-lab R353 found 5/30 identical repeats were 502s\n * scored as task failures), while retrying genuine failures silently drops\n * the hard cells and inflates every arm.\n *\n * Full-duration timeouts are the deliberate knob: on saturated shared\n * infrastructure a timeout usually means the request never got a slot\n * (retry it), but on unthrottled infrastructure it means the agent flailed\n * on the task until the clock ran out (a real score-0). Both readings were\n * needed in practice within one week, so the classifier takes it as an\n * option instead of hardcoding either.\n */\n\nexport interface TransientFailureOptions {\n /**\n * Treat full-duration timeouts (\"timeout after 180000ms\") as transient.\n * Enable on saturated shared infrastructure where queue starvation eats\n * the clock; leave off when the agent had the resources and simply failed.\n * Default false.\n */\n readonly retryFullDurationTimeouts?: boolean\n /** Additional caller-specific transient patterns. */\n readonly extraPatterns?: readonly RegExp[]\n}\n\nconst BASE_TRANSIENT =\n /\\b50[234]\\b|no stream output|produced no stream|admission timed out|admission_rejected|queue_timeout|fetch failed|ECONNRESET|This operation was aborted/i\n\nconst TIMEOUT_PATTERN = /timeout after \\d+ ?ms|cli-bridge timeout/i\n\n/**\n * True when the error text describes an infrastructure hiccup that should be\n * retried rather than scored. Empty/undefined input is not transient.\n */\nexport function isTransientTransportFailure(\n message: string | null | undefined,\n opts: TransientFailureOptions = {},\n): boolean {\n if (!message) return false\n if (BASE_TRANSIENT.test(message)) return true\n if ((opts.retryFullDurationTimeouts ?? false) && TIMEOUT_PATTERN.test(message)) return true\n for (const p of opts.extraPatterns ?? []) if (p.test(message)) return true\n return false\n}\n","/**\n * VCS-pluggable worktree adapter. One improvement = one worktree, PR-like\n * (multiple commits allowed). A code-tier proposer's `propose()` creates a\n * worktree, an agent commits the change into it, and `finalize()` returns a\n * content-addressed `CodeSurface` the measurement verifies before running.\n * On promotion the worktree becomes the PR branch.\n *\n * The interface is VCS-agnostic so a future `jj` ([jj-vcs](https://github.com/jj-vcs/jj))\n * adapter can slot in without touching proposer code. Only the git adapter\n * ships today. See `docs/design/loop-taxonomy.md`.\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n constants as fsConstants,\n fstatSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readlinkSync,\n readSync,\n realpathSync,\n rmSync,\n} from 'node:fs'\nimport { devNull, tmpdir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { assertCodeSurfaceIdentity, surfaceContentHash } from '../surface-identity'\nimport type { CodeSurface } from '../types'\n\nconst MAX_GIT_OUTPUT_BYTES = 256 * 1024 * 1024\nconst FILE_HASH_CHUNK_BYTES = 1024 * 1024\n\ntype GitOutput = string | Uint8Array\ntype GitEnvironment = Readonly<Record<string, string>>\ntype GitRunner = (args: string[], cwd: string, env?: GitEnvironment) => GitOutput\n\nconst GIT_REPOSITORY_ENV = new Set([\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_COMMON_DIR',\n 'GIT_DIR',\n 'GIT_INDEX_FILE',\n 'GIT_NAMESPACE',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_PREFIX',\n 'GIT_QUARANTINE_PATH',\n 'GIT_WORK_TREE',\n])\n\nexport interface Worktree {\n /** Absolute path to the checked-out worktree directory. */\n readonly path: string\n /** The branch the worktree is on (becomes the PR branch on promotion). */\n readonly branch: string\n /** The ref the worktree was forked from. */\n readonly baseRef: string\n /** Exact commit `baseRef` resolved to before the worktree was created. */\n readonly baseCommit: string\n /** Exact tree object for `baseCommit`. */\n readonly baseTree: string\n}\n\nexport interface WorktreeAdapter {\n /** Create an isolated worktree on a fresh branch off `baseRef`. */\n create(opts: { baseRef: string; label: string }): Promise<Worktree>\n /** Commit pending changes, freeze the exact Git objects + binary patch, and\n * verify the worktree still matches that identity. */\n finalize(worktree: Worktree, summary: string): Promise<CodeSurface>\n /** Idempotently remove the worktree and branch. Safe to retry after partial cleanup. */\n discard(worktree: Worktree): Promise<void>\n}\n\n/** Typed failure from a `WorktreeAdapter` operation (create/finalize/discard) — wraps the underlying git error as `cause`. */\nexport class WorktreeAdapterError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message)\n this.name = 'WorktreeAdapterError'\n }\n}\n\nexport interface GitWorktreeAdapterOptions {\n /** Repo root the worktrees fork from. */\n repoRoot: string\n /** Directory worktrees are created under. Default: `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Branch-name prefix. Default: `improve`. */\n branchPrefix?: string\n /** Test seam — defaults to a real `git` runner. The return value must contain\n * stdout verbatim, and runners that execute Git must forward the optional\n * environment overrides used to isolate patch generation. */\n git?: GitRunner\n}\n\nfunction defaultGit(args: string[], cwd: string, overrides?: GitEnvironment): Uint8Array {\n try {\n const env = { ...process.env }\n for (const key of Object.keys(env)) {\n if (\n GIT_REPOSITORY_ENV.has(key) ||\n key === 'GIT_CONFIG' ||\n key.startsWith('GIT_CONFIG_') ||\n key.startsWith('GIT_ATTR_') ||\n key === 'GIT_DIFF_OPTS' ||\n key === 'GIT_EXTERNAL_DIFF'\n ) {\n delete env[key]\n }\n }\n Object.assign(env, overrides)\n env.GIT_NO_REPLACE_OBJECTS = '1'\n env.LC_ALL = 'C'\n env.LANG = 'C'\n return execFileSync('git', args, { cwd, env, maxBuffer: MAX_GIT_OUTPUT_BYTES })\n } catch (err) {\n const stderr =\n err && typeof err === 'object' && 'stderr' in err\n ? String((err as { stderr: unknown }).stderr)\n : ''\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${stderr || String(err)}`, err)\n }\n}\n\nfunction gitBytes(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): Buffer {\n try {\n const output = git(args, cwd, env)\n return typeof output === 'string' ? Buffer.from(output, 'utf8') : Buffer.from(output)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`git ${args.join(' ')} failed: ${String(err)}`, err)\n }\n}\n\nfunction gitText(git: GitRunner, args: string[], cwd: string, env?: GitEnvironment): string {\n return gitBytes(git, args, cwd, env).toString('utf8').trim()\n}\n\nfunction hasRegisteredWorktree(git: GitRunner, repoRoot: string, path: string): boolean {\n const expected = Buffer.from(`worktree ${resolve(path)}`, 'utf8')\n const records = gitBytes(git, ['worktree', 'list', '--porcelain', '-z'], repoRoot)\n let start = 0\n while (start < records.length) {\n const end = records.indexOf(0, start)\n if (end < 0) {\n throw new WorktreeAdapterError('Git worktree list output was not NUL-terminated')\n }\n if (records.subarray(start, end).equals(expected)) return true\n start = end + 1\n }\n return false\n}\n\nfunction hasLocalBranch(git: GitRunner, repoRoot: string, branch: string): boolean {\n const ref = `refs/heads/${branch}`\n return gitText(git, ['for-each-ref', '--format=%(refname)', '--', ref], repoRoot)\n .split('\\n')\n .some((candidate) => candidate === ref)\n}\n\nfunction reconcileAbsent(exists: () => boolean, remove: () => void): unknown | undefined {\n try {\n if (!exists()) return undefined\n } catch (err) {\n return err\n }\n\n try {\n remove()\n return undefined\n } catch (removeError) {\n try {\n // Git may complete the mutation before the caller observes a failure, or\n // another cleanup may win the race. The desired end state is what matters.\n if (!exists()) return undefined\n } catch (recheckError) {\n return new AggregateError(\n [removeError, recheckError],\n 'Removal failed and the resulting resource state could not be checked',\n )\n }\n return removeError\n }\n}\n\nfunction sha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nconst PATCH_ARGS = [\n // Git binary patches embed a zlib stream. Pin no-compression at command\n // scope so repository/global config and compressor heuristics cannot change\n // the candidate identity for the same base and final tree.\n '-c',\n 'core.compression=0',\n '-c',\n `core.attributesFile=${devNull}`,\n '-c',\n 'core.quotePath=true',\n '-c',\n 'diff.suppressBlankEmpty=false',\n 'diff',\n '--unified=3',\n '--inter-hunk-context=0',\n `-O${devNull}`,\n '--binary',\n '--full-index',\n '--no-color',\n '--no-ext-diff',\n '--no-textconv',\n '--no-renames',\n '--diff-algorithm=myers',\n '--no-indent-heuristic',\n '--src-prefix=a/',\n '--dst-prefix=b/',\n] as const\n\nconst CANONICAL_GIT_ENV: GitEnvironment = {\n GIT_ATTR_GLOBAL: devNull,\n GIT_ATTR_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: devNull,\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_SYSTEM: devNull,\n}\n\n/** Render the transport patch from immutable objects through fresh Git metadata.\n * Source-repository config, info attributes, templates, and caller environment\n * therefore cannot alter bytes for the same two trees. */\nfunction patchBytes(\n git: GitRunner,\n cwd: string,\n baseCommit: string,\n candidateCommit: string,\n): Buffer {\n const scratch = mkdtempSync(join(tmpdir(), 'agent-eval-patch-'))\n const bareRepo = join(scratch, 'repo.git')\n const emptyTemplate = join(scratch, 'empty-template')\n mkdirSync(emptyTemplate)\n try {\n const objectFormat = gitObjectHashAlgorithm(candidateCommit)\n const sourceObjects = realpathSync(gitText(git, ['rev-parse', '--git-path', 'objects'], cwd))\n gitText(\n git,\n [\n 'init',\n '--bare',\n '--quiet',\n ...(objectFormat === 'sha256' ? ['--object-format=sha256'] : []),\n `--template=${emptyTemplate}`,\n bareRepo,\n ],\n scratch,\n CANONICAL_GIT_ENV,\n )\n return gitBytes(\n git,\n [`--git-dir=${bareRepo}`, ...PATCH_ARGS, baseCommit, candidateCommit, '--'],\n scratch,\n {\n ...CANONICAL_GIT_ENV,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: sourceObjects,\n },\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n}\n\nfunction resolveCommit(git: GitRunner, cwd: string, ref: string): string {\n return gitText(git, ['rev-parse', '--verify', `${ref}^{commit}`], cwd)\n}\n\nfunction unresolvedWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n if (isAbsolute(surface.worktreeRef)) return surface.worktreeRef\n if (worktreeDir) return join(worktreeDir, basename(surface.worktreeRef))\n return surface.worktreeRef\n}\n\ninterface GitTreeEntry {\n mode: string\n objectId: string\n path: string\n}\n\nfunction displayGitPath(path: string): string {\n return JSON.stringify(path)\n}\n\nfunction parseGitTreeEntries(bytes: Uint8Array): GitTreeEntry[] {\n const input = Buffer.from(bytes)\n const entries: GitTreeEntry[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git tree output was not NUL-terminated')\n const record = input.subarray(start, end)\n start = end + 1\n if (record.length === 0) continue\n\n const tab = record.indexOf(0x09)\n if (tab < 0) throw new WorktreeAdapterError('Git tree entry did not contain a path')\n const metadata = record.subarray(0, tab).toString('ascii').split(' ')\n if (metadata.length !== 3) throw new WorktreeAdapterError('Git tree entry was malformed')\n const mode = metadata[0]\n const type = metadata[1]\n const objectId = metadata[2]\n if (!mode || !type || !objectId) {\n throw new WorktreeAdapterError('Git tree entry was malformed')\n }\n const pathBytes = record.subarray(tab + 1)\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n if (type !== 'blob' && type !== 'commit') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git object type ${type} at ${displayGitPath(path)}`,\n )\n }\n entries.push({ mode, objectId, path })\n }\n return entries\n}\n\nfunction parseGitPathList(bytes: Uint8Array): string[] {\n const input = Buffer.from(bytes)\n const paths: string[] = []\n let start = 0\n while (start < input.length) {\n const end = input.indexOf(0, start)\n if (end < 0) throw new WorktreeAdapterError('Git path output was not NUL-terminated')\n const pathBytes = input.subarray(start, end)\n start = end + 1\n if (pathBytes.length === 0) continue\n const path = pathBytes.toString('utf8')\n if (!Buffer.from(path, 'utf8').equals(pathBytes)) {\n throw new WorktreeAdapterError('CodeSurface paths must be valid UTF-8')\n }\n paths.push(path)\n }\n return paths\n}\n\nfunction isWithinRoot(root: string, candidate: string): boolean {\n const rel = relative(root, candidate)\n return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))\n}\n\nfunction assertSafeRelativePath(root: string, path: string): string {\n if (path.length === 0 || isAbsolute(path)) {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n const absolutePath = resolve(root, path)\n if (!isWithinRoot(root, absolutePath) || absolutePath === root) {\n throw new WorktreeAdapterError(`CodeSurface path escapes its worktree: ${displayGitPath(path)}`)\n }\n\n const segments = path.split(/[\\\\/]/u)\n let parent = root\n for (const segment of segments.slice(0, -1)) {\n if (segment.length === 0 || segment === '.' || segment === '..') {\n throw new WorktreeAdapterError(`CodeSurface contains unsafe path ${displayGitPath(path)}`)\n }\n parent = join(parent, segment)\n const stat = lstatSync(parent)\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface path traverses a non-directory or symbolic link: ${displayGitPath(path)}`,\n )\n }\n }\n return absolutePath\n}\n\nfunction gitObjectHashAlgorithm(objectId: string): 'sha1' | 'sha256' {\n if (/^[a-f0-9]{40}$/.test(objectId)) return 'sha1'\n if (/^[a-f0-9]{64}$/.test(objectId)) return 'sha256'\n throw new WorktreeAdapterError(`Unsupported Git object id: ${objectId}`)\n}\n\nfunction hashGitBlobBytes(bytes: Uint8Array, objectId: string): string {\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${bytes.byteLength}\\0`)\n hash.update(bytes)\n return hash.digest('hex')\n}\n\nfunction hashGitBlobFile(path: string, objectId: string): { hash: string; executable: boolean } {\n const before = lstatSync(path)\n if (!before.isFile() || before.isSymbolicLink()) {\n throw new WorktreeAdapterError(`CodeSurface expected a regular file at ${displayGitPath(path)}`)\n }\n\n const noFollow = process.platform === 'win32' ? 0 : fsConstants.O_NOFOLLOW\n const fd = openSync(path, fsConstants.O_RDONLY | noFollow)\n try {\n const opened = fstatSync(fd)\n if (\n !opened.isFile() ||\n opened.dev !== before.dev ||\n opened.ino !== before.ino ||\n opened.size !== before.size\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n\n const hash = createHash(gitObjectHashAlgorithm(objectId))\n hash.update(`blob ${opened.size}\\0`)\n const chunk = Buffer.allocUnsafe(FILE_HASH_CHUNK_BYTES)\n let total = 0\n while (true) {\n const count = readSync(fd, chunk, 0, chunk.length, null)\n if (count === 0) break\n total += count\n hash.update(chunk.subarray(0, count))\n }\n if (total !== opened.size) {\n throw new WorktreeAdapterError(\n `CodeSurface file changed while it was being verified: ${displayGitPath(path)}`,\n )\n }\n return { hash: hash.digest('hex'), executable: (opened.mode & 0o111) !== 0 }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction assertSymlinkTargetIsBound(\n root: string,\n linkPath: string,\n trackedPaths: ReadonlySet<string>,\n): void {\n const targetBytes = readlinkSync(linkPath, { encoding: 'buffer' })\n const target = targetBytes.toString('utf8')\n if (!Buffer.from(target, 'utf8').equals(targetBytes)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link has an unsafe target at ${displayGitPath(linkPath)}`,\n )\n }\n if (isAbsolute(target)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n const lexicalTarget = resolve(dirname(linkPath), target)\n if (!isWithinRoot(root, lexicalTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n let resolvedTarget: string\n try {\n resolvedTarget = realpathSync(linkPath)\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link target is missing or cyclic at ${displayGitPath(linkPath)}`,\n err,\n )\n }\n if (!isWithinRoot(root, resolvedTarget)) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link escapes its worktree at ${displayGitPath(linkPath)}`,\n )\n }\n\n const targetRelative = relative(root, resolvedTarget).split(sep).join('/')\n const targetIsTracked =\n trackedPaths.has(targetRelative) ||\n [...trackedPaths].some((trackedPath) => trackedPath.startsWith(`${targetRelative}/`))\n if (!targetIsTracked) {\n throw new WorktreeAdapterError(\n `CodeSurface symbolic link resolves to untracked content at ${displayGitPath(linkPath)}`,\n )\n }\n}\n\nfunction assertRawTreeMatchesWorktree(git: GitRunner, root: string, candidateCommit: string): void {\n const entries = parseGitTreeEntries(\n gitBytes(git, ['ls-tree', '-r', '-z', '--full-tree', candidateCommit], root),\n )\n const trackedPaths = new Set(entries.map((entry) => entry.path))\n\n for (const entry of entries) {\n const absolutePath = assertSafeRelativePath(root, entry.path)\n if (entry.mode === '160000' || entry.mode === '040000') {\n throw new WorktreeAdapterError(\n `CodeSurface contains a Git submodule whose executable bytes are not bound: ${displayGitPath(entry.path)}`,\n )\n }\n if (entry.mode === '120000') {\n const stat = lstatSync(absolutePath)\n if (!stat.isSymbolicLink()) {\n throw new WorktreeAdapterError(\n `CodeSurface expected a symbolic link at ${displayGitPath(entry.path)}`,\n )\n }\n const targetBytes = readlinkSync(absolutePath, { encoding: 'buffer' })\n const actualObjectId = hashGitBlobBytes(targetBytes, entry.objectId)\n if (actualObjectId !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw symbolic-link bytes differ from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n assertSymlinkTargetIsBound(root, absolutePath, trackedPaths)\n continue\n }\n if (entry.mode !== '100644' && entry.mode !== '100755') {\n throw new WorktreeAdapterError(\n `CodeSurface contains unsupported Git mode ${entry.mode} at ${displayGitPath(entry.path)}`,\n )\n }\n\n const actual = hashGitBlobFile(absolutePath, entry.objectId)\n if (actual.hash !== entry.objectId) {\n throw new WorktreeAdapterError(\n `CodeSurface raw tracked bytes differ from the candidate tree because the worktree changed after finalization at ${displayGitPath(entry.path)}`,\n )\n }\n if (process.platform !== 'win32' && actual.executable !== (entry.mode === '100755')) {\n throw new WorktreeAdapterError(\n `CodeSurface executable mode differs from the candidate tree at ${displayGitPath(entry.path)}`,\n )\n }\n }\n}\n\nexport interface CodeSurfaceVerification {\n /** Verified worktree path. */\n path: string\n /** Git's canonical root for the verified checkout. */\n repoRoot: string\n /** Recomputed full content identity. */\n contentHash: `sha256:${string}`\n /** Exact verified binary-patch bytes. Candidate-bundle builders encode this\n * directly instead of reproducing Git diff options. */\n patchBytes: Uint8Array\n}\n\nfunction verifyCodeSurfaceWithGit(\n surface: CodeSurface,\n path: string,\n git: GitRunner,\n): CodeSurfaceVerification {\n assertCodeSurfaceIdentity(surface)\n if (!existsSync(path)) {\n throw new WorktreeAdapterError(`CodeSurface worktree does not exist: ${path}`)\n }\n const lexicalRoot = resolve(path)\n const canonicalRoot = realpathSync(path)\n if (\n lstatSync(lexicalRoot).isSymbolicLink() ||\n (process.platform !== 'win32' && lexicalRoot !== canonicalRoot)\n ) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator must not contain a symbolic link: ${path}`,\n )\n }\n const repoRoot = gitText(git, ['rev-parse', '--show-toplevel'], path)\n const canonicalRepoRoot = realpathSync(repoRoot)\n if (canonicalRepoRoot !== canonicalRoot) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree locator is not the repository root: expected ${repoRoot}, got ${path}`,\n )\n }\n\n const indexFlags = gitText(git, ['ls-files', '-v'], path)\n .split('\\n')\n .filter((line) => line.length > 0 && (line.startsWith('S ') || /^[a-z]/.test(line)))\n if (indexFlags.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree uses hidden index entries that cannot be verified: ${path}\\n${indexFlags.join('\\n')}`,\n )\n }\n\n const extraPaths = [\n ...parseGitPathList(gitBytes(git, ['ls-files', '--others', '--exclude-standard', '-z'], path)),\n ...parseGitPathList(\n gitBytes(git, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z'], path),\n ),\n ]\n if (extraPaths.length > 0) {\n throw new WorktreeAdapterError(\n `CodeSurface worktree changed after finalization: ${path}\\n${extraPaths.join('\\n')}`,\n )\n }\n\n const candidateCommit = resolveCommit(git, path, 'HEAD')\n if (candidateCommit !== surface.candidateCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate commit mismatch: expected ${surface.candidateCommit}, got ${candidateCommit}`,\n )\n }\n\n const baseCommit = resolveCommit(git, path, surface.baseCommit)\n if (baseCommit !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface base commit mismatch: expected ${surface.baseCommit}, got ${baseCommit}`,\n )\n }\n\n const baseTree = gitText(git, ['rev-parse', '--verify', `${surface.baseCommit}^{tree}`], path)\n if (baseTree !== surface.baseTree) {\n throw new WorktreeAdapterError(\n `CodeSurface base tree mismatch: expected ${surface.baseTree}, got ${baseTree}`,\n )\n }\n\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${surface.candidateCommit}^{tree}`],\n path,\n )\n if (candidateTree !== surface.candidateTree) {\n throw new WorktreeAdapterError(\n `CodeSurface tree mismatch: expected ${surface.candidateTree}, got ${candidateTree}`,\n )\n }\n\n try {\n gitText(\n git,\n [\n 'diff-index',\n '--cached',\n '--quiet',\n '--no-ext-diff',\n '--no-textconv',\n surface.candidateCommit,\n '--',\n ],\n path,\n )\n } catch (err) {\n throw new WorktreeAdapterError(\n `CodeSurface index differs from finalized candidate: ${path}`,\n err,\n )\n }\n\n try {\n assertRawTreeMatchesWorktree(git, canonicalRepoRoot, surface.candidateCommit)\n } catch (err) {\n if (err instanceof WorktreeAdapterError) throw err\n throw new WorktreeAdapterError(`CodeSurface raw tree verification failed: ${path}`, err)\n }\n\n const mergeBase = gitText(git, ['merge-base', surface.baseCommit, surface.candidateCommit], path)\n if (mergeBase !== surface.baseCommit) {\n throw new WorktreeAdapterError(\n `CodeSurface candidate ${surface.candidateCommit} does not descend from base ${surface.baseCommit}`,\n )\n }\n\n const patch = patchBytes(git, path, surface.baseCommit, surface.candidateCommit)\n const actualPatchHash = sha256(patch)\n if (actualPatchHash !== surface.patch.sha256 || patch.byteLength !== surface.patch.byteLength) {\n throw new WorktreeAdapterError(\n `CodeSurface patch mismatch: expected ${surface.patch.sha256}/${surface.patch.byteLength} bytes, got ${actualPatchHash}/${patch.byteLength} bytes`,\n )\n }\n\n return {\n path,\n repoRoot: canonicalRepoRoot,\n contentHash: surfaceContentHash(surface),\n patchBytes: new Uint8Array(patch),\n }\n}\n\n/** Slugify a label into a branch-safe segment. */\nfunction slug(label: string): string {\n return (\n label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 48) || 'candidate'\n )\n}\n\n/**\n * Git-backed `WorktreeAdapter`: creates isolated worktrees on fresh branches, commits agent changes, and discards losers.\n */\nexport function gitWorktreeAdapter(opts: GitWorktreeAdapterOptions): WorktreeAdapter {\n const git = opts.git ?? defaultGit\n const worktreeDir = opts.worktreeDir ?? join(opts.repoRoot, '.worktrees')\n const branchPrefix = opts.branchPrefix ?? 'improve'\n\n return {\n async create({ baseRef, label }) {\n const id = `${slug(label)}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`\n const branch = `${branchPrefix}/${id}`\n const path = join(worktreeDir, id)\n const baseCommit = resolveCommit(git, opts.repoRoot, baseRef)\n const baseTree = gitText(\n git,\n ['rev-parse', '--verify', `${baseCommit}^{tree}`],\n opts.repoRoot,\n )\n gitText(git, ['worktree', 'add', '-b', branch, path, baseCommit], opts.repoRoot)\n return { path, branch, baseRef, baseCommit, baseTree }\n },\n\n async finalize(worktree, summary) {\n // Stage + commit any pending changes the agent left in the worktree.\n // A no-op commit is refused by git, so only commit when the tree is dirty.\n const status = gitText(\n git,\n ['status', '--porcelain=v1', '--untracked-files=all'],\n worktree.path,\n )\n if (status.length > 0) {\n gitText(git, ['add', '-A'], worktree.path)\n gitText(git, ['commit', '-m', summary], worktree.path)\n }\n const candidateCommit = resolveCommit(git, worktree.path, 'HEAD')\n const candidateTree = gitText(\n git,\n ['rev-parse', '--verify', `${candidateCommit}^{tree}`],\n worktree.path,\n )\n const patch = patchBytes(git, worktree.path, worktree.baseCommit, candidateCommit)\n const surface: CodeSurface = {\n kind: 'code',\n worktreeRef: worktree.path,\n baseRef: worktree.baseRef,\n baseCommit: worktree.baseCommit,\n baseTree: worktree.baseTree,\n candidateCommit,\n candidateTree,\n patch: {\n format: 'git-diff-binary',\n sha256: sha256(patch),\n byteLength: patch.byteLength,\n },\n summary,\n }\n verifyCodeSurfaceWithGit(surface, worktree.path, git)\n return surface\n },\n\n async discard(worktree) {\n // Reconcile both resources independently so a retry can finish cleanup\n // after either command succeeded alone. Force-remove because the worktree\n // may hold uncommitted experiment state we're discarding.\n const failures = [\n reconcileAbsent(\n () => hasRegisteredWorktree(git, opts.repoRoot, worktree.path),\n () => gitText(git, ['worktree', 'remove', '--force', '--', worktree.path], opts.repoRoot),\n ),\n reconcileAbsent(\n () => hasLocalBranch(git, opts.repoRoot, worktree.branch),\n () => gitText(git, ['branch', '-D', '--', worktree.branch], opts.repoRoot),\n ),\n ].filter((failure) => failure !== undefined)\n\n if (failures.length > 0) {\n const cause =\n failures.length === 1\n ? failures[0]\n : new AggregateError(failures, 'Multiple Git resources could not be removed')\n throw new WorktreeAdapterError(\n `Failed to discard worktree ${worktree.path} and branch ${worktree.branch}`,\n cause,\n )\n }\n },\n }\n}\n\n/** Verify a finalized code surface against its current checkout. This rejects\n * dirty/ignored files, moved refs, missing Git objects, raw byte/mode\n * mismatches, external symlinks, and submodules. */\nexport function verifyCodeSurface(\n surface: CodeSurface,\n worktreeDir?: string,\n): CodeSurfaceVerification {\n const path = unresolvedWorktreePath(surface, worktreeDir)\n return verifyCodeSurfaceWithGit(surface, path, defaultGit)\n}\n\n/** Resolve a code candidate for evaluation only after verifying its immutable\n * identity against the checkout at `worktreeRef`. */\nexport function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string {\n return verifyCodeSurface(surface, worktreeDir).path\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;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AAW;AAAA,QACf;AAAA,UACE,MAAM,sBAAsB,KAAK,KAAK,UAAU,SAAS,IAAI;AAAA,UAC7D,MAAM,QAAQ,KAAK,CAAC,YAAY,UAAU,WAAW,MAAM,SAAS,IAAI,GAAG,KAAK,QAAQ;AAAA,QAC1F;AAAA,QACA;AAAA,UACE,MAAM,eAAe,KAAK,KAAK,UAAU,SAAS,MAAM;AAAA,UACxD,MAAM,QAAQ,KAAK,CAAC,UAAU,MAAM,MAAM,SAAS,MAAM,GAAG,KAAK,QAAQ;AAAA,QAC3E;AAAA,MACF,EAAE,OAAO,CAAC,YAAY,YAAY,MAAS;AAE3C,UAAI,SAAS,SAAS,GAAG;AACvB,cAAM,QACJ,SAAS,WAAW,IAChB,SAAS,CAAC,IACV,IAAI,eAAe,UAAU,6CAA6C;AAChF,cAAM,IAAI;AAAA,UACR,8BAA8B,SAAS,IAAI,eAAe,SAAS,MAAM;AAAA,UACzE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,kBACd,SACA,aACyB;AACzB,QAAM,OAAO,uBAAuB,SAAS,WAAW;AACxD,SAAO,yBAAyB,SAAS,MAAM,UAAU;AAC3D;AAIO,SAAS,oBAAoB,SAAsB,aAA8B;AACtF,SAAO,kBAAkB,SAAS,WAAW,EAAE;AACjD;","names":["result","node","unobservedTaskIds","relative","createHash","createHash","createHash","contentHash","createHash","createHash","existsSync","readFileSync","join","existsSync","readFileSync","join","createHash","mean","truncate","createHash","join","createHash","createHash","createHash","mean","join","surfaceToText","surfaceToText","writeFileSync","join","join","writeFileSync","report","unique","surfaceHash","isAnalystFindingLike","BLOCK_START","BLOCK_END","DEFAULT_HEADING","surfaceToText","createHash","existsSync","readFileSync","resolve","z","z","resolve","entry","existsSync","readFileSync","assertUnique","missingCandidateSlots","missingTaskOutcomes","missingOperations","createHash","existsSync","readFileSync","writeFileSync","createHash","existsSync","mkdirSync","mkdtempSync","tmpdir","dirname","isAbsolute","join","relative","resolve","resolve","sha256","createHash","mkdtempSync","join","tmpdir","mkdirSync","isAbsolute","relative","dirname","existsSync","slug"]}
|