@tangle-network/agent-runtime 0.107.5 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +17 -4
  2. package/dist/{activation-Ck5ksFWg.js → activation-DRpnplEm.js} +3 -3
  3. package/dist/{activation-Ck5ksFWg.js.map → activation-DRpnplEm.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{candidate-execution-BUpR0mSD.js → candidate-execution-nYMa-bc-.js} +4 -4
  8. package/dist/{candidate-execution-BUpR0mSD.js.map → candidate-execution-nYMa-bc-.js.map} +1 -1
  9. package/dist/durable.d.ts +134 -0
  10. package/dist/durable.js +124 -0
  11. package/dist/durable.js.map +1 -0
  12. package/dist/{environment-provider-IUGU3epE.d.ts → environment-provider-D0NXc4Qz.d.ts} +73 -4
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/{improvement-cycle-Ulvvbg5p.js → improvement-cycle-CRnDDdX0.js} +49 -155
  15. package/dist/improvement-cycle-CRnDDdX0.js.map +1 -0
  16. package/dist/{index-B3wAV1SJ.d.ts → index-BZbJWqoZ.d.ts} +165 -25
  17. package/dist/{index-BbB5mmK0.d.ts → index-DQp3BPeC.d.ts} +11 -159
  18. package/dist/{index-D2g5qCwg.d.ts → index-cdkwHruJ.d.ts} +3 -3
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.js +14 -121
  21. package/dist/index.js.map +1 -1
  22. package/dist/intelligence.d.ts +15 -7
  23. package/dist/intelligence.js +4 -4
  24. package/dist/{knowledge-Dizh_AtL.js → knowledge-rdrpPIXs.js} +5 -5
  25. package/dist/{knowledge-Dizh_AtL.js.map → knowledge-rdrpPIXs.js.map} +1 -1
  26. package/dist/knowledge.d.ts +1 -1
  27. package/dist/knowledge.js +1 -1
  28. package/dist/{loop-runner-bin-Dw9_OZfu.d.ts → loop-runner-bin-9-JlGqN7.d.ts} +3 -3
  29. package/dist/{loop-runner-bin-BHELvjdO.js → loop-runner-bin-B1V-XS5A.js} +3 -3
  30. package/dist/{loop-runner-bin-BHELvjdO.js.map → loop-runner-bin-B1V-XS5A.js.map} +1 -1
  31. package/dist/loop-runner-bin.d.ts +1 -1
  32. package/dist/loop-runner-bin.js +1 -1
  33. package/dist/loops.d.ts +3 -3
  34. package/dist/loops.js +5 -5
  35. package/dist/mcp/bin.js +1 -1
  36. package/dist/mcp/index.d.ts +1 -1
  37. package/dist/mcp/index.js +4 -4
  38. package/dist/{openai-tools-CKLy1C7M.js → openai-tools-BjQq2TTL.js} +2 -2
  39. package/dist/{openai-tools-CKLy1C7M.js.map → openai-tools-BjQq2TTL.js.map} +1 -1
  40. package/dist/{prepare-_WTTffkz.js → prepare-Pr19X93k.js} +141 -6
  41. package/dist/prepare-Pr19X93k.js.map +1 -0
  42. package/dist/primeintellect/index.d.ts +1 -1
  43. package/dist/{protected-model-port-ZUwVuftA.js → protected-model-port-uthtDNqu.js} +2 -2
  44. package/dist/{protected-model-port-ZUwVuftA.js.map → protected-model-port-uthtDNqu.js.map} +1 -1
  45. package/dist/{redact-C5xOm8cu.d.ts → redact-BkasKlyd.d.ts} +17 -27
  46. package/dist/{runtime-M_GIzIwe.js → runtime-CDekUROm.js} +4 -4
  47. package/dist/{runtime-M_GIzIwe.js.map → runtime-CDekUROm.js.map} +1 -1
  48. package/dist/{structural-rollout-IXUEplky.js → structural-rollout-BC81Otmc.js} +10 -9
  49. package/dist/structural-rollout-BC81Otmc.js.map +1 -0
  50. package/dist/{supervise-BiRutHS9.js → supervise-JfKPwIlO.js} +270 -69
  51. package/dist/supervise-JfKPwIlO.js.map +1 -0
  52. package/dist/{supervisor-DTKhF-RV.js → supervisor-B2LzaWRb.js} +221 -16
  53. package/dist/supervisor-B2LzaWRb.js.map +1 -0
  54. package/dist/testing.js +288 -239
  55. package/dist/testing.js.map +1 -1
  56. package/dist/{workspace-archive-CIG1VNCj.js → workspace-archive-C9w_rxt6.js} +2 -2
  57. package/dist/{workspace-archive-CIG1VNCj.js.map → workspace-archive-C9w_rxt6.js.map} +1 -1
  58. package/package.json +11 -6
  59. package/dist/improvement-cycle-Ulvvbg5p.js.map +0 -1
  60. package/dist/prepare-_WTTffkz.js.map +0 -1
  61. package/dist/structural-rollout-IXUEplky.js.map +0 -1
  62. package/dist/supervise-BiRutHS9.js.map +0 -1
  63. package/dist/supervisor-DTKhF-RV.js.map +0 -1
@@ -1,7 +1,8 @@
1
1
  import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore } from "./spawn-journal-CwPvKUTa.js";
2
- import { C as routerToolLoop, i as withDriverExecutor, t as createSupervisor } from "./supervisor-DTKhF-RV.js";
3
- import { createChatClient, estimateCost, isModelPriced, makeFinding } from "@tangle-network/agent-eval";
2
+ import { O as routerToolLoop, l as withDriverExecutor, t as createSupervisor } from "./supervisor-B2LzaWRb.js";
3
+ import { createChatClient, estimateCost, isModelPriced, makeProposalFinding } from "@tangle-network/agent-eval";
4
4
  import { randomBytes } from "node:crypto";
5
+ import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
5
6
  //#region src/improvement/optimizer-prompt.ts
6
7
  /**
7
8
  * The senior scientific-method optimizer doctrine — the ONE substantial prompt
@@ -154,9 +155,8 @@ const strategyAuthorMethod = [
154
155
  * - `learned` — durable facts written to the cross-run `Corpus` so the NEXT
155
156
  * run starts smarter (the continuous half of "continuous self-improvement").
156
157
  *
157
- * Findings are TRACE-derived, never JUDGE-derived (`derived_from_judge:false`):
158
- * the observer reads behavior, never the acceptance verdict the selector≠judge
159
- * firewall (docs/learning-flywheel.md). The observer is harness-agnostic: it
158
+ * Findings are production observations (`proposal_origin:'production'`) and
159
+ * never come from final evaluation (`derived_from_judge:false`). The observer is harness-agnostic: it
160
160
  * reads a trace + an output, so it watches opencode, codex, hermes, or a BYO
161
161
  * agent identically.
162
162
  */
@@ -253,7 +253,7 @@ async function observe(input, opts) {
253
253
  }]
254
254
  }, { ...opts.signal ? { signal: opts.signal } : {} })).content);
255
255
  const producedAt = input.runId ? `${input.runId}` : observerId;
256
- const findings = parsed.map((f) => makeFinding({
256
+ const findings = assertProposalFindings(parsed.map((f) => makeProposalFinding({
257
257
  analyst_id: observerId,
258
258
  area: `${f.area}`,
259
259
  severity: f.severity,
@@ -262,9 +262,10 @@ async function observe(input, opts) {
262
262
  confidence: typeof f.confidence === "number" ? f.confidence : .5,
263
263
  evidence_refs: [],
264
264
  derived_from_judge: false,
265
+ proposal_origin: "production",
265
266
  metadata: { audience: f.audience },
266
267
  ...input.runId ? { subject: input.runId } : {}
267
- }));
268
+ })), "observe findings");
268
269
  const learned = [];
269
270
  if (opts.corpus) for (const f of findings) {
270
271
  const record = {
@@ -285,7 +286,7 @@ async function observe(input, opts) {
285
286
  if ((await opts.corpus.append(record)).succeeded) learned.push(record);
286
287
  }
287
288
  return {
288
- findings,
289
+ findings: [...findings],
289
290
  learned,
290
291
  report: renderReport(findings)
291
292
  };
@@ -1442,4 +1443,4 @@ function structuralRollout(config = {}) {
1442
1443
  //#endregion
1443
1444
  export { observe as C, researchDriverNote as D, optimizerMethod as E, strategyAuthorMethod as O, defaultAnalystInstruction as S, buildDriverSystem as T, depthStrategy as _, defaultStructuralRolloutPolicy as a, sample as b, officialChecksFromMeta as c, selectBestIndex as d, structuralRollout as f, defineStrategy as g, breadthStrategy as h, defaultExtractCandidate as i, resolveEntrySymbol as l, adaptiveRefine as m, compareCheckOutcomes as n, filterAuthoredAsserts as o, visibleCheckScore as p, composeCheckSources as r, modelAuthoredChecks as s, canDisplace as t, sandboxCheckRunner as u, refine as v, renderReport as w, sampleThenRefine as x, runAgentic as y };
1444
1445
 
1445
- //# sourceMappingURL=structural-rollout-IXUEplky.js.map
1446
+ //# sourceMappingURL=structural-rollout-BC81Otmc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structural-rollout-BC81Otmc.js","names":[],"sources":["../src/improvement/optimizer-prompt.ts","../src/runtime/observe.ts","../src/runtime/strategy.ts","../src/runtime/structural-rollout.ts"],"sourcesContent":["/**\n * The senior scientific-method optimizer doctrine — the ONE substantial prompt\n * core shared by every builder/author surface (tool build, MCP build, codebase\n * improvement, strategy authoring) and by the driver that steers build workers\n * (`driverLoopGenerator`).\n *\n * Seeded from the proven senior prompts rather than invented: GEPA's\n * `REFLECTION_SYSTEM` (localize → diagnose → minimal generalizable fix →\n * preserve what works), the /evolve loop (one hypothesis with a mechanism and a\n * falsifiable prediction; attack the largest measured gap first), /pursue (one\n * coherent change set, no partial scaffolding), and the self-improving-loop /\n * supervisor doctrine (a keep is decided by a real check, never by the author;\n * observe → rate → decide). Generalized from \"mutate a prompt string\" to\n * \"build a code surface a held-out measurement will grade\".\n */\n\n/**\n * The shared method block every build/author prompt embeds. Domain framing\n * (what a tool/MCP/codebase-edit deliverable looks like) wraps around it; this\n * is the process itself.\n */\nexport const optimizerMethod = [\n 'THE METHOD — you are a senior engineer-scientist improving a measured system, not a code',\n 'generator. Your change is an experiment: it exists to move a real, externally graded number,',\n 'and it will be measured against a baseline on held-out tasks you cannot see. Work in this order:',\n '',\n '1. DIAGNOSE FIRST. Read every finding before touching anything — findings are ranked evidence',\n ' from real failed runs. Name the DOMINANT failure mode (the single mechanism behind the',\n ' largest share of failures) in one sentence. Attack that first; leave long-tail noise until',\n ' the dominant mode is closed. A fix aimed at the wrong mechanism measures zero however clean',\n ' the code is.',\n '2. STATE A HYPOTHESIS WITH A PREDICTED LIFT. Before designing, write down: \"failures like X',\n ' happen because MECHANISM; this change interrupts that mechanism; I predict it addresses',\n ' roughly N of the M findings shown.\" A change you cannot connect to a mechanism is a guess,',\n ' not an experiment.',\n '3. DECOMPOSE INTO SUB-GOALS. Break the work into steps that are each independently checkable',\n ' (it compiles, a test passes, the server answers). Sequence them so the riskiest assumption',\n ' is tested first — if the hypothesis is wrong, find out on step 1, not step 5.',\n '4. DESIGN TO ISOLATE THE MECHANISM. Make the smallest COHERENT change that fully tests the',\n ' hypothesis: small enough that a measured lift is attributable to this change alone, complete',\n ' enough that it actually fires on the real execution path (a lever that exists but never',\n ' fires measures zero). No drive-by refactors, no unrelated cleanup, no speculative scope —',\n ' anything changed alongside confounds the measurement.',\n '5. GENERALIZE, NEVER MEMORIZE. Fix the failure CLASS, not the shown instances: encode rules and',\n ' logic that transfer to unseen tasks. A patch memorized to the quoted examples will not',\n ' survive the held-out measurement — that is overfitting, and the gate will catch it.',\n '6. PRESERVE WHAT WORKS. The baseline already passes tasks; do not delete or weaken the behavior',\n ' those passes depend on. A fix that trades one failure class for a new one measures as noise.',\n '7. VERIFY FOR REAL, THEN REFLECT. Run the verification you were given and make it genuinely',\n ' pass — never weaken a check, stub the thing it exercises, or special-case its inputs; a',\n ' gamed check delivers nothing because promotion is decided by a separate measurement you',\n ' never see. Then record briefly: what you predicted, what the verifier actually showed, and',\n ' what you would try next if the measured lift comes back null.',\n].join('\\n')\n\n/**\n * The driver's stance for `driverLoopGenerator` — the build-domain instance of\n * the supervisor doctrine (observe → rate → decide; refine / re-scope /\n * decompose; the check decides delivery, never the driver's prose).\n */\nexport const buildDriverSystem = [\n 'You are the DRIVER of a build loop: a senior engineering lead steering a coding WORKER inside',\n 'an isolated git worktree toward a verified artifact. You never edit files yourself — your only',\n 'levers are the tools below. Your intelligence goes into three places: how you AUTHOR each',\n 'worker instruction, how you OBSERVE and RATE what a session actually produced, and what you',\n 'DECIDE next.',\n '',\n 'TOOLS',\n '- run_worker{instruction}: one full coding-harness session in the worktree, with your',\n ' instruction as its entire goal. Sessions are expensive and capped — author each one well.',\n ' The worktree PERSISTS between sessions: a later worker resumes on top of earlier edits.',\n '- inspect_worktree{}: current git status + diff — what has actually changed so far.',\n '- read_file{path,maxBytes?}: read one file from the worktree (new untracked files do not show',\n ' in the diff — read them to rate the work).',\n '- run_verifier{}: the intrinsic check of the surface (compile+tests for a tool, boot-and-probe',\n ' for an MCP server). Its exit decides what counts as delivered — your opinion does not.',\n '',\n 'AUTHOR RICHLY. A worker handed a one-line label will flail. Each instruction must carry: the',\n 'outcome in concrete terms; the hypothesis and sub-goal it serves; what already exists in the',\n 'tree that it must build on, not duplicate; where the deliverable must land; and the exact check',\n 'it will be held to. The worker sees NOTHING you were given (no findings, no method, no prior',\n 'session context) unless you fold it into the instruction.',\n '',\n 'THE LOOP — every turn: observe, rate, decide.',\n '- OBSERVE: after each session, inspect the worktree and run the verifier. Read WHAT failed and',\n ' WHY — \"it failed\" alone tells you nothing.',\n '- RATE: judge with a reason. Verified and complete → stop. Close, one correctable fault →',\n ' REFINE: author \"continue from the current tree; the check fails because X; fix X\" (depth,',\n ' not a fresh start — never let a worker revert its own near-miss). Empty tree, or it solved a',\n ' different problem → RE-SCOPE: re-author narrower and more concrete; a second identical',\n ' instruction fails identically. Too big for one session → DECOMPOSE: author the first',\n ' self-contained slice, verify it, then author the next on top.',\n '- DECIDE: exactly one move per turn, with the reason stated in one line.',\n '',\n 'STOP when the verifier passes — reply with no tool call and a short reflection: what you',\n 'predicted, what the verifier showed, what you would try next if the measured lift comes back',\n 'null. If the session budget runs out first, say plainly what remains and why. An honest',\n 'no-winner is a real result; a claimed success is not — the final keep/discard decision is made',\n 'by code from the verifier exit and the tree state, never from your words.',\n].join('\\n')\n\n/**\n * The driver's ADOPT-not-build doctrine, appended to `buildDriverSystem` when\n * a `research` tool is wired into the loop (`DriverLoopGeneratorOptions.\n * research`). Kept separate so a driver WITHOUT the tool is never told to\n * call a tool it does not have.\n */\nexport const researchDriverNote = [\n 'RESEARCH — ADOPT BEFORE BUILD. A research{query} tool is provisioned for this run. Before',\n 'authoring a from-scratch build, spend one turn researching whether an EXISTING external MCP',\n 'server already provides the missing capability — registries and vendor docs list maintained',\n 'servers for most common gaps (web search, fetch, GitHub, filesystems, databases).',\n '- If a maintained server fits, ADOPT it: report in your final reflection its endpoint or',\n ' launch command and the API key it needs BY NAME (e.g. EXA_API_KEY) — never a key value —',\n ' so the dispatch can emit a connection candidate with provisioned secrets. Adopting a fit',\n ' server beats rebuilding it: less code to verify, maintained upstream, same measured gate.',\n '- If nothing fits (unmaintained, wrong tool surface, heavier than the gap), build — and state',\n ' in one line why adoption lost.',\n].join('\\n')\n\n/**\n * The senior authoring process for `authorStrategy` — the same method, shaped\n * to the strategy contract (author-blind, conserved budget, one module out).\n */\nexport const strategyAuthorMethod = [\n 'Work as a senior researcher, in this order:',\n '1. DIAGNOSE: read the per-task losses above and name the DOMINANT failure mode in one sentence',\n ' — the single mechanism behind the largest share of lost score (e.g. first attempts near-miss',\n ' and never get corrected; fresh retries discard progress; one persona plateaus).',\n '2. HYPOTHESIS + PREDICTED LIFT: state \"these losses happen because MECHANISM; the composition',\n ' below interrupts it; I predict roughly +N on this environment at the same budget.\"',\n '3. DESIGN TO ISOLATE THE MECHANISM: change ONE coordination mechanism relative to the baselines',\n ' (carry vs fresh, where the critique lands, a persona split, a tool restriction) so any',\n ' measured lift is attributable to it. Do not stack three clever ideas — a tangled win teaches',\n ' nothing and a tangled loss cannot be debugged.',\n '4. DECOMPOSE THE BUDGET: plan how the shots divide across explore / attempt / critique / repair',\n ' before writing code, and spend the whole budget — an early stop on a mid score is a loss.',\n '5. GENERALIZE: the strategy runs on unseen tasks from this environment. Read tools via',\n ' listTools(handle), never hardcode task specifics from the losses shown.',\n '6. PREDICT, THEN REFLECT: put the hypothesis, the mechanism, and the predicted lift in a',\n ' comment at the top of the module — the holdout verdict will be read against it.',\n].join('\\n')\n","/**\n * The third-person observer — the connective tissue that closes the loop.\n *\n * A driver spawns a worker; the worker can't see itself. `observe` reads the\n * worker's TRACE (what it actually did — every tool call, cost, failure) and\n * produces two streams:\n * - `findings` / `report` — fed back DOWN (a steer for the next attempt) and\n * OUT (the operator-facing \"what I noticed + what to change\").\n * - `learned` — durable facts written to the cross-run `Corpus` so the NEXT\n * run starts smarter (the continuous half of \"continuous self-improvement\").\n *\n * Findings are production observations (`proposal_origin:'production'`) and\n * never come from final evaluation (`derived_from_judge:false`). The observer is harness-agnostic: it\n * reads a trace + an output, so it watches opencode, codex, hermes, or a BYO\n * agent identically.\n */\nimport {\n type AnalystFinding,\n type ChatClient,\n makeProposalFinding,\n type ProposalFinding,\n} from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport type { Corpus, CorpusRecord } from './personify/wave-types'\n\nconst observerId = 'observe/trace'\n\nexport interface ObserveInput {\n /** What the worker was asked to do. */\n task: string\n /** What it produced (its final answer / artifact summary). */\n output: string\n /** The worker's trace — any event array (sandbox events, tool-call records). */\n trace: ReadonlyArray<unknown>\n /** Terminal status only (passed/failed/unknown) — NOT a judge score; the\n * observer never reads the verdict, it reads behavior. */\n outcome?: 'passed' | 'failed' | 'unknown'\n /** Provenance back to the run. */\n runId?: string\n}\n\nexport interface ObserveOptions {\n /** The model-call seam (agent-eval `createChatClient`: router / cli-bridge / …). */\n chat: ChatClient\n model?: string\n /** When set, learned facts are appended (idempotent) for the next run to read. */\n corpus?: Corpus\n /** Tags written onto learned facts + used by the next run's corpus query. */\n tags?: ReadonlyArray<string>\n signal?: AbortSignal\n /** Cap the trace lines fed to the observer (keeps the call cheap). Default 80. */\n maxTraceLines?: number\n /** Override the analyst's system instruction — the prompt that turns a trace into\n * findings + recommended_actions. The analyst IS the steerer, so this is the knob a\n * prompt optimizer (GEPA) tunes. Omitted ⇒ the default observer instruction. The\n * firewall (trace-only, never the verdict) is structural (input has no score), so a\n * custom instruction cannot break it. */\n analystInstruction?: string\n}\n\n/** The default observer instruction — exported so an optimizer can seed its population. */\nexport const defaultAnalystInstruction =\n 'You are a third-person OBSERVER watching an AI agent work. You see its TRACE (what it did), not its grader. ' +\n 'From the trace, name SPECIFIC, behavior-grounded findings: wasted/duplicated tool calls, thrash/retries, ' +\n 'token/cost waste, missing verification, failure patterns. For each, a concrete recommended_action, and ' +\n 'whether the AGENT (fix its skills/prompt/tools) or the OPERATOR (fix framing/decomposition/config) should act. ' +\n 'Only claim what the trace shows. No findings if the run was clean.'\n\nexport interface Observation {\n findings: ProposalFinding[]\n /** Facts persisted to the corpus (empty when no corpus was supplied). */\n learned: CorpusRecord[]\n /** Operator-facing markdown: what the observer noticed + what to change. */\n report: string\n}\n\n/** Compact the trace into the lines the observer reasons over — tool calls,\n * errors, and statuses, in order. Keeps the model call bounded + grounded. */\nfunction summarizeTrace(trace: ReadonlyArray<unknown>, maxLines: number): string {\n const lines: string[] = []\n for (const ev of trace) {\n const e = ev as { type?: string; data?: Record<string, unknown> }\n const t = (e.type ?? '').toLowerCase()\n const d = e.data ?? {}\n const part = (d.part ?? {}) as { type?: string; tool?: string; state?: { status?: string } }\n if (part.type === 'tool')\n lines.push(`tool:${part.tool}${part.state?.status ? `(${part.state.status})` : ''}`)\n else if (t.includes('error'))\n lines.push(`ERROR: ${String(d.message ?? d.detail ?? '').slice(0, 200)}`)\n else if (t === 'status' && typeof d.status === 'string') lines.push(`status:${d.status}`)\n else if (t.includes('tool')) lines.push(`tool-event:${t}`)\n }\n // Collapse runs of identical lines into \"xN\" so repeated thrash is visible + short.\n const out: string[] = []\n for (const ln of lines) {\n const prev = out[out.length - 1]\n const m = prev?.match(/^(.*?)(?: x(\\d+))?$/)\n if (m && m[1] === ln) out[out.length - 1] = `${ln} x${(Number(m[2]) || 1) + 1}`\n else out.push(ln)\n }\n return out.slice(0, maxLines).join('\\n') || '(no tool/error events in trace)'\n}\n\nconst findingsSchema = {\n name: 'observer_findings',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n findings: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n area: {\n type: 'string',\n description: 'tool-use | cost | verification | process | failure | latency',\n },\n severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },\n claim: {\n type: 'string',\n description: 'what you OBSERVED in the trace (a fact, with the evidence)',\n },\n recommended_action: {\n type: 'string',\n description: 'the concrete change for the agent or operator',\n },\n audience: {\n type: 'string',\n enum: ['agent', 'operator'],\n description: 'who should act on this',\n },\n confidence: { type: 'number' },\n },\n required: ['area', 'severity', 'claim', 'recommended_action', 'audience', 'confidence'],\n },\n },\n },\n required: ['findings'],\n },\n} as const\n\n/** The third-person trace analyst: read a worker's trace and produce steer findings for the next attempt plus durable `learned` facts for the cross-run corpus. */\nexport async function observe(input: ObserveInput, opts: ObserveOptions): Promise<Observation> {\n const traceSummary = summarizeTrace(input.trace, opts.maxTraceLines ?? 80)\n const res = await opts.chat.chat(\n {\n ...(opts.model ? { model: opts.model } : {}),\n jsonSchema: findingsSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\n {\n role: 'system',\n content: opts.analystInstruction ?? defaultAnalystInstruction,\n },\n {\n role: 'user',\n content:\n `TASK: ${input.task}\\n\\nOUTCOME: ${input.outcome ?? 'unknown'}\\n\\n` +\n `FINAL OUTPUT (truncated):\\n${input.output.slice(0, 1200)}\\n\\n` +\n `TRACE (in order; \"xN\" = repeated):\\n${traceSummary}`,\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n\n const parsed = parseFindings(res.content)\n const producedAt = input.runId ? `${input.runId}` : observerId\n const findings = assertProposalFindings(\n parsed.map((f) =>\n makeProposalFinding({\n analyst_id: observerId,\n area: `${f.area}`,\n severity: f.severity,\n claim: f.claim,\n recommended_action: f.recommended_action,\n confidence: typeof f.confidence === 'number' ? f.confidence : 0.5,\n evidence_refs: [],\n // The observer reads behavior, never a final evaluation result.\n derived_from_judge: false,\n proposal_origin: 'production',\n metadata: { audience: f.audience },\n ...(input.runId ? { subject: input.runId } : {}),\n }),\n ),\n 'observe findings',\n )\n\n const learned: CorpusRecord[] = []\n if (opts.corpus) {\n for (const f of findings) {\n const record: CorpusRecord = {\n schemaVersion: '1.0.0',\n id: f.finding_id,\n runId: input.runId ?? observerId,\n producedAt: f.produced_at ?? producedAt,\n area: f.area,\n claim: f.recommended_action ?? f.claim,\n ...(f.claim ? { rationale: f.claim } : {}),\n tags: [...(opts.tags ?? []), `audience:${(f.metadata?.audience as string) ?? 'agent'}`],\n confidence: f.confidence,\n evidence: [{ kind: 'finding', uri: f.finding_id }],\n }\n const r = await opts.corpus.append(record)\n if (r.succeeded) learned.push(record)\n }\n }\n\n return { findings: [...findings], learned, report: renderReport(findings) }\n}\n\ninterface RawFinding {\n area: string\n severity: AnalystFinding['severity']\n claim: string\n recommended_action: string\n audience: 'agent' | 'operator'\n confidence: number\n}\n\nfunction parseFindings(content: string): RawFinding[] {\n let obj: unknown\n try {\n obj = JSON.parse(content)\n } catch {\n const m = content.match(/\\{[\\s\\S]*\\}/)\n obj = m ? JSON.parse(m[0]) : { findings: [] }\n }\n const arr = (obj as { findings?: unknown }).findings\n return Array.isArray(arr) ? (arr as RawFinding[]) : []\n}\n\n/** Operator-facing report, split by who should act. The agent block is the\n * steer; the operator block is the advice. */\nexport function renderReport(findings: ReadonlyArray<AnalystFinding>): string {\n if (findings.length === 0) return '✓ clean run — the observer found nothing to change.'\n const audience = (f: AnalystFinding): string => (f.metadata?.audience as string) ?? 'agent'\n const forAgent = findings.filter((f) => audience(f) === 'agent')\n const forOperator = findings.filter((f) => audience(f) === 'operator')\n const block = (title: string, fs: ReadonlyArray<AnalystFinding>): string =>\n fs.length === 0\n ? ''\n : `**${title}**\\n${fs\n .map((f) => `- [${f.severity}] ${f.claim}\\n → ${f.recommended_action ?? ''}`)\n .join('\\n')}\\n`\n return [\n block('For the agent (fix skills / prompt / tools)', forAgent),\n block('For you (the operator)', forOperator),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n","/**\n * The general agentic primitive — sequential (depth) and parallel (breadth) over a shared,\n * checkable artifact, driven through the keystone Supervisor as one recursive `Agent.act`.\n *\n * The domain lives behind ONE seam — `AgenticSurface` (open an artifact, list tools, call a tool,\n * score the artifact, close it). EnterpriseOps implements it (seed a gym DB, MCP tools, SQL\n * verifier); Commit0/AppWorld/terminal-bench implement it the same way (a repo workspace, shell\n * tools, the test suite). The drivers below are domain-blind: they run over any surface.\n *\n * Two shapes, the agent's POMDP rollout as the unit:\n * - DEPTH one persistent artifact carried across shots. Each shot the agent works the tool loop;\n * between shots a trace-analyst (selector≠judge: reads the trajectory, never the score)\n * steers the resumed session toward what's unfinished. shot n stands on shot n-1's\n * artifact state + history. This is continuation — long-horizon, same artifact.\n * - BREADTH K independent artifacts, each a fresh rollout, the deployable verifier picks the best.\n *\n * Both are an `Agent` whose `act` spawns leaf shots through `scope.spawn` and reacts via\n * `scope.next()` — so the conserved budget pool meters them (equal-k by construction), the journal\n * records the tree, and the same primitive nests. `runAgentic` runs the chosen driver through\n * `createSupervisor().run`. The leaf (one shot over a handle) is resolved per-spawn from a\n * surface-closed registry — the open `Executor` seam, not bespoke per-benchmark glue.\n */\n\nimport { createChatClient, estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../durable/spawn-journal'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport { observe } from './observe'\nimport type { Outcome } from './personify/types'\nimport type { Corpus } from './personify/wave-types'\nimport { routerToolLoop } from './router-client'\nimport { withDriverExecutor } from './supervise/driver-executor'\nimport { createSupervisor } from './supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Scope,\n Settled,\n} from './supervise/types'\n\n// ── The general surface seam (the only thing a new benchmark implements) ─────────\n\nexport interface AgenticTask {\n readonly id: string\n readonly systemPrompt: string\n readonly userPrompt: string\n /** Opaque domain payload the surface reads (EOPS: servers/verifiers/tools). Drivers never read it. */\n readonly meta?: Record<string, unknown>\n}\n\nexport interface ArtifactHandle {\n readonly id: string\n readonly surface: string\n /** Opaque per-artifact context the surface stashes (EOPS: the seeded gym server + db id). */\n readonly ctx?: unknown\n}\n\nexport interface AgenticTool {\n readonly type: 'function'\n readonly function: { name: string; description?: string; parameters: Record<string, unknown> }\n}\n\nexport interface SurfaceScore {\n passes: number\n total: number\n /** Checks excluded as malformed (data defect, not the agent). `total === 0` ⇒ unscoreable. */\n errored: number\n}\n\n/** A stateful, checkable environment an agent operates over with tools. Open behind one interface. */\nexport interface AgenticSurface {\n readonly name: string\n open(task: AgenticTask): Promise<ArtifactHandle>\n tools(task: AgenticTask, handle: ArtifactHandle): Promise<AgenticTool[]>\n call(handle: ArtifactHandle, name: string, args: Record<string, unknown>): Promise<string>\n score(task: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore>\n close(handle: ArtifactHandle): Promise<void>\n}\n\nexport interface AgenticOptions {\n routerBaseUrl: string\n routerKey: string\n model: string\n /** Optional completion transport (see `RouterConfig.complete`): when set, BOTH legs of an\n * offline run use it instead of `fetch`-ing the router — the worker's tool loop (threaded into\n * its `routerToolLoop` cfg) AND the analyst's critic (its `ChatClient` is bound to this same\n * transport). One injected responder serves both, as a localhost mock endpoint would. Absent ⇒\n * the live router fetch path (the default). */\n complete?: (body: Record<string, unknown>) => Promise<unknown>\n temperature?: number\n /** Completion cap per worker turn — REQUIRED for thinking models (they burn unbounded\n * budgets on reasoning and return empty content without it). Omitted ⇒ provider default. */\n maxTokens?: number\n /** Turns the agent may take within ONE shot before the driver intervenes. */\n innerTurns?: number\n /** The depth STEERER's analyst instruction (observe()'s system prompt). The knob a\n * prompt optimizer (GEPA) tunes — the analyst IS the steerer. Omitted ⇒ the default. */\n analystInstruction?: string\n /** The critic's model — lets the analyst be a stronger (or cheaper) model than the\n * worker. Omitted ⇒ the worker's `model`. */\n analystModel?: string\n /** Across-run learning: when set, the analyst's observe() pass appends trace-derived\n * facts here (the flywheel write side). Read-back is opt-in via `corpusReadback`\n * because unconditional priming can pollute context on some domains. */\n corpus?: Corpus\n /** Tags written onto learned facts (and used by the caller's priming query). */\n corpusTags?: string[]\n /** In-context learning: when set, query `corpus` before each depth shot and inject\n * the top trace-derived facts as guidance for the active run. No corpus means no read-back. */\n corpusReadback?: CorpusReadbackOptions\n}\n\nexport interface CorpusReadbackOptions {\n /** Minimum confidence for a fact to be injected. Default 0.7. */\n minConfidence?: number\n /** Extra tags a fact must carry, in addition to `corpusTags`. */\n tags?: ReadonlyArray<string>\n /** Max facts injected per shot. Default 3. */\n maxFacts?: number\n /** Default false: only facts tagged `audience:agent` are injected into the worker. */\n includeOperatorFacts?: boolean\n}\n\n// ── The unit: one agentic shot (a bounded tool loop) over a handle ───────────────\n\n/** One provider-neutral conversation record carried between strategy shots. */\nexport type StrategyMessage = Record<string, unknown>\ninterface ToolCall {\n id: string\n function: { name: string; arguments: string }\n}\n\ninterface ShotTask {\n task: AgenticTask\n handle?: ArtifactHandle // present ⇒ DEPTH (shared artifact); absent ⇒ BREADTH (open own)\n messages?: StrategyMessage[] // carried conversation (depth); fresh when absent\n steer?: string // analyst-derived steer injected before this shot (depth)\n persona?: ShotPersona // role override — multi-agent loops give each shot its own hat\n tools?: string[] // restrict THIS shot to these domain tools (names); unknown names throw\n /** analyst leaf only: a RAW instruction — the analyst answers it over the trajectory\n * directly (no findings schema). The verdict-capable channel. */\n rawInstruction?: string\n}\n\ninterface ShotOut {\n messages: StrategyMessage[]\n completions: number\n toolCalls: number\n toolErrors: number\n /** Real router usage summed over the shot's turns; zeros only when the provider omits usage. */\n tokens: { input: number; output: number }\n}\n\nconst taskNudge =\n 'Use the available tools to bring the artifact to the required final state. Address EVERY distinct ' +\n 'change the request implies. After each tool result, check what remains and continue. Re-read the ' +\n 'values you set to confirm they took. Reply DONE only once every required change is made and verified.'\n\n/** One shot: run the agent's tool loop (≤ innerTurns) over the handle, mutating the artifact via\n * `surface.call`, carrying `messages`. Returns the updated conversation + counts. */\nasync function runShot(\n surface: AgenticSurface,\n _task: AgenticTask,\n handle: ArtifactHandle,\n tools: AgenticTool[],\n messages: StrategyMessage[],\n opts: AgenticOptions,\n modelOverride?: string,\n): Promise<ShotOut> {\n // The canonical off-box tool loop (routerToolLoop) drives the turns; this shot supplies\n // the carried conversation (depth continuation, via initialMessages) and the tool dispatch\n // (surface.call). An ERROR:-prefixed result or a thrown call is a real tool outcome —\n // counted as a toolError and fed back to the model, never thrown to kill the shot.\n let toolErrors = 0\n const execute = async (name: string, args: Record<string, unknown>): Promise<string> => {\n try {\n const out = await surface.call(handle, name, args)\n if (out.startsWith('ERROR:')) toolErrors += 1\n return out\n } catch (e) {\n toolErrors += 1\n return `ERROR: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n const r = await routerToolLoop(\n {\n routerBaseUrl: opts.routerBaseUrl,\n routerKey: opts.routerKey,\n model: modelOverride ?? opts.model,\n ...(opts.complete ? { complete: opts.complete } : {}),\n },\n '',\n '',\n tools,\n execute,\n {\n maxTurns: opts.innerTurns ?? 4,\n temperature: opts.temperature ?? 0.7,\n initialMessages: messages,\n ...(opts.maxTokens ? { maxTokens: opts.maxTokens } : {}),\n },\n )\n return {\n messages: r.messages,\n completions: r.turns,\n toolCalls: r.toolCalls,\n toolErrors,\n tokens: r.usage,\n }\n}\n\n/** The trace-analyst (selector≠judge): reads ONLY the trajectory + task, never the score. */\n/** The depth STEERER, on the CANONICAL analyst: agent-eval's `observe()` (makeFinding +\n * ChatClient + the derived_from_judge firewall) reads the agent's tool-call trajectory\n * (behavior, never the score) and returns findings; we steer on their recommended_actions.\n * The trajectory (calls + RESULTS) rides in `output` so the analyst sees what actually\n * happened, not just tool names. No actionable findings ⇒ COMPLETE (depth self-terminates). */\ninterface AnalyzeOut {\n steer: string\n tokens: { input: number; output: number }\n}\n\n/** The firewall's input shape: the trajectory as compacted text — calls, results,\n * assistant text. NEVER scores, NEVER check internals. Shared by both analyst channels. */\nfunction compactTrajectory(messages: StrategyMessage[]): string {\n return messages\n .filter((m) => m.role === 'assistant' || m.role === 'tool')\n .map((m) => {\n if (m.role === 'tool') return `RESULT ${String(m.content).slice(0, 280)}`\n const calls = (m.tool_calls as ToolCall[] | undefined)\n ?.map((c) => `${c.function.name}(${c.function.arguments})`)\n .join(', ')\n return calls ? `CALL ${calls}` : `SAY ${String(m.content).slice(0, 200)}`\n })\n .join('\\n')\n .slice(0, 7000)\n}\n\n/** The analyst's chat seam: the live router by default, or — when a `complete` transport is\n * injected — that SAME transport, so an offline run drives the critic with no network too (the\n * worker and the analyst share the one injected responder, exactly as a localhost mock would\n * serve both). The critic speaks the OpenAI request shape; we forward it to `complete` and lift\n * the parsed `/chat/completions` JSON back into a `ChatResponse`. */\nfunction analystChat(\n opts: AgenticOptions,\n defaultModel: string,\n): ReturnType<typeof createChatClient> {\n if (!opts.complete) {\n return createChatClient({\n transport: 'router',\n apiKey: opts.routerKey,\n baseUrl: opts.routerBaseUrl,\n defaultModel,\n })\n }\n const complete = opts.complete\n return createChatClient({\n transport: 'mock',\n defaultModel,\n handler: async (req) => {\n const raw = (await complete({\n model: req.model ?? defaultModel,\n messages: req.messages,\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.maxTokens !== undefined ? { max_tokens: req.maxTokens } : {}),\n })) as {\n choices?: Array<{ message?: { content?: string | null }; finish_reason?: string | null }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const content = raw.choices?.[0]?.message?.content ?? ''\n const promptTokens = raw.usage?.prompt_tokens ?? 0\n const completionTokens = raw.usage?.completion_tokens ?? 0\n return {\n content,\n usage: {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n },\n costUsd: null,\n model: req.model ?? defaultModel,\n durationMs: 0,\n finishReason: raw.choices?.[0]?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n raw: raw as Record<string, unknown>,\n }\n },\n })\n}\n\n/** The RAW analyst channel: the firewalled critic answers `instruction` over the\n * trajectory directly — no findings schema, no recommended-action extraction. The\n * channel for verdict-shaped steering (budget controllers, calibrated predictions)\n * whose output format the findings protocol would strip. Same firewall as analyze():\n * trajectory in, never scores. */\nasync function consultAnalyst(\n task: AgenticTask,\n messages: StrategyMessage[],\n instruction: string,\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystModel = opts.analystModel ?? opts.model\n const chat = analystChat(opts, analystModel)\n // With a trajectory, the analyst framing (instruction as system, behavior as the user\n // turn) is the channel's shape. With NO trajectory (pre-task consults, e.g. authored\n // check generation), that framing breaks: the user turn is then just the task, which\n // reads as a solve request — measured on Llama-3-8B, the model ignores the system\n // instruction and answers the task (authored-assert yield 6/18 reps vs 18/18 with the\n // instruction and task fused into one user message, the proven rig shape).\n const consultMessages = trajectory\n ? [\n { role: 'system' as const, content: instruction },\n {\n role: 'user' as const,\n content: `TASK: ${task.userPrompt.slice(0, 1500)}\\n\\nTRAJECTORY:\\n${trajectory}`,\n },\n ]\n : [\n {\n role: 'user' as const,\n content: `${instruction}\\n\\nTASK:\\n${task.userPrompt.slice(0, 1500)}`,\n },\n ]\n const res = await chat.chat({\n model: analystModel,\n temperature: 0.2,\n maxTokens: 1024,\n messages: consultMessages,\n })\n const usage = (\n res as {\n usage?: {\n promptTokens?: number\n prompt_tokens?: number\n completionTokens?: number\n completion_tokens?: number\n }\n }\n ).usage\n return {\n steer: res.content.trim(),\n tokens: {\n input: usage?.promptTokens ?? usage?.prompt_tokens ?? 0,\n output: usage?.completionTokens ?? usage?.completion_tokens ?? 0,\n },\n }\n}\n\nasync function analyze(\n task: AgenticTask,\n messages: StrategyMessage[],\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystModel = opts.analystModel ?? opts.model\n const inner = analystChat(opts, analystModel)\n // The critic's calls are REAL spend — capture usage so the cost vector bills them\n // (an unbilled critic makes every steering-vs-sampling cost comparison dishonest).\n const tokens = { input: 0, output: 0 }\n const chat: typeof inner = {\n ...inner,\n chat: async (req, callOpts) => {\n const res = await inner.chat(req, callOpts)\n const u = (\n res as {\n usage?: {\n promptTokens?: number\n completionTokens?: number\n prompt_tokens?: number\n completion_tokens?: number\n }\n }\n ).usage\n if (u) {\n tokens.input += u.promptTokens ?? u.prompt_tokens ?? 0\n tokens.output += u.completionTokens ?? u.completion_tokens ?? 0\n }\n return res\n },\n }\n const obs = await observe(\n {\n task: task.userPrompt,\n output: trajectory,\n trace: messages,\n outcome: 'failed',\n runId: task.id,\n },\n {\n chat,\n model: analystModel,\n ...(opts.analystInstruction ? { analystInstruction: opts.analystInstruction } : {}),\n ...(opts.corpus ? { corpus: opts.corpus, tags: opts.corpusTags ?? [] } : {}),\n },\n )\n // The steer = the analyst's recommended actions for the agent. Empty ⇒ nothing left to do.\n const steer = obs.findings\n .map((f) => f.recommended_action)\n .filter((a): a is string => typeof a === 'string' && a.trim().length > 0)\n .join('\\n')\n .trim()\n return { steer: steer || 'COMPLETE', tokens }\n}\n\nasync function renderCorpusReadback(opts: AgenticOptions): Promise<string> {\n if (!opts.corpus || !opts.corpusReadback) return ''\n const maxFacts = opts.corpusReadback.maxFacts ?? 3\n if (!Number.isInteger(maxFacts) || maxFacts < 0) {\n throw new Error(`corpusReadback.maxFacts must be a non-negative integer, got ${maxFacts}`)\n }\n if (maxFacts === 0) return ''\n\n const tags = [\n ...(opts.corpusTags ?? []),\n ...(opts.corpusReadback.tags ?? []),\n ...(opts.corpusReadback.includeOperatorFacts ? [] : ['audience:agent']),\n ]\n const facts = await opts.corpus.query({\n ...(tags.length > 0 ? { tags } : {}),\n minConfidence: opts.corpusReadback.minConfidence ?? 0.7,\n limit: maxFacts,\n })\n if (facts.length === 0) return ''\n\n const rendered = facts.map((fact) =>\n fact.rationale ? `- ${fact.claim} (${fact.rationale})` : `- ${fact.claim}`,\n )\n return `Relevant learned facts from prior attempts:\\n${rendered.join('\\n')}`\n}\n\n// ── Leaf executors (one shot / one analyst), resolved per-spawn from the surface ──\n\n/** Measured result of one strategy shot. */\nexport interface StrategyShotResult {\n messages: StrategyMessage[]\n score: number\n passes: number\n total: number\n completions: number\n toolErrors: number\n}\n\n/** Resolve a shot: if `handle` given, operate on the SHARED artifact (depth); else open+score+close\n * an OWN artifact (breadth). Always scores the artifact's final state as the deployable verdict. */\nfunction shotExecutor(surface: AgenticSurface, opts: AgenticOptions): Executor<unknown> {\n let artifact: ExecutorResult<unknown> | undefined\n return {\n runtime: 'agentic-shot',\n async execute(task: unknown): Promise<ExecutorResult<unknown>> {\n const t = task as ShotTask\n const own = !t.handle\n const handle = t.handle ?? (await surface.open(t.task))\n try {\n const allTools = await surface.tools(t.task, handle)\n // Tool SELECTION is a strategy decision (which of the domain's tools this shot\n // sees) — restriction-only: a strategy can focus a shot, never grant a tool the\n // domain didn't offer. Unknown names fail loud (an authored typo must not\n // silently become an unrestricted shot).\n let tools = allTools\n if (t.tools) {\n const known = new Set(allTools.map((tool) => tool.function.name))\n const unknown = t.tools.filter((name) => !known.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `shot tools: unknown tool name(s) ${unknown.join(', ')} — domain offers: ${[...known].join(', ')}`,\n )\n }\n const want = new Set(t.tools)\n tools = allTools.filter((tool) => want.has(tool.function.name))\n }\n // An EMPTY messages array means \"fresh\" too — an authored body passing\n // `messages: []` must not silently blank the worker's system/task prompt.\n const messages: StrategyMessage[] = t.messages?.length\n ? t.messages\n : [\n { role: 'system', content: t.persona?.systemPrompt ?? t.task.systemPrompt },\n { role: 'user', content: `${t.task.userPrompt}\\n\\n${taskNudge}` },\n ]\n // On a CARRIED conversation, a persona switch arrives as a role hand-off message.\n if (t.messages?.length && t.persona?.systemPrompt) {\n messages.push({\n role: 'user',\n content: `[hand-off] You are now acting as: ${t.persona.systemPrompt}`,\n })\n }\n if (t.steer) messages.push({ role: 'user', content: t.steer })\n const shot = await runShot(surface, t.task, handle, tools, messages, opts, t.persona?.model)\n const s = await surface.score(t.task, handle)\n const score = s.total > 0 ? s.passes / s.total : 0\n const out: StrategyShotResult = {\n messages: shot.messages,\n score,\n passes: s.passes,\n total: s.total,\n completions: shot.completions,\n toolErrors: shot.toolErrors,\n }\n artifact = {\n outRef: `shot:${handle.id}:${shot.completions}:${s.passes}/${s.total}`,\n out,\n verdict: { valid: s.total > 0 && s.passes === s.total, score },\n // Real usage to the conserved pool: tokens from the router responses; usd only\n // when the model is in the price table (never a fabricated number).\n spent: {\n iterations: shot.completions,\n tokens: shot.tokens,\n usd: isModelPriced(opts.model)\n ? estimateCost(shot.tokens.input, shot.tokens.output, opts.model)\n : 0,\n ms: 0,\n },\n }\n return artifact\n } finally {\n if (own) await surface.close(handle)\n }\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('shotExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\nfunction analystExecutor(opts: AgenticOptions): Executor<unknown> {\n let artifact: ExecutorResult<unknown> | undefined\n return {\n runtime: 'agentic-analyst',\n async execute(task: unknown): Promise<ExecutorResult<unknown>> {\n const t = task as { task: AgenticTask; messages: StrategyMessage[]; rawInstruction?: string }\n const { steer, tokens } = t.rawInstruction\n ? await consultAnalyst(t.task, t.messages, t.rawInstruction, opts)\n : await analyze(t.task, t.messages, opts)\n const analystModel = opts.analystModel ?? opts.model\n artifact = {\n outRef: `analyst:${steer.length}`,\n out: steer,\n spent: {\n iterations: 1,\n tokens,\n usd: isModelPriced(analystModel)\n ? estimateCost(tokens.input, tokens.output, analystModel)\n : 0,\n ms: 0,\n },\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('analystExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\n/**\n * Registry dispatching on the child's role tag — fresh executor per spawn (no\n * shared-instance race). `withDriverExecutor` wraps it so a `role:'driver'` child resolves\n * to the recursive driver-executor (a child that drives its OWN children — agents drive\n * agents) before this leaf dispatch; `shot`/`analyst` children resolve to their leaf\n * executors here unchanged.\n */\nfunction agenticRegistry(surface: AgenticSurface, opts: AgenticOptions): ExecutorRegistry {\n const leaves: ExecutorRegistry = {\n register() {\n throw new Error('agenticRegistry: register unsupported')\n },\n resolve<Out>(spec: AgentSpec) {\n const role = (spec.profile.metadata as { role?: string } | undefined)?.role\n const factory: ExecutorFactory<Out> = (_s: AgentSpec, _ctx: ExecutorContext) =>\n (role === 'analyst' ? analystExecutor(opts) : shotExecutor(surface, opts)) as Executor<Out>\n return { succeeded: true as const, value: factory }\n },\n }\n return withDriverExecutor(leaves)\n}\n\nfunction leaf(name: string, role: 'shot' | 'analyst'): Agent<unknown, Outcome<unknown>> {\n const agent = {\n name,\n executorSpec: { profile: { name, metadata: { role } }, harness: null } as unknown as AgentSpec,\n act(): Promise<Outcome<unknown>> {\n // SPAWNED, not run: its `executorSpec` (role shot/analyst) resolves a leaf executor\n // the scope drives. `act` is never called for a spawned child; it fails loud if\n // mis-used as a root. A `role:'driver'` child instead resolves to the recursive\n // driver-executor (agents drive agents) — see `withDriverExecutor`.\n throw new Error(`agentic: spawned child \"${name}\" was run directly (the executor drives it)`)\n },\n }\n return agent as Agent<unknown, Outcome<unknown>>\n}\n\n/** Drain exactly one settlement (the just-spawned child). */\nasync function drainOne(scope: Scope<Outcome<unknown>>): Promise<Settled<Outcome<unknown>>> {\n const s = await scope.next()\n if (!s) throw new Error('agentic: spawned child never settled')\n return s\n}\n\n// ── The result + the two drivers (domain-blind Agents run by the Supervisor) ─────\n\nexport interface AgenticRunResult {\n /** The strategy name (built-in 'depth'/'breadth' or a custom strategy's name). */\n mode: string\n score: number\n resolved: boolean\n completions: number\n /** DEPTH: score after each shot — the progress-over-rounds curve. BREADTH: best-so-far per rollout. */\n progression: number[]\n shots: number\n /** The cost vector, stamped by `runAgentic` from the Supervisor's conserved pool: real\n * router tokens, priced usd (0 when the model is unpriced — never fabricated), wall ms. */\n usd: number\n ms: number\n tokens: { input: number; output: number }\n}\n\nconst perChild = (innerTurns: number): Budget => ({\n maxIterations: innerTurns + 1,\n maxTokens: 1_000_000,\n})\n\n/** DEPTH: one persistent artifact, carried across analyst-steered shots. */\nexport function depthStrategy(\n surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n cfg: { maxShots: number },\n): Agent<unknown, Outcome<unknown>> {\n const innerTurns = opts.innerTurns ?? 4\n let pendingSteer: string | undefined // analyst-derived steer carried between shots\n return {\n name: 'depth',\n async act(_t, scope): Promise<Outcome<unknown>> {\n const handle = await surface.open(task)\n const progression: number[] = []\n let messages: StrategyMessage[] | undefined\n let completions = 0\n let shots = 0\n try {\n for (shots = 0; shots < cfg.maxShots; shots += 1) {\n const child = leaf(`shot:${shots}`, 'shot')\n const memorySteer = await renderCorpusReadback(opts)\n const steer = [shots === 0 ? undefined : pendingSteer, memorySteer]\n .filter((part): part is string => typeof part === 'string' && part.trim().length > 0)\n .join('\\n\\n')\n const res = scope.spawn(child, { task, handle, messages, steer } as ShotTask, {\n budget: perChild(innerTurns),\n label: `shot:${shots}`,\n })\n if (!res.ok) break\n const settled = await drainOne(scope)\n if (settled.kind === 'down') break\n const out = settled.out as unknown as StrategyShotResult\n messages = out.messages\n completions += out.completions\n progression.push(out.score)\n if (out.score >= 1 || shots === cfg.maxShots - 1) break\n // Analyst reads the trajectory (firewalled) → steer the resumed session.\n const aChild = leaf(`analyst:${shots}`, 'analyst')\n const aRes = scope.spawn(\n aChild,\n { task, messages },\n { budget: perChild(1), label: `analyst:${shots}` },\n )\n if (!aRes.ok) break\n const aSettled = await drainOne(scope)\n completions += 1\n if (aSettled.kind === 'down') break\n const findings = aSettled.out as unknown as string\n if (/^\\s*COMPLETE\\b/i.test(findings)) break\n pendingSteer = `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`\n }\n const final = await surface.score(task, handle)\n const score = final.total > 0 ? final.passes / final.total : 0\n return {\n kind: 'done',\n deliverable: {\n mode: 'depth',\n score,\n resolved: final.total > 0 && final.passes === final.total,\n completions,\n progression,\n shots: shots + 1,\n },\n }\n } finally {\n await surface.close(handle)\n }\n },\n }\n}\n\n/** BREADTH: K independent rollouts (each own artifact), verifier picks the best. */\nexport function breadthStrategy(\n _surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n cfg: { width: number },\n): Agent<unknown, Outcome<unknown>> {\n const innerTurns = opts.innerTurns ?? 4\n return {\n name: 'breadth',\n async act(_t, scope): Promise<Outcome<unknown>> {\n let opened = 0\n for (let k = 0; k < cfg.width; k += 1) {\n const res = scope.spawn(leaf(`rollout:${k}`, 'shot'), { task } as ShotTask, {\n budget: perChild(innerTurns),\n label: `rollout:${k}`,\n })\n if (res.ok) opened += 1\n }\n if (opened === 0) return { kind: 'blocked', blockers: ['breadth: pool admitted no rollout'] }\n let best = -1\n let bestResolved = false\n let completions = 0\n const progression: number[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n if (s.kind === 'down') continue\n const out = s.out as unknown as StrategyShotResult\n completions += out.completions\n if (out.score > best) best = out.score\n if (out.total > 0 && out.passes === out.total) bestResolved = true\n progression.push(best)\n }\n if (best < 0) return { kind: 'blocked', blockers: ['breadth: every rollout went down'] }\n return {\n kind: 'done',\n deliverable: {\n mode: 'breadth',\n score: best,\n resolved: bestResolved,\n completions,\n progression,\n shots: opened,\n },\n }\n },\n }\n}\n\n/**\n * A Strategy is HOW you spend the compute budget to beat the Environment's check — it\n * builds the driver `Agent` the Supervisor runs. This is the OPEN extension point: a dev\n * authors their own by implementing `driver()` to return an Agent whose `act()` spawns\n * shots/analysts via `scope.spawn` / `scope.next` / `scope.send`. The two built-ins are\n * the reference implementations to copy:\n * sample — K INDEPENDENT attempts, keep the best-verifying (best-of-N / resample).\n * refine — attempt → observe() reads the trace → steer the next → repeat (iterate).\n * (A multi-agent \"team\" is just a Strategy whose driver spawns several different agents.)\n */\ndeclare const strategyResult: unique symbol\n\nexport interface Strategy<Result extends StrategyResult = StrategyResult> {\n readonly name: string\n /** @internal Associates a strategy with its typed result without adding a runtime field. */\n readonly [strategyResult]?: Result\n driver(\n surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n budget: number,\n ): Agent<unknown, Outcome<unknown>>\n}\n\n/** Built-in `Strategy`: K independent attempts, keep the best-verifying (best-of-N / resample). */\nexport const sample: Strategy = {\n name: 'sample',\n driver: (surface, task, opts, budget) => breadthStrategy(surface, task, opts, { width: budget }),\n}\n/** Built-in `Strategy`: attempt → `observe()` reads the trace → steer the next attempt → repeat (deepen one lineage). */\nexport const refine: Strategy = {\n name: 'refine',\n driver: (surface, task, opts, budget) => depthStrategy(surface, task, opts, { maxShots: budget }),\n}\n\n// ── The composable LEGO: author a strategy in ~15 lines from two steps ───────────\n//\n// A strategy body gets `shot()` (run one worker attempt over an artifact) and\n// `critique()` (the firewalled analyst reads the trace → a steer). Compose them — no\n// Supervisor/Scope ceremony. This is the skillifiable unit: an agent can emit a\n// `defineStrategy(name, body)` of a few step-calls; it can't reliably emit a 70-line\n// driver. (depthStrategy/breadthStrategy are the hand-written reference impls; refine/sample\n// stay on them — proven — while NEW strategies are authored compactly here.)\n\n/** A role for one shot — multi-agent loops (researcher + engineer, a panel of k\n * researchers) give each shot its own system prompt and optionally its own model. */\nexport interface ShotPersona {\n /** Replaces the task's systemPrompt for a FRESH shot; on a carried conversation it is\n * injected as a hand-off message (the transcript's earlier roles stay intact). */\n systemPrompt?: string\n /** Per-shot model override (e.g. a stronger model for the engineer shot). */\n model?: string\n}\n\nexport interface ShotSpec {\n /** present ⇒ continue this artifact (depth); absent ⇒ the shot opens a fresh one (sample/restart). */\n handle?: ArtifactHandle\n messages?: StrategyMessage[]\n steer?: string\n persona?: ShotPersona\n /** Restrict THIS shot to a subset of the domain's tools (by name) — focus a shot on\n * the relevant capabilities. Restriction-only; unknown names throw. Omitted ⇒ all. */\n tools?: string[]\n}\nexport interface StrategyResult {\n score: number\n resolved: boolean\n completions: number\n progression: number[]\n shots: number\n}\n/** Artifact lifecycle a strategy may manage itself — open/close ONLY. Raw `call`/`score`\n * are withheld: scores reach the body solely through `shot()`'s StrategyShotResult (the\n * harness-verified channel), so a body cannot peek the check or fabricate around it. */\nexport interface StrategyArtifacts {\n readonly name: string\n open(task: AgenticTask): Promise<ArtifactHandle>\n close(handle: ArtifactHandle): Promise<void>\n}\n\n/** What a strategy body composes with: the artifact lifecycle, the budget, and the two steps. */\nexport interface StrategyCtx {\n /** Open/close artifacts the body manages itself (e.g. one persistent handle for depth). */\n readonly surface: StrategyArtifacts\n readonly task: AgenticTask\n readonly opts: AgenticOptions\n readonly budget: number\n readonly scope: Scope<Outcome<unknown>>\n /** Run ONE worker shot; its harness-scored result, or null if it went down. */\n shot(spec?: ShotSpec): Promise<StrategyShotResult | null>\n /** The firewalled critic reads the trajectory → a steer string, or null on COMPLETE/down. */\n critique(messages: StrategyMessage[]): Promise<string | null>\n /** The RAW analyst channel: the firewalled critic answers `instruction` over the\n * trajectory verbatim — no findings extraction, so verdict-shaped formats\n * (CONTINUE/STOP decisions, calibrated predictions) survive. Same firewall:\n * trajectory in, never scores. Null when the analyst went down. */\n consult(messages: StrategyMessage[], instruction: string): Promise<string | null>\n /** The tools THIS artifact's task actually offers (names + descriptions only — never\n * the implementations). Tool sets vary per task on heterogeneous domains; a strategy\n * that restricts shots MUST select from this list, never from hardcoded names. */\n listTools(handle: ArtifactHandle): Promise<Array<{ name: string; description?: string }>>\n}\n\n/** Author a Strategy from the composable steps — the open, compact way. */\nexport function defineStrategy<Result extends StrategyResult>(\n name: string,\n run: (ctx: StrategyCtx) => Promise<Result>,\n): Strategy<Result> {\n return {\n name,\n driver: (surface, task, opts, budget) => ({\n name,\n async act(_t, scope): Promise<Outcome<unknown>> {\n let seq = 0\n const innerTurns = opts.innerTurns ?? 4\n // HARNESS-VERIFIED scoring: the deliverable score is computed HERE from the shots\n // the harness actually brokered + scored via surface.score() — NEVER the value the\n // (possibly authored / adversarial) body returns. An authored strategy cannot\n // fabricate a win; it can only report what its real shots achieved. Keep-best.\n let verifiedBest = 0\n let verifiedResolved = false\n // Close is IDEMPOTENT by construction for the body: authored code double-closes\n // (often as a floating promise inside a finally), and a second close must be a\n // no-op rather than a domain error that escapes as an unhandled rejection and\n // kills the whole benchmark run. A close failure on a LIVE handle still throws.\n const openHandles = new Set<string>()\n const ctx: StrategyCtx = {\n // Narrowed to open/close — the body gets no raw call()/score() access.\n surface: {\n name: surface.name,\n open: async (t) => {\n const h = await surface.open(t)\n openHandles.add(h.id)\n return h\n },\n close: async (h) => {\n if (!h || !openHandles.has(h.id)) return\n openHandles.delete(h.id)\n await surface.close(h)\n },\n },\n task,\n opts,\n budget,\n scope,\n async shot(spec) {\n const child = leaf(`shot:${seq}`, 'shot')\n seq += 1\n const res = scope.spawn(\n child,\n {\n task,\n handle: spec?.handle,\n messages: spec?.messages,\n steer: spec?.steer,\n persona: spec?.persona,\n tools: spec?.tools,\n } as ShotTask,\n { budget: perChild(innerTurns), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n const out = settled.out as unknown as StrategyShotResult\n if (out.score > verifiedBest) verifiedBest = out.score\n if (out.total > 0 && out.passes === out.total) verifiedResolved = true\n return out\n },\n async listTools(handle) {\n const tools = await surface.tools(task, handle)\n return tools.map((t) => ({\n name: t.function.name,\n ...(t.function.description ? { description: t.function.description } : {}),\n }))\n },\n async critique(messages) {\n const child = leaf(`analyst:${seq}`, 'analyst')\n seq += 1\n const res = scope.spawn(\n child,\n { task, messages },\n { budget: perChild(1), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n const findings = settled.out as unknown as string\n return /^\\s*COMPLETE\\b/i.test(findings) ? null : findings\n },\n async consult(messages, instruction) {\n const child = leaf(`analyst:${seq}`, 'analyst')\n seq += 1\n const res = scope.spawn(\n child,\n { task, messages, rawInstruction: instruction },\n { budget: perChild(1), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n return settled.out as unknown as string\n },\n }\n const r = await run(ctx)\n // Override the body's self-reported score/resolved with the harness-verified\n // values. The body's progression/completions/shots are advisory (display only) —\n // but NORMALIZED: an authored body that omits them must not poison downstream\n // consumers (losses tables, anytime curves) with undefined.\n return {\n kind: 'done',\n deliverable: {\n mode: name,\n ...r,\n progression: Array.isArray(r.progression) ? r.progression : [],\n completions: typeof r.completions === 'number' ? r.completions : 0,\n shots: typeof r.shots === 'number' ? r.shots : 0,\n score: verifiedBest,\n resolved: verifiedResolved,\n },\n }\n },\n }),\n }\n}\n\n/** A NEW strategy, authored from the steps (~20 lines): refine, but when a steered shot\n * fails to improve the score it ABANDONS that line and restarts fresh (branch-when-stuck)\n * — the widen/MCTS idea the depth-stuck failure motivated. Scored keep-best (the best\n * checkpoint across all lines), the deployable metric. This is the \"experts build BETTER\n * optimizations\" path: a new technique, compact, with zero Supervisor ceremony. */\nexport const adaptiveRefine = defineStrategy(\n 'adaptiveRefine',\n async ({ surface, task, budget, shot, critique }) => {\n let handle = await surface.open(task)\n const progression: number[] = []\n let messages: StrategyMessage[] | undefined\n let steer: string | undefined\n let completions = 0\n let best = -1\n let shots = 0\n try {\n for (shots = 0; shots < budget; shots += 1) {\n const out = await shot({ handle, messages, steer })\n if (!out) break\n completions += out.completions\n progression.push(out.score)\n if (out.score >= 1) break\n if (out.score <= best) {\n // Stuck: steering isn't improving this line — abandon it, restart fresh.\n await surface.close(handle)\n handle = await surface.open(task)\n messages = undefined\n steer = undefined\n continue\n }\n best = out.score\n messages = out.messages\n const findings = await critique(out.messages)\n completions += 1\n if (!findings) break\n steer = `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`\n }\n const score = progression.length ? Math.max(...progression) : 0\n return { score, resolved: score >= 1, completions, progression, shots }\n } finally {\n await surface.close(handle)\n }\n },\n)\n\n/** The explore-then-exploit MIX: spend ⌈budget/2⌉ on independent samples (kept open),\n * then refine the best-verifying line with the remaining budget. Sample's basin escape +\n * refine's accumulation — the third built-in, authored from the public steps. */\nexport const sampleThenRefine = defineStrategy(\n 'sampleThenRefine',\n async ({ surface, task, budget, shot, critique }) => {\n const explore = Math.max(1, Math.ceil(budget / 2))\n const open = new Set<ArtifactHandle>()\n const progression: number[] = []\n let completions = 0\n let shots = 0\n try {\n // Explore: independent lines on handles we own (kept open so the best can continue).\n let best: { handle: ArtifactHandle; out: StrategyShotResult } | undefined\n for (let i = 0; i < explore; i += 1) {\n const handle = await surface.open(task)\n open.add(handle)\n const out = await shot({ handle })\n if (!out) continue\n shots += 1\n completions += out.completions\n progression.push(out.score)\n if (!best || out.score > best.out.score) best = { handle, out }\n if (out.score >= 1) break\n }\n if (!best) return { score: 0, resolved: false, completions, progression, shots }\n // Exploit: close the losers, refine the winner with the remaining budget.\n for (const h of [...open]) {\n if (h !== best.handle) {\n await surface.close(h)\n open.delete(h)\n }\n }\n let messages = best.out.messages\n let topScore = best.out.score\n for (let i = explore; i < budget && topScore < 1; i += 1) {\n const findings = await critique(messages)\n completions += 1\n if (!findings) break\n const out = await shot({\n handle: best.handle,\n messages,\n steer: `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`,\n })\n if (!out) break\n shots += 1\n completions += out.completions\n progression.push(out.score)\n messages = out.messages\n if (out.score > topScore) topScore = out.score\n }\n const score = progression.length ? Math.max(...progression) : 0\n return { score, resolved: score >= 1, completions, progression, shots }\n } finally {\n for (const h of open) await surface.close(h)\n }\n },\n)\n\nexport interface RunAgenticOptions<Result extends StrategyResult = StrategyResult>\n extends AgenticOptions {\n surface: AgenticSurface\n task: AgenticTask\n /** Lifecycle observability — every spawn/settle (shots, analysts) streams here live.\n * The seam online watchdogs/route-auditors subscribe to. */\n hooks?: RuntimeHooks\n /** A Strategy (the open way) — author/pass your own. Overrides `mode` when present. */\n strategy?: Strategy<Result>\n /** Built-in shorthand: 'depth'→refine, 'breadth'→sample. Default 'depth'. */\n mode?: 'depth' | 'breadth'\n /** budget: refine→max shots; sample→rollout width. */\n budget: number\n rootBudget?: Budget\n}\n\n/** Run a Strategy through the keystone Supervisor — `Agent.act` over a conserved-budget Scope. */\nexport async function runAgentic<Result extends StrategyResult = StrategyResult>(\n opts: RunAgenticOptions<Result>,\n): Promise<AgenticRunResult & Result> {\n const strategy: Strategy = opts.strategy ?? (opts.mode === 'breadth' ? sample : refine)\n const driver = strategy.driver(opts.surface, opts.task, opts, opts.budget)\n const supervisor = createSupervisor<unknown, Outcome<unknown>>()\n const root: Budget = opts.rootBudget ?? {\n maxIterations: opts.budget * ((opts.innerTurns ?? 4) + 2),\n maxTokens: 1_000_000_000,\n }\n const started = Date.now()\n const result = await supervisor.run(driver, undefined, {\n budget: root,\n runId: `agentic:${strategy.name}:${opts.task.id}`,\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: agenticRegistry(opts.surface, opts),\n maxDepth: 3,\n ...(opts.hooks ? { hooks: opts.hooks } : {}),\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const reason =\n result.kind === 'winner'\n ? `blocked: ${(result.out as { blockers?: string[] }).blockers?.join('; ')}`\n : `no-winner: ${result.reason}`\n throw new Error(`runAgentic(${strategy.name}) produced no result — ${reason}`)\n }\n // Drivers deliver the strategy outcome; the cost vector is stamped here from `result.spentTotal`\n // (the journal aggregate: settled child work + metered driver inference) + wall clock.\n const core = result.out.deliverable as Omit<AgenticRunResult & Result, 'usd' | 'ms' | 'tokens'>\n return {\n ...core,\n usd: result.spentTotal.usd,\n tokens: result.spentTotal.tokens,\n ms: Date.now() - started,\n } as AgenticRunResult & Result\n}\n","/**\n * structuralRollout — the measured structural lever as a fourth member of the\n * sample/refine/sampleThenRefine strategy family: k independent samples, selection by\n * TASK-VISIBLE checks only, then a guarded self-repair loop steered by the checks'\n * failure output. Design: docs/design/structural-rollout-integration.md; measured basis\n * (bench/src/hev-structural.mts, bench/src/mbpp-structural.mts): +8.5..+21.3pp hidden-test\n * lift across Llama-3-8B/Qwen2.5-7B × HumanEval/MBPP, null only at saturation.\n *\n * Honesty invariants carried over from the proven rigs:\n * - Visible checks are generated from task-visible information only, BEFORE any\n * candidate exists, and FROZEN for every sample and repair round of the task.\n * - OFFICIAL checks (shown in the task itself) rank lexicographically above\n * model-AUTHORED guesses. This ordering is measured, not stylistic: authored guesses\n * run 17–70% wrong depending on model × spec richness, and unweighted they flipped\n * selection NEGATIVE on MBPP (6 noisy guesses outvoting the one reliable check).\n * - A candidate that crashed before the checks could run ranks below one that ran and\n * failed everything.\n * - Repair sees ONLY the checks' failure output, and never displaces a candidate that\n * passes more official checks with one that passes fewer (wrong visible examples\n * poison repair at saturation — the glm /47,/116 regressions).\n *\n * Placement rule: this is an INFERENCE-TIME capability (it wraps the model call via the\n * strategy seam). It does not belong in `improve()` (training-time); `improve()`\n * may later tune `StructuralRolloutPolicy` as an optimizable surface.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport {\n type AgenticTask,\n defineStrategy,\n type Strategy,\n type StrategyCtx,\n type StrategyResult,\n} from './strategy'\nimport type { SelectionReceipt } from './types'\n\n/** Provider-neutral conversation records read by structural candidate extraction. */\nexport type StructuralRolloutMessage = Record<string, unknown>\n\n// ── Policy ────────────────────────────────────────────────────────────────────────\n\n/** The rollout's compute recipe — promoted from the proven rigs' env vars (K/REPAIRS/\n * TESTGEN/DIVERSE/TEMPERATURE). Defaults are the measured sweet spot: repair value\n * concentrates at low k (~+12pp at k=1, +1–3pp at k=5), so `k=5, repairRounds=2` is the\n * full recipe and `k=1, repairRounds=2` the low-compute preset. */\nexport interface StructuralRolloutPolicy {\n /** Independent samples per task (selection breadth). */\n k: number\n /** Repair shots after selection, each steered by the checks' failure output. */\n repairRounds: number\n /** Model-authored visible checks requested per task; 0 disables authoring. */\n testgen: number\n /** Per-slot strategy-lens prefixes on the k samples (attacks the all-k-fail bucket).\n * Measured as a paired null (+0.6pp) — kept as an optional knob, off by default. */\n diverse?: boolean\n /** Sampling temperature for every shot of this strategy; omitted ⇒ the worker default. */\n temperature?: number\n}\n\n/** The measured default recipe: 5 samples, 2 guarded repair rounds, 6 authored checks. */\nexport const defaultStructuralRolloutPolicy: StructuralRolloutPolicy = {\n k: 5,\n repairRounds: 2,\n testgen: 6,\n}\n\nfunction resolvePolicy(overrides?: Partial<StructuralRolloutPolicy>): StructuralRolloutPolicy {\n const policy = { ...defaultStructuralRolloutPolicy, ...overrides }\n if (!Number.isInteger(policy.k) || policy.k < 1) {\n throw new Error(`structuralRollout: policy.k must be an integer >= 1, got ${policy.k}`)\n }\n if (!Number.isInteger(policy.repairRounds) || policy.repairRounds < 0) {\n throw new Error(\n `structuralRollout: policy.repairRounds must be an integer >= 0, got ${policy.repairRounds}`,\n )\n }\n if (!Number.isInteger(policy.testgen) || policy.testgen < 0) {\n throw new Error(\n `structuralRollout: policy.testgen must be an integer >= 0, got ${policy.testgen}`,\n )\n }\n return policy\n}\n\n// ── Visible checks: the CheckSource seam (the only net-new seam of the design) ──────\n\n/** One task-visible executable check (e.g. a single-line Python assert). */\nexport interface VisibleCheck {\n code: string\n /** 'official' = shown in the task itself (docstring example, shown assert);\n * 'authored' = the model's own guess. Official outranks authored in selection. */\n kind: 'official' | 'authored'\n}\n\n/** What a CheckSource composes with. `consult` is the strategy family's raw analyst\n * channel (metered by the conserved pool, offline-injectable via `opts.complete`) —\n * check authoring goes through it rather than a bespoke model client. */\nexport interface CheckSourceCtx {\n /** Authored-check budget for this task (`policy.testgen`). */\n count: number\n /** The symbol authored checks must reference; undefined ⇒ authoring is skipped\n * (no guesses beats guesses pinned to nothing). */\n entrySymbol?: string\n /** One metered LLM call: instruction in, reply text out, null when the channel went\n * down. The task's visible prompt is included by the channel itself. */\n consult(instruction: string): Promise<string | null>\n}\n\n/** Produces the task's visible checks. MUST derive them from agent-visible information\n * only, before any candidate exists — the strategy freezes the returned set for every\n * sample and repair round of the task. */\nexport interface CheckSource {\n generate(task: AgenticTask, ctx: CheckSourceCtx): Promise<VisibleCheck[]>\n}\n\nconst authorInstruction = (count: number, entry: string) =>\n `Read the task below. Write exactly ${count} single-line assert statements that test the ` +\n `function \\`${entry}\\`, based ONLY on the behavior the task itself describes. Each assert ` +\n `must be one physical line of the form \\`assert ${entry}(...) == expected\\` (or a True/False ` +\n 'check). Do NOT implement the function. Do NOT copy shown examples verbatim if you can test ' +\n 'other cases too. Output ONLY the assert lines inside a single ```python code block.'\n\n/** The proven authored-assert filter (lifted from the rigs' generateTests): keep only\n * single-line, paren-balanced asserts that reference the entry symbol — malformed lines\n * are dropped here rather than poisoning every candidate's score identically. */\nexport function filterAuthoredAsserts(reply: string, entrySymbol: string, count: number): string[] {\n const fences = [...reply.matchAll(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/gi)].map((m) =>\n (m[1] ?? '').trim(),\n )\n const block = fences.length > 0 ? fences.join('\\n') : reply\n const balanced = (s: string) => {\n let d = 0\n for (const ch of s) {\n if (ch === '(' || ch === '[' || ch === '{') d += 1\n else if (ch === ')' || ch === ']' || ch === '}') d -= 1\n if (d < 0) return false\n }\n return d === 0\n }\n return block\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.startsWith('assert ') && l.includes(entrySymbol) && balanced(l))\n .slice(0, count)\n}\n\n/** Default authored-check source: one metered LLM call per task, before sampling,\n * filtered through `filterAuthoredAsserts`. Returns [] (no signal, never a fabricated\n * check) when the budget is 0, no entry symbol resolves, or the channel went down. */\nexport function modelAuthoredChecks(overrides: { count?: number } = {}): CheckSource {\n return {\n async generate(_task, ctx): Promise<VisibleCheck[]> {\n const count = overrides.count ?? ctx.count\n if (count <= 0 || !ctx.entrySymbol) return []\n const entry = ctx.entrySymbol\n const reply = await ctx.consult(authorInstruction(count, entry))\n if (!reply) return []\n return filterAuthoredAsserts(reply, entry, count).map((code) => ({\n code,\n kind: 'authored' as const,\n }))\n },\n }\n}\n\n/** Official checks the surface stashed on the task (e.g. MBPP's shown assert). Reads\n * `task.meta[key]` as a string array; anything else means no official checks. */\nexport function officialChecksFromMeta(key = 'visibleChecks'): CheckSource {\n return {\n async generate(task): Promise<VisibleCheck[]> {\n const raw = task.meta?.[key]\n if (!Array.isArray(raw)) return []\n return raw\n .filter((c): c is string => typeof c === 'string' && c.trim().length > 0)\n .map((code) => ({ code, kind: 'official' as const }))\n },\n }\n}\n\n/** Concatenate check sources (official first by convention — ordering does not affect\n * scoring, which reads each check's `kind`). */\nexport function composeCheckSources(...sources: CheckSource[]): CheckSource {\n return {\n async generate(task, ctx): Promise<VisibleCheck[]> {\n const all: VisibleCheck[] = []\n for (const source of sources) all.push(...(await source.generate(task, ctx)))\n return all\n },\n }\n}\n\n/** The symbol authored checks are pinned to: `task.meta.entryPoint` when the surface\n * provides it, else the LAST `def name(` in the visible prompt (a code-completion stub\n * lists helpers first, the entry stub last). Undefined ⇒ authoring is skipped. */\nexport function resolveEntrySymbol(task: AgenticTask): string | undefined {\n const meta = task.meta?.entryPoint\n if (typeof meta === 'string' && meta.trim().length > 0) return meta.trim()\n const defs = [...task.userPrompt.matchAll(/(?:^|\\n)\\s*def\\s+([A-Za-z_]\\w*)\\s*\\(/g)]\n const last = defs[defs.length - 1]\n return last?.[1]\n}\n\n// ── Check execution: the CheckRunner seam ────────────────────────────────────────────\n\n/** How one candidate fared against the frozen visible checks, split by check kind. */\nexport interface CheckOutcome {\n passedOfficial: number\n totalOfficial: number\n passedAuthored: number\n totalAuthored: number\n /** The checks' failure report — the ONLY feedback the repair loop may see. */\n failureOutput: string\n /** True when the candidate crashed before any check could run — ranks below a\n * candidate that ran and failed everything. */\n crashed?: boolean\n}\n\n/** Minimal exec channel the default runner needs. `SandboxInstance` (and therefore\n * `ValidationCtx.box`) satisfies it structurally. */\nexport interface CheckExecChannel {\n exec(\n command: string,\n options?: { timeoutMs?: number },\n ): Promise<{ exitCode: number; stdout: string; stderr: string }>\n}\n\nexport interface CheckRunContext {\n task: AgenticTask\n /** Live exec channel for this run (`ValidationCtx.box` / a sandbox instance). */\n box?: CheckExecChannel\n signal?: AbortSignal\n}\n\n/** Executes the frozen checks against one candidate. Implementations MUST fail loud\n * (throw) when they cannot execute — a silent zero poisons selection. */\nexport interface CheckRunner {\n run(candidate: string, checks: VisibleCheck[], ctx: CheckRunContext): Promise<CheckOutcome>\n}\n\n/** The check program (mirrors the rigs' visible-check judge): candidate executes at\n * module level, then each check runs INDIVIDUALLY in try/except so one malformed line\n * cannot zero the rest; the summary line carries a per-call NONCE so a candidate\n * printing a forged summary cannot be parsed as the verdict. */\nfunction buildCheckProgram(\n candidate: string,\n official: string[],\n authored: string[],\n nonce: string,\n): string {\n const officialB64 = Buffer.from(JSON.stringify(official), 'utf8').toString('base64')\n const authoredB64 = Buffer.from(JSON.stringify(authored), 'utf8').toString('base64')\n return `${candidate}\\n\nimport base64 as _b64, json as _json, sys as _sys\n_official = _json.loads(_b64.b64decode(\"${officialB64}\").decode(\"utf8\"))\n_authored = _json.loads(_b64.b64decode(\"${authoredB64}\").decode(\"utf8\"))\n_lines = []\ndef _run(_tests):\n _att, _fail = 0, 0\n for _t in _tests:\n _att += 1\n try:\n exec(_t, dict(globals()))\n except Exception as _e:\n _fail += 1\n _lines.append(\"CHECK FAILED: %s -> %s: %s\" % (_t.strip()[:200], type(_e).__name__, str(_e)[:200]))\n return _att, _fail\n_o_att, _o_fail = _run(_official)\n_a_att, _a_fail = _run(_authored)\nprint(\"SRCK-${nonce} official=%d/%d authored=%d/%d\" % (_o_att - _o_fail, _o_att, _a_att - _a_fail, _a_att))\n_sys.stdout.write(\"\\\\n\".join(_lines)[-1500:])\n_sys.exit(0 if (_o_fail + _a_fail) == 0 and (_o_att + _a_att) > 0 else 1)\n`\n}\n\n/** Default CheckRunner backend: pipes the check program into `python3` over the sandbox\n * exec channel (`ctx.box`, or one bound at construction). Never shells out to docker\n * itself — the jail is the sandbox's concern. No channel ⇒ throws; it must never\n * silently score 0. Empty check sets short-circuit to a no-signal outcome (nothing to\n * execute, so no channel is required). */\nexport function sandboxCheckRunner(\n options: { box?: CheckExecChannel; python?: string; timeoutMs?: number } = {},\n): CheckRunner {\n const python = options.python ?? 'python3'\n const timeoutMs = options.timeoutMs ?? 20000\n return {\n async run(candidate, checks, ctx): Promise<CheckOutcome> {\n if (checks.length === 0) {\n return {\n passedOfficial: 0,\n totalOfficial: 0,\n passedAuthored: 0,\n totalAuthored: 0,\n failureOutput: '',\n }\n }\n const box = ctx.box ?? options.box\n if (!box) {\n throw new Error(\n 'sandboxCheckRunner: no execution channel — bind one via sandboxCheckRunner({ box }) ' +\n 'or CheckRunContext.box (ValidationCtx.box / a sandbox instance). Refusing to score ' +\n 'without executing: a silent 0 would poison selection.',\n )\n }\n const nonce = randomBytes(8).toString('hex')\n const official = checks.filter((c) => c.kind === 'official').map((c) => c.code)\n const authored = checks.filter((c) => c.kind === 'authored').map((c) => c.code)\n const program = buildCheckProgram(candidate, official, authored, nonce)\n const b64 = Buffer.from(program, 'utf8').toString('base64')\n const r = await box.exec(`printf '%s' '${b64}' | base64 -d | ${python} -`, { timeoutMs })\n const summary = new RegExp(\n `SRCK-${nonce} official=(\\\\d+)/(\\\\d+) authored=(\\\\d+)/(\\\\d+)`,\n ).exec(r.stdout)\n if (!summary) {\n // The candidate crashed (or hung) before the check scaffold could report.\n const detail =\n (r.stderr || r.stdout).slice(-1500) ||\n 'no output (crashed or timed out before the checks could run)'\n return {\n passedOfficial: 0,\n totalOfficial: 0,\n passedAuthored: 0,\n totalAuthored: 0,\n failureOutput: detail,\n crashed: true,\n }\n }\n // Strip the sentinel line from repair feedback — the model must never learn the\n // summary format it could try to forge.\n const failureOutput = r.stdout.replace(summary[0], '').slice(-1500).trim()\n return {\n passedOfficial: Number(summary[1]),\n totalOfficial: Number(summary[2]),\n passedAuthored: Number(summary[3]),\n totalAuthored: Number(summary[4]),\n failureOutput,\n }\n },\n }\n}\n\n// ── Selection order (measured, not stylistic) ────────────────────────────────────────\n\nconst frac = (passed: number, total: number) => (total > 0 ? passed / total : 0)\n\n/** The selection order: crash < ran; then official pass-fraction; authored guesses only\n * break ties. Returns > 0 when `a` outranks `b`. Strictly lexicographic — on MBPP,\n * letting 6 noisy guesses outvote the one official check flipped selection negative. */\nexport function compareCheckOutcomes(a: CheckOutcome, b: CheckOutcome): number {\n const aCrashed = a.crashed === true\n const bCrashed = b.crashed === true\n if (aCrashed !== bCrashed) return aCrashed ? -1 : 1\n if (aCrashed) return 0\n const official = frac(a.passedOfficial, a.totalOfficial) - frac(b.passedOfficial, b.totalOfficial)\n if (official !== 0) return official\n return frac(a.passedAuthored, a.totalAuthored) - frac(b.passedAuthored, b.totalAuthored)\n}\n\n/** Display scalar for receipts/reports (the rigs' `visibleScore` shape): crash = -1,\n * else official fraction + 0.001 × authored fraction. Selection itself uses the exact\n * lexicographic comparator, never this scalar. */\nexport function visibleCheckScore(o: CheckOutcome): number {\n if (o.crashed) return -1\n return frac(o.passedOfficial, o.totalOfficial) + 0.001 * frac(o.passedAuthored, o.totalAuthored)\n}\n\n/** Argmax by `compareCheckOutcomes`, FIRST index wins ties (deterministic; with zero\n * visible coverage every candidate ties at no-signal and index 0 is the blind pick). */\nexport function selectBestIndex(outcomes: ReadonlyArray<CheckOutcome>): number {\n let best = 0\n for (let i = 1; i < outcomes.length; i += 1) {\n if (compareCheckOutcomes(outcomes[i] as CheckOutcome, outcomes[best] as CheckOutcome) > 0) {\n best = i\n }\n }\n return best\n}\n\n/** The repair keep-best guard: a challenger displaces the incumbent only when it is\n * strictly better in the selection order AND passes at least as many official checks.\n * The raw-count clause is deliberate belt-and-braces over the comparator (a custom\n * runner can report shifted totals): repair must NEVER replace a candidate that passes\n * more official checks with one that passes fewer. */\nexport function canDisplace(challenger: CheckOutcome, incumbent: CheckOutcome): boolean {\n if (challenger.crashed === true) return false\n if (challenger.passedOfficial < incumbent.passedOfficial) return false\n return compareCheckOutcomes(challenger, incumbent) > 0\n}\n\nconst totalChecks = (o: CheckOutcome) => o.totalOfficial + o.totalAuthored\n\nconst passesAllChecks = (o: CheckOutcome) =>\n o.crashed !== true &&\n totalChecks(o) > 0 &&\n o.passedOfficial === o.totalOfficial &&\n o.passedAuthored === o.totalAuthored\n\n// ── Candidate extraction ─────────────────────────────────────────────────────────────\n\n/** The candidate a shot produced, read from its conversation: the LAST `submit_answer`\n * tool-call argument (verifier environments submit the artifact explicitly), else the\n * latest assistant reply's fenced code block — preferring a block containing a `def`,\n * because repair replies echo the failure report in a bare fence BEFORE the fixed code\n * (the rigs' extractRepairCode lesson) — else the latest non-empty assistant text. */\nexport function defaultExtractCandidate(messages: ReadonlyArray<StructuralRolloutMessage>): string {\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const calls = messages[i]?.tool_calls as\n | Array<{ function?: { name?: string; arguments?: string } }>\n | undefined\n if (!calls) continue\n for (let j = calls.length - 1; j >= 0; j -= 1) {\n const call = calls[j]\n if (call?.function?.name !== 'submit_answer') continue\n try {\n const args = JSON.parse(call.function.arguments ?? '{}') as { answer?: unknown }\n if (typeof args.answer === 'string' && args.answer.trim()) return args.answer.trim()\n } catch {\n /* malformed arguments — keep scanning */\n }\n }\n }\n const contents: string[] = []\n for (const m of messages) {\n if (m.role === 'assistant' && typeof m.content === 'string' && m.content.trim()) {\n contents.push(m.content)\n }\n }\n const fencesOf = (text: string) =>\n [...text.matchAll(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/gi)].map((m) => (m[1] ?? '').trim())\n for (let i = contents.length - 1; i >= 0; i -= 1) {\n const fences = fencesOf(contents[i] as string)\n for (let j = fences.length - 1; j >= 0; j -= 1) {\n if (/(^|\\n)\\s*def\\s+\\w+/.test(fences[j] as string)) return fences[j] as string\n }\n }\n for (let i = contents.length - 1; i >= 0; i -= 1) {\n const fences = fencesOf(contents[i] as string)\n if (fences.length > 0) return fences[fences.length - 1] as string\n }\n return (contents[contents.length - 1] ?? '').trim()\n}\n\n// ── The strategy ─────────────────────────────────────────────────────────────────────\n\n/** Per-slot approach lenses for `diverse` mode — copied from bench/src/directives.ts\n * (the measured rig plumbing; a paired null there, kept as an optional knob). */\nconst DIVERSE_LENSES: ReadonlyArray<string> = [\n 'Answer directly and decisively from what you already know. State the single best answer without hedging.',\n 'Decompose the question into the sub-facts it depends on. Establish each sub-fact explicitly, then compose them into the answer.',\n 'Reason from first principles. Ignore the most obvious or popular guess; derive the answer from underlying facts and relationships.',\n 'Name the most plausible WRONG answer and the trap that makes it tempting. Rule it out, then commit to the answer that survives.',\n]\n\nfunction slotLens(slot: number): string {\n const lens = DIVERSE_LENSES[slot % DIVERSE_LENSES.length] as string\n const tag =\n slot < DIVERSE_LENSES.length ? '' : ` (variant ${Math.floor(slot / DIVERSE_LENSES.length) + 1})`\n return `${lens}${tag}`\n}\n\nfunction repairSteer(outcome: CheckOutcome): string {\n return [\n 'Your latest solution failed some of the task-visible checks.',\n 'Result of running the visible checks against it:',\n '```',\n outcome.failureOutput.trim() || '(the code crashed before the checks could run)',\n '```',\n 'Fix the solution so the visible checks pass. Provide the COMPLETE corrected solution the',\n 'same way you provided the original (same tool or format) — not a fragment or a diff.',\n ].join('\\n')\n}\n\nfunction describeOutcome(label: string, o: CheckOutcome): string {\n if (o.crashed) return `${label}: crashed before the checks could run`\n return (\n `${label}: official ${o.passedOfficial}/${o.totalOfficial}, ` +\n `authored ${o.passedAuthored}/${o.totalAuthored}`\n )\n}\n\nexport type RepairStop =\n | 'already-passing'\n | 'no-signal'\n | 'repaired-pass'\n | 'rounds-exhausted'\n | 'no-candidates'\n\n/** The body's deliverable — a `StrategyResult` plus selection provenance. The extra\n * fields ride through `defineStrategy`'s deliverable spread onto `AgenticRunResult`\n * (score/resolved stay harness-verified, exactly as for every authored strategy). */\nexport interface StructuralRolloutResult extends StrategyResult {\n /** Exact selected candidate text passed to the visible checks, or null when no shot ran. */\n artifact: string | null\n /** One receipt per scored candidate (k samples, then repairs), `SelectionReceipt`\n * shaped like the kernel's (`types.ts`), selector 'driver'. */\n selection: SelectionReceipt[]\n repairStop: RepairStop\n officialChecks: number\n authoredChecks: number\n}\n\nexport interface StructuralRolloutConfig {\n /** Knobs; missing fields take the measured defaults (k=5, repairRounds=2, testgen=6). */\n policy?: Partial<StructuralRolloutPolicy>\n /** Where the visible checks come from. Default: official checks from\n * `task.meta.visibleChecks` composed with `modelAuthoredChecks()`. */\n checkSource?: CheckSource\n /** How candidates are measured. Default `sandboxCheckRunner()` — it needs an exec\n * channel (bind one to the runner, or pass `box` here) and fails loud without one. */\n checkRunner?: CheckRunner\n /** Exec channel threaded into every check run of this strategy (a sandbox instance /\n * `ValidationCtx.box`). The strategy seam itself carries no sandbox, so the caller\n * who owns one supplies it here or binds it into the runner. */\n box?: CheckExecChannel\n /** Candidate extraction from a shot's conversation. Default `defaultExtractCandidate`. */\n extractCandidate?: (messages: ReadonlyArray<StructuralRolloutMessage>) => string\n}\n\n/**\n * Build the structuralRollout `Strategy`: k shots → score each by the frozen visible\n * checks (official above authored, crash lowest) → argmax with first-index tie-break →\n * up to `repairRounds` repair shots steered by the failure output, keep-best under the\n * official-check guard. Authored via `defineStrategy`, so the deliverable score stays\n * harness-verified and every shot is metered by the conserved pool.\n *\n * Budget note: `runAgentic`'s `budget` sizes the pool — pass at least\n * `k + repairRounds + 1` so the samples, repairs, and the check-author consult all admit.\n */\nexport function structuralRollout(\n config: StructuralRolloutConfig = {},\n): Strategy<StructuralRolloutResult> {\n const policy = resolvePolicy(config.policy)\n const checkSource =\n config.checkSource ?? composeCheckSources(officialChecksFromMeta(), modelAuthoredChecks())\n const checkRunner = config.checkRunner ?? sandboxCheckRunner()\n const extract = config.extractCandidate ?? defaultExtractCandidate\n\n const inner = defineStrategy(\n 'structuralRollout',\n async (ctx: StrategyCtx): Promise<StructuralRolloutResult> => {\n const { task, shot } = ctx\n const progression: number[] = []\n const receipts: SelectionReceipt[] = []\n let completions = 0\n let shots = 0\n\n // Freeze the visible checks BEFORE any candidate exists — every sample and repair\n // round is measured against this same set. Authoring goes through the strategy's\n // raw analyst channel, so its spend is metered and the offline transport applies.\n const consult = async (instruction: string): Promise<string | null> => {\n const reply = await ctx.consult([], instruction)\n completions += 1\n return reply\n }\n const entrySymbol = resolveEntrySymbol(task)\n const checks = await checkSource.generate(task, {\n count: policy.testgen,\n ...(entrySymbol ? { entrySymbol } : {}),\n consult,\n })\n const officialChecks = checks.filter((c) => c.kind === 'official').length\n const authoredChecks = checks.length - officialChecks\n const runCtx: CheckRunContext = { task, ...(config.box ? { box: config.box } : {}) }\n\n interface Candidate {\n index: number\n messages: StructuralRolloutMessage[]\n artifact: string\n outcome: CheckOutcome\n shotScore: number\n shotResolved: boolean\n }\n\n // k independent samples, each on its own artifact, scored by the frozen checks.\n const candidates: Candidate[] = []\n for (let i = 0; i < policy.k; i += 1) {\n const out = await shot(policy.diverse ? { steer: slotLens(i) } : undefined)\n if (!out) break // pool starved — select among what settled\n shots += 1\n completions += out.completions\n progression.push(out.score)\n const artifact = extract(out.messages)\n const outcome = await checkRunner.run(artifact, checks, runCtx)\n candidates.push({\n index: candidates.length,\n messages: out.messages,\n artifact,\n outcome,\n shotScore: out.score,\n shotResolved: out.total > 0 && out.passes === out.total,\n })\n }\n if (candidates.length === 0) {\n return {\n score: 0,\n resolved: false,\n completions,\n progression,\n shots,\n artifact: null,\n selection: receipts,\n repairStop: 'no-candidates',\n officialChecks,\n authoredChecks,\n }\n }\n\n // Argmax by the official-first order; first index wins ties (the blind pick when\n // the task has zero visible coverage).\n let best = candidates[selectBestIndex(candidates.map((c) => c.outcome))] as Candidate\n for (const c of candidates) {\n receipts.push({\n candidateIndex: c.index,\n selected: false,\n score: visibleCheckScore(c.outcome),\n reason: describeOutcome('sample', c.outcome),\n selector: 'driver',\n })\n }\n\n // Guarded repair: steered ONLY by the checks' failure output, keep-best, and a\n // repair never displaces a candidate that passes more official checks.\n let seq = candidates.length\n let repairStop: RepairStop = 'already-passing'\n if (!passesAllChecks(best.outcome)) {\n if (best.outcome.crashed !== true && totalChecks(best.outcome) === 0) {\n repairStop = 'no-signal' // no visible checks ⇒ nothing honest to steer on\n } else {\n repairStop = 'rounds-exhausted'\n for (let r = 0; r < policy.repairRounds; r += 1) {\n const out = await shot({ messages: best.messages, steer: repairSteer(best.outcome) })\n if (!out) break\n shots += 1\n completions += out.completions\n progression.push(out.score)\n const artifact = extract(out.messages)\n const outcome = await checkRunner.run(artifact, checks, runCtx)\n const displaced = canDisplace(outcome, best.outcome)\n const label = displaced\n ? 'repair (displaced the incumbent)'\n : outcome.crashed !== true && outcome.passedOfficial < best.outcome.passedOfficial\n ? 'repair (held out: passes fewer official checks than the incumbent)'\n : 'repair (held out: no improvement)'\n receipts.push({\n candidateIndex: seq,\n selected: false,\n score: visibleCheckScore(outcome),\n reason: describeOutcome(label, outcome),\n selector: 'driver',\n })\n if (displaced) {\n best = {\n index: seq,\n messages: out.messages,\n artifact,\n outcome,\n shotScore: out.score,\n shotResolved: out.total > 0 && out.passes === out.total,\n }\n }\n seq += 1\n if (passesAllChecks(best.outcome)) {\n repairStop = 'repaired-pass'\n break\n }\n }\n }\n }\n\n const winner = receipts.find((r) => r.candidateIndex === best.index)\n if (winner) winner.selected = true\n\n return {\n score: best.shotScore,\n resolved: best.shotResolved,\n completions,\n progression,\n shots,\n artifact: best.artifact,\n selection: receipts,\n repairStop,\n officialChecks,\n authoredChecks,\n }\n },\n )\n\n if (policy.temperature === undefined) return inner\n // The shot temperature is an AgenticOptions concern; the policy override threads in at\n // the driver seam so the strategy stays a plain defineStrategy member.\n return {\n name: inner.name,\n driver: (surface, task, opts, budget) =>\n inner.driver(surface, task, { ...opts, temperature: policy.temperature }, budget),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;AAOX,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;AAQX,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK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