@tangle-network/agent-runtime 6.0.5 → 6.0.7

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 (74) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{activation-kpRQffeo.js → activation-Bb2ovvM5.js} +4 -4
  3. package/dist/{activation-kpRQffeo.js.map → activation-Bb2ovvM5.js.map} +1 -1
  4. package/dist/{activation-DEKw9CDD.d.ts → activation-DPz8kGpT.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +2 -2
  7. package/dist/{bundle-BET6gl5r.js → bundle-Cy5igJdv.js} +2 -2
  8. package/dist/{bundle-BET6gl5r.js.map → bundle-Cy5igJdv.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +4 -4
  10. package/dist/{coordination-manager-ds4pn4IC.js → coordination-manager-Cow3jgu1.js} +4 -4
  11. package/dist/{coordination-manager-ds4pn4IC.js.map → coordination-manager-Cow3jgu1.js.map} +1 -1
  12. package/dist/{delegate-B2Z1CueR.js → delegate-zUOoWutU.js} +2 -2
  13. package/dist/{delegate-B2Z1CueR.js.map → delegate-zUOoWutU.js.map} +1 -1
  14. package/dist/durable.d.ts +1 -1
  15. package/dist/durable.js +8 -8
  16. package/dist/{graph-flrNgUfu.js → graph-BS9p0hHV.js} +5 -5
  17. package/dist/{graph-flrNgUfu.js.map → graph-BS9p0hHV.js.map} +1 -1
  18. package/dist/{improve-DEkdGeQV.js → improve-Ca4PSA2z.js} +7 -7
  19. package/dist/{improve-DEkdGeQV.js.map → improve-Ca4PSA2z.js.map} +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +61 -13
  22. package/dist/index.js.map +1 -1
  23. package/dist/intelligence.d.ts +2 -2
  24. package/dist/intelligence.js +7 -7
  25. package/dist/kernel.d.ts +2 -2
  26. package/dist/kernel.js +13 -13
  27. package/dist/{loop-runner-CDad0CCY.d.ts → loop-runner-9surW8mg.d.ts} +2 -2
  28. package/dist/{loop-runner-CrEq3gmu.js → loop-runner-B_K3oLGC.js} +2 -2
  29. package/dist/{loop-runner-CrEq3gmu.js.map → loop-runner-B_K3oLGC.js.map} +1 -1
  30. package/dist/loop-runner-bin.d.ts +1 -1
  31. package/dist/loop-runner-bin.js +1 -1
  32. package/dist/mcp/bin.js +3 -3
  33. package/dist/mcp/index.d.ts +1 -1
  34. package/dist/mcp/index.js +5 -5
  35. package/dist/{prepare-O1HbzOqs.js → prepare-Dtfk_Wi_.js} +3 -3
  36. package/dist/{prepare-O1HbzOqs.js.map → prepare-Dtfk_Wi_.js.map} +1 -1
  37. package/dist/{profile-DcRoyryP.js → profile-CNSQjOes.js} +2 -2
  38. package/dist/{profile-DcRoyryP.js.map → profile-CNSQjOes.js.map} +1 -1
  39. package/dist/profiles.d.ts +1 -1
  40. package/dist/{provision-supervisor-CuX82sFT.js → provision-supervisor-ZG-ZxIe9.js} +4 -4
  41. package/dist/{provision-supervisor-CuX82sFT.js.map → provision-supervisor-ZG-ZxIe9.js.map} +1 -1
  42. package/dist/{run-cancellation-ZmRSYLu5.js → run-cancellation-CqF01-zj.js} +2 -2
  43. package/dist/{run-cancellation-ZmRSYLu5.js.map → run-cancellation-CqF01-zj.js.map} +1 -1
  44. package/dist/{run-state-Dt-v0Fr8.js → run-state-CeMgqULw.js} +4 -4
  45. package/dist/{run-state-Dt-v0Fr8.js.map → run-state-CeMgqULw.js.map} +1 -1
  46. package/dist/{runtime-BNSsSOZ7.js → runtime-CBt8PWn5.js} +419 -54
  47. package/dist/runtime-CBt8PWn5.js.map +1 -0
  48. package/dist/{scope-DSm2RW5I.js → scope-BF3RUg3U.js} +2 -2
  49. package/dist/{scope-DSm2RW5I.js.map → scope-BF3RUg3U.js.map} +1 -1
  50. package/dist/{search-executor-CpQIJAdh.js → search-executor-CoLgtigZ.js} +4 -4
  51. package/dist/{search-executor-CpQIJAdh.js.map → search-executor-CoLgtigZ.js.map} +1 -1
  52. package/dist/{server-umzSNbPI.js → server-Dv_wLT9_.js} +3 -3
  53. package/dist/{server-umzSNbPI.js.map → server-Dv_wLT9_.js.map} +1 -1
  54. package/dist/{structural-rollout-B8PkKbfv.js → structural-rollout-ccetqcnq.js} +4 -4
  55. package/dist/{structural-rollout-B8PkKbfv.js.map → structural-rollout-ccetqcnq.js.map} +1 -1
  56. package/dist/{supervise-B3hzcqVU.js → supervise-BMqPWSv7.js} +5 -5
  57. package/dist/{supervise-B3hzcqVU.js.map → supervise-BMqPWSv7.js.map} +1 -1
  58. package/dist/{supervision-discovery-BNChDps7.js → supervision-discovery-mF3cWh36.js} +2 -2
  59. package/dist/{supervision-discovery-BNChDps7.js.map → supervision-discovery-mF3cWh36.js.map} +1 -1
  60. package/dist/{supervisor-DpWSUrwB.js → supervisor-CigTbS9A.js} +21 -20
  61. package/dist/supervisor-CigTbS9A.js.map +1 -0
  62. package/dist/testing.d.ts +1 -1
  63. package/dist/testing.js +13 -13
  64. package/dist/{top-web-CQNkrh_j.js → top-web-DBhkr1lN.js} +4 -4
  65. package/dist/{top-web-CQNkrh_j.js.map → top-web-DBhkr1lN.js.map} +1 -1
  66. package/dist/tui/bin.js +3 -3
  67. package/dist/tui/index.d.ts +1 -1
  68. package/dist/tui/index.js +2 -2
  69. package/dist/{types-niKnm6ux.d.ts → types-DmJTtmgm.d.ts} +54 -4
  70. package/dist/{workspace-streams-uB9rRbms.js → workspace-streams-B7yNMahl.js} +2 -2
  71. package/dist/{workspace-streams-uB9rRbms.js.map → workspace-streams-B7yNMahl.js.map} +1 -1
  72. package/package.json +1 -1
  73. package/dist/runtime-BNSsSOZ7.js.map +0 -1
  74. package/dist/supervisor-DpWSUrwB.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"improve-DEkdGeQV.js","names":["truncate","canonicalCandidateDigest","resolvePath","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","sha256Bytes"],"sources":["../src/runtime-usage.ts","../src/improvement/agentic-shot-evidence.ts","../src/improvement/worktree-tree.ts","../src/improvement/agentic-generator.ts","../src/improvement/cleanup.ts","../src/improvement/improve-result.ts","../src/improvement/improvement-driver.ts","../src/improvement/profile-surface.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/code-execution.ts","../src/improvement/method-controls.ts","../src/improvement/method-cost.ts","../src/improvement/candidate-validation.ts","../src/improvement/method-identity.ts","../src/improvement/profile-improvement.ts","../src/improvement/method-execution.ts","../src/improvement/search-session.ts","../src/improvement/search-method.ts","../src/improvement/training.ts","../src/improvement/improve.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","/**\n * The evidence one agentic author shot leaves: its receipt (identity, timing,\n * usage and cost basis), the run-ledger cost receipt, and the callbacks that\n * persist both the receipt and the worktree disposition before the loop moves\n * on. A callback that throws aborts the candidate, so evidence persistence\n * fails closed.\n */\nimport type { CostReceipt, CostReceiptInput } from '@tangle-network/agent-eval'\nimport type { AgentProfile, HarnessType } from '@tangle-network/agent-interface'\nimport { sha256 } from '../content-digest'\nimport type { AgentTurnUsage, CollectedAgentTurn } from '../runtime/stream-agent-turn'\nimport type {\n AgenticGeneratorOptions,\n AgenticGeneratorShotDisposition,\n AgenticGeneratorShotExecution,\n AgenticGeneratorShotReceipt,\n} from './agentic-generator'\n\nexport async function emitShotReceipt(\n callback: AgenticGeneratorOptions['onShotCompleted'],\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n primaryError: Error | null,\n): Promise<void> {\n try {\n await callback?.(receipt, execution)\n } catch (callbackError) {\n if (primaryError !== null) {\n throw new AggregateError(\n [primaryError, callbackError],\n 'agenticGenerator: author shot failed and its receipt could not be persisted',\n )\n }\n throw callbackError\n }\n if (primaryError !== null) throw primaryError\n}\n\nexport async function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nexport async function rethrowShotSetupError(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n worktreePath: string,\n stage: Extract<AgenticGeneratorShotDisposition, { kind: 'setup-error' }>['stage'],\n cause: unknown,\n): Promise<never> {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n try {\n await emitShotDisposition(callback, receipt, {\n kind: 'setup-error',\n worktreePath,\n stage,\n error: { name: error.name, message: error.message },\n })\n } catch (callbackError) {\n throw new AggregateError(\n [cause, callbackError],\n 'agenticGenerator: shot processing failed and its worktree disposition could not be persisted',\n )\n }\n throw cause\n}\n\nexport function shotReceipt(input: {\n readonly generation: number | undefined\n readonly candidateIndex: number | undefined\n readonly shot: number\n readonly maxShots: number\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly profile: AgentProfile\n readonly profileDigest: string\n readonly prompt: string\n readonly startedAt: Date\n readonly completedAt: Date\n readonly result: AgenticGeneratorShotExecution | null\n readonly costCallId: string | null\n readonly costReceipt: CostReceipt | null\n readonly error: unknown\n}): AgenticGeneratorShotReceipt {\n const error = input.error\n ? {\n name: input.error instanceof Error ? input.error.name : 'Error',\n message: input.error instanceof Error ? input.error.message : String(input.error),\n }\n : null\n const result = input.result\n const costBasis = costBasisFor(input.costReceipt, result)\n const costUsd =\n input.costReceipt?.costUsd ?? result?.usage.costUsd ?? result?.usage.estimatedCostUsd ?? null\n return {\n generation: input.generation ?? null,\n candidateIndex: input.candidateIndex ?? null,\n shot: input.shot + 1,\n maxShots: input.maxShots,\n profileDigest: input.profileDigest,\n harness: input.harness,\n provider: input.provider,\n model: input.model,\n reasoningEffort: input.profile.model?.reasoningEffort ?? null,\n promptSha256: `sha256:${sha256(input.prompt)}`,\n startedAt: input.startedAt.toISOString(),\n completedAt: input.completedAt.toISOString(),\n durationMs: input.completedAt.getTime() - input.startedAt.getTime(),\n status: result?.status ?? null,\n usage: result ? { ...result.usage } : null,\n transportAttempts: result?.transportAttempts ?? null,\n costCallId: input.costCallId,\n costBasis,\n costUsd: costBasis === 'unknown' ? null : costUsd,\n costUsdKnown: costBasis === 'provider-reported',\n error,\n }\n}\n\nfunction costBasisFor(\n receipt: CostReceipt | null,\n turn: AgenticGeneratorShotExecution | null,\n): AgenticGeneratorShotReceipt['costBasis'] {\n if (receipt) {\n if (receipt.costUnknown) return 'unknown'\n return receipt.actualCostUsd === undefined ? 'estimated-pricing' : 'provider-reported'\n }\n if (turn?.usage.usdKnown !== false && turn?.usage.costUsd !== undefined) {\n return 'provider-reported'\n }\n return turn?.usage.estimatedCostUsd !== undefined ? 'estimated-pricing' : 'unknown'\n}\n\nexport function shotFailure(result: CollectedAgentTurn): Error | null {\n if (result.status === 'completed') return null\n if (result.status === 'aborted') {\n return new Error('agenticGenerator: author shot was cancelled by the caller')\n }\n return new Error(\n `agenticGenerator: author shot failed${result.error?.message ? `: ${result.error.message}` : ''}`,\n )\n}\n\nexport function costReceiptFromTurn(result: CollectedAgentTurn, model: string): CostReceiptInput {\n const tokensKnown = result.usage.tokensKnown !== false\n const actualCostUsd = result.usage.usdKnown === false ? undefined : result.usage.costUsd\n const cachedTokens = promptCacheReadTokens(result.usage)\n return {\n model,\n inputTokens: tokensKnown ? Math.max(0, result.usage.input - (cachedTokens ?? 0)) : 0,\n outputTokens: tokensKnown ? result.usage.output : 0,\n ...(tokensKnown ? {} : { usageUnknown: true }),\n ...(cachedTokens !== undefined ? { cachedTokens } : {}),\n ...(result.usage.reasoningTokens !== undefined\n ? { reasoningTokens: result.usage.reasoningTokens }\n : {}),\n ...(actualCostUsd !== undefined\n ? { actualCostUsd }\n : result.usage.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: result.usage.estimatedCostUsd }\n : { costUnknown: true }),\n }\n}\n\nfunction promptCacheReadTokens(usage: AgentTurnUsage): number | undefined {\n const cache = usage.promptCache\n if (!cache) return undefined\n for (const field of ['readTokens', 'cachedInputTokens', 'cacheReadInputTokens']) {\n const value = cache[field]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n return undefined\n}\n","/**\n * The exact content of a candidate worktree, as a Git tree object.\n *\n * A multi-shot candidate edits ONE directory in place, so the tree a shot\n * produced is gone as soon as the next shot writes over it. Writing that\n * content into the object store is what makes an earlier tree recoverable:\n * `agenticGenerator` snapshots a tree that verified, and puts it back when a\n * later shot ends the budget on a worse one.\n *\n * The snapshot stages into a PRIVATE index file, so the index the driver later\n * commits from is untouched.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { mkdtempSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\n/** Write the worktree's current content into the object store and return its tree id. */\nexport function snapshotWorktreeTree(worktreePath: string): string {\n const scratch = mkdtempSync(join(tmpdir(), 'agentic-generator-tree-'))\n const indexFile = join(scratch, 'index')\n try {\n // HEAD first: a tracked file that `.gitignore` also matches stays in the\n // tree. Against an EMPTY index `git add -A` reads that file as untracked\n // and drops it, and restoring such a tree would delete a tracked file.\n git(worktreePath, ['read-tree', 'HEAD'], indexFile)\n git(worktreePath, ['add', '--all'], indexFile)\n return git(worktreePath, ['write-tree'], indexFile)\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n}\n\n/**\n * Put a snapshotted tree back into the worktree, then prove the directory\n * holds exactly that tree.\n *\n * The proof is not ceremony: a restore that lands the wrong bytes ships the\n * wrong candidate, and every artifact downstream still reads as though the\n * best tree shipped.\n */\nexport function restoreWorktreeTree(worktreePath: string, tree: string): void {\n git(worktreePath, ['read-tree', '-u', '--reset', tree])\n // `read-tree` removes what the index tracked. A file a later shot added is\n // untracked, so it survives that and would ship beside the restored tree.\n // Ignored files are left alone, exactly as a commit leaves them.\n git(worktreePath, ['clean', '--force', '-d', '--quiet'])\n const restored = snapshotWorktreeTree(worktreePath)\n if (restored !== tree) {\n throw new Error(\n `agenticGenerator: restoring tree ${tree} into ${worktreePath} produced ${restored}`,\n )\n }\n}\n\nfunction git(cwd: string, args: string[], indexFile?: string): string {\n const env = { ...process.env }\n if (indexFile) env.GIT_INDEX_FILE = indexFile\n else delete env.GIT_INDEX_FILE\n const result = spawnSync('git', args, { cwd, encoding: 'utf-8', env })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git ${args[0]} failed to spawn in ${cwd}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git ${args[0]} exited ${result.status} in ${cwd}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout.trim()\n}\n\nexport function worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain=v1', '-z', '--untracked-files=all'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n const records = result.stdout.split('\\0')\n const paths: string[] = []\n for (let i = 0; i < records.length; i += 1) {\n const record = records[i]\n if (!record) continue\n paths.push(record.slice(3))\n // Rename and copy entries have a second NUL-delimited path without a status prefix.\n if (record[0] === 'R' || record[1] === 'R' || record[0] === 'C' || record[1] === 'C') {\n const source = records[++i]\n if (!source) {\n throw new Error(\n `agenticGenerator: git status omitted a rename/copy path in ${worktreePath}`,\n )\n }\n paths.push(source)\n }\n }\n return paths\n}\n","/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`. It runs a real\n * authored profile inside the candidate worktree the driver already created,\n * letting the agent read the codebase + the research proposal findings and\n * make the change in place. The driver then commits the worktree into a\n * `CodeSurface`.\n *\n * Every paid shot enters Runtime through `createExecutor` + `streamAgentTurn`.\n * The caller supplies the exact `AgentProfile` and a worktree-aware executor\n * placement; Runtime validates and records the profile that actually ran. Two\n * built-in placements edit the supplied worktree itself: `{ backend:'cli-in-place',\n * workspacePath: worktreePath }` runs a local coding CLI (claude-code / codex /\n * opencode / pi) in that directory, and `{ backend:'bridge', cwd: worktreePath }`\n * runs a cli-bridge session there. `cli-worktree` is NOT one of them — it cuts a\n * worktree of its own, so every shot would read as an empty tree.\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runAgentRounds`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no session-specific retry path needed)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * - dirty + `verify` ok + `keepGoing` → bank the tree and spend the next shot\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier, the first dirty shot is the candidate.\n *\n * BEST-OF-N is the `keepGoing` path, and the loop owns it end to end. A\n * verifier that passes a tree and asks for another shot has its tree\n * snapshotted as a Git tree object; when the budget ends, the highest-`score`\n * tree is RESTORED into the worktree and returned as the candidate. So the\n * caller ranks and the loop moves the bytes — a caller never has to write a\n * passing tree back itself. The budget ends on the last shot, or earlier on a\n * `keepGoing`-less pass, and a last shot that broke or reverted the change does\n * not cost the candidate the verified tree an earlier shot produced.\n *\n * @stable\n */\n\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { CostReceipt, MaximumCharge, ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n type HarnessType,\n type ReasoningEffort,\n} from '@tangle-network/agent-interface'\nimport { runSettledCommand } from '../mcp/worktree-harness'\nimport {\n type AgentTurnUsage,\n type CollectedAgentTurn,\n collectAgentTurn,\n streamAgentTurn,\n} from '../runtime/stream-agent-turn'\nimport {\n assertExecutableAgentProfile,\n concreteProfileModel,\n} from '../runtime/supervise/model-policy'\nimport { createExecutor, type ExecutorConfig } from '../runtime/supervise/runtime'\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport {\n costReceiptFromTurn,\n emitShotDisposition,\n emitShotReceipt,\n rethrowShotSetupError,\n shotFailure,\n shotReceipt,\n} from './agentic-shot-evidence'\nimport type { CandidateGenerator } from './improvement-driver'\nimport { restoreWorktreeTree, snapshotWorktreeTree, worktreeChangedPaths } from './worktree-tree'\n\nconst RAW_TRACE_ANALYST_ID = 'raw-trace-distiller'\nconst RAW_TRACE_AREA = 'raw-trace-context'\nconst RAW_TRACE_DIAGNOSIS_PATH = '.improve/raw-trace-diagnosis.md'\n\n/**\n * Outcome of verifying a candidate worktree.\n *\n * `ok` answers \"is this tree shippable\". `keepGoing` answers \"should the budget\n * stop here\", and `score` ranks this tree against the other trees the same\n * candidate produced — three separate questions, so a verifier can pass a tree\n * and still spend the shots it was given.\n *\n * `feedback` (compiler errors, failing test output, or the reason a passing\n * tree is being sent back) is fed into the next shot.\n */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n /**\n * Spend the remaining shots instead of returning this tree now.\n *\n * Read only when `ok` is true: a failed verification already spends the next\n * shot. Omitted means the first passing tree ends the candidate.\n */\n keepGoing?: boolean\n /**\n * How good this tree is, for ranking it against the other passing trees of\n * this candidate. Higher wins; a tie keeps the LATER tree, which is the one\n * already on disk and the one the author refined last.\n *\n * Only a passing tree is ranked — a tree that failed verification is never a\n * candidate, whatever it scored. Score every passing tree or none of them: a\n * scored tree cannot be ranked against an unscored one, and mixing the two\n * fails the run rather than guessing an order.\n */\n score?: number\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (\n worktreePath: string,\n signal?: AbortSignal,\n) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorShotReceipt {\n readonly generation: number | null\n readonly candidateIndex: number | null\n /** One-based shot number within this candidate. */\n readonly shot: number\n readonly maxShots: number\n /** Exact profile identity admitted before the shot. */\n readonly profileDigest: string\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly reasoningEffort: ReasoningEffort | null\n readonly promptSha256: `sha256:${string}`\n readonly startedAt: string\n readonly completedAt: string\n readonly durationMs: number\n readonly status: CollectedAgentTurn['status'] | null\n /** Runtime-normalized usage. Unknown token or dollar totals remain marked unknown. */\n readonly usage: Readonly<AgentTurnUsage> | null\n readonly transportAttempts: number | null\n /** Shared run-ledger call id for this exact shot. */\n readonly costCallId: string | null\n /** Whether dollars came from the provider, the pricing table, or are unknown. */\n readonly costBasis: 'provider-reported' | 'estimated-pricing' | 'unknown'\n readonly costUsd: number | null\n /** True only for a provider-reported amount, never for a pricing estimate. */\n readonly costUsdKnown: boolean\n readonly error: { readonly name: string; readonly message: string } | null\n}\n\n/** Runtime's exact terminal turn plus its complete normalized event stream. */\nexport type AgenticGeneratorShotExecution = Readonly<CollectedAgentTurn>\n\n/** Worktree decision emitted before a completed shot is retried, accepted, or\n * discarded. The callback runs while `worktreePath` is still available, so\n * callers can persist the exact diff. */\nexport type AgenticGeneratorShotDisposition =\n | {\n readonly kind: 'clean'\n readonly worktreePath: string\n }\n | {\n readonly kind: 'rejected'\n readonly worktreePath: string\n readonly stage: 'raw-trace-evidence' | 'verification'\n readonly feedback: string | null\n }\n | {\n /** The tree passed verification and the verifier asked for another shot,\n * so it was snapshotted and the budget continues. */\n readonly kind: 'kept'\n readonly worktreePath: string\n /** The rank the verifier gave this tree, or null when it scored nothing. */\n readonly score: number | null\n /** Whether this tree is now the best one this candidate has produced. */\n readonly best: boolean\n readonly feedback: string | null\n }\n | {\n readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\n /** One-based shot whose tree was put back into the worktree because it\n * outranked the tree on disk; null when the tree on disk is the one that\n * ships. Non-null is the record that best-of-n moved bytes rather than\n * only ranking them. */\n readonly restoredFromShot: number | null\n }\n | {\n readonly kind: 'setup-error'\n readonly worktreePath: string\n readonly stage: 'worktree-inspection' | 'raw-trace-evidence' | 'verification'\n readonly error: { readonly name: string; readonly message: string }\n }\n\nexport type AgenticGeneratorExecutorForWorktree = (worktreePath: string) => ExecutorConfig\n\nexport interface AgenticGeneratorOptions {\n /** Complete author identity. Harness, provider, model, prompt, tools, and resources all come from here. */\n profile: AgentProfile\n /** Place the exact profile on compute that can edit this existing worktree.\n * A local coding CLI returns `{ backend:'cli-in-place', workspacePath: worktreePath }`; a Pi\n * author over cli-bridge returns `{ backend:'bridge', cwd: worktreePath, ...transport }`. Both\n * are checked against the supplied path before the first shot spends. */\n executorForWorktree: AgenticGeneratorExecutorForWorktree\n /** Awaited once for every attempted author shot, including execution failures.\n * The second argument is Runtime's exact terminal turn and event stream.\n * Throwing aborts the candidate so evidence persistence fails closed. */\n onShotCompleted?: (\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n ) => void | Promise<void>\n /** Awaited after worktree inspection and before the shot is accepted,\n * retried, or discarded. Throwing aborts the candidate. */\n onShotDisposition?: (\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n ) => void | Promise<void>\n /** Optional hard upper bound passed to the run-wide CostLedger before each author shot. */\n maximumCharge?: MaximumCharge\n /** Per-shot wall-clock timeout. Omit for no Runtime-imposed deadline. */\n timeoutMs?: number\n /** Build the task prompt from proposal findings. Required: Runtime invents no authoring policy. */\n buildPrompt: (args: { findings: ReadonlyArray<ProposalFinding> }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. A verifier that returns\n * `keepGoing` passes a tree AND spends the remaining shots, and the\n * best-scoring tree is the one that ships. Omitted means the first dirty\n * shot is the candidate. See `commandVerifier` and `VerifyResult`. */\n verify?: Verifier\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator`: run an exact profiled author inside the existing candidate worktree. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions): CandidateGenerator {\n const profile = detachedSnapshot(\n agentProfileSchema.parse(opts.profile) as AgentProfile,\n 'agenticGenerator profile',\n )\n assertExecutableAgentProfile(profile, 'agenticGenerator')\n const harness = profile.harness!\n const author: AuthorContext = {\n opts,\n profile,\n harness,\n provider: profile.model!.provider!.trim(),\n model: concreteProfileModel(profile)!,\n profileDigest: canonicalAgentProfileDigest(profile),\n dirty: opts.isDirty ?? worktreeDirty,\n }\n\n return {\n kind: `agentic:${harness}`,\n // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context\n // are the change signal — an agentic coder proposes from them even when the\n // distiller yielded zero findings. Without this, the code candidate driver's\n // empty-findings guard short-circuits and generates ZERO candidates on the\n // first (and, for a single-generation run, only) proposal round.\n proposesWithoutFindings: true,\n generate: (request) => generateCandidate(author, request),\n }\n}\n\n/** The exact author one `agenticGenerator` runs, fixed when it is built. */\ninterface AuthorContext {\n readonly opts: AgenticGeneratorOptions\n readonly profile: AgentProfile\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly profileDigest: string\n readonly dirty: (worktreePath: string) => boolean\n}\n\ntype GenerateRequest = Parameters<CandidateGenerator['generate']>[0]\ntype AcceptedCandidate = ReturnType<typeof acceptedCandidate>\n\n/** What one candidate carries from shot to shot. */\ninterface CandidateState {\n /** Feedback appended to the base prompt for the NEXT shot — empty on shot 0. */\n attemptNote: string\n /** The best tree this candidate has produced, and where it lives. Only a\n * verifier that returns `keepGoing` can put more than one tree here: a\n * passing tree that ends the budget is banked and shipped in one step. */\n best: BankedTree | null\n /** Whether the verifier scores its trees. Set by the first passing tree;\n * a later tree that disagrees cannot be ranked and fails the run. */\n scored: boolean | null\n lastReceipt: AgenticGeneratorShotReceipt | null\n}\n\n/** Where a settled shot stands in the budget. */\ninterface ShotPosition {\n readonly shot: number\n readonly shots: number\n readonly needsRawTraceEvidence: boolean\n}\n\n/** How a settled shot ends: a candidate to ship, or the note the next shot starts from. */\ntype ShotStep = { candidate: AcceptedCandidate } | { note: string }\n\nasync function generateCandidate(\n author: AuthorContext,\n request: GenerateRequest,\n): Promise<AcceptedCandidate | { applied: false; summary: string }> {\n const { opts, harness, provider, model, profile, profileDigest } = author\n const { findings, maxShots, signal, generation, candidateIndex } = request\n signal.throwIfAborted()\n const { basePrompt, factory } = prepareAuthoring(author, request)\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n const state: CandidateState = { attemptNote: '', best: null, scored: null, lastReceipt: null }\n\n for (let shot = 0; shot < shots; shot++) {\n signal.throwIfAborted()\n // This shot may write over whatever the worktree held.\n if (state.best) state.best.onDisk = false\n const taskPrompt = state.attemptNote ? `${basePrompt}\\n\\n${state.attemptNote}` : basePrompt\n const startedAt = new Date()\n const ran = await runAuthorShot(author, request, factory, taskPrompt, shot)\n const execution = ran.turn\n ? detachedSnapshot(ran.turn, 'agenticGenerator shot execution')\n : null\n const receipt = shotReceipt({\n generation,\n candidateIndex,\n shot,\n maxShots: shots,\n harness,\n provider,\n model,\n profile,\n profileDigest,\n prompt: taskPrompt,\n startedAt,\n completedAt: new Date(),\n result: execution,\n costCallId: ran.costCallId,\n costReceipt: ran.costReceipt,\n error: ran.shotError,\n })\n state.lastReceipt = receipt\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, ran.shotError)\n signal.throwIfAborted()\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a Runtime turn')\n }\n\n const step = await settleShot(author, request, state, receipt, {\n shot,\n shots,\n needsRawTraceEvidence,\n })\n if ('candidate' in step) return step.candidate\n state.attemptNote = step.note\n }\n\n // Shots exhausted. A banked tree passed verification, so it ships even\n // though the last shot did not end the budget on it — discarding paid,\n // verified work because a later shot broke or reverted it is the loss\n // best-of-n exists to prevent.\n if (state.best !== null) {\n if (!state.lastReceipt) {\n throw new Error('agenticGenerator: a tree was banked without a shot receipt')\n }\n return await shipBankedTree(author, request, state.lastReceipt, state.best)\n }\n // No verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n}\n\n/** Check the request and build the author's prompt and executor, before any shot spends. */\nfunction prepareAuthoring(author: AuthorContext, request: GenerateRequest) {\n const { opts } = author\n const { worktreePath, findings, costLedger } = request\n if (opts.maximumCharge && !costLedger) {\n throw new Error(\n 'agenticGenerator: maximumCharge requires the run-wide CostLedger supplied by agent-eval',\n )\n }\n const basePrompt = opts.buildPrompt({ findings })\n if (typeof basePrompt !== 'string' || basePrompt.trim().length === 0) {\n throw new Error('agenticGenerator: buildPrompt must return a non-empty string')\n }\n const executorConfig = opts.executorForWorktree(worktreePath)\n if (executorConfig.backend === 'bridge' && !samePath(executorConfig.cwd, worktreePath)) {\n throw new Error('agenticGenerator: bridge executor cwd must equal the candidate worktree path')\n }\n if (\n executorConfig.backend === 'cli-in-place' &&\n !samePath(executorConfig.workspacePath, worktreePath)\n ) {\n throw new Error(\n 'agenticGenerator: cli-in-place executor workspacePath must equal the candidate worktree path',\n )\n }\n return { basePrompt, factory: createExecutor(executorConfig) }\n}\n\n/** Run one author shot through the run-wide ledger when there is one. A failure is returned, not thrown. */\nasync function runAuthorShot(\n author: AuthorContext,\n request: GenerateRequest,\n factory: ReturnType<typeof createExecutor>,\n taskPrompt: string,\n shot: number,\n) {\n const { opts, profile, harness, model } = author\n const { signal, generation, candidateIndex, costLedger, costPhase } = request\n let turn: CollectedAgentTurn | null = null\n let costReceipt: CostReceipt | null = null\n let costCallId: string | null = null\n let shotError: Error | null = null\n try {\n const execute = async (\n executionSignal: AbortSignal,\n callId?: string,\n ): Promise<CollectedAgentTurn> => {\n turn = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', profile, factory },\n { prompt: taskPrompt },\n {\n signal: executionSignal,\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(callId ? { callId } : {}),\n },\n ),\n )\n const failure = shotFailure(turn)\n if (failure) throw failure\n return turn\n }\n\n if (costLedger) {\n const paid = await costLedger.runPaidCall({\n channel: 'driver',\n phase: costPhase ?? 'search.proposal',\n actor: `agentic-generator:${harness}`,\n model,\n tags: {\n generation: String(generation ?? -1),\n candidateIndex: String(candidateIndex ?? -1),\n shot: String(shot + 1),\n },\n signal,\n ...(opts.maximumCharge ? { maximumCharge: opts.maximumCharge } : {}),\n execute: (executionSignal, callId) => execute(executionSignal, callId),\n receipt: (result) => costReceiptFromTurn(result, model),\n receiptFromError: () => (turn ? costReceiptFromTurn(turn, model) : undefined),\n })\n costCallId = paid.callId ?? null\n costReceipt = paid.receipt ?? null\n if (!paid.succeeded) throw paid.error\n turn = paid.value\n } else {\n turn = await execute(signal)\n }\n } catch (cause) {\n shotError = cause instanceof Error ? cause : new Error(String(cause))\n }\n return { turn, costReceipt, costCallId, shotError }\n}\n\n/** Decide what a completed shot's worktree means: ship it, or the note the next shot starts from. */\nasync function settleShot(\n author: AuthorContext,\n request: GenerateRequest,\n state: CandidateState,\n receipt: AgenticGeneratorShotReceipt,\n position: ShotPosition,\n): Promise<ShotStep> {\n const { opts, dirty } = author\n const { worktreePath, findings, signal } = request\n let worktreeChanged: boolean\n try {\n worktreeChanged = dirty(worktreePath)\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'worktree-inspection',\n cause,\n )\n }\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!worktreeChanged) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, { kind: 'clean', worktreePath })\n signal.throwIfAborted()\n return { note: EMPTY_TREE_NOTE }\n }\n\n if (position.needsRawTraceEvidence) {\n let problem: string | null\n try {\n problem = rawTraceEvidenceProblem(worktreePath, findings)\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'raw-trace-evidence',\n cause,\n )\n }\n if (problem) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'raw-trace-evidence',\n feedback: problem,\n })\n signal.throwIfAborted()\n return { note: problem }\n }\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the model's response text). With a verifier the candidate must pass it.\n if (!opts.verify) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n restoredFromShot: null,\n })\n signal.throwIfAborted()\n return { candidate: acceptedCandidate(findings) }\n }\n return settleVerifiedShot(author, request, state, receipt, position, opts.verify)\n}\n\n/** Run the verifier on a dirty tree, then ship, bank or reject it. */\nasync function settleVerifiedShot(\n author: AuthorContext,\n request: GenerateRequest,\n state: CandidateState,\n receipt: AgenticGeneratorShotReceipt,\n { shot, shots }: ShotPosition,\n verify: Verifier,\n): Promise<ShotStep> {\n const { opts } = author\n const { worktreePath, signal } = request\n let result: VerifyResult\n try {\n signal.throwIfAborted()\n result = await verify(worktreePath, signal)\n signal.throwIfAborted()\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'verification',\n cause,\n )\n }\n if (result.ok) {\n const score = admittedScore(result, state.scored, shot)\n state.scored = score !== null\n const previousBest = state.best\n let banked: BankedTree\n // A tie keeps the LATER tree: it is already on disk, and it is the\n // author's own refinement of the tree it tied with. `admittedScore`\n // refuses a mix of scored and unscored trees, so an unscored set is a\n // flat 0 and this rule reduces to \"the later tree wins\".\n if (previousBest === null || (score ?? 0) >= (previousBest.score ?? 0)) {\n banked = { shot: shot + 1, score, tree: null, onDisk: true }\n } else {\n banked = previousBest\n }\n const becomesBest = banked !== previousBest\n state.best = banked\n if (result.keepGoing !== true) {\n signal.throwIfAborted()\n return { candidate: await shipBankedTree(author, request, receipt, banked) }\n }\n // Shots remain, so a later one can write over this tree. Bank the\n // bytes now, while they are still on disk.\n if (becomesBest && shot < shots - 1) banked.tree = snapshotWorktreeTree(worktreePath)\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'kept',\n worktreePath,\n score,\n best: becomesBest,\n feedback: result.feedback ?? null,\n })\n signal.throwIfAborted()\n return { note: keptNote(result.feedback) }\n }\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'verification',\n feedback: result.feedback ?? null,\n })\n signal.throwIfAborted()\n // Dirty but failing — resume next shot atop these edits with the error.\n return { note: failureNote(result.feedback) }\n}\n\n/** Ship the best tree this candidate produced, restoring it when a later\n * shot wrote over it. */\nasync function shipBankedTree(\n author: AuthorContext,\n request: GenerateRequest,\n receipt: AgenticGeneratorShotReceipt,\n banked: BankedTree,\n): Promise<AcceptedCandidate> {\n const { worktreePath, findings, signal } = request\n const restoredFromShot = banked.onDisk ? null : banked.shot\n if (!banked.onDisk) {\n if (banked.tree === null) {\n throw new Error(\n `agenticGenerator: shot ${banked.shot} produced the best tree but it was never snapshotted`,\n )\n }\n restoreWorktreeTree(worktreePath, banked.tree)\n banked.onDisk = true\n }\n signal.throwIfAborted()\n await emitShotDisposition(author.opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n restoredFromShot,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\n}\n\n/** A tree that passed verification, and whether the worktree still holds it. */\ninterface BankedTree {\n /** One-based shot that produced it. */\n readonly shot: number\n /** Its rank, or null when the verifier scores nothing. */\n readonly score: number | null\n /** Its Git tree id, written only while a later shot can still overwrite it. */\n tree: string | null\n onDisk: boolean\n}\n\n/** The rank a passing tree carries, refusing a set of trees that cannot be ordered. */\nfunction admittedScore(result: VerifyResult, scored: boolean | null, shot: number): number | null {\n const has = result.score !== undefined\n if (scored !== null && has !== scored) {\n throw new Error(\n `agenticGenerator: verify ${has ? 'scored' : 'did not score'} the tree from shot ${shot + 1} and ${\n scored ? 'scored' : 'did not score'\n } an earlier passing tree; a scored tree cannot be ranked against an unscored one`,\n )\n }\n if (!has) return null\n if (typeof result.score !== 'number' || !Number.isFinite(result.score)) {\n throw new Error(\n `agenticGenerator: verify returned a non-finite score (${String(result.score)}) for shot ${shot + 1}`,\n )\n }\n return result.score\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\n/** Next-shot feedback when the worktree PASSED and the verifier asked for\n * another shot. The passing tree is banked, so the author is told to improve\n * it rather than protect it — a worse tree cannot cost it the candidate. */\nfunction keptNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree and verification PASSED.',\n 'Shots remain in this budget — keep improving the change in place, do not revert it.',\n 'The best version you produce is the one that ships.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\nfunction rawTraceEvidenceProblem(\n worktreePath: string,\n findings: ReadonlyArray<ProposalFinding>,\n): string | null {\n const changedPaths = worktreeChangedPaths(worktreePath)\n const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH)\n if (substantive.length === 0) {\n return [\n `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change.',\n ].join('\\n')\n }\n\n const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH)\n if (!existsSync(diagnosisPath)) {\n return [\n `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change.',\n ].join('\\n')\n }\n\n const body = readFileSync(diagnosisPath, 'utf8')\n const evidencePaths = traceEvidencePaths(findings)\n if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {\n return [\n `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,\n `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(', ')}`,\n ].join('\\n')\n }\n\n return null\n}\n\nfunction requiresRawTraceEvidence(findings: ReadonlyArray<ProposalFinding>): boolean {\n return findings.some((finding) => {\n const f = finding as unknown as Record<string, unknown>\n return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA\n })\n}\n\nfunction traceEvidencePaths(findings: ReadonlyArray<ProposalFinding>): string[] {\n const out: string[] = []\n for (const finding of findings) {\n const refs = (finding as unknown as { evidence_refs?: unknown }).evidence_refs\n if (!Array.isArray(refs)) continue\n for (const ref of refs) {\n if (!ref || typeof ref !== 'object') continue\n const uri = (ref as { uri?: unknown }).uri\n if (typeof uri === 'string' && uri.length > 0) out.push(uri)\n }\n }\n return [...new Set(out)]\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return async (worktreePath: string, signal?: AbortSignal): Promise<VerifyResult> => {\n let result: Awaited<ReturnType<typeof runSettledCommand>>\n try {\n result = await runSettledCommand({\n command,\n args,\n cwd: worktreePath,\n timeoutMs,\n ...(signal ? { signal } : {}),\n })\n } catch (err) {\n signal?.throwIfAborted()\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${reason}`)\n }\n if (result.timedOut || result.killedBySignal) {\n return {\n ok: false,\n feedback: `verifier '${command}' ${result.killedBySignal ? `killed by ${result.killedBySignal}` : 'timed out'} after ${timeoutMs}ms`,\n }\n }\n if (result.exitCode === 0) return { ok: true }\n const out = `${result.stdout}${result.stderr}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.exitCode}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarizeFindings(findings: ReadonlyArray<ProposalFinding>): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\n/**\n * The accepted-shot result: summary (commit message) + the attribution pair\n * the driver wraps into a `ProposedCandidate`, so the candidate stays\n * attributable through `GenerationRecord` and the emitted provenance instead\n * of landing as an anonymous surface.\n */\nfunction acceptedCandidate(findings: ReadonlyArray<ProposalFinding>): {\n applied: true\n summary: string\n label: string\n rationale: string\n} {\n const summary = summarizeFindings(findings)\n return {\n applied: true,\n summary,\n label: slugify(summary.split('\\n', 1)[0] ?? summary),\n rationale: boundedRationale(summary, findings),\n }\n}\n\n/** Short slug from the summary's first line — the candidate's human label. */\nfunction slugify(line: string): string {\n const slug = line\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return truncate(slug || 'agentic-improvement', 48)\n}\n\n/** Bounded \"because Z\" for the candidate: the findings it addressed, or the\n * summary itself when the change was proposed from raw repo/trace context. */\nfunction boundedRationale(summary: string, findings: ReadonlyArray<ProposalFinding>): string {\n if (findings.length === 0) return summary\n return truncate(\n findings.map((finding) => `(${finding.severity}) ${finding.claim}`).join('; '),\n 400,\n )\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Do two names address the same directory? An in-place placement is only in-place if it names the\n * worktree the driver created, and a byte comparison answers that wrongly on a platform whose\n * temporary directory is a symlink: macOS reports `/var/folders/...` where the resolved path is\n * `/private/var/folders/...`, and both are the same directory. */\nfunction samePath(candidate: string | undefined, worktreePath: string): boolean {\n if (typeof candidate !== 'string' || candidate.length === 0) return false\n if (candidate === worktreePath) return true\n return canonicalPath(candidate) === canonicalPath(worktreePath)\n}\n\n/** The resolved path, or the lexically absolute one when the name does not exist — a name that\n * cannot be resolved is a mismatch the caller is told about, not an error to swallow. */\nfunction canonicalPath(path: string): string {\n try {\n return realpathSync(path)\n } catch {\n return resolve(path)\n }\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n return worktreeChangedPaths(worktreePath).length > 0\n}\n","export async function rethrowAfterCleanup(\n cause: unknown,\n cleanup: () => Promise<void>,\n context: string,\n): Promise<never> {\n const cleanupErrors: unknown[] = []\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await cleanup()\n } catch (cleanupCause) {\n cleanupErrors.push(cleanupCause)\n continue\n }\n if (cleanupErrors.length === 0) throw cause\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup retry succeeded`)\n }\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup failed`)\n}\n","import type { ImproveCost } from './improve-types'\n\nexport function copyImproveCost(cost: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: readonly string[]\n}): ImproveCost {\n return {\n totalCostUsd: cost.totalCostUsd,\n accountingComplete: cost.accountingComplete,\n incompleteReasons: [...cost.incompleteReasons],\n }\n}\n","/**\n * Code-only candidate driver for Runtime-owned git worktrees.\n *\n * A `CandidateGenerator` edits an isolated checkout. This driver finalizes each\n * accepted edit as a `CodeSurface` and disposes rejected worktrees.\n *\n * @stable\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { CostLedgerHandle, ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n type CodeSurface,\n type ProposeContext,\n type ProposedCandidate,\n type SurfaceProposer,\n verifyCodeSurface,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport { rethrowAfterCleanup } from './cleanup'\n\n/** The byte-producing path that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an empty findings set\n * because it draws its change signal from the repo and raw traces on disk.\n * An agentic coder (`agenticGenerator`) sets this so it still runs the full\n * `populationSize` when the distiller yielded nothing. A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a clean checkout of the current incumbent. */\n worktreePath: string\n /** Search or production findings explicitly admitted for proposal use. */\n findings: ReadonlyArray<ProposalFinding>\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n /** Generation coordinates supplied by Runtime's internal code candidate driver. */\n generation?: number\n candidateIndex?: number\n /** Shared run-wide paid-call account supplied by agent-eval 0.117+. */\n costLedger?: CostLedgerHandle\n /** Receipt attribution phase supplied alongside `costLedger`. */\n costPhase?: string\n }): Promise<{\n applied: boolean\n summary: string\n /** Short slug for the candidate. When present (with `rationale`), the\n * driver returns a `ProposedCandidate` wrapper so the label survives to\n * `GenerationRecord` and the emitted provenance. */\n label?: string\n /** Why this change was proposed — bounded, derived from the findings the\n * shot addressed. Paired with `label`. */\n rationale?: string\n }>\n}\n\ninterface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Root ref for first-generation/direct callers. Default `main`.\n * Later code generations retain the incumbent's original root. */\n baseRef?: string\n}\n\nexport interface ManagedImprovementDriver extends SurfaceProposer<ProposalFinding> {\n /** Remove every owned candidate except explicitly retained finalized winners. */\n cleanup(retainWorktreeRefs?: readonly string[]): Promise<void>\n}\n\n/** Build the code-only proposer used internally by `improve({ surface: 'code' })`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): ManagedImprovementDriver {\n const baseRef = opts.baseRef ?? 'main'\n const owned = new Map<string, Worktree>()\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<ProposalFinding>) {\n const findings = ctx.findings\n // No findings and a generator that can only act on findings (the\n // reflective patch-applier): propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (findings.length === 0 && !opts.generator.proposesWithoutFindings) {\n return []\n }\n\n const surfaces: Array<CodeSurface | ProposedCandidate> = []\n const incumbent = verifiedCodeIncumbent(ctx.currentSurface)\n const proposalBaseRef = incumbent?.baseCommit ?? baseRef\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef: proposalBaseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\n owned.set(wt.path, wt)\n // Once a worktree exists it MUST be accounted for: finalized into a\n // surface, or discarded. A throw from generate()/finalize() must not\n // leak the worktree + branch — discard best-effort, then rethrow loud.\n try {\n if (incumbent) advanceToIncumbent(wt, incumbent)\n const { applied, summary, label, rationale } = await opts.generator.generate({\n worktreePath: wt.path,\n findings,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n generation: ctx.generation,\n candidateIndex: i,\n ...(ctx.costLedger ? { costLedger: ctx.costLedger } : {}),\n ...(ctx.costPhase ? { costPhase: ctx.costPhase } : {}),\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n owned.delete(wt.path)\n continue\n }\n const surface = await opts.worktree.finalize(wt, summary)\n // A generator that attributes its change gets a `ProposedCandidate`\n // wrapper — the loop normalizes both forms and threads {label,\n // rationale} into `GenerationRecord` + the provenance record. A bare\n // surface stays bare (blind generators remain unattributed).\n surfaces.push(\n label || rationale\n ? { surface, label: label ?? '', rationale: rationale ?? '' }\n : surface,\n )\n owned.delete(wt.path)\n owned.set(surface.worktreeRef, wt)\n } catch (err) {\n const failure = err instanceof Error ? err.message : String(err)\n return rethrowAfterCleanup(\n err,\n async () => {\n await opts.worktree.discard(wt)\n owned.delete(wt.path)\n },\n `improvementDriver: ${failure}`,\n )\n }\n }\n return surfaces\n },\n async cleanup(retainWorktreeRefs = []) {\n const retained = new Set(retainWorktreeRefs)\n const errors: unknown[] = []\n for (const [worktreeRef, worktree] of owned) {\n if (retained.has(worktreeRef)) continue\n try {\n await opts.worktree.discard(worktree)\n owned.delete(worktreeRef)\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improvementDriver: failed to discard candidate worktrees')\n }\n },\n }\n}\n\n/** A code incumbent must still match the immutable identity that was measured. */\nfunction verifiedCodeIncumbent(surface: ProposeContext['currentSurface']): CodeSurface | undefined {\n if (typeof surface !== 'object' || surface.kind !== 'code') return undefined\n verifyCodeSurface(surface)\n return surface\n}\n\n/** Start at the root commit recorded by the incumbent, then fast-forward the\n * fresh branch to the incumbent commit. The worktree stays clean for the\n * generator while `finalize()` still emits one cumulative root-to-candidate\n * patch that can be applied or rolled back independently of prior branches. */\nfunction advanceToIncumbent(worktree: Worktree, incumbent: CodeSurface): void {\n if (worktree.baseCommit !== incumbent.baseCommit || worktree.baseTree !== incumbent.baseTree) {\n throw new Error('improvementDriver: candidate worktree does not match incumbent base identity')\n }\n if (worktree.baseCommit === incumbent.candidateCommit) return\n\n const merge = spawnSync('git', ['merge', '--ff-only', incumbent.candidateCommit], {\n cwd: worktree.path,\n encoding: 'utf8',\n })\n if (merge.error) {\n throw new Error(\n `improvementDriver: failed to start candidate from incumbent: ${merge.error.message}`,\n )\n }\n if (merge.status !== 0) {\n throw new Error(\n `improvementDriver: could not fast-forward candidate to incumbent ${incumbent.candidateCommit}: ${merge.stderr.trim()}`,\n )\n }\n\n const head = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], {\n cwd: worktree.path,\n encoding: 'utf8',\n })\n if (head.error || head.status !== 0 || head.stdout.trim() !== incumbent.candidateCommit) {\n throw new Error('improvementDriver: candidate worktree did not reach the incumbent commit')\n }\n}\n","import { canonicalJson } from '@tangle-network/agent-eval'\nimport type { MutableSurface } from '@tangle-network/agent-eval/contract'\nimport {\n type AgentProfile,\n type AgentProfileResourceRef,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport type {\n ImproveProfileComponents,\n ImproveProfileSurface,\n ImproveSkillsOptions,\n ImproveSurface,\n} from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\ninterface PreparedProfileSurface {\n surface: MutableSurface\n value: unknown\n}\n\n/** Extract the baseline optimized by a method and retain its structured value\n * so external optimizers can inspect it for private fields before serialization. */\nexport function prepareProfileSurface(\n profile: ReadonlyAgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): PreparedProfileSurface {\n switch (surface) {\n case 'prompt':\n return {\n surface: profile.prompt?.systemPrompt ?? '',\n value: profile.prompt?.systemPrompt ?? '',\n }\n case 'skills': {\n const value = inlineSkill(profile, skills).content\n return { surface: value, value }\n }\n case 'tools': {\n const value = profile.tools ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'mcp': {\n const value = profile.mcp ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'hooks': {\n const value = profile.hooks ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'subagents': {\n const value = profile.subagents ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'agent-profile': {\n if (profileComponents) {\n if (\n profileComponents.encoding !== undefined &&\n profileComponents.encoding !== 'components' &&\n profileComponents.encoding !== 'json'\n ) {\n throw new ConfigError('improve(): profileComponents.encoding must be components or json')\n }\n const value = profileComponents.read(profile)\n const components = componentSurface(value, 'profileComponents.read')\n return {\n surface:\n profileComponents.encoding === 'json'\n ? canonicalJson(components.components)\n : components,\n value,\n }\n }\n return { surface: canonicalJson(profile), value: profile }\n }\n case 'memory': {\n const value = profileInstructions(profile)\n return { surface: value, value }\n }\n case 'rollout-policy': {\n const policy = structuralRolloutPolicyFromProfile(profile)\n return {\n surface: policy ? serializeRolloutPolicy(policy) : '',\n value: policy ?? null,\n }\n }\n case 'code':\n throw new ConfigError(\n 'improve(): code requires the isolated baseline created from opts.code.repoRoot',\n )\n }\n}\n\nexport function isCodeSurface(\n surface: MutableSurface | undefined,\n): surface is Extract<MutableSurface, { readonly kind: 'code' }> {\n return typeof surface === 'object' && surface !== null && surface.kind === 'code'\n}\n\ntype ComponentSurface = Extract<MutableSurface, { readonly kind: 'components' }>\n\nfunction isComponentSurface(surface: MutableSurface | undefined): surface is ComponentSurface {\n return typeof surface === 'object' && surface !== null && surface.kind === 'components'\n}\n\nfunction componentSurface(\n components: Readonly<Record<string, string>>,\n source: string,\n): ComponentSurface {\n const entries = validateComponents(components, source)\n return immutableCandidateValue({\n kind: 'components',\n components: Object.fromEntries(entries),\n } as ComponentSurface)\n}\n\nfunction validateComponents(\n components: Readonly<Record<string, string>>,\n source: string,\n): Array<[string, string]> {\n if (typeof components !== 'object' || components === null || Array.isArray(components)) {\n throw new ConfigError(`improve(): ${source} must return a component record`)\n }\n const entries = Object.entries(components)\n if (entries.length === 0) {\n throw new ConfigError(`improve(): ${source} must return at least one component`)\n }\n for (const [name, value] of entries) {\n if (!name || name.trim() !== name || typeof value !== 'string') {\n throw new ConfigError(\n `improve(): ${source} must return trimmed component names with string values`,\n )\n }\n }\n return entries\n}\n\n/** Parse a JSON winner surface with a typed, contextual error. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate is not valid JSON, so it cannot form a profile candidate: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\nexport function assertCandidateSurfaceKind(\n surface: ImproveSurface,\n baseline: MutableSurface,\n winner: MutableSurface,\n): asserts winner is MutableSurface {\n if (surface === 'code') {\n if (isCodeSurface(winner)) return\n throw new ConfigError(\n `improve(): the '${surface}' candidate returned an incompatible surface value`,\n )\n }\n if (typeof baseline === 'string') {\n if (typeof winner === 'string') return\n throw new ConfigError(\n `improve(): the '${surface}' candidate changed from a text surface to an incompatible surface value`,\n )\n }\n if (!isComponentSurface(baseline) || !isComponentSurface(winner)) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate returned an incompatible surface value`,\n )\n }\n validateComponents(winner.components, `the '${surface}' candidate`)\n const baselineNames = Object.keys(baseline.components).sort()\n const winnerNames = Object.keys(winner.components).sort()\n if (\n baselineNames.length !== winnerNames.length ||\n baselineNames.some((name, index) => name !== winnerNames[index])\n ) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate must preserve the exact component names`,\n )\n }\n}\n\n/** Materialize a detached profile candidate without changing the baseline. */\nfunction materializeImprovementProfileCandidate(\n profile: AgentProfile,\n surface: ImproveProfileSurface,\n winner: MutableSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): AgentProfile {\n let candidate: AgentProfile\n if (isComponentSurface(winner)) {\n if (surface !== 'agent-profile' || !profileComponents) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate has no profile component mapping`,\n )\n }\n const winnerComponents = immutableCandidateValue({ ...winner.components })\n const applied = profileComponents.apply(profile, winnerComponents)\n const validated = parseMaterializedProfile(applied, surface)\n const materializedComponents = Object.fromEntries(\n validateComponents(profileComponents.read(validated), 'profileComponents.read after apply'),\n )\n const names = Object.keys(winnerComponents)\n if (\n names.length !== Object.keys(materializedComponents).length ||\n names.some((name) => materializedComponents[name] !== winnerComponents[name])\n ) {\n throw new ConfigError(\n 'improve(): profileComponents.apply must round-trip every winning component exactly',\n )\n }\n return validated\n }\n if (typeof winner !== 'string') {\n throw new ConfigError(`improve(): the '${surface}' candidate cannot form an AgentProfile`)\n }\n switch (surface) {\n case 'prompt':\n candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n break\n case 'skills': {\n const selectedSkill = inlineSkill(profile, skills)\n candidate = {\n ...profile,\n resources: {\n ...profile.resources,\n skills: profile.resources?.skills?.map((resource) =>\n resource === selectedSkill ? { ...resource, content: winner } : resource,\n ),\n },\n }\n break\n }\n case 'tools':\n candidate = { ...profile, tools: parseWinnerJson(winner, surface) }\n break\n case 'mcp':\n candidate = { ...profile, mcp: parseWinnerJson(winner, surface) }\n break\n case 'hooks':\n candidate = { ...profile, hooks: parseWinnerJson(winner, surface) }\n break\n case 'subagents':\n candidate = { ...profile, subagents: parseWinnerJson(winner, surface) }\n break\n case 'agent-profile':\n candidate = parseWinnerJson(winner, surface)\n break\n case 'memory':\n candidate = {\n ...profile,\n resources: {\n ...profile.resources,\n instructions: replaceProfileInstructions(profile, winner),\n },\n }\n break\n case 'rollout-policy': {\n const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface))\n if (!policy) {\n throw new ConfigError(\n `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy ` +\n `(integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`,\n )\n }\n candidate = applyRolloutPolicyToProfile(profile, policy)\n break\n }\n }\n return parseMaterializedProfile(candidate, surface)\n}\n\nfunction parseMaterializedProfile(candidate: unknown, surface: ImproveSurface): AgentProfile {\n const parsed = agentProfileSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate does not produce a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n return immutableCandidateValue(parsed.data)\n}\n\nexport function createProfileCandidateMaterializer(\n profile: AgentProfile,\n surface: ImproveProfileSurface,\n baselineSurface: MutableSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): (candidateSurface: MutableSurface) => AgentProfile {\n const decode = (candidate: MutableSurface): MutableSurface => {\n if (profileComponents?.encoding !== 'json') return candidate\n if (typeof candidate !== 'string') {\n throw new ConfigError('improve(): JSON profile components require a text surface')\n }\n return componentSurface(parseWinnerJson(candidate, surface), 'JSON profile components')\n }\n const decodedBaseline = decode(baselineSurface)\n const baselineDigest = canonicalCandidateDigest(baselineSurface)\n if (profileComponents) {\n const reappliedBaseline = materializeImprovementProfileCandidate(\n profile,\n surface,\n decodedBaseline,\n skills,\n profileComponents,\n )\n if (canonicalAgentProfileDigest(reappliedBaseline) !== canonicalAgentProfileDigest(profile)) {\n throw new ConfigError(\n 'improve(): profileComponents.apply(profile, profileComponents.read(profile)) must reproduce the complete baseline profile exactly',\n )\n }\n }\n const candidates = new Map<Sha256Digest, AgentProfile>([[baselineDigest, profile]])\n return (candidateSurface) => {\n assertCandidateSurfaceKind(surface, baselineSurface, candidateSurface)\n const decodedCandidate = decode(candidateSurface)\n assertCandidateSurfaceKind(surface, decodedBaseline, decodedCandidate)\n const digest = canonicalCandidateDigest(candidateSurface)\n const existing = candidates.get(digest)\n if (existing) return existing\n const candidate = materializeImprovementProfileCandidate(\n profile,\n surface,\n immutableCandidateValue(decodedCandidate),\n skills,\n profileComponents,\n )\n candidates.set(digest, candidate)\n return candidate\n }\n}\n\nfunction inlineSkill(\n profile: ReadonlyAgentProfile,\n options: ImproveSkillsOptions | undefined,\n): Readonly<Extract<AgentProfileResourceRef, { kind: 'inline' }>> {\n const resourceName = options?.resourceName.trim()\n if (!resourceName) {\n throw new ConfigError(\n \"improve(): surface 'skills' requires opts.skills.resourceName for one inline profile skill\",\n )\n }\n assertFailClosedResources(profile, 'skills')\n const matches = (profile.resources?.skills ?? []).filter(\n (resource) => resource.name === resourceName,\n )\n if (matches.length !== 1 || matches[0]?.kind !== 'inline') {\n throw new ConfigError(\n `improve(): skill '${resourceName}' must identify exactly one inline profile resource`,\n )\n }\n return matches[0]\n}\n\nfunction profileInstructions(profile: ReadonlyAgentProfile): string {\n assertFailClosedResources(profile, 'memory')\n const instructions = profile.resources?.instructions\n if (instructions === undefined) return ''\n if (typeof instructions === 'string') return instructions\n if (instructions.kind === 'inline') return instructions.content\n throw new ConfigError(\n \"improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact\",\n )\n}\n\nfunction replaceProfileInstructions(\n profile: AgentProfile,\n content: string,\n): string | AgentProfileResourceRef {\n const instructions = profile.resources?.instructions\n if (typeof instructions !== 'object') return content\n if (instructions.kind !== 'inline') {\n throw new ConfigError(\n \"improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact\",\n )\n }\n return { ...instructions, content }\n}\n\nfunction assertFailClosedResources(\n profile: ReadonlyAgentProfile,\n surface: 'skills' | 'memory',\n): void {\n if (profile.resources?.failOnError !== true) {\n throw new ConfigError(\n `improve(): surface '${surface}' requires profile.resources.failOnError: true`,\n )\n }\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~1500-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~1500-char digest).\n *\n * It emits `ProposalFinding[]` so it drops into the same `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @stable\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { makeProposalFinding, type ProposalFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\ninterface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: ReadonlyArray<ProposalFinding>\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `analyzeGeneration` on `improve({ surface: 'code' })`:\n *\n * await improve({\n * surface: 'code',\n * findings: seedFindings,\n * code: { repoRoot, profile, executorForWorktree, buildPrompt },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => compareCandidateComposites(a.composite, b.composite))\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: ProposalFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: cand.composite !== null && cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} ${candidateCompositeDescription(cand.composite)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** Keep unscored candidates visible without inventing a numeric aggregate. */\nfunction compareCandidateComposites(left: number | null, right: number | null): number {\n if (left === null) return right === null ? 0 : 1\n if (right === null) return -1\n return left - right\n}\n\nfunction candidateCompositeDescription(composite: number | null): string {\n return composite === null ? 'has no aggregate score' : `scored composite ${composite.toFixed(3)}`\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","import { realpath } from 'node:fs/promises'\nimport { resolve as resolvePath } from 'node:path'\nimport { makeProposalFinding, type ProposalFinding } from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport {\n gitWorktreeAdapter,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type CodeSurface,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveOptions,\n type SelfImproveProposerResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from '../candidate-execution/digest'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport { agenticGenerator } from './agentic-generator'\nimport { rethrowAfterCleanup } from './cleanup'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveCodeOptions,\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImprovementCodeCandidate,\n} from './improve-types'\nimport { improvementDriver, type ManagedImprovementDriver } from './improvement-driver'\nimport { assertCandidateSurfaceKind, isCodeSurface } from './profile-surface'\nimport { rawTraceDistiller } from './raw-trace-distiller'\n\n/** Slice bound for distilled judge notes: wide enough that a real traceback or\n * failing assertion survives intact. */\nconst distilledNotesMaxChars = 1500\n\n/** Slice bound for a cell's error string. Full text remains on the raw cell. */\nconst distilledErrorMaxChars = 500\n\n/** Distill failing cells into typed findings for the next proposal round. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: ReadonlyArray<ProposalFinding>,\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{\n scenario: string\n composite: number\n notes: string\n claim?: string\n error?: string\n }> = []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, judge) => sum + (judge.composite ?? 0), 0) /\n judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((judge) => judge.notes)\n .filter((note): note is string => typeof note === 'string' && note.length > 0)\n .join('; ')\n .slice(0, distilledNotesMaxChars)\n const claim =\n notes ||\n (error ? `Scenario ${scenario} failed: ${error.slice(0, distilledErrorMaxChars)}` : '')\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(claim ? { claim } : {}),\n ...(error ? { error: error.slice(0, distilledErrorMaxChars) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((left, right) => left.composite - right.composite)\n return failures.slice(0, CAP).map((failure) =>\n makeProposalFinding({\n analyst_id: 'generation-failure-distiller',\n proposal_origin: 'search',\n severity: failure.error !== undefined || failure.composite < 0.5 ? 'high' : 'medium',\n area: 'generation-failure',\n confidence: 1,\n subject: failure.scenario,\n claim: `Scenario ${failure.scenario} scored composite ${failure.composite}${\n failure.notes ? `: ${failure.notes}` : ''\n }${failure.error ? ` (error: ${failure.error})` : ''}`,\n evidence_refs: [],\n metadata: {\n scenario: failure.scenario,\n composite: failure.composite,\n ...(failure.notes ? { notes: failure.notes } : {}),\n ...(failure.error !== undefined ? { error: failure.error } : {}),\n },\n }),\n )\n }\n}\n\n/** Default code-run analysis: raw trace paths for durable runs, otherwise a\n * bounded digest of failed cells. */\nfunction defaultDistillerFor<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n findings: ReadonlyArray<ProposalFinding>,\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const durableRun = opts.runDir !== undefined && !opts.runDir.startsWith('mem://')\n const useRawTraces = opts.rawTraceContext ?? durableRun\n if (useRawTraces) return rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n return generationFailureDistiller<TScenario, TArtifact>(findings)\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer<ProposalFinding>\n cleanup(retainedWinner?: MutableSurface): Promise<void>\n}\n\nasync function discardPreparedBaseline(\n worktree: WorktreeAdapter,\n baselineWorktree: Worktree,\n cause: unknown,\n): Promise<never> {\n return rethrowAfterCleanup(\n cause,\n () => worktree.discard(baselineWorktree),\n 'improve(): code preparation failed',\n )\n}\n\n/**\n * The real path of a repository root, for the one comparison that needs it.\n *\n * Git prints a RESOLVED worktree path, and the Eval worktree adapter compares what git\n * printed against the root it was handed. A root whose PREFIX is a symlink therefore never\n * matches: on macOS the OS hands out temp roots under /var, a symlink to /private/var, so the\n * adapter refuses to finalize or discard a worktree it created seconds earlier. Resolve once\n * here, where the caller's root meets git, instead of at every caller.\n *\n * A directory that does not exist yet — `worktreeDir` is created on demand — keeps its\n * lexical form; the adapter creates it under a root that is already resolved.\n */\nasync function realRoot(path: string): Promise<string> {\n try {\n return await realpath(path)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n return resolvePath(path)\n }\n}\n\n/** Create a clean incumbent checkout and the candidate producer for a code run. */\nasync function prepareCodeRun(code: ImproveCodeOptions): Promise<PreparedCodeRun> {\n const authorProfile = agentProfileSchema.parse(code.profile)\n assertExecutableAgentProfile(authorProfile, 'improve(code) author')\n const baseRef = code.baseRef ?? 'main'\n const worktree =\n code.worktree ??\n gitWorktreeAdapter({\n repoRoot: await realRoot(code.repoRoot),\n ...(code.worktreeDir ? { worktreeDir: await realRoot(code.worktreeDir) } : {}),\n })\n const baselineWorktree = await worktree.create({ baseRef, label: 'incumbent-baseline' })\n try {\n const baseline = await worktree.finalize(baselineWorktree, 'Incumbent code checkout')\n let baselineDiscarded = false\n const generator = code.generator\n ? code.generator\n : agenticGenerator({\n profile: authorProfile,\n executorForWorktree: code.executorForWorktree,\n buildPrompt: code.buildPrompt,\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs !== undefined ? { timeoutMs: code.timeoutMs } : {}),\n ...(code.maximumCharge ? { maximumCharge: code.maximumCharge } : {}),\n })\n const managed: ManagedImprovementDriver = improvementDriver({ worktree, generator, baseRef })\n\n return {\n baseline,\n proposer: managed,\n async cleanup(retainedWinner) {\n const errors: unknown[] = []\n const retainedWorktreeRef = isCodeSurface(retainedWinner)\n ? retainedWinner.worktreeRef\n : undefined\n try {\n await managed?.cleanup(retainedWorktreeRef ? [retainedWorktreeRef] : [])\n } catch (cause) {\n errors.push(cause)\n }\n if (!baselineDiscarded && retainedWorktreeRef !== baseline.worktreeRef) {\n try {\n await worktree.discard(baselineWorktree)\n baselineDiscarded = true\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improve(): failed to clean code improvement worktrees')\n }\n },\n }\n } catch (cause) {\n return discardPreparedBaseline(worktree, baselineWorktree, cause)\n }\n}\n\nfunction idempotentDispose(dispose: () => Promise<void>): () => Promise<void> {\n let disposed = false\n let inFlight: Promise<void> | undefined\n return async () => {\n if (disposed) return\n if (inFlight) return inFlight\n inFlight = (async () => {\n await dispose()\n disposed = true\n })()\n try {\n await inFlight\n } finally {\n inFlight = undefined\n }\n }\n}\n\nexport async function runCodeImprovement<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n): Promise<ImproveCodeResult<TScenario, TArtifact>> {\n const {\n gate = 'holdout',\n findings: inputFindings = [],\n rawTraceContext: _rawTraceContext,\n code,\n promotionGate,\n analyzeGeneration,\n surface: _surface,\n ...sharedOptions\n } = opts\n const findings = immutableCandidateValue([\n ...assertProposalFindings(inputFindings, 'improve() code findings'),\n ])\n const preparedCode = await prepareCodeRun(code)\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n\n let raw: SelfImproveProposerResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n baselineSurface: preparedCode.baseline,\n proposer: preparedCode.proposer,\n budget,\n findings,\n ...(promotionGate !== undefined ? { gate: promotionGate } : {}),\n ...(analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n analyzeGeneration ?? defaultDistillerFor<TScenario, TArtifact>(opts, findings),\n }),\n })\n } catch (cause) {\n return rethrowAfterCleanup(\n cause,\n () => preparedCode.cleanup(),\n 'improve(): code improvement failed',\n )\n }\n\n const winnerSurface = raw.winner.surface\n assertCandidateSurfaceKind('code', preparedCode.baseline, winnerSurface)\n try {\n await preparedCode.cleanup(winnerSurface)\n } catch (cleanupCause) {\n try {\n await preparedCode.cleanup()\n } catch (finalCleanupCause) {\n throw new AggregateError(\n [cleanupCause, finalCleanupCause],\n 'improve(): code result cleanup failed, including the final all-worktree retry',\n )\n }\n throw new AggregateError(\n [cleanupCause],\n 'improve(): code result cleanup failed; the final all-worktree retry succeeded',\n )\n }\n const dispose = idempotentDispose(async () => preparedCode.cleanup())\n const candidate = immutableCandidateValue<ImprovementCodeCandidate>({\n surface: 'code',\n value: winnerSurface,\n })\n\n return {\n mode: 'code',\n candidate,\n decision: raw.gateDecision,\n ...(raw.lift !== undefined ? { lift: raw.lift } : {}),\n cost: copyImproveCost(raw.cost),\n durationMs: raw.durationMs,\n lineage: Object.freeze({\n invocationId: raw.provenance.runId,\n runId: raw.provenance.runId,\n developmentSplitDigest: raw.provenance.evidence.search.splitDigest,\n }),\n generationsExplored: raw.generationsExplored,\n raw,\n dispose,\n }\n}\n","import type { OptimizationMethod, Scenario } from '@tangle-network/agent-eval/campaign'\nimport type { ImproveCandidateValidationInput } from './improve-types'\n\nconst methodRuntimeControls = Symbol('agent-runtime.improvement.method-runtime-controls')\n\ninterface MethodRuntimeControls {\n costAttribution: 'optimizer-run'\n validateCandidate: (input: ImproveCandidateValidationInput) => void\n}\n\ntype ControlledOptimizationMethod<TScenario extends Scenario, TArtifact> = OptimizationMethod<\n TScenario,\n TArtifact\n> & {\n [methodRuntimeControls]?: MethodRuntimeControls\n}\n\nexport function withMethodRuntimeControls<TScenario extends Scenario, TArtifact>(\n method: OptimizationMethod<TScenario, TArtifact>,\n controls: MethodRuntimeControls,\n): OptimizationMethod<TScenario, TArtifact> {\n return Object.freeze({\n ...method,\n [methodRuntimeControls]: Object.freeze({ ...controls }),\n })\n}\n\nexport function methodRuntimeControlsOf<TScenario extends Scenario, TArtifact>(\n method: OptimizationMethod<TScenario, TArtifact>,\n): MethodRuntimeControls | undefined {\n return (method as ControlledOptimizationMethod<TScenario, TArtifact>)[methodRuntimeControls]\n}\n","import type { CostReceipt } from '@tangle-network/agent-eval'\nimport type {\n CostLedgerHandle,\n OptimizationMethodInput,\n OptimizationMethodResult,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\n\ntype LedgerFilter = Parameters<CostLedgerHandle['summary']>[0]\ntype LedgerWaitOptions = Parameters<NonNullable<CostLedgerHandle['waitForIdle']>>[0]\n\nconst EVALUATION_TAG = 'runtimeEvaluationRef'\nconst INVOCATION_TAG = 'runtimeInvocationId'\n\ninterface MethodCostScope {\n evaluationRef: Sha256Digest\n invocationId: string\n methodTag?: string\n}\n\nexport type MethodCostAttribution = 'invocation' | 'optimizer-run'\n\nexport function methodInputWithScopedCost<TScenario extends Scenario, TArtifact>(\n input: OptimizationMethodInput<TScenario, TArtifact>,\n scope: MethodCostScope,\n costAttribution: MethodCostAttribution = 'invocation',\n): OptimizationMethodInput<TScenario, TArtifact> {\n return Object.freeze({\n ...input,\n costLedger: scopedCostLedger(input.costLedger, scope, costAttribution),\n })\n}\n\nexport function methodInvocationCostLedger(\n ledger: CostLedgerHandle,\n scope: MethodCostScope,\n): CostLedgerHandle {\n return scopedCostLedger(ledger, scope, 'invocation')\n}\n\nexport function assertMethodCostRecorded(\n methodName: string,\n result: Pick<OptimizationMethodResult, 'cost' | 'provenance'>,\n compatibleLedger: CostLedgerHandle,\n invocationLedger: CostLedgerHandle,\n costCeiling: number | undefined,\n costAttribution: MethodCostAttribution = 'invocation',\n historicalReceipts: readonly CostReceipt[] = [],\n): void {\n const { cost } = result\n let observed =\n costAttribution === 'optimizer-run' && result.provenance?.runId\n ? compatibleLedger.summary({ tags: { optimizerRun: result.provenance.runId } })\n : invocationLedger.summary()\n if (historicalReceipts.length > 0 && costAttribution === 'invocation') {\n const receipts = new Map(invocationLedger.list().map((receipt) => [receipt.callId, receipt]))\n for (const receipt of historicalReceipts) receipts.set(receipt.callId, receipt)\n observed = {\n ...observed,\n totalCostUsd: [...receipts.values()].reduce((sum, receipt) => sum + receipt.costUsd, 0),\n accountingComplete:\n observed.accountingComplete &&\n historicalReceipts.every(\n (receipt) => !receipt.costUnknown && receipt.usageUnknown !== true,\n ),\n }\n }\n if (costCeiling !== undefined && !cost.accountingComplete) {\n throw new ConfigError(\n `improve(): method '${methodName}' returned incomplete cost accounting under costCeiling; refusing final scoring`,\n )\n }\n if (costCeiling !== undefined && exceeds(cost.totalCostUsd, costCeiling)) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported cost $${cost.totalCostUsd} above costCeiling $${costCeiling}; refusing final scoring`,\n )\n }\n if (cost.accountingComplete && !observed.accountingComplete) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported complete cost accounting but its shared cost receipts are incomplete`,\n )\n }\n if (cost.accountingComplete && !approximatelyEqual(cost.totalCostUsd, observed.totalCostUsd)) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported $${cost.totalCostUsd} but recorded $${observed.totalCostUsd} through input.costLedger`,\n )\n }\n}\n\nfunction scopedCostLedger(\n parent: CostLedgerHandle,\n scope: MethodCostScope,\n costAttribution: MethodCostAttribution,\n): CostLedgerHandle {\n const evaluationTags = {\n [EVALUATION_TAG]: scope.evaluationRef,\n }\n const invocationTags = {\n ...evaluationTags,\n [INVOCATION_TAG]: scope.invocationId,\n ...(scope.methodTag === undefined ? {} : { [scope.methodTag]: '1' }),\n }\n const readTags = (filter: LedgerFilter): Record<string, string> =>\n costAttribution === 'optimizer-run' && hasOptimizerRunFilter(filter)\n ? evaluationTags\n : invocationTags\n return {\n costCeilingUsd: parent.costCeilingUsd,\n runPaidCall: (input) =>\n parent.runPaidCall({\n ...input,\n tags: { ...(input.tags ?? {}), ...invocationTags },\n }),\n reconcile: (...args) => parent.reconcile(...args),\n list: (filter) => parent.list(withTags(filter, readTags(filter))),\n listPending: (filter) => parent.listPending?.(withTags(filter, readTags(filter))) ?? [],\n summary: (filter) => parent.summary(withTags(filter, readTags(filter))),\n waitForIdle: (options: LedgerWaitOptions = {}) =>\n parent.waitForIdle?.({\n ...options,\n filter: withTags(options.filter, readTags(options.filter)),\n }) ??\n Promise.resolve(\n parent.summary(withTags(options.filter, readTags(options.filter))).pendingCalls === 0,\n ),\n markCompleted: (count) => parent.markCompleted(count),\n costPerCompletedTask: () => parent.costPerCompletedTask(),\n }\n}\n\nfunction hasOptimizerRunFilter(filter: LedgerFilter): boolean {\n return typeof filter?.tags?.optimizerRun === 'string' && filter.tags.optimizerRun.length > 0\n}\n\nfunction withTags(filter: LedgerFilter, tags: Record<string, string>): LedgerFilter {\n return {\n ...(filter ?? {}),\n tags: { ...(filter?.tags ?? {}), ...tags },\n }\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8\n return Math.abs(left - right) <= tolerance\n}\n\nfunction exceeds(value: number, limit: number): boolean {\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(value), Math.abs(limit)) * 8\n return value - limit > tolerance\n}\n\n/** Only prior root invocations are additional to a container's current invocation receipts. */\nexport function methodHistoricalReceipts(\n ledger: CostLedgerHandle,\n optimizerRun: string,\n invocationId: string,\n): readonly CostReceipt[] {\n return ledger\n .list({ tags: { optimizerRun } })\n .filter((receipt) => receipt.tags?.[INVOCATION_TAG] !== invocationId)\n}\n","import { redact } from '@tangle-network/agent-eval/traces'\nimport { type Sha256Digest, sha256DigestSchema } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { ImproveCandidateValidationInput, ImproveCandidateValidator } from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\n/** One spelling of the execution-identity rule for optimization, training, and the harness. */\nexport function parseExecutionRef(value: unknown, label: string): Sha256Digest {\n const parsed = sha256DigestSchema.safeParse(value)\n if (!parsed.success) {\n throw new ConfigError(`${label}: executionRef must be a lowercase sha256:<64 hex> digest`)\n }\n return parsed.data\n}\n\n/** Validate the callback itself before any optimizer, trainer, or candidate work starts. */\nexport function assertCandidateValidator(\n validator: unknown,\n): asserts validator is ImproveCandidateValidator | undefined {\n if (validator !== undefined && typeof validator !== 'function') {\n throw new ConfigError('validateCandidate must be a function when present')\n }\n}\n\n/** A validator accepts synchronously by returning void, or rejects by throwing. */\nexport function validateProfileCandidate(\n validator: ImproveCandidateValidator | undefined,\n input: ImproveCandidateValidationInput,\n): void {\n assertCandidateValidator(validator)\n const result: unknown = validator?.(Object.freeze(input))\n if (result !== undefined) {\n // Observe a rejected async callback without treating its eventual result as admission.\n void Promise.resolve(result).catch(() => {})\n throw new ConfigError('candidate validators must return void synchronously or throw')\n }\n}\n\n/**\n * Refuse exact held-out content digests already declared in this profile's training lineage.\n * Both training and trainer-visible validation rows are exposure. This is an exact\n * provenance check, not fuzzy decontamination or proof that undeclared training was fresh.\n */\nexport function assertProfileTrainingIsHeldOut(\n profile: ReadonlyAgentProfile,\n heldOutDigests: ReadonlySet<Sha256Digest>,\n): void {\n const training = profile.metadata?.training\n if (!training) return\n for (const receipt of [training.receipt, ...training.ancestors]) {\n if (receipt.dataset.tasks.some((task) => heldOutDigests.has(task.contentDigest))) {\n // Do not disclose held-out task identities or payloads to an optimizer via errors.\n throw new ConfigError('known training exposure overlaps held-out evaluation')\n }\n }\n}\n\n/**\n * JSON paths of credential and private values in candidate content, found by\n * the redaction core, which names each value it would change. A candidate that\n * leaves Runtime (an external optimizer, a search ledger) is refused on any.\n */\nexport function privateValuePaths(values: readonly unknown[]): string[] {\n return [\n ...new Set(\n values.flatMap((value) =>\n redact(value).report.findings.map((finding) => jsonPathOf(finding.path)),\n ),\n ),\n ]\n}\n\n/** `/remote/url` or `/tools/0/env` as `$.remote.url` or `$.tools[0].env`. */\nfunction jsonPathOf(pointer: string): string {\n return pointer\n .split('/')\n .slice(1)\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'))\n .reduce(\n (path, segment) => (/^\\d+$/.test(segment) ? `${path}[${segment}]` : `${path}.${segment}`),\n '$',\n )\n}\n","import type { ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n campaignScenarioIdentity,\n campaignSplitDigestFromIdentities,\n type JudgeConfig,\n type MutableSurface,\n type Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport type {\n ImproveCandidateValidator,\n ImproveOptimizationRunOptions,\n ImproveProfileSurface,\n ImproveScenarioPartitions,\n ImproveSkillsOptions,\n} from './improve-types'\n\nexport interface MethodEvaluationIdentity {\n evaluationRef: Sha256Digest\n developmentSplitDigest: Sha256Digest\n finalTestSplitDigest: Sha256Digest\n scenarioPartitions: ImproveScenarioPartitions\n judgeDescriptors: readonly MethodJudgeDescriptor[]\n}\n\ninterface MethodJudgeDescriptor {\n name: string\n dimensions: readonly { key: string; description: string }[]\n declaredVersion: string | null\n scoreImplementation: string\n appliesToImplementation: string | null\n}\n\nexport function buildMethodEvaluationIdentity<TScenario extends Scenario, TArtifact>(input: {\n executionRef: Sha256Digest\n baselineProfileDigest: Sha256Digest\n baselineSurface: MutableSurface\n surface: ImproveProfileSurface\n skills?: ImproveSkillsOptions\n validateCandidate?: ImproveCandidateValidator\n findings: ReadonlyArray<ProposalFinding>\n trainScenarios: readonly TScenario[]\n selectionScenarios: readonly TScenario[]\n testScenarios: readonly TScenario[]\n judges: readonly JudgeConfig<TArtifact, TScenario>[]\n seed?: number\n reps?: number\n costCeiling?: number\n optimizationRunOptions?: ImproveOptimizationRunOptions<TScenario, TArtifact>\n}): MethodEvaluationIdentity {\n const optimizationReps = input.optimizationRunOptions?.reps ?? 1\n const finalTestReps = input.reps ?? 1\n const scenarioPartitions = immutableCandidateValue<ImproveScenarioPartitions>({\n train: input.trainScenarios.map(campaignScenarioIdentity),\n selection: input.selectionScenarios.map(campaignScenarioIdentity),\n finalTest: input.testScenarios.map(campaignScenarioIdentity),\n optimizationReps,\n finalTestReps,\n })\n const developmentSplitDigest = canonicalCandidateDigest({\n train: campaignSplitDigestFromIdentities(scenarioPartitions.train, optimizationReps),\n selection: campaignSplitDigestFromIdentities(scenarioPartitions.selection, optimizationReps),\n })\n const finalTestSplitDigest = campaignSplitDigestFromIdentities(\n scenarioPartitions.finalTest,\n finalTestReps,\n )\n const judgeDescriptors = input.judges.map(judgeDescriptor)\n const evaluationRef = canonicalCandidateDigest({\n executionRef: input.executionRef,\n baselineProfileDigest: input.baselineProfileDigest,\n coordinate: profileCoordinate(input.surface, input.baselineSurface, input.skills),\n candidateValidation: input.validateCandidate\n ? Function.prototype.toString.call(input.validateCandidate)\n : null,\n developmentSplitDigest,\n finalTestSplitDigest,\n findings: input.findings,\n judges: judgeDescriptors,\n run: {\n seed: input.seed ?? 42,\n finalReps: input.reps ?? 1,\n optimizationReps,\n costCeiling: input.costCeiling ?? null,\n resumable: input.optimizationRunOptions?.resumable ?? true,\n maxConcurrency: input.optimizationRunOptions?.maxConcurrency ?? 2,\n abortOnCellError: input.optimizationRunOptions?.abortOnCellError ?? false,\n dispatchTimeoutMs: input.optimizationRunOptions?.dispatchTimeoutMs ?? null,\n dispatchShutdownTimeoutMs: input.optimizationRunOptions?.dispatchShutdownTimeoutMs ?? 5_000,\n tracing: input.optimizationRunOptions?.tracing ?? 'on',\n expectUsage: input.optimizationRunOptions?.expectUsage ?? 'warn',\n captureSource: input.optimizationRunOptions?.captureSource ?? null,\n captureSourceVersionHash: input.optimizationRunOptions?.captureSourceVersionHash ?? null,\n },\n })\n return {\n evaluationRef,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n judgeDescriptors,\n }\n}\n\nfunction profileCoordinate(\n surface: ImproveProfileSurface,\n baselineSurface: MutableSurface,\n skills: ImproveSkillsOptions | undefined,\n): {\n surface: ImproveProfileSurface\n resourceName: string | null\n componentNames: string[]\n} {\n return {\n surface,\n resourceName: surface === 'skills' ? (skills?.resourceName.trim() ?? null) : null,\n componentNames:\n typeof baselineSurface === 'object' &&\n baselineSurface !== null &&\n baselineSurface.kind === 'components'\n ? Object.keys(baselineSurface.components).sort()\n : [],\n }\n}\n\nfunction judgeDescriptor<TScenario extends Scenario, TArtifact>(\n judge: JudgeConfig<TArtifact, TScenario>,\n): MethodJudgeDescriptor {\n return {\n name: judge.name,\n dimensions: judge.dimensions.map((dimension) => ({ ...dimension })),\n declaredVersion: judge.judgeVersion ?? null,\n scoreImplementation: Function.prototype.toString.call(judge.score),\n appliesToImplementation: judge.appliesTo\n ? Function.prototype.toString.call(judge.appliesTo)\n : null,\n }\n}\n","/**\n * What every profile improvement prepares before any optimizer or search runs:\n * the exact surface and its baseline, the evaluation identity, identified\n * judges, the identities a search ledger records, and one materializer that\n * admits a candidate only after the held-out and caller checks. `improve()`\n * with an external method and with `searchMethod` share it, so a candidate is\n * materialized and admitted the same way on both paths.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ProposalFinding } from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport type {\n JudgeConfig,\n MutableSurface,\n Scenario,\n SearchModelIdentity,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport {\n assertCandidateValidator,\n assertProfileTrainingIsHeldOut,\n parseExecutionRef,\n validateProfileCandidate,\n} from './candidate-validation'\nimport type {\n ImproveCandidateValidator,\n ImproveMethodOptions,\n ImproveOptimizationRunOptions,\n ImproveProfileSurface,\n ImproveSearchIdentity,\n} from './improve-types'\nimport { buildMethodEvaluationIdentity, type MethodEvaluationIdentity } from './method-identity'\nimport { createProfileCandidateMaterializer, prepareProfileSurface } from './profile-surface'\n\n/** The options both improvement paths read before they diverge. */\ntype ProfileImprovementInput<TScenario extends Scenario, TArtifact> = Pick<\n ImproveMethodOptions<TScenario, TArtifact>,\n | 'surface'\n | 'executionRef'\n | 'validateCandidate'\n | 'findings'\n | 'skills'\n | 'profileComponents'\n | 'minimumLift'\n | 'subject'\n | 'trainScenarios'\n | 'selectionScenarios'\n | 'testScenarios'\n | 'judges'\n | 'seed'\n | 'costCeiling'\n> & {\n reps?: number\n optimizationRunOptions?: ImproveOptimizationRunOptions<TScenario, TArtifact>\n}\n\nexport interface PreparedProfileImprovement<TScenario extends Scenario, TArtifact> {\n profile: AgentProfile\n surface: ImproveProfileSurface\n executionRef: Sha256Digest\n findings: ReadonlyArray<ProposalFinding>\n minimumLift: number\n baselineSurface: MutableSurface\n baselineValue: unknown\n baselineProfileDigest: Sha256Digest\n identity: MethodEvaluationIdentity\n /** Unique id of this invocation, which scopes its cost receipts. */\n invocationId: string\n /** Judges carrying a `judgeVersion` derived from the evaluation identity. */\n judges: JudgeConfig<TArtifact, TScenario>[]\n searchIdentity: ImproveSearchIdentity\n /** The surface a profile holds at the searched coordinate. */\n surfaceOf(candidate: AgentProfile): MutableSurface\n /** Materialize a candidate surface without admitting it. */\n materializeCandidate(candidateSurface: MutableSurface): AgentProfile\n /** Refuse a materialized candidate unless it passes the held-out check and\n * the caller's validator; each surface is checked once. */\n admitCandidate(candidate: AgentProfile, candidateSurface: MutableSurface): void\n /** Materialize and admit a candidate surface. */\n materializeProfile(candidateSurface: MutableSurface): AgentProfile\n /** Run one validator on an exact materialized candidate. */\n validateMaterialized(\n validator: ImproveCandidateValidator | undefined,\n candidate: AgentProfile,\n candidateSurface: MutableSurface,\n isBaseline: boolean,\n ): void\n}\n\nexport function prepareProfileImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n input: ProfileImprovementInput<TScenario, TArtifact>,\n): PreparedProfileImprovement<TScenario, TArtifact> {\n const {\n surface = 'prompt',\n validateCandidate,\n skills,\n profileComponents,\n minimumLift = 0,\n } = input\n assertCandidateValidator(validateCandidate)\n if (!Number.isFinite(minimumLift) || minimumLift < 0) {\n throw new ConfigError(\n 'improve(): minimumLift must be a finite number greater than or equal to 0',\n )\n }\n if (profileComponents && surface !== 'agent-profile') {\n throw new ConfigError(\"improve(): profileComponents is valid only with surface 'agent-profile'\")\n }\n if (\n input.subject !== undefined &&\n (typeof input.subject !== 'string' ||\n !input.subject.trim() ||\n input.subject !== input.subject.trim())\n ) {\n throw new ConfigError('improve(): subject must be a trimmed non-empty string')\n }\n const executionRef = parseExecutionRef(input.executionRef, 'improve()')\n const findings = immutableCandidateValue([\n ...assertProposalFindings(input.findings ?? [], 'improve() method findings'),\n ])\n const preparedSurface = prepareProfileSurface(profile, surface, skills, profileComponents)\n const baselineSurface = preparedSurface.surface\n const baselineValue = immutableCandidateValue(preparedSurface.value)\n const baselineProfileDigest = canonicalAgentProfileDigest(profile)\n const identity = buildMethodEvaluationIdentity({\n executionRef,\n baselineProfileDigest,\n baselineSurface,\n surface,\n skills,\n validateCandidate,\n findings,\n trainScenarios: input.trainScenarios,\n selectionScenarios: input.selectionScenarios,\n testScenarios: input.testScenarios,\n judges: input.judges,\n seed: input.seed,\n reps: input.reps,\n costCeiling: input.costCeiling,\n optimizationRunOptions: input.optimizationRunOptions,\n })\n const judges = input.judges.map((judge, index) =>\n Object.freeze({\n ...judge,\n judgeVersion: canonicalCandidateDigest({\n evaluationRef: identity.evaluationRef,\n descriptor: identity.judgeDescriptors[index],\n }),\n }),\n )\n const rawMaterializeProfile = createProfileCandidateMaterializer(\n profile,\n surface,\n baselineSurface,\n skills,\n profileComponents,\n )\n const baselineSurfaceDigest = canonicalCandidateDigest(baselineSurface)\n const heldOutDigests = new Set(\n identity.scenarioPartitions.finalTest.map((task) => task.scenarioDigest),\n )\n const validatedCandidates = new Set<Sha256Digest>()\n const validateMaterialized: PreparedProfileImprovement<\n TScenario,\n TArtifact\n >['validateMaterialized'] = (validator, candidate, candidateSurface, isBaseline) => {\n const prepared = prepareProfileSurface(candidate, surface, skills, profileComponents)\n validateProfileCandidate(validator, {\n profile: candidate,\n surface,\n candidateSurface,\n value: immutableCandidateValue(prepared.value),\n isBaseline,\n })\n }\n const admitCandidate = (candidate: AgentProfile, candidateSurface: MutableSurface): void => {\n const candidateDigest = canonicalCandidateDigest(candidateSurface)\n if (validatedCandidates.has(candidateDigest)) return\n assertProfileTrainingIsHeldOut(candidate, heldOutDigests)\n validateMaterialized(\n validateCandidate,\n candidate,\n immutableCandidateValue(candidateSurface),\n candidateDigest === baselineSurfaceDigest,\n )\n validatedCandidates.add(candidateDigest)\n }\n const materializeProfile = (candidateSurface: MutableSurface): AgentProfile => {\n const candidate = rawMaterializeProfile(candidateSurface)\n admitCandidate(candidate, candidateSurface)\n return candidate\n }\n materializeProfile(baselineSurface)\n return {\n profile,\n surface,\n executionRef,\n findings,\n minimumLift,\n baselineSurface,\n baselineValue,\n baselineProfileDigest,\n identity,\n invocationId: `runtime-optimization:${randomUUID()}`,\n judges,\n searchIdentity: Object.freeze({\n subject: input.subject ?? profile.name ?? 'agent-profile',\n agent: { uri: 'agent-runtime:improve-execution-ref', revision: executionRef },\n judge: {\n uri: 'agent-runtime:improve-judges',\n revision: canonicalCandidateDigest(identity.judgeDescriptors),\n },\n model: profileModel(profile),\n }),\n surfaceOf: (candidate) =>\n prepareProfileSurface(candidate, surface, skills, profileComponents).surface,\n materializeCandidate: rawMaterializeProfile,\n admitCandidate,\n materializeProfile,\n validateMaterialized,\n }\n}\n\n/** The profile's model hint as a moving alias; each cell records what it resolved. */\nfunction profileModel(profile: AgentProfile): SearchModelIdentity {\n const hint = profile.model?.default\n if (!hint) {\n return {\n provider: 'unspecified',\n alias: 'unspecified',\n unknown: 'the profile names no model; each cell records the model it resolved',\n }\n }\n return {\n provider: profile.model?.provider ?? 'unspecified',\n alias: hint,\n unknown:\n 'the profile names a model hint, not a snapshot; each cell records the model it resolved',\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { CostReceipt } from '@tangle-network/agent-eval'\nimport {\n compareOptimizationMethods,\n fsCampaignStorage,\n type OptimizationMethod,\n type OptimizationMethodInput,\n type OptimizationMethodResult,\n verifySearchHistoryArtifact,\n} from '@tangle-network/agent-eval/campaign'\nimport type { MutableSurface, Scenario } from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile, Sha256Digest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveMethodContext,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementProfileCandidate,\n} from './improve-types'\nimport { methodRuntimeControlsOf } from './method-controls'\nimport {\n assertMethodCostRecorded,\n methodHistoricalReceipts,\n methodInputWithScopedCost,\n methodInvocationCostLedger,\n} from './method-cost'\nimport { prepareProfileImprovement } from './profile-improvement'\nimport { assertCandidateSurfaceKind } from './profile-surface'\n\nfunction resolveOptimizationMethod<TScenario extends Scenario, TArtifact>(\n source: ImproveMethodSource<TScenario, TArtifact>,\n context: ImproveMethodContext,\n): OptimizationMethod<TScenario, TArtifact> {\n const method = typeof source === 'function' ? source(context) : source\n if (\n !method ||\n typeof method !== 'object' ||\n typeof method.name !== 'string' ||\n method.name.trim() !== method.name ||\n method.name.length === 0 ||\n typeof method.optimize !== 'function'\n ) {\n throw new ConfigError(\n 'improve(): method must be a complete OptimizationMethod with a trimmed name and optimize(input)',\n )\n }\n return method\n}\n\n/**\n * Run one complete method, then compare its winner with the baseline on the\n * held-out test split. A method that records its search (GEPA and SkillOpt do\n * through `officialGepa` and `officialSkillOpt`) must close its ledger; Runtime\n * replays the bytes and returns the receipt. A method that records none\n * returns `searchHistory: null`: its lineage is unknown, not empty.\n */\nexport async function runMethodImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult> {\n const {\n surface: _surface,\n executionRef: _executionRef,\n method: methodSource,\n agent,\n validateCandidate: _validateCandidate,\n findings: _findings,\n skills: _skills,\n profileComponents: _profileComponents,\n optimizationRunOptions,\n minimumLift: _minimumLift,\n subject: _subject,\n ...comparisonOptions\n } = opts\n const prepared = prepareProfileImprovement(profile, opts)\n const {\n surface,\n identity,\n invocationId,\n baselineSurface,\n materializeProfile,\n validateMaterialized,\n minimumLift,\n } = prepared\n const { evaluationRef, developmentSplitDigest, finalTestSplitDigest, scenarioPartitions } =\n identity\n const dispatchRef = `improve:${evaluationRef}`\n const method = resolveOptimizationMethod(methodSource, {\n profile,\n evaluationRef,\n surface,\n baselineSurface,\n baselineValue: prepared.baselineValue,\n findings: prepared.findings,\n searchIdentity: prepared.searchIdentity,\n })\n const costScope = { evaluationRef: identity.evaluationRef, invocationId }\n const invoke = async (\n current: OptimizationMethod<TScenario, TArtifact>,\n input: OptimizationMethodInput<TScenario, TArtifact>,\n ): Promise<{ result: OptimizationMethodResult; historical: readonly CostReceipt[] }> => {\n const controls = methodRuntimeControlsOf(current)\n const scope = { ...costScope, methodTag: `runtimeMethod:${randomUUID()}` }\n // Every enclosing scope must preserve explicit optimizerRun reads from previous invocations.\n const scopedInput = methodInputWithScopedCost(input, scope, 'optimizer-run')\n const invocationLedger = methodInvocationCostLedger(scopedInput.costLedger, scope)\n const historical = new Map<string, CostReceipt>()\n let children = 0\n const checked = new Set<Sha256Digest>()\n const toRoot = (value: MutableSurface): MutableSurface =>\n immutableCandidateValue(input.surfaceToRoot?.(immutableCandidateValue(value)) ?? value)\n const currentBaselineDigest = canonicalCandidateDigest(toRoot(input.baselineSurface))\n const check = (value: MutableSurface): void => {\n const rootSurface = toRoot(value)\n const candidateDigest = canonicalCandidateDigest(rootSurface)\n if (checked.has(candidateDigest)) return\n validateMaterialized(\n controls?.validateCandidate,\n materializeProfile(rootSurface),\n rootSurface,\n candidateDigest === currentBaselineDigest,\n )\n checked.add(candidateDigest)\n }\n check(input.baselineSurface)\n const result = await current.optimize(\n Object.freeze({\n ...scopedInput,\n invokeMethod: async (\n child: OptimizationMethod<TScenario, TArtifact>,\n childInput: OptimizationMethodInput<TScenario, TArtifact>,\n ) => {\n const verified = await invoke(child, childInput)\n children += 1\n for (const receipt of verified.historical) historical.set(receipt.callId, receipt)\n return verified.result\n },\n dispatchWithSurface: (\n ...[value, scenario, context]: Parameters<\n OptimizationMethodInput<TScenario, TArtifact>['dispatchWithSurface']\n >\n ) => {\n check(value)\n return input.dispatchWithSurface(value, scenario, context)\n },\n }),\n )\n check(result.winnerSurface)\n assertMethodCostRecorded(\n current.name,\n result,\n scopedInput.costLedger,\n invocationLedger,\n comparisonOptions.costCeiling,\n children > 0 ? 'invocation' : controls?.costAttribution,\n [...historical.values()],\n )\n if (controls?.costAttribution === 'optimizer-run' && result.provenance?.runId) {\n for (const receipt of methodHistoricalReceipts(\n scopedInput.costLedger,\n result.provenance.runId,\n invocationId,\n ))\n historical.set(receipt.callId, receipt)\n }\n return { result, historical: [...historical.values()] }\n }\n const measuredMethod: OptimizationMethod<TScenario, TArtifact> = {\n ...method,\n async optimize(input) {\n const scopedInput = methodInputWithScopedCost(input, costScope, 'optimizer-run')\n return (await invoke(method, scopedInput)).result\n },\n }\n // The method writes its search ledger where Runtime reads it back.\n const methodStorage =\n optimizationRunOptions?.storage ?? comparisonOptions.storage ?? fsCampaignStorage()\n const startedAt = Date.now()\n const raw = await compareOptimizationMethods<TScenario, TArtifact>({\n ...comparisonOptions,\n judges: prepared.judges,\n dispatchRef,\n optimizationRunOptions: {\n ...(optimizationRunOptions ?? {}),\n storage: methodStorage,\n dispatchRef,\n },\n methods: [measuredMethod],\n baselineSurface,\n dispatchWithSurface: (candidateSurface, scenario, ctx) =>\n agent(materializeProfile(candidateSurface), scenario, ctx),\n })\n if (\n comparisonOptions.costCeiling !== undefined &&\n raw.totalCost.totalCostUsd > comparisonOptions.costCeiling\n ) {\n throw new ConfigError(\n `improve(): reported total cost $${raw.totalCost.totalCostUsd} exceeds costCeiling $${comparisonOptions.costCeiling}`,\n )\n }\n const searchHistory = raw.searchHistory.producers[0]?.receipt ?? null\n if (searchHistory) {\n if (!searchHistory.complete) {\n throw new ConfigError(\n `improve(): method '${method.name}' returned an open search ledger: ${searchHistory.incompleteReasons.join('; ')}`,\n )\n }\n verifySearchHistoryArtifact(searchHistory, methodStorage)\n }\n const score = raw.best\n const winnerSurface = immutableCandidateValue(score.winnerSurface)\n assertCandidateSurfaceKind(surface, baselineSurface, winnerSurface)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface,\n value: winnerSurface,\n profile: materializeProfile(winnerSurface),\n })\n const cost = copyImproveCost(raw.totalCost)\n return {\n mode: 'method',\n method: method.name,\n ...(score.provenance ? { provenance: immutableCandidateValue(score.provenance) } : {}),\n candidate,\n decision:\n cost.accountingComplete && score.decision.promote && score.decision.low > minimumLift\n ? 'ship'\n : 'hold',\n lift: score.lift,\n liftInterval: { ...score.liftCi },\n searchHistory,\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId,\n runId: score.provenance?.runId ?? invocationId,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n executionRef: prepared.executionRef,\n baselineProfileDigest: prepared.baselineProfileDigest,\n }),\n raw,\n async dispose() {},\n }\n}\n","/**\n * What the steps of one `runSearchImprovement` share: the search's identity,\n * storage, ledgers and recorder, and the profile nodes the kernel searches\n * over. A node is the surface a proposer wrote and the exact profile it\n * materializes to, or why it does not.\n */\nimport type { CostLedgerHandle } from '@tangle-network/agent-eval'\nimport {\n type MutableSurface,\n type Scenario,\n type SearchArtifactCodec,\n type SearchArtifactRef,\n type SearchRecorder,\n type SearchUnknown,\n searchNodeId,\n} from '@tangle-network/agent-eval/campaign'\nimport { redact } from '@tangle-network/agent-eval/traces'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n applyAgentProfileDiff,\n canonicalAgentProfileDigest,\n diffAgentProfiles,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport type { ImproveSearchMethod } from './improve-types'\nimport type { PreparedProfileImprovement } from './profile-improvement'\n\n/** A search node: the surface a proposer wrote, and the exact profile it\n * materializes to, or why it does not. */\nexport interface ProfileNode {\n surface: MutableSurface\n profile: AgentProfile | null\n refusal: string | null\n}\n\n/** One search's identity, ledgers and recorder. */\nexport interface SearchSession<TScenario extends Scenario, TArtifact> {\n readonly method: ImproveSearchMethod\n readonly prepared: PreparedProfileImprovement<TScenario, TArtifact>\n readonly searchId: string\n readonly costLedger: CostLedgerHandle\n readonly recorder: SearchRecorder\n}\n\n/** A refusal as the ledger stores it: redacted with the share profile. */\nexport function searchRefusalText(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error)\n return redact(message, { profile: 'share' }).value\n}\n\n/** The node a candidate surface becomes: materialized, or refused with the reason. */\nexport function profileNodeOf<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n candidateSurface: MutableSurface,\n): ProfileNode {\n const surface = immutableCandidateValue(candidateSurface)\n try {\n return { surface, profile: prepared.materializeCandidate(surface), refusal: null }\n } catch (error) {\n return { surface, profile: null, refusal: searchRefusalText(error) }\n }\n}\n\n/**\n * The codec that also records each node's profile by node id. Placement reads a node's profile\n * to skip the lanes that refuse it, so every node the ledger holds, and every node this process\n * registers, is known before its cells are placed.\n */\nexport function registeringProfileCodec<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n searchId: string,\n profiles: Map<string, AgentProfile | null>,\n): SearchArtifactCodec<ProfileNode> {\n const profiled = profileCodec(prepared)\n return {\n node(recorder, node) {\n const registered = profiled.node(recorder, node)\n profiles.set(searchNodeId(searchId, registered.artifactDigest), node.profile)\n return registered\n },\n diff: profiled.diff,\n load(recorder, node) {\n const loaded = profiled.load(recorder, node)\n profiles.set(node.nodeId, loaded.profile)\n return loaded\n },\n }\n}\n\n/** Profiles as search artifacts: nodes by profile digest, edges by profile diffs. */\nfunction profileCodec<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n): SearchArtifactCodec<ProfileNode> {\n const surfaceId = prepared.surface\n return {\n node(recorder, node) {\n if (node.profile) {\n const artifact = recorder.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId, kind: 'agent-profile', artifact }],\n }\n }\n const artifact = recorder.blob('surface', {\n kind: 'unmaterialized-surface',\n surface: node.surface,\n refusal: node.refusal,\n })\n return {\n artifactDigest: canonicalCandidateDigest({\n kind: 'unmaterialized-surface',\n surface: node.surface,\n }),\n artifact,\n surfaces: [{ surfaceId, kind: 'agent-profile', artifact }],\n }\n },\n diff(recorder, parent, child): SearchArtifactRef | SearchUnknown {\n if (!parent.profile || !child.profile) {\n return { unknown: 'a surface that does not materialize has no profile to diff' }\n }\n const diffs: AgentProfileDiff[] = diffAgentProfiles(parent.profile, child.profile)\n const to = canonicalAgentProfileDigest(child.profile)\n if (canonicalAgentProfileDigest(diffs.reduce(applyAgentProfileDiff, parent.profile)) !== to) {\n return { unknown: 'the Interface profile diffs do not reproduce the child profile' }\n }\n return recorder.blob('diff', {\n kind: 'agent-profile-diff',\n from: canonicalAgentProfileDigest(parent.profile),\n to,\n diffs,\n })\n },\n load(recorder, node) {\n const stored = recorder.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n surface?: MutableSurface\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new Error(`improve(): node ${node.nodeId} holds an invalid AgentProfile`)\n }\n const loaded = immutableCandidateValue(parsed.data)\n return { surface: prepared.surfaceOf(loaded), profile: loaded, refusal: null }\n }\n if (stored.kind === 'unmaterialized-surface' && stored.surface !== undefined) {\n return { surface: stored.surface, profile: null, refusal: stored.refusal ?? null }\n }\n throw new Error(`improve(): node ${node.nodeId} holds no profile search artifact`)\n },\n }\n}\n","/**\n * `searchMethod`: Runtime's native profile search on Eval's search kernel\n * (`runSearch`), with no Python bridge.\n *\n * Every node is an exact AgentProfile, content-addressed by\n * `canonicalAgentProfileDigest`, and every edge stores the Interface diffs\n * that turn its parent profile into the child. The policy chooses which node a\n * proposal extends, the allocator where cells go, and the proposer (a\n * `SurfaceProposer`) writes the child surface from the train split only. Each\n * cell is a one-cell `runCampaign` of the materialized profile, so judges,\n * timeouts, traces, the cost ledger and the cell cache behave as in every\n * other campaign. The ledger is the only checkpoint: calling `improve()` again\n * with the same inputs continues an interrupted search, and returns a finished\n * one without running anything.\n *\n * The claim is made once, on the sealed test split, by the kernel. Runtime\n * ships only a claim that shipped, re-derives from the ledger, has complete or\n * bounded cost accounting, and clears `minimumLift` with its test lower bound\n * (`search-decision.ts`).\n */\n\nimport type { ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n aide,\n asha,\n type CampaignStorage,\n campaignCellSearchResult,\n createRunCostLedger,\n fsCampaignStorage,\n isProposedCandidate,\n openSearchLedger,\n type ProposeContext,\n type RunCampaignOptions,\n renderSearchSummary,\n resolveRunDir,\n runCampaign,\n runSearch,\n type Scenario,\n type SearchAllocator,\n type SearchArtifactCodec,\n type SearchCellResult,\n type SearchExecutionIdentity,\n type SearchPolicy,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n type SearchTask,\n type SurfaceProposer,\n searchClaimReserveUsd,\n searchProposalExecution,\n searchProposerView,\n searchReceiptAccounting,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n defineEvaluationClaim,\n type EvaluationClaim,\n summarizeEvaluationUnits,\n} from '@tangle-network/agent-eval/experiment'\nimport { type AgentProfile, canonicalAgentProfileDigest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { privateValuePaths } from './candidate-validation'\nimport type {\n ImprovementProfileCandidate,\n ImproveSearchMethod,\n ImproveSearchOptions,\n ImproveSearchResult,\n} from './improve-types'\nimport { type PreparedProfileImprovement, prepareProfileImprovement } from './profile-improvement'\nimport { decideClosedSearch, improveSearchCost } from './search-decision'\nimport {\n assertSearchLanes,\n isSearchEnvironmentFault,\n reconcileInterruptedSearchCalls,\n type SearchLane,\n searchCallTags,\n searchExecutor,\n taggedLedger,\n} from './search-executor'\nimport {\n type ProfileNode,\n profileNodeOf,\n registeringProfileCodec,\n type SearchSession,\n searchRefusalText,\n} from './search-session'\n\nexport interface SearchMethodOptions {\n /** Writes each child surface from the parents the policy chose. It reads the\n * train split only (`ProposeContext.train` and `summary`); `history` is empty. */\n proposer: SurfaceProposer<ProposalFinding>\n /** Proposals the search may make. */\n maxExpansions: number\n /** Which node each proposal extends, and which node the search keeps.\n * Default `aide()`: drafts from the baseline, debugs a node whose cells\n * fail as defects, and otherwise improves a parent drawn by Thompson\n * sampling over each node's posterior, forking from the best node when a\n * lineage stalls. `beam({ width })` expands the top nodes in turn;\n * `incumbent()` is the hill climb, which needs `uniform()`. */\n policy?: SearchPolicy\n /** Where cells go. Default `asha()`: successive halving over one seeded\n * permutation of the selection units. Each node is screened on 6 selection\n * units and 2 train units, and the top third of each rung advances to twice\n * the units. `uniform()` runs every node on every train and selection task.\n * The allocator's `reps` are every split's repeats, the claim's included. */\n allocation?: SearchAllocator\n /** Where cells run: `sharedBoxLane`, `dedicatedLane`, `subscriptionLane`\n * or `routerLane`. Each cell goes to a lane that accepts the node's profile,\n * in proportion to capacity; a hard lane caps each cell's paid calls at its\n * `cellUsd`, and an estimate lane holds `cellUsd` until 20 of its cells\n * settle. The search runs at most the lanes' total capacity at once. */\n lanes: readonly SearchLane[]\n /** Children one proposal asks for. Default 1. */\n childrenPerProposal?: number\n /** Dollars held for the claim from the start. Default: the root and 3\n * finalists on every test task at the largest lane `cellUsd` a cell. */\n claimReserveUsd?: number\n /** ISO time after which the search stops expanding and claims. */\n deadline?: string\n /** Attempts per cell for retryable environment errors. Default 3. */\n maxAttempts?: number\n /** Recorded as the ledger's process name. Default `search`. */\n name?: string\n}\n\n/** Build Runtime's native search for `improve(profile, { method })`. */\nexport function searchMethod(options: SearchMethodOptions): ImproveSearchMethod {\n if (!options || typeof options !== 'object') {\n throw new ConfigError('searchMethod(): options are required')\n }\n const { proposer } = options\n if (!proposer || typeof proposer.kind !== 'string' || typeof proposer.propose !== 'function') {\n throw new ConfigError('searchMethod(): proposer must be a SurfaceProposer')\n }\n const count = (name: string, value: number | undefined, fallback: number, min: number) => {\n const resolved = value ?? fallback\n if (!Number.isSafeInteger(resolved) || resolved < min) {\n throw new ConfigError(`searchMethod(): ${name} must be an integer of at least ${min}`)\n }\n return resolved\n }\n const dollars = (name: string, value: number | undefined): number | null => {\n if (value === undefined) return null\n if (!Number.isFinite(value) || value < 0) {\n throw new ConfigError(`searchMethod(): ${name} must be a finite non-negative number`)\n }\n return value\n }\n if (options.deadline !== undefined && !Number.isFinite(Date.parse(options.deadline))) {\n throw new ConfigError('searchMethod(): deadline must be an ISO time')\n }\n const name = options.name ?? 'search'\n if (!name.trim() || name.trim() !== name) {\n throw new ConfigError('searchMethod(): name must be a trimmed non-empty string')\n }\n assertSearchLanes(options.lanes, 'searchMethod()')\n return Object.freeze({\n kind: 'search' as const,\n name,\n policy: options.policy ?? aide(),\n allocation: options.allocation ?? asha(),\n proposer,\n maxExpansions: count('maxExpansions', options.maxExpansions, Number.NaN, 0),\n childrenPerProposal: count('childrenPerProposal', options.childrenPerProposal, 1, 1),\n lanes: Object.freeze([...options.lanes]),\n claimReserveUsd: dollars('claimReserveUsd', options.claimReserveUsd),\n deadline: options.deadline === undefined ? null : new Date(options.deadline).toISOString(),\n maxAttempts: count('maxAttempts', options.maxAttempts, 3, 1),\n })\n}\n\nexport function isImproveSearchMethod(value: unknown): value is ImproveSearchMethod {\n return (\n typeof value === 'object' && value !== null && (value as { kind?: unknown }).kind === 'search'\n )\n}\n\n/**\n * The rules `runSearchImprovement` adds to the kernel's. Its digest is the\n * process revision every searchMethod ledger records. The ship rule is not here:\n * it decides a closed ledger and writes nothing to it, so a changed ship rule\n * re-decides the same search instead of starting another.\n */\nconst SEARCH_METHOD_DEFINITION = {\n name: 'agent-runtime.search-method.2026-09',\n node: 'an exact AgentProfile materialized from the baseline and one surface, content-addressed by canonicalAgentProfileDigest; a surface that does not materialize is a node addressed by its surface and refused',\n edge: 'the Interface diffs from the parent profile to the child, stored when they reproduce the child digest',\n admission:\n 'a candidate is refused when it does not materialize, declares training on a test task, fails the caller validator, carries a credential or private value, or no lane can run its profile',\n cell: 'a one-cell runCampaign of the materialized profile in a directory addressed by its digest, on a lane that accepts the profile; a cached cell is read back, not run again; a finished attempt is recorded by run id before it settles and adopted after a restart',\n lanes:\n 'a hard lane refuses a paid call that declares no priced maximum or would take the cell past its cellUsd; an environment fault settles errored and retryable; a subscription seat reports no tokens and charges no dollars',\n proposer:\n 'a SurfaceProposer reads the parents, the train view and the train summary; paid calls it makes are its operation accounting',\n} as const\n\nconst SEARCH_METHOD_SOURCE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-runtime#searchMethod',\n revision: canonicalCandidateDigest(SEARCH_METHOD_DEFINITION),\n}\n\nexport async function runSearchImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveSearchResult> {\n const {\n method,\n claim: inputClaim,\n agent,\n executionRunId,\n recordCell,\n trainScenarios,\n selectionScenarios,\n testScenarios,\n judges: _judges,\n surface: _surface,\n executionRef: _executionRef,\n validateCandidate: _validateCandidate,\n findings: _findings,\n skills: _skills,\n profileComponents: _profileComponents,\n minimumLift: _minimumLift,\n subject: _subject,\n costCeiling,\n costLedger: inputCostLedger,\n seed = 42,\n signal,\n workerSlots,\n budgetPool,\n trace,\n ...campaignOptions\n } = opts\n const splitScenarios = { trainScenarios, selectionScenarios, testScenarios }\n const claim = assertSearchRequest(method, inputClaim, splitScenarios)\n const { allocation, policy, lanes } = method\n const reps = allocation.reps\n const concurrency = lanes.reduce((total, lane) => total + lane.capacity, 0)\n const prepared = prepareProfileImprovement(profile, {\n ...opts,\n seed,\n reps,\n optimizationRunOptions: { reps, maxConcurrency: concurrency },\n })\n const { evaluationRef } = prepared.identity\n const storage: CampaignStorage = campaignOptions.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(campaignOptions.runDir, campaignOptions.repo)\n const searchKey = canonicalCandidateDigest({\n evaluationRef,\n process: SEARCH_METHOD_SOURCE,\n method: searchMethodDescriptor(method),\n }).slice('sha256:'.length, 'sha256:'.length + 24)\n const searchId = `improve-${searchKey}`\n const searchDir = `${runDir}/search/${searchId}`\n const costLedger =\n inputCostLedger ??\n createRunCostLedger({ storage, runDir: searchDir, costCeilingUsd: costCeiling })\n const execution = searchExecutionIdentity(prepared)\n const recorder = await openSearchRecorder({\n method,\n prepared,\n claim,\n splits: searchSplits(claim, splitScenarios),\n storage,\n searchId,\n searchDir,\n seed,\n costCeiling,\n concurrency,\n execution,\n })\n const session: SearchSession<TScenario, TArtifact> = {\n method,\n prepared,\n searchId,\n costLedger,\n recorder,\n }\n\n const profiles = new Map<string, AgentProfile | null>()\n const codec = registeringProfileCodec(prepared, searchId, profiles)\n for (const node of (await recorder.state()).nodes()) codec.load(recorder, node)\n await reconcileInterruptedSearchCalls(costLedger, searchId, lanes)\n const root = profileNodeOf(prepared, prepared.baselineSurface)\n if (root.profile) {\n const refused = laneRefusal(lanes, root.profile)\n if (refused) throw new ConfigError(`improve(): the baseline profile cannot run: ${refused}`)\n }\n const scenarios = [...trainScenarios, ...selectionScenarios, ...testScenarios]\n assertDistinctScenarios(scenarios)\n const executor = searchExecutor<ProfileNode>({\n lanes,\n profileOf(nodeId) {\n const known = profiles.get(nodeId)\n if (known === undefined) throw new Error(`improve(): node ${nodeId} was placed unregistered`)\n return known\n },\n costLedger,\n identity: execution,\n storage,\n dir: searchDir,\n ...(workerSlots ? { workerSlots } : {}),\n ...(budgetPool ? { budgetPool } : {}),\n ...(trace ? { trace } : {}),\n runAttempt: searchCellRunner<TScenario, TArtifact>({\n campaignOptions: campaignOptions as Omit<\n RunCampaignOptions<TScenario, TArtifact>,\n 'scenarios' | 'dispatch'\n >,\n prepared,\n agent,\n executionRunId,\n recordCell,\n scenarios,\n seed,\n reps,\n storage,\n searchDir,\n evaluationRef,\n execution,\n }),\n })\n\n const startedAt = Date.now()\n const result = await runSearch({\n recorder,\n root,\n codec,\n policy,\n allocation,\n proposer: searchProposerPort(session),\n executor,\n admit: (node) => admissionRefusal(session, node),\n maxExpansions: method.maxExpansions,\n maxAttempts: method.maxAttempts,\n ...(signal ? { signal } : {}),\n })\n return decideSearchResult({ session, codec, result, costCeiling, startedAt })\n}\n\ninterface OpenSearchRecorderInput<TScenario extends Scenario, TArtifact> {\n method: ImproveSearchMethod\n prepared: PreparedProfileImprovement<TScenario, TArtifact>\n claim: EvaluationClaim\n splits: ReturnType<typeof searchSplits>\n storage: CampaignStorage\n searchId: string\n searchDir: string\n seed: number\n costCeiling: number | undefined\n concurrency: number\n execution: SearchExecutionIdentity\n}\n\n/** Open the search's ledger: a fresh search records its opening, an interrupted one continues. */\nfunction openSearchRecorder<TScenario extends Scenario, TArtifact>(\n input: OpenSearchRecorderInput<TScenario, TArtifact>,\n): Promise<SearchRecorder> {\n const { method, prepared, claim, splits, storage, searchId, searchDir, seed, costCeiling } = input\n const { policy, allocation, lanes } = method\n const reservedClaimUsd = Math.max(\n method.claimReserveUsd ?? 0,\n searchClaimReserveUsd({\n testTasks: splits.test.length,\n reps: allocation.reps,\n cellUsd: Math.max(...lanes.map((lane) => lane.cellUsd)),\n }),\n )\n return SearchRecorder.open(\n {\n ledger:\n storage.kind === 'filesystem'\n ? openSearchLedger({ path: `${searchDir}/ledger.jsonl`, searchId })\n : openSearchLedger({ path: `${searchDir}/ledger.jsonl`, searchId, store: storage }),\n storage,\n },\n {\n subject: prepared.searchIdentity.subject,\n process: { name: method.name, executionRef: SEARCH_METHOD_SOURCE },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'composite',\n direction: 'maximize',\n judge: prepared.searchIdentity.judge,\n claim,\n },\n splits,\n policy: { expansion: policy.name, allocation: allocation.name, seed },\n budget: {\n maxUsd: costCeiling ?? null,\n maxCells: null,\n maxNodes: 1 + method.maxExpansions * method.childrenPerProposal,\n deadline: method.deadline,\n maxConcurrency: input.concurrency,\n reservedClaimUsd: costCeiling === undefined ? 0 : reservedClaimUsd,\n },\n containment: null,\n derivedFrom: null,\n identity: input.execution,\n },\n )\n}\n\n/** The request is a search with a claim that can be powered, and every split has scenarios. */\nfunction assertSearchRequest<TScenario extends Scenario>(\n method: unknown,\n inputClaim: EvaluationClaim,\n splits: Record<'trainScenarios' | 'selectionScenarios' | 'testScenarios', readonly TScenario[]>,\n): EvaluationClaim {\n if (!isImproveSearchMethod(method)) {\n throw new ConfigError('improve(): a search needs method: searchMethod(...)')\n }\n const claim = defineEvaluationClaim(inputClaim)\n if (claim.minimumEffect === undefined) {\n throw new ConfigError('improve(): a search claim needs minimumEffect for its power check')\n }\n for (const [name, split] of Object.entries(splits)) {\n if (!Array.isArray(split) || split.length === 0) {\n throw new ConfigError(`improve(): a search needs at least one of ${name}`)\n }\n }\n return claim\n}\n\nfunction assertDistinctScenarios(scenarios: readonly Scenario[]): void {\n const scenarioIds = new Set<string>()\n for (const scenario of scenarios) {\n if (scenarioIds.has(scenario.id)) {\n throw new ConfigError(`improve(): scenario '${scenario.id}' appears in more than one split`)\n }\n scenarioIds.add(scenario.id)\n }\n}\n\n/** The search tasks of each split, and whether the test units are held out of development. */\nfunction searchSplits<TScenario extends Scenario>(\n claim: EvaluationClaim,\n scenarios: Record<\n 'trainScenarios' | 'selectionScenarios' | 'testScenarios',\n readonly TScenario[]\n >,\n) {\n const unitOf = (scenario: TScenario): string =>\n summarizeEvaluationUnits(claim, [scenario]).units[0]!.id\n const tasks = (list: readonly TScenario[]): SearchTask[] =>\n list.map((scenario) => ({\n taskId: scenario.id,\n unitId: unitOf(scenario),\n source: { uri: `scenario://${scenario.id}`, revision: canonicalCandidateDigest(scenario) },\n }))\n const splits = {\n train: tasks(scenarios.trainScenarios),\n selection: tasks(scenarios.selectionScenarios),\n test: tasks(scenarios.testScenarios),\n }\n const developmentUnits = new Set(\n [...splits.train, ...splits.selection].map((task) => task.unitId),\n )\n return {\n ...splits,\n heldOutUnits: splits.test.every((task) => !developmentUnits.has(task.unitId)),\n }\n}\n\nfunction searchExecutionIdentity<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n): SearchExecutionIdentity {\n return {\n model: prepared.searchIdentity.model,\n agent: prepared.searchIdentity.agent,\n benchmark: {\n uri: 'agent-runtime:improve-splits',\n revision: canonicalCandidateDigest({\n development: prepared.identity.developmentSplitDigest,\n test: prepared.identity.finalTestSplitDigest,\n }),\n },\n }\n}\n\n/** Why no lane can run the profile, or null when one can. */\nfunction laneRefusal(lanes: readonly SearchLane[], nodeProfile: AgentProfile): string | null {\n const refusals = lanes.map((lane) => `${lane.name}: ${lane.refusal(nodeProfile)}`)\n return lanes.some((lane) => lane.refusal(nodeProfile) === undefined)\n ? null\n : `no lane can run the profile (${refusals.join('; ')})`\n}\n\n/** Why a node is refused admission to the search, or null when it is admitted. */\nfunction admissionRefusal<TScenario extends Scenario, TArtifact>(\n { prepared, method }: SearchSession<TScenario, TArtifact>,\n node: ProfileNode,\n): string | null {\n if (node.refusal !== null || node.profile === null) return node.refusal\n try {\n prepared.admitCandidate(node.profile, node.surface)\n } catch (error) {\n return searchRefusalText(error)\n }\n const paths = privateValuePaths([node.surface])\n if (paths.length > 0) {\n return `the surface carries a credential or private value at ${paths.slice(0, 8).join(', ')}`\n }\n return laneRefusal(method.lanes, node.profile)\n}\n\n/** Read the closed search back from its ledger and decide whether its leader ships. */\nasync function decideSearchResult<TScenario extends Scenario, TArtifact>(input: {\n session: SearchSession<TScenario, TArtifact>\n codec: SearchArtifactCodec<ProfileNode>\n result: Awaited<ReturnType<typeof runSearch<ProfileNode>>>\n costCeiling: number | undefined\n startedAt: number\n}): Promise<ImproveSearchResult> {\n const { session, codec, result, costCeiling, startedAt } = input\n const { method, prepared, searchId, costLedger, recorder } = session\n const { state } = result\n const claimResult = result.claim\n if (!claimResult || !result.claimVerification) {\n throw new Error(`improve(): search ${searchId} closed without a claim`)\n }\n const kept = codec.load(recorder, state.node(result.leader)!)\n if (!kept.profile) throw new Error(`improve(): search ${searchId} kept a refused node`)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface: prepared.surface,\n value: kept.surface,\n profile: kept.profile,\n })\n const cost = improveSearchCost(costLedger)\n const decided = await decideClosedSearch({\n state,\n claim: claimResult,\n claimVerification: result.claimVerification,\n cost,\n costCeiling,\n minimumLift: prepared.minimumLift,\n profileOf(nodeId) {\n const node = state.node(nodeId)\n const loaded = node ? codec.load(recorder, node) : null\n if (!loaded?.profile)\n throw new Error(`improve(): search ${searchId} node ${nodeId} holds no profile`)\n return loaded.profile\n },\n })\n return {\n mode: 'search',\n method: method.name,\n candidate,\n ...decided,\n claim: claimResult,\n claimVerification: result.claimVerification,\n searchHistory: recorder.receipt({ producerId: method.name, runId: searchId }),\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId: prepared.invocationId,\n runId: searchId,\n developmentSplitDigest: prepared.identity.developmentSplitDigest,\n finalTestSplitDigest: prepared.identity.finalTestSplitDigest,\n scenarioPartitions: prepared.identity.scenarioPartitions,\n executionRef: prepared.executionRef,\n baselineProfileDigest: prepared.baselineProfileDigest,\n }),\n async dispose() {},\n }\n}\n\n/** Everything that decides which search a call continues. */\nfunction searchMethodDescriptor(method: ImproveSearchMethod): unknown {\n return {\n name: method.name,\n policy: method.policy.name,\n allocation: method.allocation.name,\n reps: method.allocation.reps,\n proposer: method.proposer.kind,\n maxExpansions: method.maxExpansions,\n childrenPerProposal: method.childrenPerProposal,\n lanes: method.lanes.map(({ name, kind, capacity, costCap, cellUsd }) => ({\n name,\n kind,\n capacity,\n costCap,\n cellUsd,\n })),\n claimReserveUsd: method.claimReserveUsd,\n deadline: method.deadline,\n maxAttempts: method.maxAttempts,\n }\n}\n\nconst PROPOSAL_PHASE = 'search.proposal'\n\nfunction searchProposerPort<TScenario extends Scenario, TArtifact>(\n session: SearchSession<TScenario, TArtifact>,\n): SearchProposerPort<ProfileNode> {\n const { method, prepared, recorder, costLedger, searchId } = session\n const { proposer } = method\n const proposerSource: SearchSourceRef = {\n uri: `proposer:${proposer.kind}`,\n revision: canonicalCandidateDigest({\n kind: proposer.kind,\n propose: Function.prototype.toString.call(proposer.propose),\n decide: proposer.decide ? Function.prototype.toString.call(proposer.decide) : null,\n }),\n }\n return {\n name: proposer.kind,\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: method.childrenPerProposal,\n async propose(request) {\n // The proposal's calls carry its operation, so its accounting is exactly them.\n const tags = searchCallTags(searchId, { operation: request.operationId })\n // Read the ledger once, synchronously, before any await: the kernel\n // retires a state view when it appends.\n const state = await recorder.state()\n const parents = request.parents.map(({ nodeId, artifact }) => ({\n nodeId,\n artifact: artifact.surface,\n }))\n const context: ProposeContext<ProposalFinding> = Object.freeze({\n currentSurface: parents[0]?.artifact ?? prepared.baselineSurface,\n operator: request.operator,\n parents,\n train: searchProposerView(state),\n summary: renderSearchSummary(state, { split: 'train' }),\n history: [],\n findings: prepared.findings,\n populationSize: method.childrenPerProposal,\n generation: request.expansion,\n signal: request.signal,\n costLedger: taggedLedger(costLedger, tags),\n costPhase: PROPOSAL_PHASE,\n })\n const decision = proposer.decide?.({ history: [] })\n const proposed = decision?.stop ? [] : await proposer.propose(context)\n if (!Array.isArray(proposed)) {\n throw new ConfigError('improve(): the search proposer must return an array')\n }\n const fresh = costLedger.list({ phase: PROPOSAL_PHASE, tags })\n return {\n children: proposed.slice(0, method.childrenPerProposal).map((child) =>\n isProposedCandidate(child)\n ? {\n artifact: profileNodeOf(prepared, child.surface),\n label: child.label,\n rationale: child.rationale,\n ...(child.attribution ? { attribution: child.attribution } : {}),\n }\n : { artifact: profileNodeOf(prepared, child), label: '', rationale: '' },\n ),\n ...(decision?.stop ? { stop: decision.reason ?? 'the proposer decided to stop' } : {}),\n accounting: searchReceiptAccounting(fresh),\n execution: searchProposalExecution(\n fresh,\n prepared.searchIdentity.model.provider,\n proposerSource,\n ),\n }\n },\n }\n}\n\ntype RunAttempt = Parameters<typeof searchExecutor<ProfileNode>>[0]['runAttempt']\n\n/** What every cell of one search shares. */\ninterface SearchCellEnvironment<TScenario extends Scenario, TArtifact> {\n readonly campaignOptions: Omit<RunCampaignOptions<TScenario, TArtifact>, 'scenarios' | 'dispatch'>\n readonly prepared: PreparedProfileImprovement<TScenario, TArtifact>\n readonly agent: ImproveSearchOptions<TScenario, TArtifact>['agent']\n readonly executionRunId: ImproveSearchOptions<TScenario, TArtifact>['executionRunId']\n readonly recordCell: ImproveSearchOptions<TScenario, TArtifact>['recordCell']\n readonly scenarios: TScenario[]\n readonly seed: number\n readonly reps: number\n readonly storage: CampaignStorage\n readonly searchDir: string\n readonly evaluationRef: string\n readonly execution: SearchExecutionIdentity\n}\n\n/** The executor's cell runner for one search. */\nfunction searchCellRunner<TScenario extends Scenario, TArtifact>(\n env: SearchCellEnvironment<TScenario, TArtifact>,\n): RunAttempt {\n const { campaignOptions, prepared, executionRunId, recordCell, execution } = env\n return async ({ work, lane, context, costLedger: cellLedger, span }) => {\n const nodeProfile = work.artifact.profile\n if (!nodeProfile) throw new Error(`improve(): refused node ${work.nodeId} was given a cell`)\n const profileDigest = canonicalAgentProfileDigest(nodeProfile)\n let fault: unknown\n const campaign = await runCampaign<TScenario, TArtifact>({\n ...campaignOptions,\n // A seat's work leaves no receipt, which the campaign would otherwise report as a stub.\n ...(lane.kind === 'subscription' &&\n (campaignOptions as { expectUsage?: unknown }).expectUsage === undefined\n ? { expectUsage: 'off' as const }\n : {}),\n scenarios: env.scenarios,\n judges: prepared.judges.map((judge) => ({\n ...judge,\n async score(input) {\n try {\n return await judge.score(input)\n } catch (error) {\n if (isSearchEnvironmentFault(error)) fault = error\n throw error\n }\n },\n })),\n seed: env.seed,\n reps: env.reps,\n storage: env.storage,\n runDir: `${env.searchDir}/nodes/${profileDigest.slice('sha256:'.length)}`,\n dispatchRef: `improve:${env.evaluationRef}:${profileDigest}`,\n async dispatch(scenario, ctx) {\n try {\n return await env.agent(nodeProfile, scenario, { ...ctx, search: context })\n } catch (error) {\n if (isSearchEnvironmentFault(error)) fault = error\n throw error\n }\n },\n cellFilter: ({ scenario, rep }) => scenario.id === work.taskId && rep === work.rep,\n resumable: true,\n maxConcurrency: 1,\n costLedger: cellLedger,\n costPhase: `search.${work.stage}`,\n buildTraceWriter: () => ({ span, flush: async () => {} }),\n signal: work.signal,\n })\n const cell = campaign.cells[0]\n if (!cell) throw new Error(`improve(): cell ${work.cellId} produced no campaign cell`)\n const result = campaignCellSearchResult(cell, { execution, lane: lane.name })\n const execRunId = cell.error ? null : (executionRunId?.(cell.artifact) ?? null)\n const settled = faultResult(\n execRunId && context.trace\n ? {\n ...result,\n traceRef: {\n traceId: context.trace.traceId,\n execRunId,\n spansWritten: null,\n spansDropped: null,\n },\n }\n : result,\n fault,\n )\n return recordCell && settled.outcome.status !== 'errored'\n ? {\n ...settled,\n recordCell: (finalResult) => recordCell({ cell, search: context, result: finalResult }),\n }\n : settled\n }\n}\n\n/**\n * An environment fault the agent raised settles retryable. The campaign reports every error as\n * final because it applies its own retry policy; here the kernel owns retries.\n */\nfunction faultResult(result: SearchCellResult, fault: unknown): SearchCellResult {\n if (fault === undefined || result.outcome.status !== 'errored') return result\n return {\n ...result,\n outcome: {\n ...result.outcome,\n error: { code: 'environment-fault', message: searchRefusalText(fault), retryable: true },\n },\n }\n}\n","import { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { chmod, mkdir, mkdtemp, open, realpath, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport {\n type AgentProfile,\n type AgentTrainingDatasetIdentity,\n type AgentTrainingReceipt,\n type AgentTrainingTask,\n agentProfileEnvironmentSchema,\n agentProfileTrainingSchema,\n agentTrainingDatasetIdentitySchema,\n agentTrainingParametersSchema,\n agentTrainingReceiptSchema,\n agentTrainingTaskKey,\n agentTrainingTaskSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateBytes,\n type Sha256Digest,\n sha256DigestSchema,\n snapshotAgentProfile,\n trainedModelIdForArtifact,\n} from '@tangle-network/agent-interface'\nimport {\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from '../candidate-execution/digest'\nimport { terminateProcessTreeAndConfirm } from '../runtime/process-tree'\nimport { linkAbort, runAbortable } from '../runtime/supervise/abortable'\nimport { armDeadlineTimer } from '../runtime/supervise/deadline'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport {\n assertCandidateValidator,\n parseExecutionRef,\n validateProfileCandidate,\n} from './candidate-validation'\nimport type { ImproveCandidateValidator } from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\nexport interface TrainingDatasetDocument {\n version: 1\n format: 'sft' | 'dpo' | 'grpo'\n /** Existing Eval export rows, without rewriting their payloads. Include every exposed partition. */\n rows: Array<{ task: AgentTrainingTask; partition: 'train' | 'validation'; data: unknown }>\n}\n\nexport interface ProfileTrainerRequest {\n version: 1\n invocationId: string\n datasetPath: string\n checkpointPath: string\n parentProfilePath: string\n parentProfileDigest: Sha256Digest\n parameters: AgentTrainingReceipt['trainer']['parameters']\n executionRef: Sha256Digest\n}\n\nexport type TrainingBoundaryResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; reason: string }\n\n/** Managed adapters use this same port: cancel the job on abort and download one exact checkpoint file. */\nexport interface ProfileTrainer {\n identity: Omit<AgentTrainingReceipt['trainer'], 'parameters'>\n execute(\n request: Readonly<ProfileTrainerRequest>,\n signal: AbortSignal,\n ): Promise<TrainingBoundaryResult<void>>\n}\n\nexport interface CheckpointServingPort {\n /** Verify the immutable Router route independently of the trainer's output. */\n serve(input: {\n artifactPath: string\n artifactDigest: Sha256Digest\n artifactBytes: number\n routerModelId: string\n signal: AbortSignal\n }): Promise<\n TrainingBoundaryResult<{\n routerModelId: string\n artifactDigest: Sha256Digest\n evidenceDigest: Sha256Digest\n }>\n >\n}\n\nexport interface ImproveTrainingOptions {\n mode: 'training'\n trainer: ProfileTrainer\n dataset: { path: string; digest: Sha256Digest }\n parameters: AgentTrainingReceipt['trainer']['parameters']\n /** Pins trainer, serving adapter and their private dependencies, just like the bound profile harness. */\n executionRef: Sha256Digest\n serving: CheckpointServingPort\n outputDirectory: string\n /** Optional overall deadline. Omit to rely on caller cancellation; long durations are supported. */\n timeoutMs?: number\n maxCheckpointBytes: number\n signal?: AbortSignal\n validateCandidate?: ImproveCandidateValidator\n}\n\nexport type ImproveTrainingResult =\n | {\n mode: 'training'\n succeeded: true\n profile: ReadonlyAgentProfile\n profileDigest: Sha256Digest\n receipt: AgentTrainingReceipt\n artifactPath: string\n receiptPath: string\n profilePath: string\n }\n | {\n mode: 'training'\n succeeded: false\n stage:\n | 'admission'\n | 'dataset'\n | 'training'\n | 'checkpoint'\n | 'serving'\n | 'profile'\n | 'persistence'\n reason: string\n /** Partial artifacts are retained for diagnosis; they are not a runnable profile. */\n outputDirectory?: string\n /** A serving request began; an interrupted adapter may still own a deployment. */\n servingMayExist: boolean\n /** A timed-out managed adapter may still own a remote training job. */\n trainingMayExist: boolean\n cleanupError?: string\n }\n\nexport interface ControlledTrainingCommand {\n id: string\n executable: { path: string; digest: Sha256Digest }\n args: string[]\n /** Script/config files used by the command, verified before and after execution. */\n inputs: Array<{ path: string; digest: Sha256Digest }>\n /** Explicit public environment only. Ambient credentials are never inherited. */\n environment: Record<string, string>\n /** Total stdout + stderr byte budget. Output is drained, not retained in memory. */\n maxOutputBytes: number\n}\n\nfunction positiveLimit(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`invalid ${label}`)\n}\n\nasync function hashFile(\n path: string,\n maximum: number,\n signal: AbortSignal,\n capture = false,\n): Promise<{\n digest: Sha256Digest\n bytes: number\n content?: Buffer\n}> {\n signal.throwIfAborted()\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)\n try {\n const before = await file.stat()\n if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size > maximum)\n throw new Error('artifact must be a bounded regular file')\n const hash = createHash('sha256')\n const chunks: Buffer[] = []\n let bytes = 0\n // The signal is read here and per chunk, never handed to the stream: a stream given a signal\n // that aborted during `open` or `stat` raises its AbortError before the iterator listens, as an\n // uncaught exception (the training timeout firing during the dataset stage). An abort therefore\n // lands within one 64 KiB chunk read.\n signal.throwIfAborted()\n for await (const chunk of file.createReadStream({ autoClose: false })) {\n signal.throwIfAborted()\n bytes += chunk.length\n if (bytes > maximum) throw new Error('artifact exceeded its byte limit')\n if (bytes > before.size) throw new Error('artifact changed while being hashed')\n hash.update(chunk)\n if (capture) chunks.push(Buffer.from(chunk))\n }\n const after = await file.stat()\n if (\n before.size !== bytes ||\n after.size !== bytes ||\n before.mtimeMs !== after.mtimeMs ||\n before.ctimeMs !== after.ctimeMs\n ) {\n throw new Error('artifact changed while being hashed')\n }\n return {\n digest: `sha256:${hash.digest('hex')}`,\n bytes,\n ...(capture ? { content: Buffer.concat(chunks) } : {}),\n }\n } finally {\n await file.close()\n }\n}\n\n/** Execute one pinned command without a shell, in the runtime-owned job directory. POSIX only. */\nexport function createCommandProfileTrainer(input: ControlledTrainingCommand): ProfileTrainer {\n const command = immutableCandidateValue(input)\n positiveLimit(command.maxOutputBytes, 'trainer output limit')\n if (\n !command.id ||\n command.id.trim() !== command.id ||\n !Array.isArray(command.args) ||\n !command.args.every((arg) => typeof arg === 'string' && !arg.includes('\\0'))\n )\n throw new Error('invalid trainer command')\n for (const file of [command.executable, ...command.inputs]) {\n if (!isAbsolute(file.path)) throw new Error('trainer files must use absolute paths')\n sha256DigestSchema.parse(file.digest)\n }\n for (const [name, value] of Object.entries(command.environment)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || value.includes('\\0'))\n throw new Error('invalid trainer environment')\n }\n agentProfileEnvironmentSchema.parse(\n Object.fromEntries(\n Object.entries(command.environment).map(([key, value]) => [key, { kind: 'public', value }]),\n ),\n )\n const identity = immutableCandidateValue({\n mode: 'command' as const,\n id: command.id,\n revision: canonicalCandidateDigest(command),\n })\n agentTrainingReceiptSchema.shape.trainer.parse({ ...identity, parameters: {} })\n return Object.freeze({\n identity,\n async execute(\n request: Readonly<ProfileTrainerRequest>,\n signal: AbortSignal,\n ): Promise<TrainingBoundaryResult<void>> {\n try {\n if (process.platform === 'win32')\n throw new Error('controlled trainers require POSIX process-group cancellation')\n // Serialize before spawning and before any await: caller mutation cannot redirect the job,\n // and a malformed request cannot leave a live child behind an early rejected promise.\n const requestSnapshot = immutableCandidateValue(request)\n const inputBytes = Buffer.from(canonicalCandidateBytes(requestSnapshot))\n const verifyInputs = async () => {\n for (const file of [command.executable, ...command.inputs]) {\n if (\n (await hashFile(file.path, Number.MAX_SAFE_INTEGER, signal)).digest !== file.digest\n ) {\n throw new Error('trainer executable or input digest mismatch')\n }\n }\n }\n await verifyInputs()\n signal.throwIfAborted()\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable.path, command.args, {\n cwd: dirname(requestSnapshot.checkpointPath),\n env: command.environment,\n shell: false,\n detached: true,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let failure: Error | undefined\n let outputBytes = 0\n let leaderClosed = false\n let termination: Promise<void> | undefined\n const stop = () => {\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(\n child,\n () => leaderClosed,\n 'createCommandProfileTrainer',\n )\n // Teardown can finish before close. Observe its failure in both event orders.\n void termination.catch((error) => {\n failure ??= error\n })\n }\n return termination\n }\n const abort = () => {\n failure ??= new Error('trainer cancelled')\n stop()\n }\n signal.addEventListener('abort', abort, { once: true })\n if (signal.aborted) abort()\n const count = (chunk: Buffer) => {\n outputBytes += chunk.length\n if (outputBytes > command.maxOutputBytes) {\n failure ??= new Error('trainer output limit exceeded')\n stop()\n }\n }\n child.stdout.on('data', count)\n child.stderr.on('data', count)\n child.stdin.on('error', (error) => {\n failure ??= error\n stop()\n })\n child.on('error', (error) => {\n failure ??= error\n })\n // A successful parent may not leave descendants mutating the checkpoint.\n child.on('exit', stop)\n child.on('close', (code, exitSignal) => {\n leaderClosed = true\n signal.removeEventListener('abort', abort)\n void stop().then(() => {\n if (failure) reject(failure)\n else if (code !== 0 || exitSignal !== null)\n reject(new Error(`trainer exited unsuccessfully (${code ?? exitSignal})`))\n else resolve()\n }, reject)\n })\n child.stdin.end(inputBytes)\n })\n await verifyInputs()\n return { succeeded: true, value: undefined }\n } catch (error) {\n return {\n succeeded: false,\n reason: error instanceof Error ? error.message : 'trainer failed',\n }\n }\n },\n })\n}\n\nfunction datasetIdentity(bytes: Uint8Array): AgentTrainingDatasetIdentity {\n const dataset = JSON.parse(\n new TextDecoder('utf-8', { fatal: true }).decode(bytes),\n ) as TrainingDatasetDocument\n canonicalCandidateBytes(dataset)\n if (\n !dataset ||\n typeof dataset !== 'object' ||\n Object.keys(dataset).sort().join(',') !== 'format,rows,version' ||\n dataset.version !== 1 ||\n !['sft', 'dpo', 'grpo'].includes(dataset.format) ||\n !Array.isArray(dataset.rows) ||\n dataset.rows.length === 0 ||\n dataset.rows.length > 1_000_000\n )\n throw new Error('invalid training dataset')\n const tasks = new Map<string, AgentTrainingTask>()\n const partitions = new Map<string, string>()\n let trainingRows = 0\n for (const row of dataset.rows) {\n if (\n !row ||\n typeof row !== 'object' ||\n Object.keys(row).sort().join(',') !== 'data,partition,task' ||\n !['train', 'validation'].includes(row.partition)\n )\n throw new Error('every dataset row needs its exposure identity and partition')\n if (row.partition === 'train') trainingRows++\n const task = agentTrainingTaskSchema.parse(row.task)\n for (const identity of [JSON.stringify([task.benchmark, task.task]), task.contentDigest]) {\n const previous = partitions.get(identity)\n if (previous !== undefined && previous !== row.partition)\n throw new Error('training and validation task partitions intersect')\n partitions.set(identity, row.partition)\n }\n tasks.set(agentTrainingTaskKey(task), task)\n }\n if (trainingRows === 0) throw new Error('dataset contains no training rows')\n const members = [...tasks.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([, task]) => task)\n return agentTrainingDatasetIdentitySchema.parse({\n digest: sha256Bytes(bytes),\n taskSetDigest: canonicalCandidateDigest(members),\n tasks: members,\n })\n}\n\n/** Training materializes a candidate; it never emits a ship verdict or changes a live agent. */\nexport async function runProfileTraining(\n profile: ReadonlyAgentProfile,\n options: ImproveTrainingOptions,\n): Promise<ImproveTrainingResult> {\n let stage: Extract<ImproveTrainingResult, { succeeded: false }>['stage'] = 'admission'\n let jobDirectory: string | undefined\n const cancellation = linkAbort(...(options.signal ? [options.signal] : []))\n const signal = cancellation.signal\n const outputDirectory = options.outputDirectory\n const timeoutMs = options.timeoutMs\n let servingMayExist = false\n let trainingMayExist = false\n let clearTimer: (() => void) | undefined\n try {\n if (options.mode !== 'training') throw new Error('training mode is required')\n const parent = snapshotAgentProfile(profile)\n if (!parent.harness || !parent.model?.default?.trim() || !parent.model.provider?.trim()) {\n throw new Error('training requires an explicit parent harness, provider and model')\n }\n const parentProfileDigest = canonicalAgentProfileDigest(parent)\n const parentBytes = Buffer.from(JSON.stringify(parent), 'utf8')\n sha256DigestSchema.parse(options.dataset.digest)\n if (timeoutMs !== undefined) positiveLimit(timeoutMs, 'training timeout')\n positiveLimit(options.maxCheckpointBytes, 'checkpoint byte limit')\n if (\n typeof options.trainer?.execute !== 'function' ||\n typeof options.serving?.serve !== 'function'\n )\n throw new Error('trainer and verified serving ports are required')\n const trainer = immutableCandidateValue(options.trainer.identity)\n const parameters = immutableCandidateValue(\n agentTrainingParametersSchema.parse(options.parameters),\n )\n agentTrainingReceiptSchema.shape.trainer.parse({ ...trainer, parameters })\n assertCandidateValidator(options.validateCandidate)\n const execute = options.trainer.execute.bind(options.trainer)\n const serve = options.serving.serve.bind(options.serving)\n const executionRef = parseExecutionRef(options.executionRef, 'training')\n const expectedDatasetDigest = options.dataset.digest\n const sourceDataset = options.dataset.path\n const maxCheckpointBytes = options.maxCheckpointBytes\n const validateCandidate = options.validateCandidate\n // Interface owns both the ancestry bound and the portable receipt shape.\n const ancestry = agentProfileTrainingSchema.shape.ancestors.parse(\n parent.metadata?.training\n ? [parent.metadata.training.receipt, ...parent.metadata.training.ancestors]\n : [],\n )\n const validate = (candidate: AgentProfile, isBaseline: boolean) =>\n validateProfileCandidate(validateCandidate, {\n profile: candidate,\n surface: 'agent-profile',\n candidateSurface: JSON.stringify(candidate),\n value: candidate,\n isBaseline,\n })\n if (timeoutMs !== undefined) {\n clearTimer = armDeadlineTimer(\n timeoutMs,\n () => cancellation.abort(new Error('training deadline exceeded')),\n true,\n )\n }\n signal.throwIfAborted()\n validate(parent, true)\n await mkdir(outputDirectory, { recursive: true })\n const outputRoot = await realpath(outputDirectory)\n jobDirectory = await mkdtemp(join(outputRoot, 'training-'))\n await chmod(jobDirectory, 0o700)\n syncDurableDirectory(outputRoot)\n const datasetPath = join(jobDirectory, 'dataset.json')\n const parentProfilePath = join(jobDirectory, 'parent-profile.json')\n const artifactPath = join(jobDirectory, 'checkpoint.bin')\n stage = 'dataset'\n const source = await hashFile(sourceDataset, 128 * 1024 * 1024, signal, true)\n if (source.digest !== expectedDatasetDigest) throw new Error('training dataset digest mismatch')\n const bytes = source.content!\n if (bytes.length !== source.bytes) throw new Error('training dataset snapshot is incomplete')\n const dataset = datasetIdentity(bytes)\n await writeFile(datasetPath, bytes, { flag: 'wx', mode: 0o400 })\n await writeFile(parentProfilePath, parentBytes, { flag: 'wx', mode: 0o400 })\n const request = immutableCandidateValue({\n version: 1 as const,\n invocationId: jobDirectory,\n datasetPath,\n checkpointPath: artifactPath,\n parentProfilePath,\n parentProfileDigest,\n parameters,\n executionRef,\n })\n stage = 'training'\n const trained = await runAbortable(\n () => {\n trainingMayExist = true\n return execute(request, signal)\n },\n signal,\n 'training cancelled',\n )\n signal.throwIfAborted()\n if (trained?.succeeded !== true)\n throw new Error(trained?.reason ?? 'trainer did not report success')\n trainingMayExist = false\n stage = 'checkpoint'\n if (\n (await hashFile(datasetPath, 128 * 1024 * 1024, signal)).digest !== dataset.digest ||\n (await hashFile(parentProfilePath, parentBytes.byteLength, signal)).digest !==\n sha256Bytes(parentBytes)\n ) {\n throw new Error('trainer changed its pinned inputs')\n }\n const artifact = await hashFile(artifactPath, maxCheckpointBytes, signal)\n if (artifact.bytes === 0) throw new Error('checkpoint must be nonempty')\n await chmod(artifactPath, 0o400)\n const checkpoint = await open(artifactPath, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n await checkpoint.sync()\n } finally {\n await checkpoint.close()\n }\n stage = 'serving'\n const served = await runAbortable(\n () => {\n servingMayExist = true\n return serve({\n artifactPath,\n artifactDigest: artifact.digest,\n artifactBytes: artifact.bytes,\n routerModelId: trainedModelIdForArtifact(artifact.digest),\n signal,\n })\n },\n signal,\n 'checkpoint serving cancelled',\n )\n signal.throwIfAborted()\n if (served?.succeeded !== true)\n throw new Error(served?.reason ?? 'checkpoint serving is unverified')\n if (served.value.artifactDigest !== artifact.digest)\n throw new Error('Router serving evidence names a different checkpoint')\n // Snapshot caller-owned evidence before awaiting another read.\n const receipt = immutableCandidateValue(\n agentTrainingReceiptSchema.parse({\n version: 1,\n dataset,\n parentProfileDigest,\n parentReceiptDigest: ancestry[0] ? canonicalCandidateDigest(ancestry[0]) : null,\n executionRef,\n trainer: { ...trainer, parameters },\n checkpoint: {\n artifactDigest: artifact.digest,\n artifactBytes: artifact.bytes,\n routerModelId: served.value.routerModelId,\n servingDigest: served.value.evidenceDigest,\n },\n }),\n )\n if ((await hashFile(artifactPath, maxCheckpointBytes, signal)).digest !== artifact.digest)\n throw new Error('checkpoint changed during serving')\n stage = 'profile'\n const previousModel = parent.metadata?.training?.receipt.checkpoint.routerModelId\n const routerModelId = receipt.checkpoint.routerModelId\n const rebindModels = <T extends { model?: string }>(entries: Record<string, T>) =>\n Object.fromEntries(\n Object.entries(entries).map(([key, value]) => [\n key,\n previousModel && value.model === previousModel\n ? { ...value, model: routerModelId }\n : value,\n ]),\n )\n const candidate = snapshotAgentProfile({\n ...parent,\n model: {\n ...parent.model,\n default: routerModelId,\n ...(previousModel && parent.model.small === previousModel ? { small: routerModelId } : {}),\n },\n // Only references to the old trained artifact follow the new receipt; other models stay put.\n ...(parent.subagents && { subagents: rebindModels(parent.subagents) }),\n ...(parent.modes && { modes: rebindModels(parent.modes) }),\n metadata: { ...parent.metadata, training: { receipt, ancestors: ancestry } },\n })\n validate(candidate, false)\n // The validator is caller code too; publish only the bytes the receipt actually names.\n if ((await hashFile(artifactPath, maxCheckpointBytes, signal)).digest !== artifact.digest)\n throw new Error('checkpoint changed during candidate validation')\n stage = 'persistence'\n const receiptPath = join(jobDirectory, 'receipt.json')\n const profilePath = join(jobDirectory, 'profile.json')\n const profileDigest = canonicalAgentProfileDigest(candidate)\n // Reuse the runtime's no-clobber, fsynced publication primitive. Once the\n // profile is committed, a late cancellation must not retract an observed result.\n for (const [path, value] of [\n [receiptPath, receipt],\n [profilePath, candidate],\n ] as const) {\n signal.throwIfAborted()\n if (!publishExclusiveDurableFile(path, JSON.stringify(value), { mode: 0o400 }))\n throw new Error('training publication path already exists')\n }\n return {\n mode: 'training',\n succeeded: true,\n profile: candidate,\n profileDigest,\n receipt,\n artifactPath,\n receiptPath,\n profilePath,\n }\n } catch (error) {\n let cleanupError: string | undefined\n if (jobDirectory) {\n try {\n await rm(join(jobDirectory, 'profile.json'), { force: true })\n syncDurableDirectory(jobDirectory)\n } catch (failure) {\n cleanupError = failure instanceof Error ? failure.message : 'profile cleanup failed'\n }\n }\n return {\n mode: 'training',\n succeeded: false,\n stage,\n reason:\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'training failed',\n servingMayExist,\n trainingMayExist,\n ...(cleanupError ? { cleanupError } : {}),\n ...(jobDirectory ? { outputDirectory: jobDirectory } : {}),\n }\n } finally {\n clearTimer?.()\n cancellation.release()\n }\n}\n","/**\n * `improve` runs one complete optimization method against an exact profile\n * surface. Runtime extracts and materializes the profile value; agent-eval owns\n * optimization, disjoint data partitions, final-test scoring, and uncertainty.\n *\n * Code owns isolated git worktrees. Training owns checkpoint execution and\n * serving receipts; unlike optimization, it does not make a promotion decision.\n *\n * @stable\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/contract'\nimport { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { runCodeImprovement } from './code-execution'\nimport type {\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveResult,\n ImproveSearchOptions,\n ImproveSearchResult,\n} from './improve-types'\nimport { runMethodImprovement } from './method-execution'\nimport type { ReadonlyAgentProfile } from './profile-types'\nimport { isImproveSearchMethod, runSearchImprovement } from './search-method'\nimport {\n type ImproveTrainingOptions,\n type ImproveTrainingResult,\n runProfileTraining,\n} from './training'\n\n// The owning modules are the single list of these names; re-exporting them by\n// hand made every new option type a three-file edit.\nexport type * from './improve-types'\nexport { decideSearchImprovement } from './search-decision'\nexport {\n dedicatedLane,\n routerLane,\n type SearchCellContext,\n SearchEnvironmentFault,\n type SearchLane,\n sharedBoxLane,\n subscriptionLane,\n} from './search-executor'\nexport { searchMethod } from './search-method'\nexport type * from './training'\nexport { createCommandProfileTrainer } from './training'\n\n/** Train and serve a checkpoint without implying that it improved held-out quality. */\nexport function improve(\n profile: ReadonlyAgentProfile,\n opts: ImproveTrainingOptions,\n): Promise<ImproveTrainingResult>\n/**\n * Search one exact profile surface with Runtime's native search\n * (`method: searchMethod(...)`): the kernel expands, allocates and claims on\n * the sealed test split, and the claim decides.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveSearchResult>\n/**\n * Optimize one exact profile surface with a complete method.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult>\n/** Optimize one exact profile surface with a complete method or a search. */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact> | ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult | ImproveSearchResult>\n/**\n * Optimize repository code through Runtime's isolated worktree path.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n): Promise<ImproveCodeResult<TScenario, TArtifact>>\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profileOrCode: ReadonlyAgentProfile | ImproveCodeRunOptions<TScenario, TArtifact>,\n opts?:\n | ImproveMethodOptions<TScenario, TArtifact>\n | ImproveSearchOptions<TScenario, TArtifact>\n | ImproveTrainingOptions,\n): Promise<ImproveResult<TScenario, TArtifact> | ImproveTrainingResult> {\n if (opts === undefined) {\n const code = profileOrCode as ImproveCodeRunOptions<TScenario, TArtifact>\n if (code?.surface !== 'code') {\n throw new ConfigError(\"improve(): the one-argument form requires { surface: 'code', ... }\")\n }\n return runCodeImprovement(code)\n }\n if (opts === null || typeof opts !== 'object') {\n throw new ConfigError('improve(): options must be an object')\n }\n if ('mode' in opts) {\n if (opts.mode !== 'training') throw new ConfigError('improve(): unsupported mode')\n return runProfileTraining(profileOrCode as ReadonlyAgentProfile, opts)\n }\n if ((opts as { surface?: string }).surface === 'code') {\n throw new ConfigError(\"improve(): code takes one argument: improve({ surface: 'code', ... })\")\n }\n const parsedProfile = agentProfileSchema.safeParse(profileOrCode)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n const exact = immutableCandidateValue(parsedProfile.data)\n if (isImproveSearchMethod(opts.method)) {\n return runSearchImprovement(exact, opts as ImproveSearchOptions<TScenario, TArtifact>)\n }\n return runMethodImprovement(exact, opts as ImproveMethodOptions<TScenario, TArtifact>)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,UAAU;CAAE;AAC9D;AAEA,SAAgB,cAAc,OAAiC;CAC7D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS;AACzE;;AAGA,SAAgB,gBACd,QACA,OACM;CACN,OAAO,YAAY;CACnB,KAAK,MAAM,OAAO;EAAC;EAAY;EAAa;CAAS,GAAY;EAC/D,MAAM,QAAQ,MAAM;EACpB,IAAI,cAAc,KAAK,GAAG,OAAO,QAAQ;OACpC,IAAI,QAAQ,WAAW,OAAO,WAAW;OACzC,OAAO,cAAc;CAC5B;CACA,IAAI,MAAM,gBAAgB,OAAO,OAAO,cAAc;CACtD,IAAI,MAAM,aAAa,OAAO,OAAO,WAAW;CAChD,IAAI,cAAc,MAAM,gBAAgB,GACtC,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;AAErE;;AC3BA,eAAsB,gBACpB,UACA,SACA,WACA,cACe;CACf,IAAI;EACF,MAAM,WAAW,SAAS,SAAS;CACrC,SAAS,eAAe;EACtB,IAAI,iBAAiB,MACnB,MAAM,IAAI,eACR,CAAC,cAAc,aAAa,GAC5B,6EACF;EAEF,MAAM;CACR;CACA,IAAI,iBAAiB,MAAM,MAAM;AACnC;AAEA,e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Y,QACpB,MAAM,IAAI,YAAY,oEAAoE;EAE5F,OAAO,mBAAmB,IAAI;CAChC;CACA,IAAI,SAAS,QAAQ,OAAO,SAAS,UACnC,MAAM,IAAI,YAAY,sCAAsC;CAE9D,IAAI,UAAU,MAAM;EAClB,IAAI,KAAK,SAAS,YAAY,MAAM,IAAI,YAAY,6BAA6B;EACjF,OAAO,mBAAmB,eAAuC,IAAI;CACvE;CACA,IAAK,KAA8B,YAAY,QAC7C,MAAM,IAAI,YAAY,uEAAuE;CAE/F,MAAM,gBAAgB,mBAAmB,UAAU,aAAa;CAChE,IAAI,CAAC,cAAc,SACjB,MAAM,IAAI,YACR,iDAAiD,cAAc,MAAM,SACvE;CAEF,MAAM,QAAQ,wBAAwB,cAAc,IAAI;CACxD,IAAI,sBAAsB,KAAK,MAAM,GACnC,OAAO,qBAAqB,OAAO,IAAkD;CAEvF,OAAO,qBAAqB,OAAO,IAAkD;AACvF"}
1
+ {"version":3,"file":"improve-Ca4PSA2z.js","names":["truncate","canonicalCandidateDigest","resolvePath","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","sha256Bytes"],"sources":["../src/runtime-usage.ts","../src/improvement/agentic-shot-evidence.ts","../src/improvement/worktree-tree.ts","../src/improvement/agentic-generator.ts","../src/improvement/cleanup.ts","../src/improvement/improve-result.ts","../src/improvement/improvement-driver.ts","../src/improvement/profile-surface.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/code-execution.ts","../src/improvement/method-controls.ts","../src/improvement/method-cost.ts","../src/improvement/candidate-validation.ts","../src/improvement/method-identity.ts","../src/improvement/profile-improvement.ts","../src/improvement/method-execution.ts","../src/improvement/search-session.ts","../src/improvement/search-method.ts","../src/improvement/training.ts","../src/improvement/improve.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","/**\n * The evidence one agentic author shot leaves: its receipt (identity, timing,\n * usage and cost basis), the run-ledger cost receipt, and the callbacks that\n * persist both the receipt and the worktree disposition before the loop moves\n * on. A callback that throws aborts the candidate, so evidence persistence\n * fails closed.\n */\nimport type { CostReceipt, CostReceiptInput } from '@tangle-network/agent-eval'\nimport type { AgentProfile, HarnessType } from '@tangle-network/agent-interface'\nimport { sha256 } from '../content-digest'\nimport type { AgentTurnUsage, CollectedAgentTurn } from '../runtime/stream-agent-turn'\nimport type {\n AgenticGeneratorOptions,\n AgenticGeneratorShotDisposition,\n AgenticGeneratorShotExecution,\n AgenticGeneratorShotReceipt,\n} from './agentic-generator'\n\nexport async function emitShotReceipt(\n callback: AgenticGeneratorOptions['onShotCompleted'],\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n primaryError: Error | null,\n): Promise<void> {\n try {\n await callback?.(receipt, execution)\n } catch (callbackError) {\n if (primaryError !== null) {\n throw new AggregateError(\n [primaryError, callbackError],\n 'agenticGenerator: author shot failed and its receipt could not be persisted',\n )\n }\n throw callbackError\n }\n if (primaryError !== null) throw primaryError\n}\n\nexport async function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nexport async function rethrowShotSetupError(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n worktreePath: string,\n stage: Extract<AgenticGeneratorShotDisposition, { kind: 'setup-error' }>['stage'],\n cause: unknown,\n): Promise<never> {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n try {\n await emitShotDisposition(callback, receipt, {\n kind: 'setup-error',\n worktreePath,\n stage,\n error: { name: error.name, message: error.message },\n })\n } catch (callbackError) {\n throw new AggregateError(\n [cause, callbackError],\n 'agenticGenerator: shot processing failed and its worktree disposition could not be persisted',\n )\n }\n throw cause\n}\n\nexport function shotReceipt(input: {\n readonly generation: number | undefined\n readonly candidateIndex: number | undefined\n readonly shot: number\n readonly maxShots: number\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly profile: AgentProfile\n readonly profileDigest: string\n readonly prompt: string\n readonly startedAt: Date\n readonly completedAt: Date\n readonly result: AgenticGeneratorShotExecution | null\n readonly costCallId: string | null\n readonly costReceipt: CostReceipt | null\n readonly error: unknown\n}): AgenticGeneratorShotReceipt {\n const error = input.error\n ? {\n name: input.error instanceof Error ? input.error.name : 'Error',\n message: input.error instanceof Error ? input.error.message : String(input.error),\n }\n : null\n const result = input.result\n const costBasis = costBasisFor(input.costReceipt, result)\n const costUsd =\n input.costReceipt?.costUsd ?? result?.usage.costUsd ?? result?.usage.estimatedCostUsd ?? null\n return {\n generation: input.generation ?? null,\n candidateIndex: input.candidateIndex ?? null,\n shot: input.shot + 1,\n maxShots: input.maxShots,\n profileDigest: input.profileDigest,\n harness: input.harness,\n provider: input.provider,\n model: input.model,\n reasoningEffort: input.profile.model?.reasoningEffort ?? null,\n promptSha256: `sha256:${sha256(input.prompt)}`,\n startedAt: input.startedAt.toISOString(),\n completedAt: input.completedAt.toISOString(),\n durationMs: input.completedAt.getTime() - input.startedAt.getTime(),\n status: result?.status ?? null,\n usage: result ? { ...result.usage } : null,\n transportAttempts: result?.transportAttempts ?? null,\n costCallId: input.costCallId,\n costBasis,\n costUsd: costBasis === 'unknown' ? null : costUsd,\n costUsdKnown: costBasis === 'provider-reported',\n error,\n }\n}\n\nfunction costBasisFor(\n receipt: CostReceipt | null,\n turn: AgenticGeneratorShotExecution | null,\n): AgenticGeneratorShotReceipt['costBasis'] {\n if (receipt) {\n if (receipt.costUnknown) return 'unknown'\n return receipt.actualCostUsd === undefined ? 'estimated-pricing' : 'provider-reported'\n }\n if (turn?.usage.usdKnown !== false && turn?.usage.costUsd !== undefined) {\n return 'provider-reported'\n }\n return turn?.usage.estimatedCostUsd !== undefined ? 'estimated-pricing' : 'unknown'\n}\n\nexport function shotFailure(result: CollectedAgentTurn): Error | null {\n if (result.status === 'completed') return null\n if (result.status === 'aborted') {\n return new Error('agenticGenerator: author shot was cancelled by the caller')\n }\n return new Error(\n `agenticGenerator: author shot failed${result.error?.message ? `: ${result.error.message}` : ''}`,\n )\n}\n\nexport function costReceiptFromTurn(result: CollectedAgentTurn, model: string): CostReceiptInput {\n const tokensKnown = result.usage.tokensKnown !== false\n const actualCostUsd = result.usage.usdKnown === false ? undefined : result.usage.costUsd\n const cachedTokens = promptCacheReadTokens(result.usage)\n return {\n model,\n inputTokens: tokensKnown ? Math.max(0, result.usage.input - (cachedTokens ?? 0)) : 0,\n outputTokens: tokensKnown ? result.usage.output : 0,\n ...(tokensKnown ? {} : { usageUnknown: true }),\n ...(cachedTokens !== undefined ? { cachedTokens } : {}),\n ...(result.usage.reasoningTokens !== undefined\n ? { reasoningTokens: result.usage.reasoningTokens }\n : {}),\n ...(actualCostUsd !== undefined\n ? { actualCostUsd }\n : result.usage.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: result.usage.estimatedCostUsd }\n : { costUnknown: true }),\n }\n}\n\nfunction promptCacheReadTokens(usage: AgentTurnUsage): number | undefined {\n const cache = usage.promptCache\n if (!cache) return undefined\n for (const field of ['readTokens', 'cachedInputTokens', 'cacheReadInputTokens']) {\n const value = cache[field]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n return undefined\n}\n","/**\n * The exact content of a candidate worktree, as a Git tree object.\n *\n * A multi-shot candidate edits ONE directory in place, so the tree a shot\n * produced is gone as soon as the next shot writes over it. Writing that\n * content into the object store is what makes an earlier tree recoverable:\n * `agenticGenerator` snapshots a tree that verified, and puts it back when a\n * later shot ends the budget on a worse one.\n *\n * The snapshot stages into a PRIVATE index file, so the index the driver later\n * commits from is untouched.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { mkdtempSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\n/** Write the worktree's current content into the object store and return its tree id. */\nexport function snapshotWorktreeTree(worktreePath: string): string {\n const scratch = mkdtempSync(join(tmpdir(), 'agentic-generator-tree-'))\n const indexFile = join(scratch, 'index')\n try {\n // HEAD first: a tracked file that `.gitignore` also matches stays in the\n // tree. Against an EMPTY index `git add -A` reads that file as untracked\n // and drops it, and restoring such a tree would delete a tracked file.\n git(worktreePath, ['read-tree', 'HEAD'], indexFile)\n git(worktreePath, ['add', '--all'], indexFile)\n return git(worktreePath, ['write-tree'], indexFile)\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n}\n\n/**\n * Put a snapshotted tree back into the worktree, then prove the directory\n * holds exactly that tree.\n *\n * The proof is not ceremony: a restore that lands the wrong bytes ships the\n * wrong candidate, and every artifact downstream still reads as though the\n * best tree shipped.\n */\nexport function restoreWorktreeTree(worktreePath: string, tree: string): void {\n git(worktreePath, ['read-tree', '-u', '--reset', tree])\n // `read-tree` removes what the index tracked. A file a later shot added is\n // untracked, so it survives that and would ship beside the restored tree.\n // Ignored files are left alone, exactly as a commit leaves them.\n git(worktreePath, ['clean', '--force', '-d', '--quiet'])\n const restored = snapshotWorktreeTree(worktreePath)\n if (restored !== tree) {\n throw new Error(\n `agenticGenerator: restoring tree ${tree} into ${worktreePath} produced ${restored}`,\n )\n }\n}\n\nfunction git(cwd: string, args: string[], indexFile?: string): string {\n const env = { ...process.env }\n if (indexFile) env.GIT_INDEX_FILE = indexFile\n else delete env.GIT_INDEX_FILE\n const result = spawnSync('git', args, { cwd, encoding: 'utf-8', env })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git ${args[0]} failed to spawn in ${cwd}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git ${args[0]} exited ${result.status} in ${cwd}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout.trim()\n}\n\nexport function worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain=v1', '-z', '--untracked-files=all'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n const records = result.stdout.split('\\0')\n const paths: string[] = []\n for (let i = 0; i < records.length; i += 1) {\n const record = records[i]\n if (!record) continue\n paths.push(record.slice(3))\n // Rename and copy entries have a second NUL-delimited path without a status prefix.\n if (record[0] === 'R' || record[1] === 'R' || record[0] === 'C' || record[1] === 'C') {\n const source = records[++i]\n if (!source) {\n throw new Error(\n `agenticGenerator: git status omitted a rename/copy path in ${worktreePath}`,\n )\n }\n paths.push(source)\n }\n }\n return paths\n}\n","/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`. It runs a real\n * authored profile inside the candidate worktree the driver already created,\n * letting the agent read the codebase + the research proposal findings and\n * make the change in place. The driver then commits the worktree into a\n * `CodeSurface`.\n *\n * Every paid shot enters Runtime through `createExecutor` + `streamAgentTurn`.\n * The caller supplies the exact `AgentProfile` and a worktree-aware executor\n * placement; Runtime validates and records the profile that actually ran. Two\n * built-in placements edit the supplied worktree itself: `{ backend:'cli-in-place',\n * workspacePath: worktreePath }` runs a local coding CLI (claude-code / codex /\n * opencode / pi) in that directory, and `{ backend:'bridge', cwd: worktreePath }`\n * runs a cli-bridge session there. `cli-worktree` is NOT one of them — it cuts a\n * worktree of its own, so every shot would read as an empty tree.\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runAgentRounds`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no session-specific retry path needed)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * - dirty + `verify` ok + `keepGoing` → bank the tree and spend the next shot\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier, the first dirty shot is the candidate.\n *\n * BEST-OF-N is the `keepGoing` path, and the loop owns it end to end. A\n * verifier that passes a tree and asks for another shot has its tree\n * snapshotted as a Git tree object; when the budget ends, the highest-`score`\n * tree is RESTORED into the worktree and returned as the candidate. So the\n * caller ranks and the loop moves the bytes — a caller never has to write a\n * passing tree back itself. The budget ends on the last shot, or earlier on a\n * `keepGoing`-less pass, and a last shot that broke or reverted the change does\n * not cost the candidate the verified tree an earlier shot produced.\n *\n * @stable\n */\n\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { CostReceipt, MaximumCharge, ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n type HarnessType,\n type ReasoningEffort,\n} from '@tangle-network/agent-interface'\nimport { runSettledCommand } from '../mcp/worktree-harness'\nimport {\n type AgentTurnUsage,\n type CollectedAgentTurn,\n collectAgentTurn,\n streamAgentTurn,\n} from '../runtime/stream-agent-turn'\nimport {\n assertExecutableAgentProfile,\n concreteProfileModel,\n} from '../runtime/supervise/model-policy'\nimport { createExecutor, type ExecutorConfig } from '../runtime/supervise/runtime'\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport {\n costReceiptFromTurn,\n emitShotDisposition,\n emitShotReceipt,\n rethrowShotSetupError,\n shotFailure,\n shotReceipt,\n} from './agentic-shot-evidence'\nimport type { CandidateGenerator } from './improvement-driver'\nimport { restoreWorktreeTree, snapshotWorktreeTree, worktreeChangedPaths } from './worktree-tree'\n\nconst RAW_TRACE_ANALYST_ID = 'raw-trace-distiller'\nconst RAW_TRACE_AREA = 'raw-trace-context'\nconst RAW_TRACE_DIAGNOSIS_PATH = '.improve/raw-trace-diagnosis.md'\n\n/**\n * Outcome of verifying a candidate worktree.\n *\n * `ok` answers \"is this tree shippable\". `keepGoing` answers \"should the budget\n * stop here\", and `score` ranks this tree against the other trees the same\n * candidate produced — three separate questions, so a verifier can pass a tree\n * and still spend the shots it was given.\n *\n * `feedback` (compiler errors, failing test output, or the reason a passing\n * tree is being sent back) is fed into the next shot.\n */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n /**\n * Spend the remaining shots instead of returning this tree now.\n *\n * Read only when `ok` is true: a failed verification already spends the next\n * shot. Omitted means the first passing tree ends the candidate.\n */\n keepGoing?: boolean\n /**\n * How good this tree is, for ranking it against the other passing trees of\n * this candidate. Higher wins; a tie keeps the LATER tree, which is the one\n * already on disk and the one the author refined last.\n *\n * Only a passing tree is ranked — a tree that failed verification is never a\n * candidate, whatever it scored. Score every passing tree or none of them: a\n * scored tree cannot be ranked against an unscored one, and mixing the two\n * fails the run rather than guessing an order.\n */\n score?: number\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (\n worktreePath: string,\n signal?: AbortSignal,\n) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorShotReceipt {\n readonly generation: number | null\n readonly candidateIndex: number | null\n /** One-based shot number within this candidate. */\n readonly shot: number\n readonly maxShots: number\n /** Exact profile identity admitted before the shot. */\n readonly profileDigest: string\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly reasoningEffort: ReasoningEffort | null\n readonly promptSha256: `sha256:${string}`\n readonly startedAt: string\n readonly completedAt: string\n readonly durationMs: number\n readonly status: CollectedAgentTurn['status'] | null\n /** Runtime-normalized usage. Unknown token or dollar totals remain marked unknown. */\n readonly usage: Readonly<AgentTurnUsage> | null\n readonly transportAttempts: number | null\n /** Shared run-ledger call id for this exact shot. */\n readonly costCallId: string | null\n /** Whether dollars came from the provider, the pricing table, or are unknown. */\n readonly costBasis: 'provider-reported' | 'estimated-pricing' | 'unknown'\n readonly costUsd: number | null\n /** True only for a provider-reported amount, never for a pricing estimate. */\n readonly costUsdKnown: boolean\n readonly error: { readonly name: string; readonly message: string } | null\n}\n\n/** Runtime's exact terminal turn plus its complete normalized event stream. */\nexport type AgenticGeneratorShotExecution = Readonly<CollectedAgentTurn>\n\n/** Worktree decision emitted before a completed shot is retried, accepted, or\n * discarded. The callback runs while `worktreePath` is still available, so\n * callers can persist the exact diff. */\nexport type AgenticGeneratorShotDisposition =\n | {\n readonly kind: 'clean'\n readonly worktreePath: string\n }\n | {\n readonly kind: 'rejected'\n readonly worktreePath: string\n readonly stage: 'raw-trace-evidence' | 'verification'\n readonly feedback: string | null\n }\n | {\n /** The tree passed verification and the verifier asked for another shot,\n * so it was snapshotted and the budget continues. */\n readonly kind: 'kept'\n readonly worktreePath: string\n /** The rank the verifier gave this tree, or null when it scored nothing. */\n readonly score: number | null\n /** Whether this tree is now the best one this candidate has produced. */\n readonly best: boolean\n readonly feedback: string | null\n }\n | {\n readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\n /** One-based shot whose tree was put back into the worktree because it\n * outranked the tree on disk; null when the tree on disk is the one that\n * ships. Non-null is the record that best-of-n moved bytes rather than\n * only ranking them. */\n readonly restoredFromShot: number | null\n }\n | {\n readonly kind: 'setup-error'\n readonly worktreePath: string\n readonly stage: 'worktree-inspection' | 'raw-trace-evidence' | 'verification'\n readonly error: { readonly name: string; readonly message: string }\n }\n\nexport type AgenticGeneratorExecutorForWorktree = (worktreePath: string) => ExecutorConfig\n\nexport interface AgenticGeneratorOptions {\n /** Complete author identity. Harness, provider, model, prompt, tools, and resources all come from here. */\n profile: AgentProfile\n /** Place the exact profile on compute that can edit this existing worktree.\n * A local coding CLI returns `{ backend:'cli-in-place', workspacePath: worktreePath }`; a Pi\n * author over cli-bridge returns `{ backend:'bridge', cwd: worktreePath, ...transport }`. Both\n * are checked against the supplied path before the first shot spends. */\n executorForWorktree: AgenticGeneratorExecutorForWorktree\n /** Awaited once for every attempted author shot, including execution failures.\n * The second argument is Runtime's exact terminal turn and event stream.\n * Throwing aborts the candidate so evidence persistence fails closed. */\n onShotCompleted?: (\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n ) => void | Promise<void>\n /** Awaited after worktree inspection and before the shot is accepted,\n * retried, or discarded. Throwing aborts the candidate. */\n onShotDisposition?: (\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n ) => void | Promise<void>\n /** Optional hard upper bound passed to the run-wide CostLedger before each author shot. */\n maximumCharge?: MaximumCharge\n /** Per-shot wall-clock timeout. Omit for no Runtime-imposed deadline. */\n timeoutMs?: number\n /** Build the task prompt from proposal findings. Required: Runtime invents no authoring policy. */\n buildPrompt: (args: { findings: ReadonlyArray<ProposalFinding> }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. A verifier that returns\n * `keepGoing` passes a tree AND spends the remaining shots, and the\n * best-scoring tree is the one that ships. Omitted means the first dirty\n * shot is the candidate. See `commandVerifier` and `VerifyResult`. */\n verify?: Verifier\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator`: run an exact profiled author inside the existing candidate worktree. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions): CandidateGenerator {\n const profile = detachedSnapshot(\n agentProfileSchema.parse(opts.profile) as AgentProfile,\n 'agenticGenerator profile',\n )\n assertExecutableAgentProfile(profile, 'agenticGenerator')\n const harness = profile.harness!\n const author: AuthorContext = {\n opts,\n profile,\n harness,\n provider: profile.model!.provider!.trim(),\n model: concreteProfileModel(profile)!,\n profileDigest: canonicalAgentProfileDigest(profile),\n dirty: opts.isDirty ?? worktreeDirty,\n }\n\n return {\n kind: `agentic:${harness}`,\n // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context\n // are the change signal — an agentic coder proposes from them even when the\n // distiller yielded zero findings. Without this, the code candidate driver's\n // empty-findings guard short-circuits and generates ZERO candidates on the\n // first (and, for a single-generation run, only) proposal round.\n proposesWithoutFindings: true,\n generate: (request) => generateCandidate(author, request),\n }\n}\n\n/** The exact author one `agenticGenerator` runs, fixed when it is built. */\ninterface AuthorContext {\n readonly opts: AgenticGeneratorOptions\n readonly profile: AgentProfile\n readonly harness: HarnessType\n readonly provider: string\n readonly model: string\n readonly profileDigest: string\n readonly dirty: (worktreePath: string) => boolean\n}\n\ntype GenerateRequest = Parameters<CandidateGenerator['generate']>[0]\ntype AcceptedCandidate = ReturnType<typeof acceptedCandidate>\n\n/** What one candidate carries from shot to shot. */\ninterface CandidateState {\n /** Feedback appended to the base prompt for the NEXT shot — empty on shot 0. */\n attemptNote: string\n /** The best tree this candidate has produced, and where it lives. Only a\n * verifier that returns `keepGoing` can put more than one tree here: a\n * passing tree that ends the budget is banked and shipped in one step. */\n best: BankedTree | null\n /** Whether the verifier scores its trees. Set by the first passing tree;\n * a later tree that disagrees cannot be ranked and fails the run. */\n scored: boolean | null\n lastReceipt: AgenticGeneratorShotReceipt | null\n}\n\n/** Where a settled shot stands in the budget. */\ninterface ShotPosition {\n readonly shot: number\n readonly shots: number\n readonly needsRawTraceEvidence: boolean\n}\n\n/** How a settled shot ends: a candidate to ship, or the note the next shot starts from. */\ntype ShotStep = { candidate: AcceptedCandidate } | { note: string }\n\nasync function generateCandidate(\n author: AuthorContext,\n request: GenerateRequest,\n): Promise<AcceptedCandidate | { applied: false; summary: string }> {\n const { opts, harness, provider, model, profile, profileDigest } = author\n const { findings, maxShots, signal, generation, candidateIndex } = request\n signal.throwIfAborted()\n const { basePrompt, factory } = prepareAuthoring(author, request)\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n const state: CandidateState = { attemptNote: '', best: null, scored: null, lastReceipt: null }\n\n for (let shot = 0; shot < shots; shot++) {\n signal.throwIfAborted()\n // This shot may write over whatever the worktree held.\n if (state.best) state.best.onDisk = false\n const taskPrompt = state.attemptNote ? `${basePrompt}\\n\\n${state.attemptNote}` : basePrompt\n const startedAt = new Date()\n const ran = await runAuthorShot(author, request, factory, taskPrompt, shot)\n const execution = ran.turn\n ? detachedSnapshot(ran.turn, 'agenticGenerator shot execution')\n : null\n const receipt = shotReceipt({\n generation,\n candidateIndex,\n shot,\n maxShots: shots,\n harness,\n provider,\n model,\n profile,\n profileDigest,\n prompt: taskPrompt,\n startedAt,\n completedAt: new Date(),\n result: execution,\n costCallId: ran.costCallId,\n costReceipt: ran.costReceipt,\n error: ran.shotError,\n })\n state.lastReceipt = receipt\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, ran.shotError)\n signal.throwIfAborted()\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a Runtime turn')\n }\n\n const step = await settleShot(author, request, state, receipt, {\n shot,\n shots,\n needsRawTraceEvidence,\n })\n if ('candidate' in step) return step.candidate\n state.attemptNote = step.note\n }\n\n // Shots exhausted. A banked tree passed verification, so it ships even\n // though the last shot did not end the budget on it — discarding paid,\n // verified work because a later shot broke or reverted it is the loss\n // best-of-n exists to prevent.\n if (state.best !== null) {\n if (!state.lastReceipt) {\n throw new Error('agenticGenerator: a tree was banked without a shot receipt')\n }\n return await shipBankedTree(author, request, state.lastReceipt, state.best)\n }\n // No verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n}\n\n/** Check the request and build the author's prompt and executor, before any shot spends. */\nfunction prepareAuthoring(author: AuthorContext, request: GenerateRequest) {\n const { opts } = author\n const { worktreePath, findings, costLedger } = request\n if (opts.maximumCharge && !costLedger) {\n throw new Error(\n 'agenticGenerator: maximumCharge requires the run-wide CostLedger supplied by agent-eval',\n )\n }\n const basePrompt = opts.buildPrompt({ findings })\n if (typeof basePrompt !== 'string' || basePrompt.trim().length === 0) {\n throw new Error('agenticGenerator: buildPrompt must return a non-empty string')\n }\n const executorConfig = opts.executorForWorktree(worktreePath)\n if (executorConfig.backend === 'bridge' && !samePath(executorConfig.cwd, worktreePath)) {\n throw new Error('agenticGenerator: bridge executor cwd must equal the candidate worktree path')\n }\n if (\n executorConfig.backend === 'cli-in-place' &&\n !samePath(executorConfig.workspacePath, worktreePath)\n ) {\n throw new Error(\n 'agenticGenerator: cli-in-place executor workspacePath must equal the candidate worktree path',\n )\n }\n return { basePrompt, factory: createExecutor(executorConfig) }\n}\n\n/** Run one author shot through the run-wide ledger when there is one. A failure is returned, not thrown. */\nasync function runAuthorShot(\n author: AuthorContext,\n request: GenerateRequest,\n factory: ReturnType<typeof createExecutor>,\n taskPrompt: string,\n shot: number,\n) {\n const { opts, profile, harness, model } = author\n const { signal, generation, candidateIndex, costLedger, costPhase } = request\n let turn: CollectedAgentTurn | null = null\n let costReceipt: CostReceipt | null = null\n let costCallId: string | null = null\n let shotError: Error | null = null\n try {\n const execute = async (\n executionSignal: AbortSignal,\n callId?: string,\n ): Promise<CollectedAgentTurn> => {\n turn = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', profile, factory },\n { prompt: taskPrompt },\n {\n signal: executionSignal,\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(callId ? { callId } : {}),\n },\n ),\n )\n const failure = shotFailure(turn)\n if (failure) throw failure\n return turn\n }\n\n if (costLedger) {\n const paid = await costLedger.runPaidCall({\n channel: 'driver',\n phase: costPhase ?? 'search.proposal',\n actor: `agentic-generator:${harness}`,\n model,\n tags: {\n generation: String(generation ?? -1),\n candidateIndex: String(candidateIndex ?? -1),\n shot: String(shot + 1),\n },\n signal,\n ...(opts.maximumCharge ? { maximumCharge: opts.maximumCharge } : {}),\n execute: (executionSignal, callId) => execute(executionSignal, callId),\n receipt: (result) => costReceiptFromTurn(result, model),\n receiptFromError: () => (turn ? costReceiptFromTurn(turn, model) : undefined),\n })\n costCallId = paid.callId ?? null\n costReceipt = paid.receipt ?? null\n if (!paid.succeeded) throw paid.error\n turn = paid.value\n } else {\n turn = await execute(signal)\n }\n } catch (cause) {\n shotError = cause instanceof Error ? cause : new Error(String(cause))\n }\n return { turn, costReceipt, costCallId, shotError }\n}\n\n/** Decide what a completed shot's worktree means: ship it, or the note the next shot starts from. */\nasync function settleShot(\n author: AuthorContext,\n request: GenerateRequest,\n state: CandidateState,\n receipt: AgenticGeneratorShotReceipt,\n position: ShotPosition,\n): Promise<ShotStep> {\n const { opts, dirty } = author\n const { worktreePath, findings, signal } = request\n let worktreeChanged: boolean\n try {\n worktreeChanged = dirty(worktreePath)\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'worktree-inspection',\n cause,\n )\n }\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!worktreeChanged) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, { kind: 'clean', worktreePath })\n signal.throwIfAborted()\n return { note: EMPTY_TREE_NOTE }\n }\n\n if (position.needsRawTraceEvidence) {\n let problem: string | null\n try {\n problem = rawTraceEvidenceProblem(worktreePath, findings)\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'raw-trace-evidence',\n cause,\n )\n }\n if (problem) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'raw-trace-evidence',\n feedback: problem,\n })\n signal.throwIfAborted()\n return { note: problem }\n }\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the model's response text). With a verifier the candidate must pass it.\n if (!opts.verify) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n restoredFromShot: null,\n })\n signal.throwIfAborted()\n return { candidate: acceptedCandidate(findings) }\n }\n return settleVerifiedShot(author, request, state, receipt, position, opts.verify)\n}\n\n/** Run the verifier on a dirty tree, then ship, bank or reject it. */\nasync function settleVerifiedShot(\n author: AuthorContext,\n request: GenerateRequest,\n state: CandidateState,\n receipt: AgenticGeneratorShotReceipt,\n { shot, shots }: ShotPosition,\n verify: Verifier,\n): Promise<ShotStep> {\n const { opts } = author\n const { worktreePath, signal } = request\n let result: VerifyResult\n try {\n signal.throwIfAborted()\n result = await verify(worktreePath, signal)\n signal.throwIfAborted()\n } catch (cause) {\n signal.throwIfAborted()\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'verification',\n cause,\n )\n }\n if (result.ok) {\n const score = admittedScore(result, state.scored, shot)\n state.scored = score !== null\n const previousBest = state.best\n let banked: BankedTree\n // A tie keeps the LATER tree: it is already on disk, and it is the\n // author's own refinement of the tree it tied with. `admittedScore`\n // refuses a mix of scored and unscored trees, so an unscored set is a\n // flat 0 and this rule reduces to \"the later tree wins\".\n if (previousBest === null || (score ?? 0) >= (previousBest.score ?? 0)) {\n banked = { shot: shot + 1, score, tree: null, onDisk: true }\n } else {\n banked = previousBest\n }\n const becomesBest = banked !== previousBest\n state.best = banked\n if (result.keepGoing !== true) {\n signal.throwIfAborted()\n return { candidate: await shipBankedTree(author, request, receipt, banked) }\n }\n // Shots remain, so a later one can write over this tree. Bank the\n // bytes now, while they are still on disk.\n if (becomesBest && shot < shots - 1) banked.tree = snapshotWorktreeTree(worktreePath)\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'kept',\n worktreePath,\n score,\n best: becomesBest,\n feedback: result.feedback ?? null,\n })\n signal.throwIfAborted()\n return { note: keptNote(result.feedback) }\n }\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'verification',\n feedback: result.feedback ?? null,\n })\n signal.throwIfAborted()\n // Dirty but failing — resume next shot atop these edits with the error.\n return { note: failureNote(result.feedback) }\n}\n\n/** Ship the best tree this candidate produced, restoring it when a later\n * shot wrote over it. */\nasync function shipBankedTree(\n author: AuthorContext,\n request: GenerateRequest,\n receipt: AgenticGeneratorShotReceipt,\n banked: BankedTree,\n): Promise<AcceptedCandidate> {\n const { worktreePath, findings, signal } = request\n const restoredFromShot = banked.onDisk ? null : banked.shot\n if (!banked.onDisk) {\n if (banked.tree === null) {\n throw new Error(\n `agenticGenerator: shot ${banked.shot} produced the best tree but it was never snapshotted`,\n )\n }\n restoreWorktreeTree(worktreePath, banked.tree)\n banked.onDisk = true\n }\n signal.throwIfAborted()\n await emitShotDisposition(author.opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n restoredFromShot,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\n}\n\n/** A tree that passed verification, and whether the worktree still holds it. */\ninterface BankedTree {\n /** One-based shot that produced it. */\n readonly shot: number\n /** Its rank, or null when the verifier scores nothing. */\n readonly score: number | null\n /** Its Git tree id, written only while a later shot can still overwrite it. */\n tree: string | null\n onDisk: boolean\n}\n\n/** The rank a passing tree carries, refusing a set of trees that cannot be ordered. */\nfunction admittedScore(result: VerifyResult, scored: boolean | null, shot: number): number | null {\n const has = result.score !== undefined\n if (scored !== null && has !== scored) {\n throw new Error(\n `agenticGenerator: verify ${has ? 'scored' : 'did not score'} the tree from shot ${shot + 1} and ${\n scored ? 'scored' : 'did not score'\n } an earlier passing tree; a scored tree cannot be ranked against an unscored one`,\n )\n }\n if (!has) return null\n if (typeof result.score !== 'number' || !Number.isFinite(result.score)) {\n throw new Error(\n `agenticGenerator: verify returned a non-finite score (${String(result.score)}) for shot ${shot + 1}`,\n )\n }\n return result.score\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\n/** Next-shot feedback when the worktree PASSED and the verifier asked for\n * another shot. The passing tree is banked, so the author is told to improve\n * it rather than protect it — a worse tree cannot cost it the candidate. */\nfunction keptNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree and verification PASSED.',\n 'Shots remain in this budget — keep improving the change in place, do not revert it.',\n 'The best version you produce is the one that ships.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\nfunction rawTraceEvidenceProblem(\n worktreePath: string,\n findings: ReadonlyArray<ProposalFinding>,\n): string | null {\n const changedPaths = worktreeChangedPaths(worktreePath)\n const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH)\n if (substantive.length === 0) {\n return [\n `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change.',\n ].join('\\n')\n }\n\n const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH)\n if (!existsSync(diagnosisPath)) {\n return [\n `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change.',\n ].join('\\n')\n }\n\n const body = readFileSync(diagnosisPath, 'utf8')\n const evidencePaths = traceEvidencePaths(findings)\n if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {\n return [\n `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,\n `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(', ')}`,\n ].join('\\n')\n }\n\n return null\n}\n\nfunction requiresRawTraceEvidence(findings: ReadonlyArray<ProposalFinding>): boolean {\n return findings.some((finding) => {\n const f = finding as unknown as Record<string, unknown>\n return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA\n })\n}\n\nfunction traceEvidencePaths(findings: ReadonlyArray<ProposalFinding>): string[] {\n const out: string[] = []\n for (const finding of findings) {\n const refs = (finding as unknown as { evidence_refs?: unknown }).evidence_refs\n if (!Array.isArray(refs)) continue\n for (const ref of refs) {\n if (!ref || typeof ref !== 'object') continue\n const uri = (ref as { uri?: unknown }).uri\n if (typeof uri === 'string' && uri.length > 0) out.push(uri)\n }\n }\n return [...new Set(out)]\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return async (worktreePath: string, signal?: AbortSignal): Promise<VerifyResult> => {\n let result: Awaited<ReturnType<typeof runSettledCommand>>\n try {\n result = await runSettledCommand({\n command,\n args,\n cwd: worktreePath,\n timeoutMs,\n ...(signal ? { signal } : {}),\n })\n } catch (err) {\n signal?.throwIfAborted()\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${reason}`)\n }\n if (result.timedOut || result.killedBySignal) {\n return {\n ok: false,\n feedback: `verifier '${command}' ${result.killedBySignal ? `killed by ${result.killedBySignal}` : 'timed out'} after ${timeoutMs}ms`,\n }\n }\n if (result.exitCode === 0) return { ok: true }\n const out = `${result.stdout}${result.stderr}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.exitCode}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarizeFindings(findings: ReadonlyArray<ProposalFinding>): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\n/**\n * The accepted-shot result: summary (commit message) + the attribution pair\n * the driver wraps into a `ProposedCandidate`, so the candidate stays\n * attributable through `GenerationRecord` and the emitted provenance instead\n * of landing as an anonymous surface.\n */\nfunction acceptedCandidate(findings: ReadonlyArray<ProposalFinding>): {\n applied: true\n summary: string\n label: string\n rationale: string\n} {\n const summary = summarizeFindings(findings)\n return {\n applied: true,\n summary,\n label: slugify(summary.split('\\n', 1)[0] ?? summary),\n rationale: boundedRationale(summary, findings),\n }\n}\n\n/** Short slug from the summary's first line — the candidate's human label. */\nfunction slugify(line: string): string {\n const slug = line\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return truncate(slug || 'agentic-improvement', 48)\n}\n\n/** Bounded \"because Z\" for the candidate: the findings it addressed, or the\n * summary itself when the change was proposed from raw repo/trace context. */\nfunction boundedRationale(summary: string, findings: ReadonlyArray<ProposalFinding>): string {\n if (findings.length === 0) return summary\n return truncate(\n findings.map((finding) => `(${finding.severity}) ${finding.claim}`).join('; '),\n 400,\n )\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Do two names address the same directory? An in-place placement is only in-place if it names the\n * worktree the driver created, and a byte comparison answers that wrongly on a platform whose\n * temporary directory is a symlink: macOS reports `/var/folders/...` where the resolved path is\n * `/private/var/folders/...`, and both are the same directory. */\nfunction samePath(candidate: string | undefined, worktreePath: string): boolean {\n if (typeof candidate !== 'string' || candidate.length === 0) return false\n if (candidate === worktreePath) return true\n return canonicalPath(candidate) === canonicalPath(worktreePath)\n}\n\n/** The resolved path, or the lexically absolute one when the name does not exist — a name that\n * cannot be resolved is a mismatch the caller is told about, not an error to swallow. */\nfunction canonicalPath(path: string): string {\n try {\n return realpathSync(path)\n } catch {\n return resolve(path)\n }\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n return worktreeChangedPaths(worktreePath).length > 0\n}\n","export async function rethrowAfterCleanup(\n cause: unknown,\n cleanup: () => Promise<void>,\n context: string,\n): Promise<never> {\n const cleanupErrors: unknown[] = []\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await cleanup()\n } catch (cleanupCause) {\n cleanupErrors.push(cleanupCause)\n continue\n }\n if (cleanupErrors.length === 0) throw cause\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup retry succeeded`)\n }\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup failed`)\n}\n","import type { ImproveCost } from './improve-types'\n\nexport function copyImproveCost(cost: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: readonly string[]\n}): ImproveCost {\n return {\n totalCostUsd: cost.totalCostUsd,\n accountingComplete: cost.accountingComplete,\n incompleteReasons: [...cost.incompleteReasons],\n }\n}\n","/**\n * Code-only candidate driver for Runtime-owned git worktrees.\n *\n * A `CandidateGenerator` edits an isolated checkout. This driver finalizes each\n * accepted edit as a `CodeSurface` and disposes rejected worktrees.\n *\n * @stable\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { CostLedgerHandle, ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n type CodeSurface,\n type ProposeContext,\n type ProposedCandidate,\n type SurfaceProposer,\n verifyCodeSurface,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport { rethrowAfterCleanup } from './cleanup'\n\n/** The byte-producing path that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an empty findings set\n * because it draws its change signal from the repo and raw traces on disk.\n * An agentic coder (`agenticGenerator`) sets this so it still runs the full\n * `populationSize` when the distiller yielded nothing. A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a clean checkout of the current incumbent. */\n worktreePath: string\n /** Search or production findings explicitly admitted for proposal use. */\n findings: ReadonlyArray<ProposalFinding>\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n /** Generation coordinates supplied by Runtime's internal code candidate driver. */\n generation?: number\n candidateIndex?: number\n /** Shared run-wide paid-call account supplied by agent-eval 0.117+. */\n costLedger?: CostLedgerHandle\n /** Receipt attribution phase supplied alongside `costLedger`. */\n costPhase?: string\n }): Promise<{\n applied: boolean\n summary: string\n /** Short slug for the candidate. When present (with `rationale`), the\n * driver returns a `ProposedCandidate` wrapper so the label survives to\n * `GenerationRecord` and the emitted provenance. */\n label?: string\n /** Why this change was proposed — bounded, derived from the findings the\n * shot addressed. Paired with `label`. */\n rationale?: string\n }>\n}\n\ninterface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Root ref for first-generation/direct callers. Default `main`.\n * Later code generations retain the incumbent's original root. */\n baseRef?: string\n}\n\nexport interface ManagedImprovementDriver extends SurfaceProposer<ProposalFinding> {\n /** Remove every owned candidate except explicitly retained finalized winners. */\n cleanup(retainWorktreeRefs?: readonly string[]): Promise<void>\n}\n\n/** Build the code-only proposer used internally by `improve({ surface: 'code' })`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): ManagedImprovementDriver {\n const baseRef = opts.baseRef ?? 'main'\n const owned = new Map<string, Worktree>()\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<ProposalFinding>) {\n const findings = ctx.findings\n // No findings and a generator that can only act on findings (the\n // reflective patch-applier): propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (findings.length === 0 && !opts.generator.proposesWithoutFindings) {\n return []\n }\n\n const surfaces: Array<CodeSurface | ProposedCandidate> = []\n const incumbent = verifiedCodeIncumbent(ctx.currentSurface)\n const proposalBaseRef = incumbent?.baseCommit ?? baseRef\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef: proposalBaseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\n owned.set(wt.path, wt)\n // Once a worktree exists it MUST be accounted for: finalized into a\n // surface, or discarded. A throw from generate()/finalize() must not\n // leak the worktree + branch — discard best-effort, then rethrow loud.\n try {\n if (incumbent) advanceToIncumbent(wt, incumbent)\n const { applied, summary, label, rationale } = await opts.generator.generate({\n worktreePath: wt.path,\n findings,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n generation: ctx.generation,\n candidateIndex: i,\n ...(ctx.costLedger ? { costLedger: ctx.costLedger } : {}),\n ...(ctx.costPhase ? { costPhase: ctx.costPhase } : {}),\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n owned.delete(wt.path)\n continue\n }\n const surface = await opts.worktree.finalize(wt, summary)\n // A generator that attributes its change gets a `ProposedCandidate`\n // wrapper — the loop normalizes both forms and threads {label,\n // rationale} into `GenerationRecord` + the provenance record. A bare\n // surface stays bare (blind generators remain unattributed).\n surfaces.push(\n label || rationale\n ? { surface, label: label ?? '', rationale: rationale ?? '' }\n : surface,\n )\n owned.delete(wt.path)\n owned.set(surface.worktreeRef, wt)\n } catch (err) {\n const failure = err instanceof Error ? err.message : String(err)\n return rethrowAfterCleanup(\n err,\n async () => {\n await opts.worktree.discard(wt)\n owned.delete(wt.path)\n },\n `improvementDriver: ${failure}`,\n )\n }\n }\n return surfaces\n },\n async cleanup(retainWorktreeRefs = []) {\n const retained = new Set(retainWorktreeRefs)\n const errors: unknown[] = []\n for (const [worktreeRef, worktree] of owned) {\n if (retained.has(worktreeRef)) continue\n try {\n await opts.worktree.discard(worktree)\n owned.delete(worktreeRef)\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improvementDriver: failed to discard candidate worktrees')\n }\n },\n }\n}\n\n/** A code incumbent must still match the immutable identity that was measured. */\nfunction verifiedCodeIncumbent(surface: ProposeContext['currentSurface']): CodeSurface | undefined {\n if (typeof surface !== 'object' || surface.kind !== 'code') return undefined\n verifyCodeSurface(surface)\n return surface\n}\n\n/** Start at the root commit recorded by the incumbent, then fast-forward the\n * fresh branch to the incumbent commit. The worktree stays clean for the\n * generator while `finalize()` still emits one cumulative root-to-candidate\n * patch that can be applied or rolled back independently of prior branches. */\nfunction advanceToIncumbent(worktree: Worktree, incumbent: CodeSurface): void {\n if (worktree.baseCommit !== incumbent.baseCommit || worktree.baseTree !== incumbent.baseTree) {\n throw new Error('improvementDriver: candidate worktree does not match incumbent base identity')\n }\n if (worktree.baseCommit === incumbent.candidateCommit) return\n\n const merge = spawnSync('git', ['merge', '--ff-only', incumbent.candidateCommit], {\n cwd: worktree.path,\n encoding: 'utf8',\n })\n if (merge.error) {\n throw new Error(\n `improvementDriver: failed to start candidate from incumbent: ${merge.error.message}`,\n )\n }\n if (merge.status !== 0) {\n throw new Error(\n `improvementDriver: could not fast-forward candidate to incumbent ${incumbent.candidateCommit}: ${merge.stderr.trim()}`,\n )\n }\n\n const head = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], {\n cwd: worktree.path,\n encoding: 'utf8',\n })\n if (head.error || head.status !== 0 || head.stdout.trim() !== incumbent.candidateCommit) {\n throw new Error('improvementDriver: candidate worktree did not reach the incumbent commit')\n }\n}\n","import { canonicalJson } from '@tangle-network/agent-eval'\nimport type { MutableSurface } from '@tangle-network/agent-eval/contract'\nimport {\n type AgentProfile,\n type AgentProfileResourceRef,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport type {\n ImproveProfileComponents,\n ImproveProfileSurface,\n ImproveSkillsOptions,\n ImproveSurface,\n} from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\ninterface PreparedProfileSurface {\n surface: MutableSurface\n value: unknown\n}\n\n/** Extract the baseline optimized by a method and retain its structured value\n * so external optimizers can inspect it for private fields before serialization. */\nexport function prepareProfileSurface(\n profile: ReadonlyAgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): PreparedProfileSurface {\n switch (surface) {\n case 'prompt':\n return {\n surface: profile.prompt?.systemPrompt ?? '',\n value: profile.prompt?.systemPrompt ?? '',\n }\n case 'skills': {\n const value = inlineSkill(profile, skills).content\n return { surface: value, value }\n }\n case 'tools': {\n const value = profile.tools ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'mcp': {\n const value = profile.mcp ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'hooks': {\n const value = profile.hooks ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'subagents': {\n const value = profile.subagents ?? {}\n return { surface: canonicalJson(value), value }\n }\n case 'agent-profile': {\n if (profileComponents) {\n if (\n profileComponents.encoding !== undefined &&\n profileComponents.encoding !== 'components' &&\n profileComponents.encoding !== 'json'\n ) {\n throw new ConfigError('improve(): profileComponents.encoding must be components or json')\n }\n const value = profileComponents.read(profile)\n const components = componentSurface(value, 'profileComponents.read')\n return {\n surface:\n profileComponents.encoding === 'json'\n ? canonicalJson(components.components)\n : components,\n value,\n }\n }\n return { surface: canonicalJson(profile), value: profile }\n }\n case 'memory': {\n const value = profileInstructions(profile)\n return { surface: value, value }\n }\n case 'rollout-policy': {\n const policy = structuralRolloutPolicyFromProfile(profile)\n return {\n surface: policy ? serializeRolloutPolicy(policy) : '',\n value: policy ?? null,\n }\n }\n case 'code':\n throw new ConfigError(\n 'improve(): code requires the isolated baseline created from opts.code.repoRoot',\n )\n }\n}\n\nexport function isCodeSurface(\n surface: MutableSurface | undefined,\n): surface is Extract<MutableSurface, { readonly kind: 'code' }> {\n return typeof surface === 'object' && surface !== null && surface.kind === 'code'\n}\n\ntype ComponentSurface = Extract<MutableSurface, { readonly kind: 'components' }>\n\nfunction isComponentSurface(surface: MutableSurface | undefined): surface is ComponentSurface {\n return typeof surface === 'object' && surface !== null && surface.kind === 'components'\n}\n\nfunction componentSurface(\n components: Readonly<Record<string, string>>,\n source: string,\n): ComponentSurface {\n const entries = validateComponents(components, source)\n return immutableCandidateValue({\n kind: 'components',\n components: Object.fromEntries(entries),\n } as ComponentSurface)\n}\n\nfunction validateComponents(\n components: Readonly<Record<string, string>>,\n source: string,\n): Array<[string, string]> {\n if (typeof components !== 'object' || components === null || Array.isArray(components)) {\n throw new ConfigError(`improve(): ${source} must return a component record`)\n }\n const entries = Object.entries(components)\n if (entries.length === 0) {\n throw new ConfigError(`improve(): ${source} must return at least one component`)\n }\n for (const [name, value] of entries) {\n if (!name || name.trim() !== name || typeof value !== 'string') {\n throw new ConfigError(\n `improve(): ${source} must return trimmed component names with string values`,\n )\n }\n }\n return entries\n}\n\n/** Parse a JSON winner surface with a typed, contextual error. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate is not valid JSON, so it cannot form a profile candidate: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\nexport function assertCandidateSurfaceKind(\n surface: ImproveSurface,\n baseline: MutableSurface,\n winner: MutableSurface,\n): asserts winner is MutableSurface {\n if (surface === 'code') {\n if (isCodeSurface(winner)) return\n throw new ConfigError(\n `improve(): the '${surface}' candidate returned an incompatible surface value`,\n )\n }\n if (typeof baseline === 'string') {\n if (typeof winner === 'string') return\n throw new ConfigError(\n `improve(): the '${surface}' candidate changed from a text surface to an incompatible surface value`,\n )\n }\n if (!isComponentSurface(baseline) || !isComponentSurface(winner)) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate returned an incompatible surface value`,\n )\n }\n validateComponents(winner.components, `the '${surface}' candidate`)\n const baselineNames = Object.keys(baseline.components).sort()\n const winnerNames = Object.keys(winner.components).sort()\n if (\n baselineNames.length !== winnerNames.length ||\n baselineNames.some((name, index) => name !== winnerNames[index])\n ) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate must preserve the exact component names`,\n )\n }\n}\n\n/** Materialize a detached profile candidate without changing the baseline. */\nfunction materializeImprovementProfileCandidate(\n profile: AgentProfile,\n surface: ImproveProfileSurface,\n winner: MutableSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): AgentProfile {\n let candidate: AgentProfile\n if (isComponentSurface(winner)) {\n if (surface !== 'agent-profile' || !profileComponents) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate has no profile component mapping`,\n )\n }\n const winnerComponents = immutableCandidateValue({ ...winner.components })\n const applied = profileComponents.apply(profile, winnerComponents)\n const validated = parseMaterializedProfile(applied, surface)\n const materializedComponents = Object.fromEntries(\n validateComponents(profileComponents.read(validated), 'profileComponents.read after apply'),\n )\n const names = Object.keys(winnerComponents)\n if (\n names.length !== Object.keys(materializedComponents).length ||\n names.some((name) => materializedComponents[name] !== winnerComponents[name])\n ) {\n throw new ConfigError(\n 'improve(): profileComponents.apply must round-trip every winning component exactly',\n )\n }\n return validated\n }\n if (typeof winner !== 'string') {\n throw new ConfigError(`improve(): the '${surface}' candidate cannot form an AgentProfile`)\n }\n switch (surface) {\n case 'prompt':\n candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n break\n case 'skills': {\n const selectedSkill = inlineSkill(profile, skills)\n candidate = {\n ...profile,\n resources: {\n ...profile.resources,\n skills: profile.resources?.skills?.map((resource) =>\n resource === selectedSkill ? { ...resource, content: winner } : resource,\n ),\n },\n }\n break\n }\n case 'tools':\n candidate = { ...profile, tools: parseWinnerJson(winner, surface) }\n break\n case 'mcp':\n candidate = { ...profile, mcp: parseWinnerJson(winner, surface) }\n break\n case 'hooks':\n candidate = { ...profile, hooks: parseWinnerJson(winner, surface) }\n break\n case 'subagents':\n candidate = { ...profile, subagents: parseWinnerJson(winner, surface) }\n break\n case 'agent-profile':\n candidate = parseWinnerJson(winner, surface)\n break\n case 'memory':\n candidate = {\n ...profile,\n resources: {\n ...profile.resources,\n instructions: replaceProfileInstructions(profile, winner),\n },\n }\n break\n case 'rollout-policy': {\n const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface))\n if (!policy) {\n throw new ConfigError(\n `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy ` +\n `(integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`,\n )\n }\n candidate = applyRolloutPolicyToProfile(profile, policy)\n break\n }\n }\n return parseMaterializedProfile(candidate, surface)\n}\n\nfunction parseMaterializedProfile(candidate: unknown, surface: ImproveSurface): AgentProfile {\n const parsed = agentProfileSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new ConfigError(\n `improve(): the '${surface}' candidate does not produce a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n return immutableCandidateValue(parsed.data)\n}\n\nexport function createProfileCandidateMaterializer(\n profile: AgentProfile,\n surface: ImproveProfileSurface,\n baselineSurface: MutableSurface,\n skills?: ImproveSkillsOptions,\n profileComponents?: ImproveProfileComponents,\n): (candidateSurface: MutableSurface) => AgentProfile {\n const decode = (candidate: MutableSurface): MutableSurface => {\n if (profileComponents?.encoding !== 'json') return candidate\n if (typeof candidate !== 'string') {\n throw new ConfigError('improve(): JSON profile components require a text surface')\n }\n return componentSurface(parseWinnerJson(candidate, surface), 'JSON profile components')\n }\n const decodedBaseline = decode(baselineSurface)\n const baselineDigest = canonicalCandidateDigest(baselineSurface)\n if (profileComponents) {\n const reappliedBaseline = materializeImprovementProfileCandidate(\n profile,\n surface,\n decodedBaseline,\n skills,\n profileComponents,\n )\n if (canonicalAgentProfileDigest(reappliedBaseline) !== canonicalAgentProfileDigest(profile)) {\n throw new ConfigError(\n 'improve(): profileComponents.apply(profile, profileComponents.read(profile)) must reproduce the complete baseline profile exactly',\n )\n }\n }\n const candidates = new Map<Sha256Digest, AgentProfile>([[baselineDigest, profile]])\n return (candidateSurface) => {\n assertCandidateSurfaceKind(surface, baselineSurface, candidateSurface)\n const decodedCandidate = decode(candidateSurface)\n assertCandidateSurfaceKind(surface, decodedBaseline, decodedCandidate)\n const digest = canonicalCandidateDigest(candidateSurface)\n const existing = candidates.get(digest)\n if (existing) return existing\n const candidate = materializeImprovementProfileCandidate(\n profile,\n surface,\n immutableCandidateValue(decodedCandidate),\n skills,\n profileComponents,\n )\n candidates.set(digest, candidate)\n return candidate\n }\n}\n\nfunction inlineSkill(\n profile: ReadonlyAgentProfile,\n options: ImproveSkillsOptions | undefined,\n): Readonly<Extract<AgentProfileResourceRef, { kind: 'inline' }>> {\n const resourceName = options?.resourceName.trim()\n if (!resourceName) {\n throw new ConfigError(\n \"improve(): surface 'skills' requires opts.skills.resourceName for one inline profile skill\",\n )\n }\n assertFailClosedResources(profile, 'skills')\n const matches = (profile.resources?.skills ?? []).filter(\n (resource) => resource.name === resourceName,\n )\n if (matches.length !== 1 || matches[0]?.kind !== 'inline') {\n throw new ConfigError(\n `improve(): skill '${resourceName}' must identify exactly one inline profile resource`,\n )\n }\n return matches[0]\n}\n\nfunction profileInstructions(profile: ReadonlyAgentProfile): string {\n assertFailClosedResources(profile, 'memory')\n const instructions = profile.resources?.instructions\n if (instructions === undefined) return ''\n if (typeof instructions === 'string') return instructions\n if (instructions.kind === 'inline') return instructions.content\n throw new ConfigError(\n \"improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact\",\n )\n}\n\nfunction replaceProfileInstructions(\n profile: AgentProfile,\n content: string,\n): string | AgentProfileResourceRef {\n const instructions = profile.resources?.instructions\n if (typeof instructions !== 'object') return content\n if (instructions.kind !== 'inline') {\n throw new ConfigError(\n \"improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact\",\n )\n }\n return { ...instructions, content }\n}\n\nfunction assertFailClosedResources(\n profile: ReadonlyAgentProfile,\n surface: 'skills' | 'memory',\n): void {\n if (profile.resources?.failOnError !== true) {\n throw new ConfigError(\n `improve(): surface '${surface}' requires profile.resources.failOnError: true`,\n )\n }\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~1500-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~1500-char digest).\n *\n * It emits `ProposalFinding[]` so it drops into the same `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @stable\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { makeProposalFinding, type ProposalFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\ninterface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: ReadonlyArray<ProposalFinding>\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `analyzeGeneration` on `improve({ surface: 'code' })`:\n *\n * await improve({\n * surface: 'code',\n * findings: seedFindings,\n * code: { repoRoot, profile, executorForWorktree, buildPrompt },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => compareCandidateComposites(a.composite, b.composite))\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: ProposalFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeProposalFinding({\n analyst_id: ANALYST_ID,\n proposal_origin: 'search',\n severity: cand.composite !== null && cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} ${candidateCompositeDescription(cand.composite)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** Keep unscored candidates visible without inventing a numeric aggregate. */\nfunction compareCandidateComposites(left: number | null, right: number | null): number {\n if (left === null) return right === null ? 0 : 1\n if (right === null) return -1\n return left - right\n}\n\nfunction candidateCompositeDescription(composite: number | null): string {\n return composite === null ? 'has no aggregate score' : `scored composite ${composite.toFixed(3)}`\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","import { realpath } from 'node:fs/promises'\nimport { resolve as resolvePath } from 'node:path'\nimport { makeProposalFinding, type ProposalFinding } from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport {\n gitWorktreeAdapter,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type CodeSurface,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveOptions,\n type SelfImproveProposerResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from '../candidate-execution/digest'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport { agenticGenerator } from './agentic-generator'\nimport { rethrowAfterCleanup } from './cleanup'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveCodeOptions,\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImprovementCodeCandidate,\n} from './improve-types'\nimport { improvementDriver, type ManagedImprovementDriver } from './improvement-driver'\nimport { assertCandidateSurfaceKind, isCodeSurface } from './profile-surface'\nimport { rawTraceDistiller } from './raw-trace-distiller'\n\n/** Slice bound for distilled judge notes: wide enough that a real traceback or\n * failing assertion survives intact. */\nconst distilledNotesMaxChars = 1500\n\n/** Slice bound for a cell's error string. Full text remains on the raw cell. */\nconst distilledErrorMaxChars = 500\n\n/** Distill failing cells into typed findings for the next proposal round. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: ReadonlyArray<ProposalFinding>,\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{\n scenario: string\n composite: number\n notes: string\n claim?: string\n error?: string\n }> = []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, judge) => sum + (judge.composite ?? 0), 0) /\n judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((judge) => judge.notes)\n .filter((note): note is string => typeof note === 'string' && note.length > 0)\n .join('; ')\n .slice(0, distilledNotesMaxChars)\n const claim =\n notes ||\n (error ? `Scenario ${scenario} failed: ${error.slice(0, distilledErrorMaxChars)}` : '')\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(claim ? { claim } : {}),\n ...(error ? { error: error.slice(0, distilledErrorMaxChars) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((left, right) => left.composite - right.composite)\n return failures.slice(0, CAP).map((failure) =>\n makeProposalFinding({\n analyst_id: 'generation-failure-distiller',\n proposal_origin: 'search',\n severity: failure.error !== undefined || failure.composite < 0.5 ? 'high' : 'medium',\n area: 'generation-failure',\n confidence: 1,\n subject: failure.scenario,\n claim: `Scenario ${failure.scenario} scored composite ${failure.composite}${\n failure.notes ? `: ${failure.notes}` : ''\n }${failure.error ? ` (error: ${failure.error})` : ''}`,\n evidence_refs: [],\n metadata: {\n scenario: failure.scenario,\n composite: failure.composite,\n ...(failure.notes ? { notes: failure.notes } : {}),\n ...(failure.error !== undefined ? { error: failure.error } : {}),\n },\n }),\n )\n }\n}\n\n/** Default code-run analysis: raw trace paths for durable runs, otherwise a\n * bounded digest of failed cells. */\nfunction defaultDistillerFor<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n findings: ReadonlyArray<ProposalFinding>,\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const durableRun = opts.runDir !== undefined && !opts.runDir.startsWith('mem://')\n const useRawTraces = opts.rawTraceContext ?? durableRun\n if (useRawTraces) return rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n return generationFailureDistiller<TScenario, TArtifact>(findings)\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer<ProposalFinding>\n cleanup(retainedWinner?: MutableSurface): Promise<void>\n}\n\nasync function discardPreparedBaseline(\n worktree: WorktreeAdapter,\n baselineWorktree: Worktree,\n cause: unknown,\n): Promise<never> {\n return rethrowAfterCleanup(\n cause,\n () => worktree.discard(baselineWorktree),\n 'improve(): code preparation failed',\n )\n}\n\n/**\n * The real path of a repository root, for the one comparison that needs it.\n *\n * Git prints a RESOLVED worktree path, and the Eval worktree adapter compares what git\n * printed against the root it was handed. A root whose PREFIX is a symlink therefore never\n * matches: on macOS the OS hands out temp roots under /var, a symlink to /private/var, so the\n * adapter refuses to finalize or discard a worktree it created seconds earlier. Resolve once\n * here, where the caller's root meets git, instead of at every caller.\n *\n * A directory that does not exist yet — `worktreeDir` is created on demand — keeps its\n * lexical form; the adapter creates it under a root that is already resolved.\n */\nasync function realRoot(path: string): Promise<string> {\n try {\n return await realpath(path)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n return resolvePath(path)\n }\n}\n\n/** Create a clean incumbent checkout and the candidate producer for a code run. */\nasync function prepareCodeRun(code: ImproveCodeOptions): Promise<PreparedCodeRun> {\n const authorProfile = agentProfileSchema.parse(code.profile)\n assertExecutableAgentProfile(authorProfile, 'improve(code) author')\n const baseRef = code.baseRef ?? 'main'\n const worktree =\n code.worktree ??\n gitWorktreeAdapter({\n repoRoot: await realRoot(code.repoRoot),\n ...(code.worktreeDir ? { worktreeDir: await realRoot(code.worktreeDir) } : {}),\n })\n const baselineWorktree = await worktree.create({ baseRef, label: 'incumbent-baseline' })\n try {\n const baseline = await worktree.finalize(baselineWorktree, 'Incumbent code checkout')\n let baselineDiscarded = false\n const generator = code.generator\n ? code.generator\n : agenticGenerator({\n profile: authorProfile,\n executorForWorktree: code.executorForWorktree,\n buildPrompt: code.buildPrompt,\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs !== undefined ? { timeoutMs: code.timeoutMs } : {}),\n ...(code.maximumCharge ? { maximumCharge: code.maximumCharge } : {}),\n })\n const managed: ManagedImprovementDriver = improvementDriver({ worktree, generator, baseRef })\n\n return {\n baseline,\n proposer: managed,\n async cleanup(retainedWinner) {\n const errors: unknown[] = []\n const retainedWorktreeRef = isCodeSurface(retainedWinner)\n ? retainedWinner.worktreeRef\n : undefined\n try {\n await managed?.cleanup(retainedWorktreeRef ? [retainedWorktreeRef] : [])\n } catch (cause) {\n errors.push(cause)\n }\n if (!baselineDiscarded && retainedWorktreeRef !== baseline.worktreeRef) {\n try {\n await worktree.discard(baselineWorktree)\n baselineDiscarded = true\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improve(): failed to clean code improvement worktrees')\n }\n },\n }\n } catch (cause) {\n return discardPreparedBaseline(worktree, baselineWorktree, cause)\n }\n}\n\nfunction idempotentDispose(dispose: () => Promise<void>): () => Promise<void> {\n let disposed = false\n let inFlight: Promise<void> | undefined\n return async () => {\n if (disposed) return\n if (inFlight) return inFlight\n inFlight = (async () => {\n await dispose()\n disposed = true\n })()\n try {\n await inFlight\n } finally {\n inFlight = undefined\n }\n }\n}\n\nexport async function runCodeImprovement<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n): Promise<ImproveCodeResult<TScenario, TArtifact>> {\n const {\n gate = 'holdout',\n findings: inputFindings = [],\n rawTraceContext: _rawTraceContext,\n code,\n promotionGate,\n analyzeGeneration,\n surface: _surface,\n ...sharedOptions\n } = opts\n const findings = immutableCandidateValue([\n ...assertProposalFindings(inputFindings, 'improve() code findings'),\n ])\n const preparedCode = await prepareCodeRun(code)\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n\n let raw: SelfImproveProposerResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n baselineSurface: preparedCode.baseline,\n proposer: preparedCode.proposer,\n budget,\n findings,\n ...(promotionGate !== undefined ? { gate: promotionGate } : {}),\n ...(analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n analyzeGeneration ?? defaultDistillerFor<TScenario, TArtifact>(opts, findings),\n }),\n })\n } catch (cause) {\n return rethrowAfterCleanup(\n cause,\n () => preparedCode.cleanup(),\n 'improve(): code improvement failed',\n )\n }\n\n const winnerSurface = raw.winner.surface\n assertCandidateSurfaceKind('code', preparedCode.baseline, winnerSurface)\n try {\n await preparedCode.cleanup(winnerSurface)\n } catch (cleanupCause) {\n try {\n await preparedCode.cleanup()\n } catch (finalCleanupCause) {\n throw new AggregateError(\n [cleanupCause, finalCleanupCause],\n 'improve(): code result cleanup failed, including the final all-worktree retry',\n )\n }\n throw new AggregateError(\n [cleanupCause],\n 'improve(): code result cleanup failed; the final all-worktree retry succeeded',\n )\n }\n const dispose = idempotentDispose(async () => preparedCode.cleanup())\n const candidate = immutableCandidateValue<ImprovementCodeCandidate>({\n surface: 'code',\n value: winnerSurface,\n })\n\n return {\n mode: 'code',\n candidate,\n decision: raw.gateDecision,\n ...(raw.lift !== undefined ? { lift: raw.lift } : {}),\n cost: copyImproveCost(raw.cost),\n durationMs: raw.durationMs,\n lineage: Object.freeze({\n invocationId: raw.provenance.runId,\n runId: raw.provenance.runId,\n developmentSplitDigest: raw.provenance.evidence.search.splitDigest,\n }),\n generationsExplored: raw.generationsExplored,\n raw,\n dispose,\n }\n}\n","import type { OptimizationMethod, Scenario } from '@tangle-network/agent-eval/campaign'\nimport type { ImproveCandidateValidationInput } from './improve-types'\n\nconst methodRuntimeControls = Symbol('agent-runtime.improvement.method-runtime-controls')\n\ninterface MethodRuntimeControls {\n costAttribution: 'optimizer-run'\n validateCandidate: (input: ImproveCandidateValidationInput) => void\n}\n\ntype ControlledOptimizationMethod<TScenario extends Scenario, TArtifact> = OptimizationMethod<\n TScenario,\n TArtifact\n> & {\n [methodRuntimeControls]?: MethodRuntimeControls\n}\n\nexport function withMethodRuntimeControls<TScenario extends Scenario, TArtifact>(\n method: OptimizationMethod<TScenario, TArtifact>,\n controls: MethodRuntimeControls,\n): OptimizationMethod<TScenario, TArtifact> {\n return Object.freeze({\n ...method,\n [methodRuntimeControls]: Object.freeze({ ...controls }),\n })\n}\n\nexport function methodRuntimeControlsOf<TScenario extends Scenario, TArtifact>(\n method: OptimizationMethod<TScenario, TArtifact>,\n): MethodRuntimeControls | undefined {\n return (method as ControlledOptimizationMethod<TScenario, TArtifact>)[methodRuntimeControls]\n}\n","import type { CostReceipt } from '@tangle-network/agent-eval'\nimport type {\n CostLedgerHandle,\n OptimizationMethodInput,\n OptimizationMethodResult,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\n\ntype LedgerFilter = Parameters<CostLedgerHandle['summary']>[0]\ntype LedgerWaitOptions = Parameters<NonNullable<CostLedgerHandle['waitForIdle']>>[0]\n\nconst EVALUATION_TAG = 'runtimeEvaluationRef'\nconst INVOCATION_TAG = 'runtimeInvocationId'\n\ninterface MethodCostScope {\n evaluationRef: Sha256Digest\n invocationId: string\n methodTag?: string\n}\n\nexport type MethodCostAttribution = 'invocation' | 'optimizer-run'\n\nexport function methodInputWithScopedCost<TScenario extends Scenario, TArtifact>(\n input: OptimizationMethodInput<TScenario, TArtifact>,\n scope: MethodCostScope,\n costAttribution: MethodCostAttribution = 'invocation',\n): OptimizationMethodInput<TScenario, TArtifact> {\n return Object.freeze({\n ...input,\n costLedger: scopedCostLedger(input.costLedger, scope, costAttribution),\n })\n}\n\nexport function methodInvocationCostLedger(\n ledger: CostLedgerHandle,\n scope: MethodCostScope,\n): CostLedgerHandle {\n return scopedCostLedger(ledger, scope, 'invocation')\n}\n\nexport function assertMethodCostRecorded(\n methodName: string,\n result: Pick<OptimizationMethodResult, 'cost' | 'provenance'>,\n compatibleLedger: CostLedgerHandle,\n invocationLedger: CostLedgerHandle,\n costCeiling: number | undefined,\n costAttribution: MethodCostAttribution = 'invocation',\n historicalReceipts: readonly CostReceipt[] = [],\n): void {\n const { cost } = result\n let observed =\n costAttribution === 'optimizer-run' && result.provenance?.runId\n ? compatibleLedger.summary({ tags: { optimizerRun: result.provenance.runId } })\n : invocationLedger.summary()\n if (historicalReceipts.length > 0 && costAttribution === 'invocation') {\n const receipts = new Map(invocationLedger.list().map((receipt) => [receipt.callId, receipt]))\n for (const receipt of historicalReceipts) receipts.set(receipt.callId, receipt)\n observed = {\n ...observed,\n totalCostUsd: [...receipts.values()].reduce((sum, receipt) => sum + receipt.costUsd, 0),\n accountingComplete:\n observed.accountingComplete &&\n historicalReceipts.every(\n (receipt) => !receipt.costUnknown && receipt.usageUnknown !== true,\n ),\n }\n }\n if (costCeiling !== undefined && !cost.accountingComplete) {\n throw new ConfigError(\n `improve(): method '${methodName}' returned incomplete cost accounting under costCeiling; refusing final scoring`,\n )\n }\n if (costCeiling !== undefined && exceeds(cost.totalCostUsd, costCeiling)) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported cost $${cost.totalCostUsd} above costCeiling $${costCeiling}; refusing final scoring`,\n )\n }\n if (cost.accountingComplete && !observed.accountingComplete) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported complete cost accounting but its shared cost receipts are incomplete`,\n )\n }\n if (cost.accountingComplete && !approximatelyEqual(cost.totalCostUsd, observed.totalCostUsd)) {\n throw new ConfigError(\n `improve(): method '${methodName}' reported $${cost.totalCostUsd} but recorded $${observed.totalCostUsd} through input.costLedger`,\n )\n }\n}\n\nfunction scopedCostLedger(\n parent: CostLedgerHandle,\n scope: MethodCostScope,\n costAttribution: MethodCostAttribution,\n): CostLedgerHandle {\n const evaluationTags = {\n [EVALUATION_TAG]: scope.evaluationRef,\n }\n const invocationTags = {\n ...evaluationTags,\n [INVOCATION_TAG]: scope.invocationId,\n ...(scope.methodTag === undefined ? {} : { [scope.methodTag]: '1' }),\n }\n const readTags = (filter: LedgerFilter): Record<string, string> =>\n costAttribution === 'optimizer-run' && hasOptimizerRunFilter(filter)\n ? evaluationTags\n : invocationTags\n return {\n costCeilingUsd: parent.costCeilingUsd,\n runPaidCall: (input) =>\n parent.runPaidCall({\n ...input,\n tags: { ...(input.tags ?? {}), ...invocationTags },\n }),\n reconcile: (...args) => parent.reconcile(...args),\n list: (filter) => parent.list(withTags(filter, readTags(filter))),\n listPending: (filter) => parent.listPending?.(withTags(filter, readTags(filter))) ?? [],\n summary: (filter) => parent.summary(withTags(filter, readTags(filter))),\n waitForIdle: (options: LedgerWaitOptions = {}) =>\n parent.waitForIdle?.({\n ...options,\n filter: withTags(options.filter, readTags(options.filter)),\n }) ??\n Promise.resolve(\n parent.summary(withTags(options.filter, readTags(options.filter))).pendingCalls === 0,\n ),\n markCompleted: (count) => parent.markCompleted(count),\n costPerCompletedTask: () => parent.costPerCompletedTask(),\n }\n}\n\nfunction hasOptimizerRunFilter(filter: LedgerFilter): boolean {\n return typeof filter?.tags?.optimizerRun === 'string' && filter.tags.optimizerRun.length > 0\n}\n\nfunction withTags(filter: LedgerFilter, tags: Record<string, string>): LedgerFilter {\n return {\n ...(filter ?? {}),\n tags: { ...(filter?.tags ?? {}), ...tags },\n }\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8\n return Math.abs(left - right) <= tolerance\n}\n\nfunction exceeds(value: number, limit: number): boolean {\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(value), Math.abs(limit)) * 8\n return value - limit > tolerance\n}\n\n/** Only prior root invocations are additional to a container's current invocation receipts. */\nexport function methodHistoricalReceipts(\n ledger: CostLedgerHandle,\n optimizerRun: string,\n invocationId: string,\n): readonly CostReceipt[] {\n return ledger\n .list({ tags: { optimizerRun } })\n .filter((receipt) => receipt.tags?.[INVOCATION_TAG] !== invocationId)\n}\n","import { redact } from '@tangle-network/agent-eval/traces'\nimport { type Sha256Digest, sha256DigestSchema } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { ImproveCandidateValidationInput, ImproveCandidateValidator } from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\n/** One spelling of the execution-identity rule for optimization, training, and the harness. */\nexport function parseExecutionRef(value: unknown, label: string): Sha256Digest {\n const parsed = sha256DigestSchema.safeParse(value)\n if (!parsed.success) {\n throw new ConfigError(`${label}: executionRef must be a lowercase sha256:<64 hex> digest`)\n }\n return parsed.data\n}\n\n/** Validate the callback itself before any optimizer, trainer, or candidate work starts. */\nexport function assertCandidateValidator(\n validator: unknown,\n): asserts validator is ImproveCandidateValidator | undefined {\n if (validator !== undefined && typeof validator !== 'function') {\n throw new ConfigError('validateCandidate must be a function when present')\n }\n}\n\n/** A validator accepts synchronously by returning void, or rejects by throwing. */\nexport function validateProfileCandidate(\n validator: ImproveCandidateValidator | undefined,\n input: ImproveCandidateValidationInput,\n): void {\n assertCandidateValidator(validator)\n const result: unknown = validator?.(Object.freeze(input))\n if (result !== undefined) {\n // Observe a rejected async callback without treating its eventual result as admission.\n void Promise.resolve(result).catch(() => {})\n throw new ConfigError('candidate validators must return void synchronously or throw')\n }\n}\n\n/**\n * Refuse exact held-out content digests already declared in this profile's training lineage.\n * Both training and trainer-visible validation rows are exposure. This is an exact\n * provenance check, not fuzzy decontamination or proof that undeclared training was fresh.\n */\nexport function assertProfileTrainingIsHeldOut(\n profile: ReadonlyAgentProfile,\n heldOutDigests: ReadonlySet<Sha256Digest>,\n): void {\n const training = profile.metadata?.training\n if (!training) return\n for (const receipt of [training.receipt, ...training.ancestors]) {\n if (receipt.dataset.tasks.some((task) => heldOutDigests.has(task.contentDigest))) {\n // Do not disclose held-out task identities or payloads to an optimizer via errors.\n throw new ConfigError('known training exposure overlaps held-out evaluation')\n }\n }\n}\n\n/**\n * JSON paths of credential and private values in candidate content, found by\n * the redaction core, which names each value it would change. A candidate that\n * leaves Runtime (an external optimizer, a search ledger) is refused on any.\n */\nexport function privateValuePaths(values: readonly unknown[]): string[] {\n return [\n ...new Set(\n values.flatMap((value) =>\n redact(value).report.findings.map((finding) => jsonPathOf(finding.path)),\n ),\n ),\n ]\n}\n\n/** `/remote/url` or `/tools/0/env` as `$.remote.url` or `$.tools[0].env`. */\nfunction jsonPathOf(pointer: string): string {\n return pointer\n .split('/')\n .slice(1)\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'))\n .reduce(\n (path, segment) => (/^\\d+$/.test(segment) ? `${path}[${segment}]` : `${path}.${segment}`),\n '$',\n )\n}\n","import type { ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n campaignScenarioIdentity,\n campaignSplitDigestFromIdentities,\n type JudgeConfig,\n type MutableSurface,\n type Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport type {\n ImproveCandidateValidator,\n ImproveOptimizationRunOptions,\n ImproveProfileSurface,\n ImproveScenarioPartitions,\n ImproveSkillsOptions,\n} from './improve-types'\n\nexport interface MethodEvaluationIdentity {\n evaluationRef: Sha256Digest\n developmentSplitDigest: Sha256Digest\n finalTestSplitDigest: Sha256Digest\n scenarioPartitions: ImproveScenarioPartitions\n judgeDescriptors: readonly MethodJudgeDescriptor[]\n}\n\ninterface MethodJudgeDescriptor {\n name: string\n dimensions: readonly { key: string; description: string }[]\n declaredVersion: string | null\n scoreImplementation: string\n appliesToImplementation: string | null\n}\n\nexport function buildMethodEvaluationIdentity<TScenario extends Scenario, TArtifact>(input: {\n executionRef: Sha256Digest\n baselineProfileDigest: Sha256Digest\n baselineSurface: MutableSurface\n surface: ImproveProfileSurface\n skills?: ImproveSkillsOptions\n validateCandidate?: ImproveCandidateValidator\n findings: ReadonlyArray<ProposalFinding>\n trainScenarios: readonly TScenario[]\n selectionScenarios: readonly TScenario[]\n testScenarios: readonly TScenario[]\n judges: readonly JudgeConfig<TArtifact, TScenario>[]\n seed?: number\n reps?: number\n costCeiling?: number\n optimizationRunOptions?: ImproveOptimizationRunOptions<TScenario, TArtifact>\n}): MethodEvaluationIdentity {\n const optimizationReps = input.optimizationRunOptions?.reps ?? 1\n const finalTestReps = input.reps ?? 1\n const scenarioPartitions = immutableCandidateValue<ImproveScenarioPartitions>({\n train: input.trainScenarios.map(campaignScenarioIdentity),\n selection: input.selectionScenarios.map(campaignScenarioIdentity),\n finalTest: input.testScenarios.map(campaignScenarioIdentity),\n optimizationReps,\n finalTestReps,\n })\n const developmentSplitDigest = canonicalCandidateDigest({\n train: campaignSplitDigestFromIdentities(scenarioPartitions.train, optimizationReps),\n selection: campaignSplitDigestFromIdentities(scenarioPartitions.selection, optimizationReps),\n })\n const finalTestSplitDigest = campaignSplitDigestFromIdentities(\n scenarioPartitions.finalTest,\n finalTestReps,\n )\n const judgeDescriptors = input.judges.map(judgeDescriptor)\n const evaluationRef = canonicalCandidateDigest({\n executionRef: input.executionRef,\n baselineProfileDigest: input.baselineProfileDigest,\n coordinate: profileCoordinate(input.surface, input.baselineSurface, input.skills),\n candidateValidation: input.validateCandidate\n ? Function.prototype.toString.call(input.validateCandidate)\n : null,\n developmentSplitDigest,\n finalTestSplitDigest,\n findings: input.findings,\n judges: judgeDescriptors,\n run: {\n seed: input.seed ?? 42,\n finalReps: input.reps ?? 1,\n optimizationReps,\n costCeiling: input.costCeiling ?? null,\n resumable: input.optimizationRunOptions?.resumable ?? true,\n maxConcurrency: input.optimizationRunOptions?.maxConcurrency ?? 2,\n abortOnCellError: input.optimizationRunOptions?.abortOnCellError ?? false,\n dispatchTimeoutMs: input.optimizationRunOptions?.dispatchTimeoutMs ?? null,\n dispatchShutdownTimeoutMs: input.optimizationRunOptions?.dispatchShutdownTimeoutMs ?? 5_000,\n tracing: input.optimizationRunOptions?.tracing ?? 'on',\n expectUsage: input.optimizationRunOptions?.expectUsage ?? 'warn',\n captureSource: input.optimizationRunOptions?.captureSource ?? null,\n captureSourceVersionHash: input.optimizationRunOptions?.captureSourceVersionHash ?? null,\n },\n })\n return {\n evaluationRef,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n judgeDescriptors,\n }\n}\n\nfunction profileCoordinate(\n surface: ImproveProfileSurface,\n baselineSurface: MutableSurface,\n skills: ImproveSkillsOptions | undefined,\n): {\n surface: ImproveProfileSurface\n resourceName: string | null\n componentNames: string[]\n} {\n return {\n surface,\n resourceName: surface === 'skills' ? (skills?.resourceName.trim() ?? null) : null,\n componentNames:\n typeof baselineSurface === 'object' &&\n baselineSurface !== null &&\n baselineSurface.kind === 'components'\n ? Object.keys(baselineSurface.components).sort()\n : [],\n }\n}\n\nfunction judgeDescriptor<TScenario extends Scenario, TArtifact>(\n judge: JudgeConfig<TArtifact, TScenario>,\n): MethodJudgeDescriptor {\n return {\n name: judge.name,\n dimensions: judge.dimensions.map((dimension) => ({ ...dimension })),\n declaredVersion: judge.judgeVersion ?? null,\n scoreImplementation: Function.prototype.toString.call(judge.score),\n appliesToImplementation: judge.appliesTo\n ? Function.prototype.toString.call(judge.appliesTo)\n : null,\n }\n}\n","/**\n * What every profile improvement prepares before any optimizer or search runs:\n * the exact surface and its baseline, the evaluation identity, identified\n * judges, the identities a search ledger records, and one materializer that\n * admits a candidate only after the held-out and caller checks. `improve()`\n * with an external method and with `searchMethod` share it, so a candidate is\n * materialized and admitted the same way on both paths.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ProposalFinding } from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport type {\n JudgeConfig,\n MutableSurface,\n Scenario,\n SearchModelIdentity,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport {\n assertCandidateValidator,\n assertProfileTrainingIsHeldOut,\n parseExecutionRef,\n validateProfileCandidate,\n} from './candidate-validation'\nimport type {\n ImproveCandidateValidator,\n ImproveMethodOptions,\n ImproveOptimizationRunOptions,\n ImproveProfileSurface,\n ImproveSearchIdentity,\n} from './improve-types'\nimport { buildMethodEvaluationIdentity, type MethodEvaluationIdentity } from './method-identity'\nimport { createProfileCandidateMaterializer, prepareProfileSurface } from './profile-surface'\n\n/** The options both improvement paths read before they diverge. */\ntype ProfileImprovementInput<TScenario extends Scenario, TArtifact> = Pick<\n ImproveMethodOptions<TScenario, TArtifact>,\n | 'surface'\n | 'executionRef'\n | 'validateCandidate'\n | 'findings'\n | 'skills'\n | 'profileComponents'\n | 'minimumLift'\n | 'subject'\n | 'trainScenarios'\n | 'selectionScenarios'\n | 'testScenarios'\n | 'judges'\n | 'seed'\n | 'costCeiling'\n> & {\n reps?: number\n optimizationRunOptions?: ImproveOptimizationRunOptions<TScenario, TArtifact>\n}\n\nexport interface PreparedProfileImprovement<TScenario extends Scenario, TArtifact> {\n profile: AgentProfile\n surface: ImproveProfileSurface\n executionRef: Sha256Digest\n findings: ReadonlyArray<ProposalFinding>\n minimumLift: number\n baselineSurface: MutableSurface\n baselineValue: unknown\n baselineProfileDigest: Sha256Digest\n identity: MethodEvaluationIdentity\n /** Unique id of this invocation, which scopes its cost receipts. */\n invocationId: string\n /** Judges carrying a `judgeVersion` derived from the evaluation identity. */\n judges: JudgeConfig<TArtifact, TScenario>[]\n searchIdentity: ImproveSearchIdentity\n /** The surface a profile holds at the searched coordinate. */\n surfaceOf(candidate: AgentProfile): MutableSurface\n /** Materialize a candidate surface without admitting it. */\n materializeCandidate(candidateSurface: MutableSurface): AgentProfile\n /** Refuse a materialized candidate unless it passes the held-out check and\n * the caller's validator; each surface is checked once. */\n admitCandidate(candidate: AgentProfile, candidateSurface: MutableSurface): void\n /** Materialize and admit a candidate surface. */\n materializeProfile(candidateSurface: MutableSurface): AgentProfile\n /** Run one validator on an exact materialized candidate. */\n validateMaterialized(\n validator: ImproveCandidateValidator | undefined,\n candidate: AgentProfile,\n candidateSurface: MutableSurface,\n isBaseline: boolean,\n ): void\n}\n\nexport function prepareProfileImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n input: ProfileImprovementInput<TScenario, TArtifact>,\n): PreparedProfileImprovement<TScenario, TArtifact> {\n const {\n surface = 'prompt',\n validateCandidate,\n skills,\n profileComponents,\n minimumLift = 0,\n } = input\n assertCandidateValidator(validateCandidate)\n if (!Number.isFinite(minimumLift) || minimumLift < 0) {\n throw new ConfigError(\n 'improve(): minimumLift must be a finite number greater than or equal to 0',\n )\n }\n if (profileComponents && surface !== 'agent-profile') {\n throw new ConfigError(\"improve(): profileComponents is valid only with surface 'agent-profile'\")\n }\n if (\n input.subject !== undefined &&\n (typeof input.subject !== 'string' ||\n !input.subject.trim() ||\n input.subject !== input.subject.trim())\n ) {\n throw new ConfigError('improve(): subject must be a trimmed non-empty string')\n }\n const executionRef = parseExecutionRef(input.executionRef, 'improve()')\n const findings = immutableCandidateValue([\n ...assertProposalFindings(input.findings ?? [], 'improve() method findings'),\n ])\n const preparedSurface = prepareProfileSurface(profile, surface, skills, profileComponents)\n const baselineSurface = preparedSurface.surface\n const baselineValue = immutableCandidateValue(preparedSurface.value)\n const baselineProfileDigest = canonicalAgentProfileDigest(profile)\n const identity = buildMethodEvaluationIdentity({\n executionRef,\n baselineProfileDigest,\n baselineSurface,\n surface,\n skills,\n validateCandidate,\n findings,\n trainScenarios: input.trainScenarios,\n selectionScenarios: input.selectionScenarios,\n testScenarios: input.testScenarios,\n judges: input.judges,\n seed: input.seed,\n reps: input.reps,\n costCeiling: input.costCeiling,\n optimizationRunOptions: input.optimizationRunOptions,\n })\n const judges = input.judges.map((judge, index) =>\n Object.freeze({\n ...judge,\n judgeVersion: canonicalCandidateDigest({\n evaluationRef: identity.evaluationRef,\n descriptor: identity.judgeDescriptors[index],\n }),\n }),\n )\n const rawMaterializeProfile = createProfileCandidateMaterializer(\n profile,\n surface,\n baselineSurface,\n skills,\n profileComponents,\n )\n const baselineSurfaceDigest = canonicalCandidateDigest(baselineSurface)\n const heldOutDigests = new Set(\n identity.scenarioPartitions.finalTest.map((task) => task.scenarioDigest),\n )\n const validatedCandidates = new Set<Sha256Digest>()\n const validateMaterialized: PreparedProfileImprovement<\n TScenario,\n TArtifact\n >['validateMaterialized'] = (validator, candidate, candidateSurface, isBaseline) => {\n const prepared = prepareProfileSurface(candidate, surface, skills, profileComponents)\n validateProfileCandidate(validator, {\n profile: candidate,\n surface,\n candidateSurface,\n value: immutableCandidateValue(prepared.value),\n isBaseline,\n })\n }\n const admitCandidate = (candidate: AgentProfile, candidateSurface: MutableSurface): void => {\n const candidateDigest = canonicalCandidateDigest(candidateSurface)\n if (validatedCandidates.has(candidateDigest)) return\n assertProfileTrainingIsHeldOut(candidate, heldOutDigests)\n validateMaterialized(\n validateCandidate,\n candidate,\n immutableCandidateValue(candidateSurface),\n candidateDigest === baselineSurfaceDigest,\n )\n validatedCandidates.add(candidateDigest)\n }\n const materializeProfile = (candidateSurface: MutableSurface): AgentProfile => {\n const candidate = rawMaterializeProfile(candidateSurface)\n admitCandidate(candidate, candidateSurface)\n return candidate\n }\n materializeProfile(baselineSurface)\n return {\n profile,\n surface,\n executionRef,\n findings,\n minimumLift,\n baselineSurface,\n baselineValue,\n baselineProfileDigest,\n identity,\n invocationId: `runtime-optimization:${randomUUID()}`,\n judges,\n searchIdentity: Object.freeze({\n subject: input.subject ?? profile.name ?? 'agent-profile',\n agent: { uri: 'agent-runtime:improve-execution-ref', revision: executionRef },\n judge: {\n uri: 'agent-runtime:improve-judges',\n revision: canonicalCandidateDigest(identity.judgeDescriptors),\n },\n model: profileModel(profile),\n }),\n surfaceOf: (candidate) =>\n prepareProfileSurface(candidate, surface, skills, profileComponents).surface,\n materializeCandidate: rawMaterializeProfile,\n admitCandidate,\n materializeProfile,\n validateMaterialized,\n }\n}\n\n/** The profile's model hint as a moving alias; each cell records what it resolved. */\nfunction profileModel(profile: AgentProfile): SearchModelIdentity {\n const hint = profile.model?.default\n if (!hint) {\n return {\n provider: 'unspecified',\n alias: 'unspecified',\n unknown: 'the profile names no model; each cell records the model it resolved',\n }\n }\n return {\n provider: profile.model?.provider ?? 'unspecified',\n alias: hint,\n unknown:\n 'the profile names a model hint, not a snapshot; each cell records the model it resolved',\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { CostReceipt } from '@tangle-network/agent-eval'\nimport {\n compareOptimizationMethods,\n fsCampaignStorage,\n type OptimizationMethod,\n type OptimizationMethodInput,\n type OptimizationMethodResult,\n verifySearchHistoryArtifact,\n} from '@tangle-network/agent-eval/campaign'\nimport type { MutableSurface, Scenario } from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile, Sha256Digest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveMethodContext,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementProfileCandidate,\n} from './improve-types'\nimport { methodRuntimeControlsOf } from './method-controls'\nimport {\n assertMethodCostRecorded,\n methodHistoricalReceipts,\n methodInputWithScopedCost,\n methodInvocationCostLedger,\n} from './method-cost'\nimport { prepareProfileImprovement } from './profile-improvement'\nimport { assertCandidateSurfaceKind } from './profile-surface'\n\nfunction resolveOptimizationMethod<TScenario extends Scenario, TArtifact>(\n source: ImproveMethodSource<TScenario, TArtifact>,\n context: ImproveMethodContext,\n): OptimizationMethod<TScenario, TArtifact> {\n const method = typeof source === 'function' ? source(context) : source\n if (\n !method ||\n typeof method !== 'object' ||\n typeof method.name !== 'string' ||\n method.name.trim() !== method.name ||\n method.name.length === 0 ||\n typeof method.optimize !== 'function'\n ) {\n throw new ConfigError(\n 'improve(): method must be a complete OptimizationMethod with a trimmed name and optimize(input)',\n )\n }\n return method\n}\n\n/**\n * Run one complete method, then compare its winner with the baseline on the\n * held-out test split. A method that records its search (GEPA and SkillOpt do\n * through `officialGepa` and `officialSkillOpt`) must close its ledger; Runtime\n * replays the bytes and returns the receipt. A method that records none\n * returns `searchHistory: null`: its lineage is unknown, not empty.\n */\nexport async function runMethodImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult> {\n const {\n surface: _surface,\n executionRef: _executionRef,\n method: methodSource,\n agent,\n validateCandidate: _validateCandidate,\n findings: _findings,\n skills: _skills,\n profileComponents: _profileComponents,\n optimizationRunOptions,\n minimumLift: _minimumLift,\n subject: _subject,\n ...comparisonOptions\n } = opts\n const prepared = prepareProfileImprovement(profile, opts)\n const {\n surface,\n identity,\n invocationId,\n baselineSurface,\n materializeProfile,\n validateMaterialized,\n minimumLift,\n } = prepared\n const { evaluationRef, developmentSplitDigest, finalTestSplitDigest, scenarioPartitions } =\n identity\n const dispatchRef = `improve:${evaluationRef}`\n const method = resolveOptimizationMethod(methodSource, {\n profile,\n evaluationRef,\n surface,\n baselineSurface,\n baselineValue: prepared.baselineValue,\n findings: prepared.findings,\n searchIdentity: prepared.searchIdentity,\n })\n const costScope = { evaluationRef: identity.evaluationRef, invocationId }\n const invoke = async (\n current: OptimizationMethod<TScenario, TArtifact>,\n input: OptimizationMethodInput<TScenario, TArtifact>,\n ): Promise<{ result: OptimizationMethodResult; historical: readonly CostReceipt[] }> => {\n const controls = methodRuntimeControlsOf(current)\n const scope = { ...costScope, methodTag: `runtimeMethod:${randomUUID()}` }\n // Every enclosing scope must preserve explicit optimizerRun reads from previous invocations.\n const scopedInput = methodInputWithScopedCost(input, scope, 'optimizer-run')\n const invocationLedger = methodInvocationCostLedger(scopedInput.costLedger, scope)\n const historical = new Map<string, CostReceipt>()\n let children = 0\n const checked = new Set<Sha256Digest>()\n const toRoot = (value: MutableSurface): MutableSurface =>\n immutableCandidateValue(input.surfaceToRoot?.(immutableCandidateValue(value)) ?? value)\n const currentBaselineDigest = canonicalCandidateDigest(toRoot(input.baselineSurface))\n const check = (value: MutableSurface): void => {\n const rootSurface = toRoot(value)\n const candidateDigest = canonicalCandidateDigest(rootSurface)\n if (checked.has(candidateDigest)) return\n validateMaterialized(\n controls?.validateCandidate,\n materializeProfile(rootSurface),\n rootSurface,\n candidateDigest === currentBaselineDigest,\n )\n checked.add(candidateDigest)\n }\n check(input.baselineSurface)\n const result = await current.optimize(\n Object.freeze({\n ...scopedInput,\n invokeMethod: async (\n child: OptimizationMethod<TScenario, TArtifact>,\n childInput: OptimizationMethodInput<TScenario, TArtifact>,\n ) => {\n const verified = await invoke(child, childInput)\n children += 1\n for (const receipt of verified.historical) historical.set(receipt.callId, receipt)\n return verified.result\n },\n dispatchWithSurface: (\n ...[value, scenario, context]: Parameters<\n OptimizationMethodInput<TScenario, TArtifact>['dispatchWithSurface']\n >\n ) => {\n check(value)\n return input.dispatchWithSurface(value, scenario, context)\n },\n }),\n )\n check(result.winnerSurface)\n assertMethodCostRecorded(\n current.name,\n result,\n scopedInput.costLedger,\n invocationLedger,\n comparisonOptions.costCeiling,\n children > 0 ? 'invocation' : controls?.costAttribution,\n [...historical.values()],\n )\n if (controls?.costAttribution === 'optimizer-run' && result.provenance?.runId) {\n for (const receipt of methodHistoricalReceipts(\n scopedInput.costLedger,\n result.provenance.runId,\n invocationId,\n ))\n historical.set(receipt.callId, receipt)\n }\n return { result, historical: [...historical.values()] }\n }\n const measuredMethod: OptimizationMethod<TScenario, TArtifact> = {\n ...method,\n async optimize(input) {\n const scopedInput = methodInputWithScopedCost(input, costScope, 'optimizer-run')\n return (await invoke(method, scopedInput)).result\n },\n }\n // The method writes its search ledger where Runtime reads it back.\n const methodStorage =\n optimizationRunOptions?.storage ?? comparisonOptions.storage ?? fsCampaignStorage()\n const startedAt = Date.now()\n const raw = await compareOptimizationMethods<TScenario, TArtifact>({\n ...comparisonOptions,\n judges: prepared.judges,\n dispatchRef,\n optimizationRunOptions: {\n ...(optimizationRunOptions ?? {}),\n storage: methodStorage,\n dispatchRef,\n },\n methods: [measuredMethod],\n baselineSurface,\n dispatchWithSurface: (candidateSurface, scenario, ctx) =>\n agent(materializeProfile(candidateSurface), scenario, ctx),\n })\n if (\n comparisonOptions.costCeiling !== undefined &&\n raw.totalCost.totalCostUsd > comparisonOptions.costCeiling\n ) {\n throw new ConfigError(\n `improve(): reported total cost $${raw.totalCost.totalCostUsd} exceeds costCeiling $${comparisonOptions.costCeiling}`,\n )\n }\n const searchHistory = raw.searchHistory.producers[0]?.receipt ?? null\n if (searchHistory) {\n if (!searchHistory.complete) {\n throw new ConfigError(\n `improve(): method '${method.name}' returned an open search ledger: ${searchHistory.incompleteReasons.join('; ')}`,\n )\n }\n verifySearchHistoryArtifact(searchHistory, methodStorage)\n }\n const score = raw.best\n const winnerSurface = immutableCandidateValue(score.winnerSurface)\n assertCandidateSurfaceKind(surface, baselineSurface, winnerSurface)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface,\n value: winnerSurface,\n profile: materializeProfile(winnerSurface),\n })\n const cost = copyImproveCost(raw.totalCost)\n return {\n mode: 'method',\n method: method.name,\n ...(score.provenance ? { provenance: immutableCandidateValue(score.provenance) } : {}),\n candidate,\n decision:\n cost.accountingComplete && score.decision.promote && score.decision.low > minimumLift\n ? 'ship'\n : 'hold',\n lift: score.lift,\n liftInterval: { ...score.liftCi },\n searchHistory,\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId,\n runId: score.provenance?.runId ?? invocationId,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n executionRef: prepared.executionRef,\n baselineProfileDigest: prepared.baselineProfileDigest,\n }),\n raw,\n async dispose() {},\n }\n}\n","/**\n * What the steps of one `runSearchImprovement` share: the search's identity,\n * storage, ledgers and recorder, and the profile nodes the kernel searches\n * over. A node is the surface a proposer wrote and the exact profile it\n * materializes to, or why it does not.\n */\nimport type { CostLedgerHandle } from '@tangle-network/agent-eval'\nimport {\n type MutableSurface,\n type Scenario,\n type SearchArtifactCodec,\n type SearchArtifactRef,\n type SearchRecorder,\n type SearchUnknown,\n searchNodeId,\n} from '@tangle-network/agent-eval/campaign'\nimport { redact } from '@tangle-network/agent-eval/traces'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n applyAgentProfileDiff,\n canonicalAgentProfileDigest,\n diffAgentProfiles,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport type { ImproveSearchMethod } from './improve-types'\nimport type { PreparedProfileImprovement } from './profile-improvement'\n\n/** A search node: the surface a proposer wrote, and the exact profile it\n * materializes to, or why it does not. */\nexport interface ProfileNode {\n surface: MutableSurface\n profile: AgentProfile | null\n refusal: string | null\n}\n\n/** One search's identity, ledgers and recorder. */\nexport interface SearchSession<TScenario extends Scenario, TArtifact> {\n readonly method: ImproveSearchMethod\n readonly prepared: PreparedProfileImprovement<TScenario, TArtifact>\n readonly searchId: string\n readonly costLedger: CostLedgerHandle\n readonly recorder: SearchRecorder\n}\n\n/** A refusal as the ledger stores it: redacted with the share profile. */\nexport function searchRefusalText(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error)\n return redact(message, { profile: 'share' }).value\n}\n\n/** The node a candidate surface becomes: materialized, or refused with the reason. */\nexport function profileNodeOf<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n candidateSurface: MutableSurface,\n): ProfileNode {\n const surface = immutableCandidateValue(candidateSurface)\n try {\n return { surface, profile: prepared.materializeCandidate(surface), refusal: null }\n } catch (error) {\n return { surface, profile: null, refusal: searchRefusalText(error) }\n }\n}\n\n/**\n * The codec that also records each node's profile by node id. Placement reads a node's profile\n * to skip the lanes that refuse it, so every node the ledger holds, and every node this process\n * registers, is known before its cells are placed.\n */\nexport function registeringProfileCodec<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n searchId: string,\n profiles: Map<string, AgentProfile | null>,\n): SearchArtifactCodec<ProfileNode> {\n const profiled = profileCodec(prepared)\n return {\n node(recorder, node) {\n const registered = profiled.node(recorder, node)\n profiles.set(searchNodeId(searchId, registered.artifactDigest), node.profile)\n return registered\n },\n diff: profiled.diff,\n load(recorder, node) {\n const loaded = profiled.load(recorder, node)\n profiles.set(node.nodeId, loaded.profile)\n return loaded\n },\n }\n}\n\n/** Profiles as search artifacts: nodes by profile digest, edges by profile diffs. */\nfunction profileCodec<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n): SearchArtifactCodec<ProfileNode> {\n const surfaceId = prepared.surface\n return {\n node(recorder, node) {\n if (node.profile) {\n const artifact = recorder.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId, kind: 'agent-profile', artifact }],\n }\n }\n const artifact = recorder.blob('surface', {\n kind: 'unmaterialized-surface',\n surface: node.surface,\n refusal: node.refusal,\n })\n return {\n artifactDigest: canonicalCandidateDigest({\n kind: 'unmaterialized-surface',\n surface: node.surface,\n }),\n artifact,\n surfaces: [{ surfaceId, kind: 'agent-profile', artifact }],\n }\n },\n diff(recorder, parent, child): SearchArtifactRef | SearchUnknown {\n if (!parent.profile || !child.profile) {\n return { unknown: 'a surface that does not materialize has no profile to diff' }\n }\n const diffs: AgentProfileDiff[] = diffAgentProfiles(parent.profile, child.profile)\n const to = canonicalAgentProfileDigest(child.profile)\n if (canonicalAgentProfileDigest(diffs.reduce(applyAgentProfileDiff, parent.profile)) !== to) {\n return { unknown: 'the Interface profile diffs do not reproduce the child profile' }\n }\n return recorder.blob('diff', {\n kind: 'agent-profile-diff',\n from: canonicalAgentProfileDigest(parent.profile),\n to,\n diffs,\n })\n },\n load(recorder, node) {\n const stored = recorder.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n surface?: MutableSurface\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new Error(`improve(): node ${node.nodeId} holds an invalid AgentProfile`)\n }\n const loaded = immutableCandidateValue(parsed.data)\n return { surface: prepared.surfaceOf(loaded), profile: loaded, refusal: null }\n }\n if (stored.kind === 'unmaterialized-surface' && stored.surface !== undefined) {\n return { surface: stored.surface, profile: null, refusal: stored.refusal ?? null }\n }\n throw new Error(`improve(): node ${node.nodeId} holds no profile search artifact`)\n },\n }\n}\n","/**\n * `searchMethod`: Runtime's native profile search on Eval's search kernel\n * (`runSearch`), with no Python bridge.\n *\n * Every node is an exact AgentProfile, content-addressed by\n * `canonicalAgentProfileDigest`, and every edge stores the Interface diffs\n * that turn its parent profile into the child. The policy chooses which node a\n * proposal extends, the allocator where cells go, and the proposer (a\n * `SurfaceProposer`) writes the child surface from the train split only. Each\n * cell is a one-cell `runCampaign` of the materialized profile, so judges,\n * timeouts, traces, the cost ledger and the cell cache behave as in every\n * other campaign. The ledger is the only checkpoint: calling `improve()` again\n * with the same inputs continues an interrupted search, and returns a finished\n * one without running anything.\n *\n * The claim is made once, on the sealed test split, by the kernel. Runtime\n * ships only a claim that shipped, re-derives from the ledger, has complete or\n * bounded cost accounting, and clears `minimumLift` with its test lower bound\n * (`search-decision.ts`).\n */\n\nimport type { ProposalFinding } from '@tangle-network/agent-eval'\nimport {\n aide,\n asha,\n type CampaignStorage,\n campaignCellSearchResult,\n createRunCostLedger,\n fsCampaignStorage,\n isProposedCandidate,\n openSearchLedger,\n type ProposeContext,\n type RunCampaignOptions,\n renderSearchSummary,\n resolveRunDir,\n runCampaign,\n runSearch,\n type Scenario,\n type SearchAllocator,\n type SearchArtifactCodec,\n type SearchCellResult,\n type SearchExecutionIdentity,\n type SearchPolicy,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n type SearchTask,\n type SurfaceProposer,\n searchClaimReserveUsd,\n searchProposalExecution,\n searchProposerView,\n searchReceiptAccounting,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n defineEvaluationClaim,\n type EvaluationClaim,\n summarizeEvaluationUnits,\n} from '@tangle-network/agent-eval/experiment'\nimport { type AgentProfile, canonicalAgentProfileDigest } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { privateValuePaths } from './candidate-validation'\nimport type {\n ImprovementProfileCandidate,\n ImproveSearchMethod,\n ImproveSearchOptions,\n ImproveSearchResult,\n} from './improve-types'\nimport { type PreparedProfileImprovement, prepareProfileImprovement } from './profile-improvement'\nimport { decideClosedSearch, improveSearchCost } from './search-decision'\nimport {\n assertSearchLanes,\n isSearchEnvironmentFault,\n reconcileInterruptedSearchCalls,\n type SearchLane,\n searchCallTags,\n searchExecutor,\n taggedLedger,\n} from './search-executor'\nimport {\n type ProfileNode,\n profileNodeOf,\n registeringProfileCodec,\n type SearchSession,\n searchRefusalText,\n} from './search-session'\n\nexport interface SearchMethodOptions {\n /** Writes each child surface from the parents the policy chose. It reads the\n * train split only (`ProposeContext.train` and `summary`); `history` is empty. */\n proposer: SurfaceProposer<ProposalFinding>\n /** Proposals the search may make. */\n maxExpansions: number\n /** Which node each proposal extends, and which node the search keeps.\n * Default `aide()`: drafts from the baseline, debugs a node whose cells\n * fail as defects, and otherwise improves a parent drawn by Thompson\n * sampling over each node's posterior, forking from the best node when a\n * lineage stalls. `beam({ width })` expands the top nodes in turn;\n * `incumbent()` is the hill climb, which needs `uniform()`. */\n policy?: SearchPolicy\n /** Where cells go. Default `asha()`: successive halving over one seeded\n * permutation of the selection units. Each node is screened on 6 selection\n * units and 2 train units, and the top third of each rung advances to twice\n * the units. `uniform()` runs every node on every train and selection task.\n * The allocator's `reps` are every split's repeats, the claim's included. */\n allocation?: SearchAllocator\n /** Where cells run: `sharedBoxLane`, `dedicatedLane`, `subscriptionLane`\n * or `routerLane`. Each cell goes to a lane that accepts the node's profile,\n * in proportion to capacity; a hard lane caps each cell's paid calls at its\n * `cellUsd`, and an estimate lane holds `cellUsd` until 20 of its cells\n * settle. The search runs at most the lanes' total capacity at once. */\n lanes: readonly SearchLane[]\n /** Children one proposal asks for. Default 1. */\n childrenPerProposal?: number\n /** Dollars held for the claim from the start. Default: the root and 3\n * finalists on every test task at the largest lane `cellUsd` a cell. */\n claimReserveUsd?: number\n /** ISO time after which the search stops expanding and claims. */\n deadline?: string\n /** Attempts per cell for retryable environment errors. Default 3. */\n maxAttempts?: number\n /** Recorded as the ledger's process name. Default `search`. */\n name?: string\n}\n\n/** Build Runtime's native search for `improve(profile, { method })`. */\nexport function searchMethod(options: SearchMethodOptions): ImproveSearchMethod {\n if (!options || typeof options !== 'object') {\n throw new ConfigError('searchMethod(): options are required')\n }\n const { proposer } = options\n if (!proposer || typeof proposer.kind !== 'string' || typeof proposer.propose !== 'function') {\n throw new ConfigError('searchMethod(): proposer must be a SurfaceProposer')\n }\n const count = (name: string, value: number | undefined, fallback: number, min: number) => {\n const resolved = value ?? fallback\n if (!Number.isSafeInteger(resolved) || resolved < min) {\n throw new ConfigError(`searchMethod(): ${name} must be an integer of at least ${min}`)\n }\n return resolved\n }\n const dollars = (name: string, value: number | undefined): number | null => {\n if (value === undefined) return null\n if (!Number.isFinite(value) || value < 0) {\n throw new ConfigError(`searchMethod(): ${name} must be a finite non-negative number`)\n }\n return value\n }\n if (options.deadline !== undefined && !Number.isFinite(Date.parse(options.deadline))) {\n throw new ConfigError('searchMethod(): deadline must be an ISO time')\n }\n const name = options.name ?? 'search'\n if (!name.trim() || name.trim() !== name) {\n throw new ConfigError('searchMethod(): name must be a trimmed non-empty string')\n }\n assertSearchLanes(options.lanes, 'searchMethod()')\n return Object.freeze({\n kind: 'search' as const,\n name,\n policy: options.policy ?? aide(),\n allocation: options.allocation ?? asha(),\n proposer,\n maxExpansions: count('maxExpansions', options.maxExpansions, Number.NaN, 0),\n childrenPerProposal: count('childrenPerProposal', options.childrenPerProposal, 1, 1),\n lanes: Object.freeze([...options.lanes]),\n claimReserveUsd: dollars('claimReserveUsd', options.claimReserveUsd),\n deadline: options.deadline === undefined ? null : new Date(options.deadline).toISOString(),\n maxAttempts: count('maxAttempts', options.maxAttempts, 3, 1),\n })\n}\n\nexport function isImproveSearchMethod(value: unknown): value is ImproveSearchMethod {\n return (\n typeof value === 'object' && value !== null && (value as { kind?: unknown }).kind === 'search'\n )\n}\n\n/**\n * The rules `runSearchImprovement` adds to the kernel's. Its digest is the\n * process revision every searchMethod ledger records. The ship rule is not here:\n * it decides a closed ledger and writes nothing to it, so a changed ship rule\n * re-decides the same search instead of starting another.\n */\nconst SEARCH_METHOD_DEFINITION = {\n name: 'agent-runtime.search-method.2026-09',\n node: 'an exact AgentProfile materialized from the baseline and one surface, content-addressed by canonicalAgentProfileDigest; a surface that does not materialize is a node addressed by its surface and refused',\n edge: 'the Interface diffs from the parent profile to the child, stored when they reproduce the child digest',\n admission:\n 'a candidate is refused when it does not materialize, declares training on a test task, fails the caller validator, carries a credential or private value, or no lane can run its profile',\n cell: 'a one-cell runCampaign of the materialized profile in a directory addressed by its digest, on a lane that accepts the profile; a cached cell is read back, not run again; a finished attempt is recorded by run id before it settles and adopted after a restart',\n lanes:\n 'a hard lane refuses a paid call that declares no priced maximum or would take the cell past its cellUsd; an environment fault settles errored and retryable; a subscription seat reports no tokens and charges no dollars',\n proposer:\n 'a SurfaceProposer reads the parents, the train view and the train summary; paid calls it makes are its operation accounting',\n} as const\n\nconst SEARCH_METHOD_SOURCE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-runtime#searchMethod',\n revision: canonicalCandidateDigest(SEARCH_METHOD_DEFINITION),\n}\n\nexport async function runSearchImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveSearchResult> {\n const {\n method,\n claim: inputClaim,\n agent,\n executionRunId,\n recordCell,\n trainScenarios,\n selectionScenarios,\n testScenarios,\n judges: _judges,\n surface: _surface,\n executionRef: _executionRef,\n validateCandidate: _validateCandidate,\n findings: _findings,\n skills: _skills,\n profileComponents: _profileComponents,\n minimumLift: _minimumLift,\n subject: _subject,\n costCeiling,\n costLedger: inputCostLedger,\n seed = 42,\n signal,\n workerSlots,\n budgetPool,\n trace,\n ...campaignOptions\n } = opts\n const splitScenarios = { trainScenarios, selectionScenarios, testScenarios }\n const claim = assertSearchRequest(method, inputClaim, splitScenarios)\n const { allocation, policy, lanes } = method\n const reps = allocation.reps\n const concurrency = lanes.reduce((total, lane) => total + lane.capacity, 0)\n const prepared = prepareProfileImprovement(profile, {\n ...opts,\n seed,\n reps,\n optimizationRunOptions: { reps, maxConcurrency: concurrency },\n })\n const { evaluationRef } = prepared.identity\n const storage: CampaignStorage = campaignOptions.storage ?? fsCampaignStorage()\n const runDir = resolveRunDir(campaignOptions.runDir, campaignOptions.repo)\n const searchKey = canonicalCandidateDigest({\n evaluationRef,\n process: SEARCH_METHOD_SOURCE,\n method: searchMethodDescriptor(method),\n }).slice('sha256:'.length, 'sha256:'.length + 24)\n const searchId = `improve-${searchKey}`\n const searchDir = `${runDir}/search/${searchId}`\n const costLedger =\n inputCostLedger ??\n createRunCostLedger({ storage, runDir: searchDir, costCeilingUsd: costCeiling })\n const execution = searchExecutionIdentity(prepared)\n const recorder = await openSearchRecorder({\n method,\n prepared,\n claim,\n splits: searchSplits(claim, splitScenarios),\n storage,\n searchId,\n searchDir,\n seed,\n costCeiling,\n concurrency,\n execution,\n })\n const session: SearchSession<TScenario, TArtifact> = {\n method,\n prepared,\n searchId,\n costLedger,\n recorder,\n }\n\n const profiles = new Map<string, AgentProfile | null>()\n const codec = registeringProfileCodec(prepared, searchId, profiles)\n for (const node of (await recorder.state()).nodes()) codec.load(recorder, node)\n await reconcileInterruptedSearchCalls(costLedger, searchId, lanes)\n const root = profileNodeOf(prepared, prepared.baselineSurface)\n if (root.profile) {\n const refused = laneRefusal(lanes, root.profile)\n if (refused) throw new ConfigError(`improve(): the baseline profile cannot run: ${refused}`)\n }\n const scenarios = [...trainScenarios, ...selectionScenarios, ...testScenarios]\n assertDistinctScenarios(scenarios)\n const executor = searchExecutor<ProfileNode>({\n lanes,\n profileOf(nodeId) {\n const known = profiles.get(nodeId)\n if (known === undefined) throw new Error(`improve(): node ${nodeId} was placed unregistered`)\n return known\n },\n costLedger,\n identity: execution,\n storage,\n dir: searchDir,\n ...(workerSlots ? { workerSlots } : {}),\n ...(budgetPool ? { budgetPool } : {}),\n ...(trace ? { trace } : {}),\n runAttempt: searchCellRunner<TScenario, TArtifact>({\n campaignOptions: campaignOptions as Omit<\n RunCampaignOptions<TScenario, TArtifact>,\n 'scenarios' | 'dispatch'\n >,\n prepared,\n agent,\n executionRunId,\n recordCell,\n scenarios,\n seed,\n reps,\n storage,\n searchDir,\n evaluationRef,\n execution,\n }),\n })\n\n const startedAt = Date.now()\n const result = await runSearch({\n recorder,\n root,\n codec,\n policy,\n allocation,\n proposer: searchProposerPort(session),\n executor,\n admit: (node) => admissionRefusal(session, node),\n maxExpansions: method.maxExpansions,\n maxAttempts: method.maxAttempts,\n ...(signal ? { signal } : {}),\n })\n return decideSearchResult({ session, codec, result, costCeiling, startedAt })\n}\n\ninterface OpenSearchRecorderInput<TScenario extends Scenario, TArtifact> {\n method: ImproveSearchMethod\n prepared: PreparedProfileImprovement<TScenario, TArtifact>\n claim: EvaluationClaim\n splits: ReturnType<typeof searchSplits>\n storage: CampaignStorage\n searchId: string\n searchDir: string\n seed: number\n costCeiling: number | undefined\n concurrency: number\n execution: SearchExecutionIdentity\n}\n\n/** Open the search's ledger: a fresh search records its opening, an interrupted one continues. */\nfunction openSearchRecorder<TScenario extends Scenario, TArtifact>(\n input: OpenSearchRecorderInput<TScenario, TArtifact>,\n): Promise<SearchRecorder> {\n const { method, prepared, claim, splits, storage, searchId, searchDir, seed, costCeiling } = input\n const { policy, allocation, lanes } = method\n const reservedClaimUsd = Math.max(\n method.claimReserveUsd ?? 0,\n searchClaimReserveUsd({\n testTasks: splits.test.length,\n reps: allocation.reps,\n cellUsd: Math.max(...lanes.map((lane) => lane.cellUsd)),\n }),\n )\n return SearchRecorder.open(\n {\n ledger:\n storage.kind === 'filesystem'\n ? openSearchLedger({ path: `${searchDir}/ledger.jsonl`, searchId })\n : openSearchLedger({ path: `${searchDir}/ledger.jsonl`, searchId, store: storage }),\n storage,\n },\n {\n subject: prepared.searchIdentity.subject,\n process: { name: method.name, executionRef: SEARCH_METHOD_SOURCE },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'composite',\n direction: 'maximize',\n judge: prepared.searchIdentity.judge,\n claim,\n },\n splits,\n policy: { expansion: policy.name, allocation: allocation.name, seed },\n budget: {\n maxUsd: costCeiling ?? null,\n maxCells: null,\n maxNodes: 1 + method.maxExpansions * method.childrenPerProposal,\n deadline: method.deadline,\n maxConcurrency: input.concurrency,\n reservedClaimUsd: costCeiling === undefined ? 0 : reservedClaimUsd,\n },\n containment: null,\n derivedFrom: null,\n identity: input.execution,\n },\n )\n}\n\n/** The request is a search with a claim that can be powered, and every split has scenarios. */\nfunction assertSearchRequest<TScenario extends Scenario>(\n method: unknown,\n inputClaim: EvaluationClaim,\n splits: Record<'trainScenarios' | 'selectionScenarios' | 'testScenarios', readonly TScenario[]>,\n): EvaluationClaim {\n if (!isImproveSearchMethod(method)) {\n throw new ConfigError('improve(): a search needs method: searchMethod(...)')\n }\n const claim = defineEvaluationClaim(inputClaim)\n if (claim.minimumEffect === undefined) {\n throw new ConfigError('improve(): a search claim needs minimumEffect for its power check')\n }\n for (const [name, split] of Object.entries(splits)) {\n if (!Array.isArray(split) || split.length === 0) {\n throw new ConfigError(`improve(): a search needs at least one of ${name}`)\n }\n }\n return claim\n}\n\nfunction assertDistinctScenarios(scenarios: readonly Scenario[]): void {\n const scenarioIds = new Set<string>()\n for (const scenario of scenarios) {\n if (scenarioIds.has(scenario.id)) {\n throw new ConfigError(`improve(): scenario '${scenario.id}' appears in more than one split`)\n }\n scenarioIds.add(scenario.id)\n }\n}\n\n/** The search tasks of each split, and whether the test units are held out of development. */\nfunction searchSplits<TScenario extends Scenario>(\n claim: EvaluationClaim,\n scenarios: Record<\n 'trainScenarios' | 'selectionScenarios' | 'testScenarios',\n readonly TScenario[]\n >,\n) {\n const unitOf = (scenario: TScenario): string =>\n summarizeEvaluationUnits(claim, [scenario]).units[0]!.id\n const tasks = (list: readonly TScenario[]): SearchTask[] =>\n list.map((scenario) => ({\n taskId: scenario.id,\n unitId: unitOf(scenario),\n source: { uri: `scenario://${scenario.id}`, revision: canonicalCandidateDigest(scenario) },\n }))\n const splits = {\n train: tasks(scenarios.trainScenarios),\n selection: tasks(scenarios.selectionScenarios),\n test: tasks(scenarios.testScenarios),\n }\n const developmentUnits = new Set(\n [...splits.train, ...splits.selection].map((task) => task.unitId),\n )\n return {\n ...splits,\n heldOutUnits: splits.test.every((task) => !developmentUnits.has(task.unitId)),\n }\n}\n\nfunction searchExecutionIdentity<TScenario extends Scenario, TArtifact>(\n prepared: PreparedProfileImprovement<TScenario, TArtifact>,\n): SearchExecutionIdentity {\n return {\n model: prepared.searchIdentity.model,\n agent: prepared.searchIdentity.agent,\n benchmark: {\n uri: 'agent-runtime:improve-splits',\n revision: canonicalCandidateDigest({\n development: prepared.identity.developmentSplitDigest,\n test: prepared.identity.finalTestSplitDigest,\n }),\n },\n }\n}\n\n/** Why no lane can run the profile, or null when one can. */\nfunction laneRefusal(lanes: readonly SearchLane[], nodeProfile: AgentProfile): string | null {\n const refusals = lanes.map((lane) => `${lane.name}: ${lane.refusal(nodeProfile)}`)\n return lanes.some((lane) => lane.refusal(nodeProfile) === undefined)\n ? null\n : `no lane can run the profile (${refusals.join('; ')})`\n}\n\n/** Why a node is refused admission to the search, or null when it is admitted. */\nfunction admissionRefusal<TScenario extends Scenario, TArtifact>(\n { prepared, method }: SearchSession<TScenario, TArtifact>,\n node: ProfileNode,\n): string | null {\n if (node.refusal !== null || node.profile === null) return node.refusal\n try {\n prepared.admitCandidate(node.profile, node.surface)\n } catch (error) {\n return searchRefusalText(error)\n }\n const paths = privateValuePaths([node.surface])\n if (paths.length > 0) {\n return `the surface carries a credential or private value at ${paths.slice(0, 8).join(', ')}`\n }\n return laneRefusal(method.lanes, node.profile)\n}\n\n/** Read the closed search back from its ledger and decide whether its leader ships. */\nasync function decideSearchResult<TScenario extends Scenario, TArtifact>(input: {\n session: SearchSession<TScenario, TArtifact>\n codec: SearchArtifactCodec<ProfileNode>\n result: Awaited<ReturnType<typeof runSearch<ProfileNode>>>\n costCeiling: number | undefined\n startedAt: number\n}): Promise<ImproveSearchResult> {\n const { session, codec, result, costCeiling, startedAt } = input\n const { method, prepared, searchId, costLedger, recorder } = session\n const { state } = result\n const claimResult = result.claim\n if (!claimResult || !result.claimVerification) {\n throw new Error(`improve(): search ${searchId} closed without a claim`)\n }\n const kept = codec.load(recorder, state.node(result.leader)!)\n if (!kept.profile) throw new Error(`improve(): search ${searchId} kept a refused node`)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface: prepared.surface,\n value: kept.surface,\n profile: kept.profile,\n })\n const cost = improveSearchCost(costLedger)\n const decided = await decideClosedSearch({\n state,\n claim: claimResult,\n claimVerification: result.claimVerification,\n cost,\n costCeiling,\n minimumLift: prepared.minimumLift,\n profileOf(nodeId) {\n const node = state.node(nodeId)\n const loaded = node ? codec.load(recorder, node) : null\n if (!loaded?.profile)\n throw new Error(`improve(): search ${searchId} node ${nodeId} holds no profile`)\n return loaded.profile\n },\n })\n return {\n mode: 'search',\n method: method.name,\n candidate,\n ...decided,\n claim: claimResult,\n claimVerification: result.claimVerification,\n searchHistory: recorder.receipt({ producerId: method.name, runId: searchId }),\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId: prepared.invocationId,\n runId: searchId,\n developmentSplitDigest: prepared.identity.developmentSplitDigest,\n finalTestSplitDigest: prepared.identity.finalTestSplitDigest,\n scenarioPartitions: prepared.identity.scenarioPartitions,\n executionRef: prepared.executionRef,\n baselineProfileDigest: prepared.baselineProfileDigest,\n }),\n async dispose() {},\n }\n}\n\n/** Everything that decides which search a call continues. */\nfunction searchMethodDescriptor(method: ImproveSearchMethod): unknown {\n return {\n name: method.name,\n policy: method.policy.name,\n allocation: method.allocation.name,\n reps: method.allocation.reps,\n proposer: method.proposer.kind,\n maxExpansions: method.maxExpansions,\n childrenPerProposal: method.childrenPerProposal,\n lanes: method.lanes.map(({ name, kind, capacity, costCap, cellUsd }) => ({\n name,\n kind,\n capacity,\n costCap,\n cellUsd,\n })),\n claimReserveUsd: method.claimReserveUsd,\n deadline: method.deadline,\n maxAttempts: method.maxAttempts,\n }\n}\n\nconst PROPOSAL_PHASE = 'search.proposal'\n\nfunction searchProposerPort<TScenario extends Scenario, TArtifact>(\n session: SearchSession<TScenario, TArtifact>,\n): SearchProposerPort<ProfileNode> {\n const { method, prepared, recorder, costLedger, searchId } = session\n const { proposer } = method\n const proposerSource: SearchSourceRef = {\n uri: `proposer:${proposer.kind}`,\n revision: canonicalCandidateDigest({\n kind: proposer.kind,\n propose: Function.prototype.toString.call(proposer.propose),\n decide: proposer.decide ? Function.prototype.toString.call(proposer.decide) : null,\n }),\n }\n return {\n name: proposer.kind,\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: method.childrenPerProposal,\n async propose(request) {\n // The proposal's calls carry its operation, so its accounting is exactly them.\n const tags = searchCallTags(searchId, { operation: request.operationId })\n // Read the ledger once, synchronously, before any await: the kernel\n // retires a state view when it appends.\n const state = await recorder.state()\n const parents = request.parents.map(({ nodeId, artifact }) => ({\n nodeId,\n artifact: artifact.surface,\n }))\n const context: ProposeContext<ProposalFinding> = Object.freeze({\n currentSurface: parents[0]?.artifact ?? prepared.baselineSurface,\n operator: request.operator,\n parents,\n train: searchProposerView(state),\n summary: renderSearchSummary(state, { split: 'train' }),\n history: [],\n findings: prepared.findings,\n populationSize: method.childrenPerProposal,\n generation: request.expansion,\n signal: request.signal,\n costLedger: taggedLedger(costLedger, tags),\n costPhase: PROPOSAL_PHASE,\n })\n const decision = proposer.decide?.({ history: [] })\n const proposed = decision?.stop ? [] : await proposer.propose(context)\n if (!Array.isArray(proposed)) {\n throw new ConfigError('improve(): the search proposer must return an array')\n }\n const fresh = costLedger.list({ phase: PROPOSAL_PHASE, tags })\n return {\n children: proposed.slice(0, method.childrenPerProposal).map((child) =>\n isProposedCandidate(child)\n ? {\n artifact: profileNodeOf(prepared, child.surface),\n label: child.label,\n rationale: child.rationale,\n ...(child.attribution ? { attribution: child.attribution } : {}),\n }\n : { artifact: profileNodeOf(prepared, child), label: '', rationale: '' },\n ),\n ...(decision?.stop ? { stop: decision.reason ?? 'the proposer decided to stop' } : {}),\n accounting: searchReceiptAccounting(fresh),\n execution: searchProposalExecution(\n fresh,\n prepared.searchIdentity.model.provider,\n proposerSource,\n ),\n }\n },\n }\n}\n\ntype RunAttempt = Parameters<typeof searchExecutor<ProfileNode>>[0]['runAttempt']\n\n/** What every cell of one search shares. */\ninterface SearchCellEnvironment<TScenario extends Scenario, TArtifact> {\n readonly campaignOptions: Omit<RunCampaignOptions<TScenario, TArtifact>, 'scenarios' | 'dispatch'>\n readonly prepared: PreparedProfileImprovement<TScenario, TArtifact>\n readonly agent: ImproveSearchOptions<TScenario, TArtifact>['agent']\n readonly executionRunId: ImproveSearchOptions<TScenario, TArtifact>['executionRunId']\n readonly recordCell: ImproveSearchOptions<TScenario, TArtifact>['recordCell']\n readonly scenarios: TScenario[]\n readonly seed: number\n readonly reps: number\n readonly storage: CampaignStorage\n readonly searchDir: string\n readonly evaluationRef: string\n readonly execution: SearchExecutionIdentity\n}\n\n/** The executor's cell runner for one search. */\nfunction searchCellRunner<TScenario extends Scenario, TArtifact>(\n env: SearchCellEnvironment<TScenario, TArtifact>,\n): RunAttempt {\n const { campaignOptions, prepared, executionRunId, recordCell, execution } = env\n return async ({ work, lane, context, costLedger: cellLedger, span }) => {\n const nodeProfile = work.artifact.profile\n if (!nodeProfile) throw new Error(`improve(): refused node ${work.nodeId} was given a cell`)\n const profileDigest = canonicalAgentProfileDigest(nodeProfile)\n let fault: unknown\n const campaign = await runCampaign<TScenario, TArtifact>({\n ...campaignOptions,\n // A seat's work leaves no receipt, which the campaign would otherwise report as a stub.\n ...(lane.kind === 'subscription' &&\n (campaignOptions as { expectUsage?: unknown }).expectUsage === undefined\n ? { expectUsage: 'off' as const }\n : {}),\n scenarios: env.scenarios,\n judges: prepared.judges.map((judge) => ({\n ...judge,\n async score(input) {\n try {\n return await judge.score(input)\n } catch (error) {\n if (isSearchEnvironmentFault(error)) fault = error\n throw error\n }\n },\n })),\n seed: env.seed,\n reps: env.reps,\n storage: env.storage,\n runDir: `${env.searchDir}/nodes/${profileDigest.slice('sha256:'.length)}`,\n dispatchRef: `improve:${env.evaluationRef}:${profileDigest}`,\n async dispatch(scenario, ctx) {\n try {\n return await env.agent(nodeProfile, scenario, { ...ctx, search: context })\n } catch (error) {\n if (isSearchEnvironmentFault(error)) fault = error\n throw error\n }\n },\n cellFilter: ({ scenario, rep }) => scenario.id === work.taskId && rep === work.rep,\n resumable: true,\n maxConcurrency: 1,\n costLedger: cellLedger,\n costPhase: `search.${work.stage}`,\n buildTraceWriter: () => ({ span, flush: async () => {} }),\n signal: work.signal,\n })\n const cell = campaign.cells[0]\n if (!cell) throw new Error(`improve(): cell ${work.cellId} produced no campaign cell`)\n const result = campaignCellSearchResult(cell, { execution, lane: lane.name })\n const execRunId = cell.error ? null : (executionRunId?.(cell.artifact) ?? null)\n const settled = faultResult(\n execRunId && context.trace\n ? {\n ...result,\n traceRef: {\n traceId: context.trace.traceId,\n execRunId,\n spansWritten: null,\n spansDropped: null,\n },\n }\n : result,\n fault,\n )\n return recordCell && settled.outcome.status !== 'errored'\n ? {\n ...settled,\n recordCell: (finalResult) => recordCell({ cell, search: context, result: finalResult }),\n }\n : settled\n }\n}\n\n/**\n * An environment fault the agent raised settles retryable. The campaign reports every error as\n * final because it applies its own retry policy; here the kernel owns retries.\n */\nfunction faultResult(result: SearchCellResult, fault: unknown): SearchCellResult {\n if (fault === undefined || result.outcome.status !== 'errored') return result\n return {\n ...result,\n outcome: {\n ...result.outcome,\n error: { code: 'environment-fault', message: searchRefusalText(fault), retryable: true },\n },\n }\n}\n","import { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { chmod, mkdir, mkdtemp, open, realpath, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport {\n type AgentProfile,\n type AgentTrainingDatasetIdentity,\n type AgentTrainingReceipt,\n type AgentTrainingTask,\n agentProfileEnvironmentSchema,\n agentProfileTrainingSchema,\n agentTrainingDatasetIdentitySchema,\n agentTrainingParametersSchema,\n agentTrainingReceiptSchema,\n agentTrainingTaskKey,\n agentTrainingTaskSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateBytes,\n type Sha256Digest,\n sha256DigestSchema,\n snapshotAgentProfile,\n trainedModelIdForArtifact,\n} from '@tangle-network/agent-interface'\nimport {\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from '../candidate-execution/digest'\nimport { terminateProcessTreeAndConfirm } from '../runtime/process-tree'\nimport { linkAbort, runAbortable } from '../runtime/supervise/abortable'\nimport { armDeadlineTimer } from '../runtime/supervise/deadline'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport {\n assertCandidateValidator,\n parseExecutionRef,\n validateProfileCandidate,\n} from './candidate-validation'\nimport type { ImproveCandidateValidator } from './improve-types'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\nexport interface TrainingDatasetDocument {\n version: 1\n format: 'sft' | 'dpo' | 'grpo'\n /** Existing Eval export rows, without rewriting their payloads. Include every exposed partition. */\n rows: Array<{ task: AgentTrainingTask; partition: 'train' | 'validation'; data: unknown }>\n}\n\nexport interface ProfileTrainerRequest {\n version: 1\n invocationId: string\n datasetPath: string\n checkpointPath: string\n parentProfilePath: string\n parentProfileDigest: Sha256Digest\n parameters: AgentTrainingReceipt['trainer']['parameters']\n executionRef: Sha256Digest\n}\n\nexport type TrainingBoundaryResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; reason: string }\n\n/** Managed adapters use this same port: cancel the job on abort and download one exact checkpoint file. */\nexport interface ProfileTrainer {\n identity: Omit<AgentTrainingReceipt['trainer'], 'parameters'>\n execute(\n request: Readonly<ProfileTrainerRequest>,\n signal: AbortSignal,\n ): Promise<TrainingBoundaryResult<void>>\n}\n\nexport interface CheckpointServingPort {\n /** Verify the immutable Router route independently of the trainer's output. */\n serve(input: {\n artifactPath: string\n artifactDigest: Sha256Digest\n artifactBytes: number\n routerModelId: string\n signal: AbortSignal\n }): Promise<\n TrainingBoundaryResult<{\n routerModelId: string\n artifactDigest: Sha256Digest\n evidenceDigest: Sha256Digest\n }>\n >\n}\n\nexport interface ImproveTrainingOptions {\n mode: 'training'\n trainer: ProfileTrainer\n dataset: { path: string; digest: Sha256Digest }\n parameters: AgentTrainingReceipt['trainer']['parameters']\n /** Pins trainer, serving adapter and their private dependencies, just like the bound profile harness. */\n executionRef: Sha256Digest\n serving: CheckpointServingPort\n outputDirectory: string\n /** Optional overall deadline. Omit to rely on caller cancellation; long durations are supported. */\n timeoutMs?: number\n maxCheckpointBytes: number\n signal?: AbortSignal\n validateCandidate?: ImproveCandidateValidator\n}\n\nexport type ImproveTrainingResult =\n | {\n mode: 'training'\n succeeded: true\n profile: ReadonlyAgentProfile\n profileDigest: Sha256Digest\n receipt: AgentTrainingReceipt\n artifactPath: string\n receiptPath: string\n profilePath: string\n }\n | {\n mode: 'training'\n succeeded: false\n stage:\n | 'admission'\n | 'dataset'\n | 'training'\n | 'checkpoint'\n | 'serving'\n | 'profile'\n | 'persistence'\n reason: string\n /** Partial artifacts are retained for diagnosis; they are not a runnable profile. */\n outputDirectory?: string\n /** A serving request began; an interrupted adapter may still own a deployment. */\n servingMayExist: boolean\n /** A timed-out managed adapter may still own a remote training job. */\n trainingMayExist: boolean\n cleanupError?: string\n }\n\nexport interface ControlledTrainingCommand {\n id: string\n executable: { path: string; digest: Sha256Digest }\n args: string[]\n /** Script/config files used by the command, verified before and after execution. */\n inputs: Array<{ path: string; digest: Sha256Digest }>\n /** Explicit public environment only. Ambient credentials are never inherited. */\n environment: Record<string, string>\n /** Total stdout + stderr byte budget. Output is drained, not retained in memory. */\n maxOutputBytes: number\n}\n\nfunction positiveLimit(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`invalid ${label}`)\n}\n\nasync function hashFile(\n path: string,\n maximum: number,\n signal: AbortSignal,\n capture = false,\n): Promise<{\n digest: Sha256Digest\n bytes: number\n content?: Buffer\n}> {\n signal.throwIfAborted()\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)\n try {\n const before = await file.stat()\n if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size > maximum)\n throw new Error('artifact must be a bounded regular file')\n const hash = createHash('sha256')\n const chunks: Buffer[] = []\n let bytes = 0\n // The signal is read here and per chunk, never handed to the stream: a stream given a signal\n // that aborted during `open` or `stat` raises its AbortError before the iterator listens, as an\n // uncaught exception (the training timeout firing during the dataset stage). An abort therefore\n // lands within one 64 KiB chunk read.\n signal.throwIfAborted()\n for await (const chunk of file.createReadStream({ autoClose: false })) {\n signal.throwIfAborted()\n bytes += chunk.length\n if (bytes > maximum) throw new Error('artifact exceeded its byte limit')\n if (bytes > before.size) throw new Error('artifact changed while being hashed')\n hash.update(chunk)\n if (capture) chunks.push(Buffer.from(chunk))\n }\n const after = await file.stat()\n if (\n before.size !== bytes ||\n after.size !== bytes ||\n before.mtimeMs !== after.mtimeMs ||\n before.ctimeMs !== after.ctimeMs\n ) {\n throw new Error('artifact changed while being hashed')\n }\n return {\n digest: `sha256:${hash.digest('hex')}`,\n bytes,\n ...(capture ? { content: Buffer.concat(chunks) } : {}),\n }\n } finally {\n await file.close()\n }\n}\n\n/** Execute one pinned command without a shell, in the runtime-owned job directory. POSIX only. */\nexport function createCommandProfileTrainer(input: ControlledTrainingCommand): ProfileTrainer {\n const command = immutableCandidateValue(input)\n positiveLimit(command.maxOutputBytes, 'trainer output limit')\n if (\n !command.id ||\n command.id.trim() !== command.id ||\n !Array.isArray(command.args) ||\n !command.args.every((arg) => typeof arg === 'string' && !arg.includes('\\0'))\n )\n throw new Error('invalid trainer command')\n for (const file of [command.executable, ...command.inputs]) {\n if (!isAbsolute(file.path)) throw new Error('trainer files must use absolute paths')\n sha256DigestSchema.parse(file.digest)\n }\n for (const [name, value] of Object.entries(command.environment)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || value.includes('\\0'))\n throw new Error('invalid trainer environment')\n }\n agentProfileEnvironmentSchema.parse(\n Object.fromEntries(\n Object.entries(command.environment).map(([key, value]) => [key, { kind: 'public', value }]),\n ),\n )\n const identity = immutableCandidateValue({\n mode: 'command' as const,\n id: command.id,\n revision: canonicalCandidateDigest(command),\n })\n agentTrainingReceiptSchema.shape.trainer.parse({ ...identity, parameters: {} })\n return Object.freeze({\n identity,\n async execute(\n request: Readonly<ProfileTrainerRequest>,\n signal: AbortSignal,\n ): Promise<TrainingBoundaryResult<void>> {\n try {\n if (process.platform === 'win32')\n throw new Error('controlled trainers require POSIX process-group cancellation')\n // Serialize before spawning and before any await: caller mutation cannot redirect the job,\n // and a malformed request cannot leave a live child behind an early rejected promise.\n const requestSnapshot = immutableCandidateValue(request)\n const inputBytes = Buffer.from(canonicalCandidateBytes(requestSnapshot))\n const verifyInputs = async () => {\n for (const file of [command.executable, ...command.inputs]) {\n if (\n (await hashFile(file.path, Number.MAX_SAFE_INTEGER, signal)).digest !== file.digest\n ) {\n throw new Error('trainer executable or input digest mismatch')\n }\n }\n }\n await verifyInputs()\n signal.throwIfAborted()\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable.path, command.args, {\n cwd: dirname(requestSnapshot.checkpointPath),\n env: command.environment,\n shell: false,\n detached: true,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let failure: Error | undefined\n let outputBytes = 0\n let leaderClosed = false\n let termination: Promise<void> | undefined\n const stop = () => {\n if (!termination) {\n termination = terminateProcessTreeAndConfirm(\n child,\n () => leaderClosed,\n 'createCommandProfileTrainer',\n )\n // Teardown can finish before close. Observe its failure in both event orders.\n void termination.catch((error) => {\n failure ??= error\n })\n }\n return termination\n }\n const abort = () => {\n failure ??= new Error('trainer cancelled')\n stop()\n }\n signal.addEventListener('abort', abort, { once: true })\n if (signal.aborted) abort()\n const count = (chunk: Buffer) => {\n outputBytes += chunk.length\n if (outputBytes > command.maxOutputBytes) {\n failure ??= new Error('trainer output limit exceeded')\n stop()\n }\n }\n child.stdout.on('data', count)\n child.stderr.on('data', count)\n child.stdin.on('error', (error) => {\n failure ??= error\n stop()\n })\n child.on('error', (error) => {\n failure ??= error\n })\n // A successful parent may not leave descendants mutating the checkpoint.\n child.on('exit', stop)\n child.on('close', (code, exitSignal) => {\n leaderClosed = true\n signal.removeEventListener('abort', abort)\n void stop().then(() => {\n if (failure) reject(failure)\n else if (code !== 0 || exitSignal !== null)\n reject(new Error(`trainer exited unsuccessfully (${code ?? exitSignal})`))\n else resolve()\n }, reject)\n })\n child.stdin.end(inputBytes)\n })\n await verifyInputs()\n return { succeeded: true, value: undefined }\n } catch (error) {\n return {\n succeeded: false,\n reason: error instanceof Error ? error.message : 'trainer failed',\n }\n }\n },\n })\n}\n\nfunction datasetIdentity(bytes: Uint8Array): AgentTrainingDatasetIdentity {\n const dataset = JSON.parse(\n new TextDecoder('utf-8', { fatal: true }).decode(bytes),\n ) as TrainingDatasetDocument\n canonicalCandidateBytes(dataset)\n if (\n !dataset ||\n typeof dataset !== 'object' ||\n Object.keys(dataset).sort().join(',') !== 'format,rows,version' ||\n dataset.version !== 1 ||\n !['sft', 'dpo', 'grpo'].includes(dataset.format) ||\n !Array.isArray(dataset.rows) ||\n dataset.rows.length === 0 ||\n dataset.rows.length > 1_000_000\n )\n throw new Error('invalid training dataset')\n const tasks = new Map<string, AgentTrainingTask>()\n const partitions = new Map<string, string>()\n let trainingRows = 0\n for (const row of dataset.rows) {\n if (\n !row ||\n typeof row !== 'object' ||\n Object.keys(row).sort().join(',') !== 'data,partition,task' ||\n !['train', 'validation'].includes(row.partition)\n )\n throw new Error('every dataset row needs its exposure identity and partition')\n if (row.partition === 'train') trainingRows++\n const task = agentTrainingTaskSchema.parse(row.task)\n for (const identity of [JSON.stringify([task.benchmark, task.task]), task.contentDigest]) {\n const previous = partitions.get(identity)\n if (previous !== undefined && previous !== row.partition)\n throw new Error('training and validation task partitions intersect')\n partitions.set(identity, row.partition)\n }\n tasks.set(agentTrainingTaskKey(task), task)\n }\n if (trainingRows === 0) throw new Error('dataset contains no training rows')\n const members = [...tasks.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([, task]) => task)\n return agentTrainingDatasetIdentitySchema.parse({\n digest: sha256Bytes(bytes),\n taskSetDigest: canonicalCandidateDigest(members),\n tasks: members,\n })\n}\n\n/** Training materializes a candidate; it never emits a ship verdict or changes a live agent. */\nexport async function runProfileTraining(\n profile: ReadonlyAgentProfile,\n options: ImproveTrainingOptions,\n): Promise<ImproveTrainingResult> {\n let stage: Extract<ImproveTrainingResult, { succeeded: false }>['stage'] = 'admission'\n let jobDirectory: string | undefined\n const cancellation = linkAbort(...(options.signal ? [options.signal] : []))\n const signal = cancellation.signal\n const outputDirectory = options.outputDirectory\n const timeoutMs = options.timeoutMs\n let servingMayExist = false\n let trainingMayExist = false\n let clearTimer: (() => void) | undefined\n try {\n if (options.mode !== 'training') throw new Error('training mode is required')\n const parent = snapshotAgentProfile(profile)\n if (!parent.harness || !parent.model?.default?.trim() || !parent.model.provider?.trim()) {\n throw new Error('training requires an explicit parent harness, provider and model')\n }\n const parentProfileDigest = canonicalAgentProfileDigest(parent)\n const parentBytes = Buffer.from(JSON.stringify(parent), 'utf8')\n sha256DigestSchema.parse(options.dataset.digest)\n if (timeoutMs !== undefined) positiveLimit(timeoutMs, 'training timeout')\n positiveLimit(options.maxCheckpointBytes, 'checkpoint byte limit')\n if (\n typeof options.trainer?.execute !== 'function' ||\n typeof options.serving?.serve !== 'function'\n )\n throw new Error('trainer and verified serving ports are required')\n const trainer = immutableCandidateValue(options.trainer.identity)\n const parameters = immutableCandidateValue(\n agentTrainingParametersSchema.parse(options.parameters),\n )\n agentTrainingReceiptSchema.shape.trainer.parse({ ...trainer, parameters })\n assertCandidateValidator(options.validateCandidate)\n const execute = options.trainer.execute.bind(options.trainer)\n const serve = options.serving.serve.bind(options.serving)\n const executionRef = parseExecutionRef(options.executionRef, 'training')\n const expectedDatasetDigest = options.dataset.digest\n const sourceDataset = options.dataset.path\n const maxCheckpointBytes = options.maxCheckpointBytes\n const validateCandidate = options.validateCandidate\n // Interface owns both the ancestry bound and the portable receipt shape.\n const ancestry = agentProfileTrainingSchema.shape.ancestors.parse(\n parent.metadata?.training\n ? [parent.metadata.training.receipt, ...parent.metadata.training.ancestors]\n : [],\n )\n const validate = (candidate: AgentProfile, isBaseline: boolean) =>\n validateProfileCandidate(validateCandidate, {\n profile: candidate,\n surface: 'agent-profile',\n candidateSurface: JSON.stringify(candidate),\n value: candidate,\n isBaseline,\n })\n if (timeoutMs !== undefined) {\n clearTimer = armDeadlineTimer(\n timeoutMs,\n () => cancellation.abort(new Error('training deadline exceeded')),\n true,\n )\n }\n signal.throwIfAborted()\n validate(parent, true)\n await mkdir(outputDirectory, { recursive: true })\n const outputRoot = await realpath(outputDirectory)\n jobDirectory = await mkdtemp(join(outputRoot, 'training-'))\n await chmod(jobDirectory, 0o700)\n syncDurableDirectory(outputRoot)\n const datasetPath = join(jobDirectory, 'dataset.json')\n const parentProfilePath = join(jobDirectory, 'parent-profile.json')\n const artifactPath = join(jobDirectory, 'checkpoint.bin')\n stage = 'dataset'\n const source = await hashFile(sourceDataset, 128 * 1024 * 1024, signal, true)\n if (source.digest !== expectedDatasetDigest) throw new Error('training dataset digest mismatch')\n const bytes = source.content!\n if (bytes.length !== source.bytes) throw new Error('training dataset snapshot is incomplete')\n const dataset = datasetIdentity(bytes)\n await writeFile(datasetPath, bytes, { flag: 'wx', mode: 0o400 })\n await writeFile(parentProfilePath, parentBytes, { flag: 'wx', mode: 0o400 })\n const request = immutableCandidateValue({\n version: 1 as const,\n invocationId: jobDirectory,\n datasetPath,\n checkpointPath: artifactPath,\n parentProfilePath,\n parentProfileDigest,\n parameters,\n executionRef,\n })\n stage = 'training'\n const trained = await runAbortable(\n () => {\n trainingMayExist = true\n return execute(request, signal)\n },\n signal,\n 'training cancelled',\n )\n signal.throwIfAborted()\n if (trained?.succeeded !== true)\n throw new Error(trained?.reason ?? 'trainer did not report success')\n trainingMayExist = false\n stage = 'checkpoint'\n if (\n (await hashFile(datasetPath, 128 * 1024 * 1024, signal)).digest !== dataset.digest ||\n (await hashFile(parentProfilePath, parentBytes.byteLength, signal)).digest !==\n sha256Bytes(parentBytes)\n ) {\n throw new Error('trainer changed its pinned inputs')\n }\n const artifact = await hashFile(artifactPath, maxCheckpointBytes, signal)\n if (artifact.bytes === 0) throw new Error('checkpoint must be nonempty')\n await chmod(artifactPath, 0o400)\n const checkpoint = await open(artifactPath, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n await checkpoint.sync()\n } finally {\n await checkpoint.close()\n }\n stage = 'serving'\n const served = await runAbortable(\n () => {\n servingMayExist = true\n return serve({\n artifactPath,\n artifactDigest: artifact.digest,\n artifactBytes: artifact.bytes,\n routerModelId: trainedModelIdForArtifact(artifact.digest),\n signal,\n })\n },\n signal,\n 'checkpoint serving cancelled',\n )\n signal.throwIfAborted()\n if (served?.succeeded !== true)\n throw new Error(served?.reason ?? 'checkpoint serving is unverified')\n if (served.value.artifactDigest !== artifact.digest)\n throw new Error('Router serving evidence names a different checkpoint')\n // Snapshot caller-owned evidence before awaiting another read.\n const receipt = immutableCandidateValue(\n agentTrainingReceiptSchema.parse({\n version: 1,\n dataset,\n parentProfileDigest,\n parentReceiptDigest: ancestry[0] ? canonicalCandidateDigest(ancestry[0]) : null,\n executionRef,\n trainer: { ...trainer, parameters },\n checkpoint: {\n artifactDigest: artifact.digest,\n artifactBytes: artifact.bytes,\n routerModelId: served.value.routerModelId,\n servingDigest: served.value.evidenceDigest,\n },\n }),\n )\n if ((await hashFile(artifactPath, maxCheckpointBytes, signal)).digest !== artifact.digest)\n throw new Error('checkpoint changed during serving')\n stage = 'profile'\n const previousModel = parent.metadata?.training?.receipt.checkpoint.routerModelId\n const routerModelId = receipt.checkpoint.routerModelId\n const rebindModels = <T extends { model?: string }>(entries: Record<string, T>) =>\n Object.fromEntries(\n Object.entries(entries).map(([key, value]) => [\n key,\n previousModel && value.model === previousModel\n ? { ...value, model: routerModelId }\n : value,\n ]),\n )\n const candidate = snapshotAgentProfile({\n ...parent,\n model: {\n ...parent.model,\n default: routerModelId,\n ...(previousModel && parent.model.small === previousModel ? { small: routerModelId } : {}),\n },\n // Only references to the old trained artifact follow the new receipt; other models stay put.\n ...(parent.subagents && { subagents: rebindModels(parent.subagents) }),\n ...(parent.modes && { modes: rebindModels(parent.modes) }),\n metadata: { ...parent.metadata, training: { receipt, ancestors: ancestry } },\n })\n validate(candidate, false)\n // The validator is caller code too; publish only the bytes the receipt actually names.\n if ((await hashFile(artifactPath, maxCheckpointBytes, signal)).digest !== artifact.digest)\n throw new Error('checkpoint changed during candidate validation')\n stage = 'persistence'\n const receiptPath = join(jobDirectory, 'receipt.json')\n const profilePath = join(jobDirectory, 'profile.json')\n const profileDigest = canonicalAgentProfileDigest(candidate)\n // Reuse the runtime's no-clobber, fsynced publication primitive. Once the\n // profile is committed, a late cancellation must not retract an observed result.\n for (const [path, value] of [\n [receiptPath, receipt],\n [profilePath, candidate],\n ] as const) {\n signal.throwIfAborted()\n if (!publishExclusiveDurableFile(path, JSON.stringify(value), { mode: 0o400 }))\n throw new Error('training publication path already exists')\n }\n return {\n mode: 'training',\n succeeded: true,\n profile: candidate,\n profileDigest,\n receipt,\n artifactPath,\n receiptPath,\n profilePath,\n }\n } catch (error) {\n let cleanupError: string | undefined\n if (jobDirectory) {\n try {\n await rm(join(jobDirectory, 'profile.json'), { force: true })\n syncDurableDirectory(jobDirectory)\n } catch (failure) {\n cleanupError = failure instanceof Error ? failure.message : 'profile cleanup failed'\n }\n }\n return {\n mode: 'training',\n succeeded: false,\n stage,\n reason:\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'training failed',\n servingMayExist,\n trainingMayExist,\n ...(cleanupError ? { cleanupError } : {}),\n ...(jobDirectory ? { outputDirectory: jobDirectory } : {}),\n }\n } finally {\n clearTimer?.()\n cancellation.release()\n }\n}\n","/**\n * `improve` runs one complete optimization method against an exact profile\n * surface. Runtime extracts and materializes the profile value; agent-eval owns\n * optimization, disjoint data partitions, final-test scoring, and uncertainty.\n *\n * Code owns isolated git worktrees. Training owns checkpoint execution and\n * serving receipts; unlike optimization, it does not make a promotion decision.\n *\n * @stable\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/contract'\nimport { agentProfileSchema } from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { runCodeImprovement } from './code-execution'\nimport type {\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveResult,\n ImproveSearchOptions,\n ImproveSearchResult,\n} from './improve-types'\nimport { runMethodImprovement } from './method-execution'\nimport type { ReadonlyAgentProfile } from './profile-types'\nimport { isImproveSearchMethod, runSearchImprovement } from './search-method'\nimport {\n type ImproveTrainingOptions,\n type ImproveTrainingResult,\n runProfileTraining,\n} from './training'\n\n// The owning modules are the single list of these names; re-exporting them by\n// hand made every new option type a three-file edit.\nexport type * from './improve-types'\nexport { decideSearchImprovement } from './search-decision'\nexport {\n dedicatedLane,\n routerLane,\n type SearchCellContext,\n SearchEnvironmentFault,\n type SearchLane,\n sharedBoxLane,\n subscriptionLane,\n} from './search-executor'\nexport { searchMethod } from './search-method'\nexport type * from './training'\nexport { createCommandProfileTrainer } from './training'\n\n/** Train and serve a checkpoint without implying that it improved held-out quality. */\nexport function improve(\n profile: ReadonlyAgentProfile,\n opts: ImproveTrainingOptions,\n): Promise<ImproveTrainingResult>\n/**\n * Search one exact profile surface with Runtime's native search\n * (`method: searchMethod(...)`): the kernel expands, allocates and claims on\n * the sealed test split, and the claim decides.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveSearchResult>\n/**\n * Optimize one exact profile surface with a complete method.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult>\n/** Optimize one exact profile surface with a complete method or a search. */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: ReadonlyAgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact> | ImproveSearchOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult | ImproveSearchResult>\n/**\n * Optimize repository code through Runtime's isolated worktree path.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n opts: ImproveCodeRunOptions<TScenario, TArtifact>,\n): Promise<ImproveCodeResult<TScenario, TArtifact>>\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profileOrCode: ReadonlyAgentProfile | ImproveCodeRunOptions<TScenario, TArtifact>,\n opts?:\n | ImproveMethodOptions<TScenario, TArtifact>\n | ImproveSearchOptions<TScenario, TArtifact>\n | ImproveTrainingOptions,\n): Promise<ImproveResult<TScenario, TArtifact> | ImproveTrainingResult> {\n if (opts === undefined) {\n const code = profileOrCode as ImproveCodeRunOptions<TScenario, TArtifact>\n if (code?.surface !== 'code') {\n throw new ConfigError(\"improve(): the one-argument form requires { surface: 'code', ... }\")\n }\n return runCodeImprovement(code)\n }\n if (opts === null || typeof opts !== 'object') {\n throw new ConfigError('improve(): options must be an object')\n }\n if ('mode' in opts) {\n if (opts.mode !== 'training') throw new ConfigError('improve(): unsupported mode')\n return runProfileTraining(profileOrCode as ReadonlyAgentProfile, opts)\n }\n if ((opts as { surface?: string }).surface === 'code') {\n throw new ConfigError(\"improve(): code takes one argument: improve({ surface: 'code', ... })\")\n }\n const parsedProfile = agentProfileSchema.safeParse(profileOrCode)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n const exact = immutableCandidateValue(parsedProfile.data)\n if (isImproveSearchMethod(opts.method)) {\n return runSearchImprovement(exact, opts as ImproveSearchOptions<TScenario, TArtifact>)\n }\n return runMethodImprovement(exact, opts as ImproveMethodOptions<TScenario, TArtifact>)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,U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