@tangle-network/agent-runtime 0.94.13 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/agent.d.ts +2 -25
  2. package/dist/agent.js +9 -12
  3. package/dist/agent.js.map +1 -1
  4. package/dist/{agentic-generator-DDMM45kZ.d.ts → agentic-generator-hCaQRAes.d.ts} +0 -1
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/candidate-execution/index.d.ts +43 -16
  7. package/dist/candidate-execution/index.js +18 -8
  8. package/dist/{chunk-VYA2YEKA.js → chunk-2KGAN2HM.js} +83 -14
  9. package/dist/chunk-2KGAN2HM.js.map +1 -0
  10. package/dist/{chunk-TVJQAYQM.js → chunk-6YBA64Z2.js} +120 -716
  11. package/dist/chunk-6YBA64Z2.js.map +1 -0
  12. package/dist/{chunk-HGRW27YY.js → chunk-AP7CPGMZ.js} +139 -19
  13. package/dist/chunk-AP7CPGMZ.js.map +1 -0
  14. package/dist/{chunk-XP5KDM3R.js → chunk-BPGXIKK7.js} +3 -3
  15. package/dist/{chunk-D3H7F6L2.js → chunk-DHCHL6OG.js} +2 -3
  16. package/dist/chunk-DHCHL6OG.js.map +1 -0
  17. package/dist/{chunk-PCURO3DL.js → chunk-G55QE4IQ.js} +512 -36
  18. package/dist/chunk-G55QE4IQ.js.map +1 -0
  19. package/dist/{chunk-C3UKLQ54.js → chunk-IADLKE7I.js} +14 -4
  20. package/dist/chunk-IADLKE7I.js.map +1 -0
  21. package/dist/{chunk-WIPGQ4GT.js → chunk-IMSNJSXH.js} +1 -1
  22. package/dist/{chunk-WIPGQ4GT.js.map → chunk-IMSNJSXH.js.map} +1 -1
  23. package/dist/{chunk-VSWBYWFK.js → chunk-M6MD6JBS.js} +20 -27
  24. package/dist/chunk-M6MD6JBS.js.map +1 -0
  25. package/dist/chunk-MKGRLDWB.js +684 -0
  26. package/dist/chunk-MKGRLDWB.js.map +1 -0
  27. package/dist/{chunk-AEG3NGJ2.js → chunk-Q2JSAVQ3.js} +34 -2
  28. package/dist/chunk-Q2JSAVQ3.js.map +1 -0
  29. package/dist/{chunk-CNH7DF7Z.js → chunk-WTZ37EQY.js} +922 -504
  30. package/dist/chunk-WTZ37EQY.js.map +1 -0
  31. package/dist/{chunk-U33YZ7B2.js → chunk-YLUOTX6U.js} +4 -4
  32. package/dist/{chunk-33OG2NN3.js → chunk-Z5I642SY.js} +2 -2
  33. package/dist/{completion-gate-D1gX1-hg.d.ts → completion-gate-C80jiRfN.d.ts} +1 -1
  34. package/dist/conversation.d.ts +12 -1
  35. package/dist/conversation.js +2 -2
  36. package/dist/{coordination-Dr_axlAf.d.ts → coordination-BFE3Den7.d.ts} +10 -11
  37. package/dist/environment-provider.d.ts +2 -2
  38. package/dist/environment-provider.js +1 -1
  39. package/dist/{improve-BN3HyXIO.d.ts → improve-B-UYaEH5.d.ts} +3 -3
  40. package/dist/index.d.ts +22 -25
  41. package/dist/index.js +45 -50
  42. package/dist/index.js.map +1 -1
  43. package/dist/intelligence.d.ts +177 -119
  44. package/dist/intelligence.js +501 -342
  45. package/dist/intelligence.js.map +1 -1
  46. package/dist/knowledge.d.ts +22 -11
  47. package/dist/knowledge.js +9 -4
  48. package/dist/lifecycle.d.ts +2 -2
  49. package/dist/lifecycle.js +1 -1
  50. package/dist/{loop-runner-bin-BRQSQdHa.d.ts → loop-runner-bin-BIQldFS8.d.ts} +2 -2
  51. package/dist/loop-runner-bin.d.ts +5 -5
  52. package/dist/loop-runner-bin.js +6 -6
  53. package/dist/loops.d.ts +12 -12
  54. package/dist/loops.js +5 -5
  55. package/dist/mcp/bin.js +3 -3
  56. package/dist/mcp/index.d.ts +6 -6
  57. package/dist/mcp/index.js +6 -6
  58. package/dist/{mcp-serve-verifier-DQQDbuyz.d.ts → mcp-serve-verifier-Bs_n0xPc.d.ts} +1 -1
  59. package/dist/primeintellect/index.js +1 -1
  60. package/dist/profile-DbfaMTdk.d.ts +233 -0
  61. package/dist/profiles.d.ts +1 -1
  62. package/dist/{supervise-DmYOug5f.d.ts → supervise-BLPI50-w.d.ts} +3 -3
  63. package/dist/{types-ByAYqlVb.d.ts → types-B3vAW0Oq.d.ts} +1 -1
  64. package/dist/{prepare-CtdtsFNG.d.ts → types-CWqfCO8s.d.ts} +67 -298
  65. package/dist/{types-1d5QGK3t.d.ts → types-CmnA2iL3.d.ts} +3 -3
  66. package/dist/{worktree-fanout-CPprU-qI.d.ts → worktree-fanout-DCA3G4bO.d.ts} +3 -3
  67. package/package.json +13 -10
  68. package/dist/chunk-AEG3NGJ2.js.map +0 -1
  69. package/dist/chunk-C3UKLQ54.js.map +0 -1
  70. package/dist/chunk-CNH7DF7Z.js.map +0 -1
  71. package/dist/chunk-D3H7F6L2.js.map +0 -1
  72. package/dist/chunk-HGRW27YY.js.map +0 -1
  73. package/dist/chunk-PCURO3DL.js.map +0 -1
  74. package/dist/chunk-TVJQAYQM.js.map +0 -1
  75. package/dist/chunk-VSWBYWFK.js.map +0 -1
  76. package/dist/chunk-VYA2YEKA.js.map +0 -1
  77. /package/dist/{chunk-XP5KDM3R.js.map → chunk-BPGXIKK7.js.map} +0 -0
  78. /package/dist/{chunk-U33YZ7B2.js.map → chunk-YLUOTX6U.js.map} +0 -0
  79. /package/dist/{chunk-33OG2NN3.js.map → chunk-Z5I642SY.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/improvement/improvement-driver.ts","../src/improvement/cleanup.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/improve.ts","../src/intelligence/improvement-cycle.ts"],"sourcesContent":["/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { AnalystFinding, CostLedgerHandle } from '@tangle-network/agent-eval'\nimport {\n type CodeSurface,\n type LabeledScenarioStore,\n type ProposeContext,\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 seam — the ONE thing 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 * and no phase-2 report — i.e. it draws its change signal from the repo and\n * the raw-trace filesystem context on disk, not only from pre-summarized\n * findings. An agentic coder (`agenticGenerator`) sets this: the seed repo +\n * raw traces ARE the signal, so it must still run the full `populationSize`\n * when the distiller yielded nothing (this is the meta-harness contract — the\n * agent diagnoses from the raw traces itself). 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 /** Phase-2 research report (analyst findings + diff), opaque. */\n report: unknown\n /** Findings resolved from the report or the loop context. */\n findings: AnalystFinding[]\n /** Handle to all captured data, to ground the change. */\n dataset?: LabeledScenarioStore\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n /** Improvement-loop coordinates. Present when called through improvementDriver. */\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<{ applied: boolean; summary: string }>\n}\n\nexport interface 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<AnalystFinding> {\n /** Remove every owned candidate except explicitly retained finalized winners. */\n cleanup(retainWorktreeRefs?: readonly string[]): Promise<void>\n}\n\n/** The one reflective/agentic improvement proposer (`SurfaceProposer`): owns the candidate worktree lifecycle and delegates HOW a change is produced to a pluggable `CandidateGenerator`. */\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<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the 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 (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: CodeSurface[] = []\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 } = await opts.generator.generate({\n worktreePath: wt.path,\n report: ctx.report,\n findings,\n dataset: ctx.dataset,\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 surfaces.push(surface)\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\n/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) return f as AnalystFinding[]\n }\n return ctx.findings\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","/**\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 `AnalystFinding[]` 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 * @experimental\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { type AnalystFinding, makeFinding } 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\nexport interface 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?: unknown[]\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 `opts.analyzeGeneration` on `improve()` / `selfImprove()`:\n *\n * await improve(profile, seedFindings, {\n * surface: 'code',\n * code: { repoRoot },\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) => 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 makeFinding({\n analyst_id: ANALYST_ID,\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: AnalystFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\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 makeFinding({\n analyst_id: ANALYST_ID,\n severity: cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} 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/** 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","/**\n *\n * `improve` — the ONE public, surface-pluggable RSI verb.\n *\n * A thin facade over agent-eval's `selfImprove` (the held-out-gated closed\n * loop). It removes the two things a caller otherwise has to know to drive the\n * loop by hand: WHICH `MutableSurface` of the profile is being optimized, and\n * WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the\n * facade picks the matching default proposer, extracts the baseline surface from\n * the profile, runs `selfImprove`, and (on a ship verdict) writes the promoted\n * winner back into the corresponding profile field.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.\n * - `surface: 'memory'` → `memoryCurationProposer` curates a bounded durable\n * lesson document supplied through `opts.memory`.\n * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete\n * canonical AgentProfile JSON in one candidate.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `agent-profile`} → no zero-config default\n * proposer exists (a code/config proposer needs caller-supplied wiring — a\n * worktree repo root, a candidate generator, a serializer). The facade\n * requires an explicit `opts.generator` for these and throws a `ConfigError`\n * otherwise. This is a designed boundary, not a missing default: there is\n * no safe value the facade could invent for those surfaces. Code instead\n * requires `opts.code.repoRoot` and accepts only the runtime-owned\n * `opts.code.generator` path so every isolated checkout can be released.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport { canonicalJson } from '@tangle-network/agent-eval'\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n memoryCurationProposer,\n skillOptProposer,\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 SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport { rethrowAfterCleanup } from './cleanup'\nimport {\n type CandidateGenerator,\n improvementDriver,\n type ManagedImprovementDriver,\n} from './improvement-driver'\nimport { rawTraceDistiller } from './raw-trace-distiller'\n\n/** The executable agent lever `improve` optimizes. Profile fields remain\n * portable AgentProfile coordinates; implementation and orchestration files\n * use the code surface so a winner can be sealed into an exact candidate. */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'subagents'\n | 'agent-profile'\n | 'memory'\n | 'code'\n\nexport type ImproveOptions<TScenario extends Scenario, TArtifact> = Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'analyzeGeneration' | 'baselineSurface' | 'findings' | 'gate' | 'proposer'\n> & {\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates a profile surface. When unset, the facade\n * picks the default for prompt, skills, and memory; surfaces\n * with no default REQUIRE this (fail-loud otherwise). Forbidden for code;\n * use `code.generator` so the runtime owns candidate cleanup. */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: the built-in failure distiller — after each generation it turns the\n * worst-scoring/errored cells into structured findings ({ scenario, composite,\n * notes, error }) for the NEXT proposal round, so the proposer reasons over what\n * actually failed instead of a static seed. Pass your own producer (e.g. a\n * trace-analyst over the runDir's traces) to replace it; pass `null` to disable\n * and keep the static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the ~1500-char distilled findings, feed the\n * proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Requires a REAL `runDir` (that is where the traces live).\n * Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`\n * (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag\n * is the one-line enable. Default `false` (the distiller stays the default). */\n rawTraceContext?: boolean\n /** CODE-surface wiring: name `surface: 'code'`, point at a repo, and the\n * facade assembles the whole candidate pipeline — an isolated incumbent plus git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Required for every code run because a real\n * repository and base ref are necessary to measure the incumbent. */\n code?: ImproveCodeOptions\n /** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,\n * `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)\n * — which `skillOptProposer` (a document patcher) cannot meaningfully edit.\n * Provide the document CONTENT to optimize + a `writeBack` to persist the\n * shipped winner (the profile ref points at a file the caller owns). This is\n * what makes skillOpt reachable through improve(). */\n skills?: ImproveSkillsOptions\n /** MEMORY-surface wiring for a curated durable memory document. The default\n * deterministic proposer deduplicates and ranks lessons from findings, then\n * replaces its managed block instead of growing memory without bound. */\n memory?: ImproveMemoryOptions\n /** Custom held-back-exam decision. The string `gate` above controls whether\n * the exam runs; this callback controls how its evidence decides promotion. */\n promotionGate?: SelfImproveOptions<TScenario, TArtifact>['gate']\n}\n\nexport interface ImproveSkillsOptions {\n /** The skill document's current text — the baseline `skillOptProposer` patches. */\n document: string\n /** Persist the shipped winner document (write the file the profile ref points at).\n * Called only on a ship verdict. When omitted, the winner is still returned in\n * `result.raw.winner.surface` for the caller to materialize. */\n writeBack?: (winnerDocument: string) => void | Promise<void>\n}\n\nexport interface ImproveMemoryOptions {\n /** Current durable memory text used as the measured baseline. */\n document: string\n /** Persist the promoted memory document. Never called on hold or error. */\n writeBack?: (winnerDocument: string) => void | Promise<void>\n}\n\nexport interface ImproveCodeOptions {\n /** Repo root candidate worktrees fork from. */\n repoRoot: string\n /** Base ref candidates fork from. Default `main`. */\n baseRef?: string\n /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Git-compatible adapter override, primarily for tests. Candidate advancement\n * still requires normal Git worktree and commit semantics. */\n worktree?: WorktreeAdapter\n /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** The profile after improvement: the winner surface applied back into the\n * matching field when the gate shipped, else the input profile unchanged. */\n profile: AgentProfile\n /** True when `gateDecision === 'ship'`. */\n shipped: boolean\n /** Held-out lift (`winner − baseline` composite). */\n lift: number\n /** The five-valued gate verdict from `selfImprove`. */\n gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Full `selfImprove` result for advanced inspection. For code runs,\n * `raw.winner.surface.worktreeRef` remains live after return whether the\n * candidate shipped or held; call `dispose()` after consuming it. */\n raw: SelfImproveResult<TScenario, TArtifact>\n /** Release resources owned by this result. Idempotent; currently disposes\n * the returned code worktree and is a no-op for profile-only surfaces. */\n dispose(): Promise<void>\n}\n\n/** Default model id for the reflective drivers when `llm.model` is unset — a model the Tangle\n * router actually serves (callers should pass their own `llm.model`). */\nconst defaultReflectionModel = 'deepseek-v4-flash'\n\n/** The reflective proposers (`gepaProposer`/`skillOptProposer`) take a full\n * `LlmClientOptions`; `SelfImproveLlm` is the thin user-facing subset. */\nfunction llmClientOptions(llm: SelfImproveLlm | undefined): { baseUrl?: string; apiKey?: string } {\n return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey }\n}\n\n/** The default proposer for a surface, or `undefined` when the surface has no\n * zero-config default (the caller must supply `opts.generator`). */\nfunction defaultGeneratorFor(\n surface: ImproveSurface,\n llm: SelfImproveLlm | undefined,\n): SurfaceProposer | undefined {\n const model = llm?.model ?? defaultReflectionModel\n switch (surface) {\n case 'prompt':\n return gepaProposer({ llm: llmClientOptions(llm), model, target: 'agent system prompt' })\n case 'skills':\n return skillOptProposer({ llm: llmClientOptions(llm), model, target: 'agent skill document' })\n case 'memory':\n return memoryCurationProposer()\n default:\n return undefined\n }\n}\n\n/** Extract the baseline surface a driver mutates from the profile field that\n * backs `surface`. Prompt, skills, and memory are text surfaces; config\n * surfaces serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n memory?: ImproveMemoryOptions,\n): MutableSurface {\n switch (surface) {\n case 'prompt':\n return profile.prompt?.systemPrompt ?? ''\n case 'skills':\n // With a document supplied, optimize its CONTENT (the real skillOpt path);\n // otherwise fall back to the refs-array surface for back-compat.\n return skills?.document ?? JSON.stringify(profile.resources?.skills ?? [])\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'subagents':\n return JSON.stringify(profile.subagents ?? {})\n case 'agent-profile':\n return canonicalJson(profile)\n case 'memory':\n if (!memory) {\n throw new ConfigError(\"improve(): surface 'memory' requires opts.memory.document\")\n }\n return memory.document\n case 'code':\n throw new ConfigError(\n 'improve(): code requires the isolated baseline created from opts.code.repoRoot',\n )\n }\n}\n\n/** Slice bound for distilled judge notes: wide enough that a real traceback /\n * failing-assertion note survives intact — clipping mid-traceback would leave\n * the proposer trace-blind. Referenced by the `rawTraceContext` docs. */\nconst DISTILLED_NOTES_MAX_CHARS = 1500\n\n/** Slice bound for a cell's error string — tighter than notes (errors are\n * usually one line; the full text stays on the raw cell). Also bounds the\n * error-derived `claim` fallback. */\nconst DISTILLED_ERROR_MAX_CHARS = 500\n\n/** The default `analyzeGeneration`: distill each generation's failing cells into\n * findings for the next proposal round. Deliberately dependency-free — judge notes\n * and errors are already the domain's own diagnosis (executable gates put their\n * reasons there); a trace-analyst can replace this wholesale via\n * `opts.analyzeGeneration`. Falls back to the static seed findings when the\n * generation had no failures, so a clean round never wipes the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\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, j) => sum + (j.composite ?? 0), 0) / judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((j) => j.notes)\n .filter((n): n is string => typeof n === 'string' && n.length > 0)\n .join('; ')\n .slice(0, DISTILLED_NOTES_MAX_CHARS)\n const claim =\n notes ||\n (error ? `Scenario ${scenario} failed: ${error.slice(0, DISTILLED_ERROR_MAX_CHARS)}` : '')\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(claim ? { claim } : {}),\n ...(error ? { error: error.slice(0, DISTILLED_ERROR_MAX_CHARS) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP)\n }\n}\n\n/** Memory accumulates durable lessons, so keep the caller's seed findings while\n * adding fresh judge failures. Curator proposers consume `claim`; the generic\n * distiller retains the richer diagnostic fields for reflective proposers. */\nfunction memoryGenerationDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const distillFailures = generationFailureDistiller<TScenario, TArtifact>(staticFindings)\n return async (input) => {\n const fresh = await distillFailures(input)\n return fresh === staticFindings ? staticFindings : [...staticFindings, ...fresh]\n }\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer\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\nfunction isCodeSurface(surface: MutableSurface | undefined): surface is CodeSurface {\n return typeof surface === 'object' && surface !== null && surface.kind === 'code'\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 baseRef = code.baseRef ?? 'main'\n const worktree =\n code.worktree ??\n gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: 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 =\n code.generator ??\n agenticGenerator({\n ...(code.harness ? { harness: code.harness } : {}),\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}),\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\n/** Parse a JSON winner surface (`tools`/`mcp`/`hooks`/`subagents`/`agent-profile`) with a typed,\n * contextual error. A malformed generator output must fail loud here, not throw\n * a raw `SyntaxError` to the caller after a ship verdict. */\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 shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\n/** Apply a promoted winner surface back into the profile field for `surface`.\n * Returns a shallow copy; never mutates the input profile. */\nexport function applyImprovementWinnerToProfile(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n): AgentProfile {\n // Only string surfaces map cleanly back onto a profile field. A `CodeSurface`\n // winner (the `code` lever) is a worktree ref, not a profile value — the\n // caller materializes it from `raw.winner.surface`; the returned profile is\n // unchanged for that lever.\n if (typeof winner !== 'string') return profile\n let candidate: AgentProfile\n switch (surface) {\n case 'prompt':\n candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n break\n case 'skills':\n candidate = {\n ...profile,\n resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) },\n }\n break\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 return profile\n case 'code':\n return profile\n }\n const parsed = agentProfileSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner does not produce a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n return parsed.data\n}\n\n/**\n * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.shipped) deploy(out.profile)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const {\n surface = 'prompt',\n gate = 'holdout',\n generator,\n allowedModels,\n rawTraceContext,\n code,\n skills,\n memory,\n promotionGate,\n analyzeGeneration,\n ...sharedOptions\n } = opts\n\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n if (surface === 'skills' && !generator && !skills) {\n throw new ConfigError(\n 'improve(): the default skills optimizer requires opts.skills.document; pass the skill text or an explicit generator that understands resource refs',\n )\n }\n if (surface === 'memory' && !memory) {\n throw new ConfigError(\"improve(): surface 'memory' requires opts.memory.document\")\n }\n if (surface === 'code' && generator) {\n throw new ConfigError(\n \"improve(): surface 'code' forbids opts.generator because an external SurfaceProposer cannot transfer checkout ownership; pass opts.code.generator instead\",\n )\n }\n const usesReflectionModel = !generator && (surface === 'prompt' || surface === 'skills')\n if (usesReflectionModel) {\n assertModelAllowed(sharedOptions.llm?.model ?? defaultReflectionModel, allowedModels)\n }\n\n let preparedCode: PreparedCodeRun | undefined\n if (surface === 'code') {\n if (!code) {\n throw new ConfigError(\n \"improve(): surface 'code' requires opts.code.repoRoot so the incumbent can run from an isolated checkout\",\n )\n }\n preparedCode = await prepareCodeRun(code)\n }\n const proposer =\n preparedCode?.proposer ?? generator ?? defaultGeneratorFor(surface, sharedOptions.llm)\n if (!proposer) {\n throw new ConfigError(\n `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n\n let raw: SelfImproveResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n baselineSurface:\n preparedCode?.baseline ?? baselineSurfaceFor(profile, surface, skills, memory),\n proposer,\n budget,\n findings,\n ...(promotionGate !== undefined ? { gate: promotionGate } : {}),\n ...(analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n analyzeGeneration ??\n (rawTraceContext\n ? rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n : surface === 'memory'\n ? memoryGenerationDistiller<TScenario, TArtifact>(findings)\n : generationFailureDistiller<TScenario, TArtifact>(findings)),\n }),\n })\n } catch (cause) {\n if (!preparedCode) throw cause\n return rethrowAfterCleanup(\n cause,\n () => preparedCode.cleanup(),\n 'improve(): code improvement failed',\n )\n }\n\n const shipped = raw.gateDecision === 'ship'\n const winnerSurface = raw.winner.surface\n if (preparedCode) {\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 }\n const dispose = idempotentDispose(async () => preparedCode?.cleanup())\n // When a skill DOCUMENT was optimized, the winner is document text — persist it\n // via writeBack (the profile ref points at the caller's file, unchanged) rather\n // than parsing it as a refs array. Otherwise use the standard field write-back.\n const externalDocument =\n surface === 'skills' && skills ? skills : surface === 'memory' && memory ? memory : undefined\n if (shipped && externalDocument) {\n if (typeof winnerSurface !== 'string') {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner must be text before it can be persisted`,\n )\n }\n await externalDocument.writeBack?.(winnerSurface)\n }\n const nextProfile =\n shipped && !externalDocument\n ? applyImprovementWinnerToProfile(profile, surface, winnerSurface)\n : profile\n\n return {\n profile: nextProfile,\n shipped,\n lift: raw.lift,\n gateDecision: raw.gateDecision,\n raw,\n dispose,\n }\n}\n","import { type AnalystFinding, assertNoJudgeVerdict } from '@tangle-network/agent-eval/analyst'\nimport {\n type CandidateExperimentExecutionInput,\n type CompareCandidateExperimentOptions,\n measuredComparisonFromCandidateExperiment,\n runCandidateExperiment,\n type Scenario,\n verifyCandidateExperiment,\n verifyCandidateExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateBenchmarkCellRef,\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentCandidateExperimentMeasurement,\n AgentCandidateRunCell,\n AgentImprovementActivation,\n AgentImprovementActivationTarget,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n AgentImprovementSurface,\n AgentProfile,\n CandidateExecutionEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateMaterializationReceiptSchema,\n agentCandidateRunReceiptSchema,\n agentImprovementActivationSchema,\n agentImprovementProposalSchema,\n agentImprovementReviewSchema,\n candidateExecutionEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { materializeCandidateProfile } from '@tangle-network/agent-profile-materialize'\n\nimport { runAnalystLoop } from '../analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from '../analyst-loop/types'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n type ExecutePreparedAgentCandidateOptions,\n executePreparedAgentCandidate,\n} from '../candidate-execution/execute'\nimport {\n type PrepareAgentCandidateExecutionOptions,\n prepareAgentCandidateExecution,\n} from '../candidate-execution/prepare'\nimport {\n agentCandidateProfileAsAgentProfile,\n candidateMaterializerHarness,\n createAgentCandidateProfileActivation,\n parseAgentCandidateProfileActivation,\n} from '../candidate-execution/profile'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateRunFinalization,\n AgentCandidateTaskExecution,\n} from '../candidate-execution/types'\nimport {\n verifiedResourceTextByDigest,\n verifyAgentCandidateBundle,\n} from '../candidate-execution/verify'\nimport { rethrowAfterCleanup } from '../improvement/cleanup'\nimport { type ImproveOptions, type ImproveResult, improve } from '../improvement/improve'\n\nexport type {\n AgentImprovementActivation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n CandidateExecutionEvidence,\n} from '@tangle-network/agent-interface'\n\nexport interface AgentCandidateExperimentCellPlacement {\n executionId: string\n attempt?: number\n executionRoots: AgentCandidateTaskExecution['executionRoots']\n stagingRoots: AgentCandidateTaskExecution['stagingRoots']\n ports: AgentCandidateExecutionPorts\n preparation?: PrepareAgentCandidateExecutionOptions\n execution: ExecutePreparedAgentCandidateOptions\n}\n\nexport interface RunAgentCandidateExperimentOptions\n extends Omit<CompareCandidateExperimentOptions, 'experiment' | 'measurements'> {\n experiment: AgentCandidateExperiment\n placeCell: (\n input: CandidateExperimentExecutionInput,\n ) => AgentCandidateExperimentCellPlacement | Promise<AgentCandidateExperimentCellPlacement>\n maxConcurrency?: number\n signal?: AbortSignal\n}\n\nexport interface RunAgentCandidateExperimentResult {\n experiment: AgentCandidateExperiment\n measurements: AgentCandidateExperimentMeasurement[]\n evaluation: AgentImprovementMeasuredComparison\n}\n\nexport interface ExecuteAgentCandidateExperimentCellOptions\n extends CandidateExperimentExecutionInput,\n AgentCandidateExperimentCellPlacement {}\n\nexport interface VerifyCandidateExecutionEvidenceOptions {\n experiment: AgentCandidateExperiment\n arm: 'baseline' | 'candidate'\n benchmarkCell: AgentCandidateBenchmarkCellRef\n seed: number\n attempt?: number\n resolvedResources?: ReadonlyMap<Sha256Digest, string>\n}\n\n/** A failed baseline or candidate cell with its complete Runtime failure result. */\nexport class AgentCandidateExperimentCellExecutionError extends Error {\n readonly finalization: Extract<AgentCandidateRunFinalization, { succeeded: false }>\n\n constructor(finalization: Extract<AgentCandidateRunFinalization, { succeeded: false }>) {\n super(`candidate experiment cell failed: ${finalization.reason}`)\n this.name = 'AgentCandidateExperimentCellExecutionError'\n this.finalization = finalization\n }\n}\n\nexport interface CreateAgentImprovementProposalOptions {\n runId: string\n findings: readonly AnalystFinding[]\n evaluation: AgentImprovementMeasuredComparison\n now?: () => Date\n}\n\nexport type CreateAgentImprovementMeasuredComparisonOptions = CompareCandidateExperimentOptions\n\nexport interface ReviewAgentImprovementInput {\n decision: AgentImprovementReviewDecision\n reviewedBy: string\n reason: string\n feedback?: string\n now?: () => Date\n}\n\nexport interface CreateAgentImprovementActivationOptions {\n targets: [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]]\n fundingOwner: string\n authorizedBy: string\n now?: () => Date\n}\n\nexport interface ProposeAgentImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n profile: AgentProfile\n analysis: Omit<RunAnalystLoopOpts, 'runId' | 'improvementAdapter' | 'autoApply'>\n improvement: ImproveOptions<TScenario, TArtifact>\n buildExperiment: (input: {\n analysis: RunAnalystLoopResult\n improvement: ImproveResult<TScenario, TArtifact>\n }) => AgentCandidateExperiment | Promise<AgentCandidateExperiment>\n placeCell: RunAgentCandidateExperimentOptions['placeCell']\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentImprovementMeasuredComparison['candidate']\n metadata?: AgentImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\nexport interface ProposeAgentImprovementResult<TScenario extends Scenario, TArtifact> {\n analysis: RunAnalystLoopResult\n improvement: ImproveResult<TScenario, TArtifact>\n experiment: AgentCandidateExperiment\n measurements: AgentCandidateExperimentMeasurement[]\n proposal: AgentImprovementProposal\n}\n\ntype AnalystImprovementProposal = Omit<AgentImprovementProposal, 'findings'> & {\n findings: AnalystFinding[]\n}\n\n/** Execute both arms of one immutable experiment and derive its paired result. */\nexport async function runAgentCandidateExperiment(\n options: RunAgentCandidateExperimentOptions,\n): Promise<RunAgentCandidateExperimentResult> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const measurements = await runCandidateExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const placement = await options.placeCell(input)\n return await executeAgentCandidateExperimentCell({ ...input, ...placement })\n },\n })\n const evaluation = createAgentImprovementMeasuredComparison({\n experiment,\n measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n ...(options.generationsExplored === undefined\n ? {}\n : { generationsExplored: options.generationsExplored }),\n ...(options.searchDurationMs === undefined\n ? {}\n : { searchDurationMs: options.searchDurationMs }),\n ...(options.searchCostUsd === undefined ? {} : { searchCostUsd: options.searchCostUsd }),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n return { experiment, measurements, evaluation }\n}\n\n/** Execute one exact arm, task, repetition, seed, and attempt through Runtime. */\nexport async function executeAgentCandidateExperimentCell(\n options: ExecuteAgentCandidateExperimentCellOptions,\n): Promise<CandidateExecutionEvidence> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const bundle = experiment[options.arm]\n assertExactExperimentInput(options, experiment, bundle)\n const attempt = options.attempt ?? 1\n if (attempt > options.task.attempt.maxAttempts) {\n throw new Error('candidate experiment attempt exceeds the signed task policy')\n }\n const runCell = canonicalCandidateDocument<AgentCandidateRunCell>({\n kind: 'agent-candidate-run-cell',\n experimentDigest: experiment.digest,\n arm: options.arm,\n bundleDigest: bundle.digest,\n suiteDigest: options.benchmarkCell.suiteDigest,\n taskDigest: options.task.digest,\n taskIndex: options.benchmarkCell.taskIndex,\n repetition: options.benchmarkCell.repetition,\n seed: options.seed,\n attempt,\n }).value\n const verified = await verifyAgentCandidateBundle(bundle, options.ports)\n const prepared = await prepareAgentCandidateExecution(\n verified,\n {\n executionId: options.executionId,\n runCell,\n benchmarkSuite: experiment.benchmark.suite,\n task: options.task,\n executionRoots: options.executionRoots,\n stagingRoots: options.stagingRoots,\n },\n options.ports,\n options.preparation,\n )\n const finalization = await executePreparedAgentCandidate(prepared, options.execution)\n if (!finalization.succeeded) {\n throw new AgentCandidateExperimentCellExecutionError(finalization)\n }\n const evidence = canonicalCandidateDocument<CandidateExecutionEvidence>({\n kind: 'agent-candidate-execution-evidence',\n materializationReceipt: prepared.materializationReceipt.value,\n receipt: finalization.receipt.value,\n }).value\n return verifyCandidateExecutionEvidence(evidence, {\n experiment,\n arm: options.arm,\n benchmarkCell: options.benchmarkCell,\n seed: options.seed,\n attempt,\n resolvedResources: verifiedResourceTextByDigest(verified),\n })\n}\n\n/** Delegate all statistics and promotion checks to agent-eval's receipt-based comparison. */\nexport function createAgentImprovementMeasuredComparison(\n options: CreateAgentImprovementMeasuredComparisonOptions,\n): AgentImprovementMeasuredComparison {\n return verifyCandidateExperimentComparison(measuredComparisonFromCandidateExperiment(options))\n}\n\n/** Analyze, search, then remeasure the resulting exact candidate before proposing it. */\nexport async function proposeAgentImprovement<TScenario extends Scenario, TArtifact>(\n options: ProposeAgentImprovementOptions<TScenario, TArtifact>,\n): Promise<ProposeAgentImprovementResult<TScenario, TArtifact>> {\n const writeBackSurface = options.improvement.skills?.writeBack\n ? 'skill'\n : options.improvement.memory?.writeBack\n ? 'memory'\n : null\n if (writeBackSurface) {\n throw new Error(`proposeAgentImprovement cannot write ${writeBackSurface} before approval`)\n }\n const analysis = await runAnalystLoop({ ...options.analysis, runId: options.runId })\n const findings = assertNoJudgeVerdict(\n analysis.analystResult.findings,\n 'proposeAgentImprovement findings',\n )\n const improvement = await improve(options.profile, [...findings], options.improvement)\n try {\n if (!improvement.shipped) {\n throw new Error('agent improvement search did not produce a promotable candidate')\n }\n const experiment = verifyCandidateExperiment(\n await options.buildExperiment({ analysis, improvement }),\n )\n if (\n canonicalCandidateDigest(experiment.baseline.profile) !==\n canonicalCandidateDigest(options.profile)\n ) {\n throw new Error('candidate experiment baseline does not match the analyzed agent profile')\n }\n const measured = await runAgentCandidateExperiment({\n experiment,\n runId: options.runId,\n placeCell: options.placeCell,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.candidate ? { candidate: options.candidate } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n generationsExplored: improvement.raw.generationsExplored,\n searchDurationMs: improvement.raw.durationMs,\n searchCostUsd: improvement.raw.totalCostUsd,\n })\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings,\n evaluation: measured.evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return {\n analysis,\n improvement,\n experiment,\n measurements: measured.measurements,\n proposal,\n }\n } catch (cause) {\n return rethrowAfterCleanup(cause, () => improvement.dispose(), 'proposeAgentImprovement failed')\n }\n}\n\n/** Create the reviewable record only from a complete, recomputable experiment result. */\nexport function createAgentImprovementProposal(\n options: CreateAgentImprovementProposalOptions,\n): AgentImprovementProposal {\n const findings = assertNoJudgeVerdict(\n [...options.findings],\n 'createAgentImprovementProposal findings',\n )\n const evaluation = verifyCandidateExperimentComparison(options.evaluation)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error('agent improvement proposal requires a passing experiment')\n }\n if (options.runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces = deriveChangedSurfaces(\n evaluation.experiment.baseline,\n evaluation.experiment.candidate,\n )\n return agentImprovementProposalSchema.parse(\n canonicalCandidateDocument<AnalystImprovementProposal>({\n kind: 'agent-improvement-proposal',\n runId: options.runId,\n changedSurfaces,\n proposedAt: (options.now ?? (() => new Date()))().toISOString(),\n findings: [...findings],\n evaluation,\n }).value,\n )\n}\n\n/** Persist a human or tenant-policy decision bound to one exact proposal. */\nexport function reviewAgentImprovementProposal(\n inputProposal: AgentImprovementProposal,\n input: ReviewAgentImprovementInput,\n): AgentImprovementReview {\n const proposal = verifyAgentImprovementProposal(inputProposal)\n if (!input.reviewedBy.trim()) throw new Error('candidate review requires reviewedBy')\n if (!input.reason.trim()) throw new Error('candidate review requires a reason')\n if (input.decision === 'approve' && proposal.evaluation.decision.outcome !== 'ship') {\n throw new Error('candidate cannot be approved without a passing experiment')\n }\n return agentImprovementReviewSchema.parse(\n canonicalCandidateDocument<AgentImprovementReview>({\n kind: 'agent-improvement-review',\n proposalDigest: proposal.digest,\n decision: input.decision,\n reviewedBy: input.reviewedBy,\n reviewedAt: (input.now ?? (() => new Date()))().toISOString(),\n reason: input.reason,\n ...(input.feedback === undefined ? {} : { feedback: input.feedback }),\n }).value,\n )\n}\n\n/** Authorize product-owned writes only after the exact candidate was measured and approved. */\nexport function createAgentImprovementActivation(\n inputProposal: AgentImprovementProposal,\n inputReview: AgentImprovementReview,\n options: CreateAgentImprovementActivationOptions,\n): AgentImprovementActivation {\n const proposal = verifyAgentImprovementProposal(inputProposal)\n const review = verifyAgentImprovementReview(inputReview)\n if (review.decision !== 'approve' || review.proposalDigest !== proposal.digest) {\n throw new Error('candidate activation requires an approval for the exact proposal')\n }\n if (!options.fundingOwner.trim() || !options.authorizedBy.trim()) {\n throw new Error('candidate activation authority must be non-empty')\n }\n const experiment = proposal.evaluation.experiment\n assertActivationTargets(proposal.changedSurfaces, experiment, options.targets)\n return agentImprovementActivationSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivation>({\n kind: 'agent-improvement-activation',\n proposalDigest: proposal.digest,\n reviewDigest: review.digest,\n experimentDigest: experiment.digest,\n candidateBundleDigest: experiment.candidate.digest,\n targets: options.targets,\n fundingOwner: options.fundingOwner,\n authorizedBy: options.authorizedBy,\n authorizedAt: (options.now ?? (() => new Date()))().toISOString(),\n }).value,\n )\n}\n\n/** Validate a proposal and recompute every binding to its measured experiment. */\nexport function verifyAgentImprovementProposal(input: unknown): AgentImprovementProposal {\n const proposal = verifyCanonicalCandidateDocument(\n agentImprovementProposalSchema.parse(input),\n 'agent improvement proposal',\n )\n const evaluation = verifyCandidateExperimentComparison(proposal.evaluation)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error('agent improvement proposal does not contain a passing experiment')\n }\n if (proposal.runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces = deriveChangedSurfaces(\n evaluation.experiment.baseline,\n evaluation.experiment.candidate,\n )\n if (!sameOrderedValues(proposal.changedSurfaces, changedSurfaces)) {\n throw new Error('proposal changed surfaces do not match its exact experiment')\n }\n assertNoJudgeDerivedProposalFindings(proposal.findings)\n return proposal\n}\n\n/** Validate the canonical identity and wire shape of an improvement review. */\nexport function verifyAgentImprovementReview(input: unknown): AgentImprovementReview {\n return verifyCanonicalCandidateDocument(\n agentImprovementReviewSchema.parse(input),\n 'agent improvement review',\n )\n}\n\n/** Validate activation authority against the exact proposal, review, experiment, and base state. */\nexport function verifyAgentImprovementActivation(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n}): AgentImprovementActivation {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const review = verifyAgentImprovementReview(input.review)\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(input.activation),\n 'agent improvement activation',\n )\n const experiment = proposal.evaluation.experiment\n if (\n review.decision !== 'approve' ||\n review.proposalDigest !== proposal.digest ||\n activation.proposalDigest !== proposal.digest ||\n activation.reviewDigest !== review.digest ||\n activation.experimentDigest !== experiment.digest ||\n activation.candidateBundleDigest !== experiment.candidate.digest\n ) {\n throw new Error('candidate activation does not bind the measured and approved candidate')\n }\n assertActivationTargets(proposal.changedSurfaces, experiment, activation.targets)\n return activation\n}\n\n/** Recheck one Runtime receipt against its exact signed experiment cell. */\nexport function verifyCandidateExecutionEvidence(\n input: unknown,\n options: VerifyCandidateExecutionEvidenceOptions,\n): CandidateExecutionEvidence {\n const experiment = verifyCandidateExperiment(options.experiment)\n const bundle = experiment[options.arm]\n const task = experiment.benchmark.tasks[options.benchmarkCell.taskIndex]\n const index =\n options.benchmarkCell.taskIndex * experiment.benchmark.suite.reps +\n options.benchmarkCell.repetition\n if (\n !task ||\n options.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest ||\n options.seed !== experiment.benchmark.suite.seeds[index]\n ) {\n throw new Error('candidate execution evidence points outside its signed experiment')\n }\n const evidence = verifyCanonicalCandidateDocument(\n candidateExecutionEvidenceSchema.parse(input),\n 'candidate execution evidence',\n )\n const materialization = verifyCanonicalCandidateDocument(\n agentCandidateMaterializationReceiptSchema.parse(evidence.materializationReceipt),\n 'candidate materialization receipt',\n )\n const receipt = verifyCanonicalCandidateDocument(\n agentCandidateRunReceiptSchema.parse(evidence.receipt),\n 'candidate run receipt',\n )\n const plan = materialization.executionPlan\n const cell = plan.material.runCell\n const attempt = options.attempt ?? 1\n if (\n cell.experimentDigest !== experiment.digest ||\n cell.arm !== options.arm ||\n cell.bundleDigest !== bundle.digest ||\n cell.suiteDigest !== experiment.benchmark.suite.digest ||\n cell.taskDigest !== task.digest ||\n cell.taskIndex !== options.benchmarkCell.taskIndex ||\n cell.repetition !== options.benchmarkCell.repetition ||\n cell.seed !== options.seed ||\n cell.attempt !== attempt ||\n canonicalCandidateDigest(omitTopLevelDigest(cell)) !== cell.digest\n ) {\n throw new Error('candidate execution receipt substituted its signed experiment cell')\n }\n assertCapturedInput(\n materialization.benchmark.suite,\n experiment.benchmark.suite,\n 'benchmark suite',\n )\n assertCapturedInput(materialization.benchmark.task, task, 'benchmark task')\n assertEvidenceMaterialDigest(plan, 'candidate execution plan')\n assertEvidenceMaterialDigest(\n materialization.profileActivation.profilePlan,\n 'candidate profile plan',\n )\n const expectedProfilePlan = materializeCandidateProfile(\n bundle.profile,\n candidateMaterializerHarness(materialization.harness),\n { resolvedResources: options.resolvedResources },\n )\n const activation = parseAgentCandidateProfileActivation(\n materialization.profileActivation,\n materialization.profileActivation.profilePlan.digest,\n )\n const regeneratedActivation = createAgentCandidateProfileActivation(\n expectedProfilePlan,\n materialization.profileActivation.profilePlan,\n )\n if (activation.digest !== regeneratedActivation.digest) {\n throw new Error('candidate profile activation does not match the experiment bundle')\n }\n if (\n materialization.bundleDigest !== bundle.digest ||\n receipt.bundleDigest !== bundle.digest ||\n receipt.runCellDigest !== cell.digest ||\n receipt.materializationReceiptDigest !== materialization.digest ||\n receipt.executionPlanDigest !== plan.digest\n ) {\n throw new Error('candidate execution evidence does not bind one exact Runtime run')\n }\n assertEvidenceMaterialDigest(receipt.modelSettlement, 'candidate model settlement')\n assertEvidenceMaterialDigest(receipt.taskOutcome, 'candidate task outcome')\n assertEvidenceMaterialDigest(receipt.benchmarkResult, 'candidate benchmark result')\n return immutableCandidateValue(evidence)\n}\n\nfunction assertExactExperimentInput(\n input: CandidateExperimentExecutionInput,\n experiment: AgentCandidateExperiment,\n bundle: AgentCandidateBundle,\n): void {\n const task = experiment.benchmark.tasks[input.benchmarkCell.taskIndex]\n const index =\n input.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + input.benchmarkCell.repetition\n if (\n input.experiment.digest !== experiment.digest ||\n input.bundle.digest !== bundle.digest ||\n !task ||\n input.task.digest !== task.digest ||\n input.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest ||\n input.seed !== experiment.benchmark.suite.seeds[index]\n ) {\n throw new Error('Runtime received a substituted candidate experiment cell')\n }\n}\n\nfunction assertCapturedInput(\n captured: { digest: Sha256Digest; material: { sha256: Sha256Digest; byteLength: number } },\n expected: { digest: Sha256Digest },\n label: string,\n): void {\n const bytes = canonicalCandidateBytes(omitTopLevelDigest(expected))\n if (\n captured.digest !== expected.digest ||\n captured.material.sha256 !== expected.digest ||\n captured.material.byteLength !== bytes.byteLength\n ) {\n throw new Error(`candidate materialization substituted its ${label}`)\n }\n}\n\nfunction assertEvidenceMaterialDigest(\n evidence: {\n digest: Sha256Digest\n material: unknown\n artifact: { sha256: Sha256Digest; byteLength: number }\n },\n label: string,\n): void {\n const bytes = canonicalCandidateBytes(evidence.material)\n if (\n canonicalCandidateDigest(evidence.material) !== evidence.digest ||\n evidence.artifact.sha256 !== evidence.digest ||\n evidence.artifact.byteLength !== bytes.byteLength\n ) {\n throw new Error(`${label} digest does not match its canonical material`)\n }\n}\n\nconst CHANGED_SURFACE_ORDER: readonly AgentImprovementSurface[] = [\n 'prompt',\n 'skills',\n 'tools',\n 'mcp',\n 'hooks',\n 'subagents',\n 'agent-profile',\n 'memory',\n 'code',\n 'knowledge',\n]\n\nfunction deriveChangedSurfaces(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n const baseline = improvementSurfaceValues(baselineBundle)\n const candidate = improvementSurfaceValues(candidateBundle)\n const changed = new Set<AgentImprovementSurface>()\n for (const surface of CHANGED_SURFACE_ORDER) {\n if (\n canonicalCandidateDigest(baseline[surface]) !== canonicalCandidateDigest(candidate[surface])\n ) {\n changed.add(surface)\n }\n }\n const ordered = CHANGED_SURFACE_ORDER.filter((surface) => changed.has(surface))\n if (ordered.length === 0) throw new Error('candidate experiment does not change an agent surface')\n return ordered as [AgentImprovementSurface, ...AgentImprovementSurface[]]\n}\n\nfunction improvementSurfaceValues(\n bundle: AgentCandidateBundle,\n): Record<AgentImprovementSurface, unknown> {\n const profile = agentCandidateProfileAsAgentProfile(bundle.profile)\n return {\n prompt: {\n prompt: profile.prompt ?? null,\n instructions: profile.resources?.instructions ?? null,\n },\n skills: profile.resources?.skills ?? null,\n tools: {\n tools: profile.tools ?? null,\n resources: profile.resources?.tools ?? null,\n },\n mcp: profile.mcp ?? null,\n hooks: profile.hooks ?? null,\n subagents: {\n subagents: profile.subagents ?? null,\n resources: profile.resources?.agents ?? null,\n },\n 'agent-profile': { profile: opaqueProfileSlice(profile), execution: bundle.execution },\n memory: bundle.memory,\n code: bundle.code,\n knowledge: bundle.knowledge ?? null,\n }\n}\n\nfunction opaqueProfileSlice(profile: AgentProfile): unknown {\n const {\n prompt: _prompt,\n tools: _tools,\n mcp: _mcp,\n hooks: _hooks,\n subagents: _subagents,\n resources,\n ...opaqueProfile\n } = profile\n const {\n instructions: _instructions,\n skills: _skills,\n tools: _resourceTools,\n agents: _agents,\n ...opaqueResources\n } = resources ?? {}\n return {\n ...opaqueProfile,\n ...(Object.keys(opaqueResources).length > 0 ? { resources: opaqueResources } : {}),\n }\n}\n\nfunction assertActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentCandidateExperiment,\n targets: readonly AgentImprovementActivationTarget[],\n): void {\n const expected = new Set(surfaces)\n const actual = new Set(targets.map((target) => target.surface))\n const baselineValues = improvementSurfaceValues(experiment.baseline)\n if (\n targets.some((target) => !target.identity.trim()) ||\n targets.some(\n (target) =>\n target.expectedBaseDigest !==\n expectedActivationBaseDigest(experiment, target.surface, baselineValues),\n ) ||\n expected.size !== actual.size ||\n [...expected].some((surface) => !actual.has(surface))\n ) {\n throw new Error('candidate activation targets must cover exactly the changed surfaces')\n }\n}\n\nfunction expectedActivationBaseDigest(\n experiment: AgentCandidateExperiment,\n surface: AgentImprovementSurface,\n baselineValues: Record<AgentImprovementSurface, unknown>,\n): Sha256Digest {\n if (surface === 'knowledge' && experiment.candidate.knowledge) {\n return experiment.candidate.knowledge.candidate.baseHash\n }\n return canonicalCandidateDigest(baselineValues[surface])\n}\n\nfunction sameOrderedValues<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction assertNoJudgeDerivedProposalFindings(\n findings: AgentImprovementProposal['findings'],\n): void {\n const leaked = findings.filter((finding) => finding.derived_from_judge === true)\n if (leaked.length === 0) return\n const identifiers = leaked.map((finding) =>\n typeof finding.finding_id === 'string' ? finding.finding_id : '<unknown>',\n )\n throw new Error(\n 'agent improvement proposal findings: judge-derived findings cannot steer an improvement: ' +\n `[${identifiers.join(', ')}]`,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,iBAAiB;AAE1B;AAAA,EAKE;AAAA,OAGK;;;AChCP,eAAsB,oBACpB,OACA,SACA,SACgB;AAChB,QAAM,gBAA2B,CAAC;AAClC,WAAS,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;AAC/C,QAAI;AACF,YAAM,QAAQ;AAAA,IAChB,SAAS,cAAc;AACrB,oBAAc,KAAK,YAAY;AAC/B;AAAA,IACF;AACA,QAAI,cAAc,WAAW,EAAG,OAAM;AACtC,UAAM,IAAI,eAAe,CAAC,OAAO,GAAG,aAAa,GAAG,GAAG,OAAO,2BAA2B;AAAA,EAC3F;AACA,QAAM,IAAI,eAAe,CAAC,OAAO,GAAG,aAAa,GAAG,GAAG,OAAO,kBAAkB;AAClF;;;ADwEO,SAAS,kBAAkB,MAA0D;AAC1F,QAAM,UAAU,KAAK,WAAW;AAChC,QAAM,QAAQ,oBAAI,IAAsB;AAExC,SAAO;AAAA,IACL,MAAM,eAAe,KAAK,UAAU,IAAI;AAAA,IACxC,MAAM,QAAQ,KAAqC;AACjD,YAAM,WAAW,gBAAgB,GAAG;AAQpC,UACE,SAA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ACA,SACA,gBACc;AACd,MAAI,YAAY,eAAe,WAAW,UAAU,WAAW;AAC7D,WAAO,WAAW,UAAU,UAAU,UAAU;AAAA,EAClD;AACA,SAAO,yBAAyB,eAAe,OAAO,CAAC;AACzD;AAEA,SAAS,kBAAqB,MAAoB,OAA8B;AAC9E,SAAO,KAAK,WAAW,MAAM,UAAU,KAAK,MAAM,CAAC,OAAO,UAAU,UAAU,MAAM,KAAK,CAAC;AAC5F;AAEA,SAAS,qCACP,UACM;AACN,QAAM,SAAS,SAAS,OAAO,CAAC,YAAY,QAAQ,uBAAuB,IAAI;AAC/E,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,cAAc,OAAO;AAAA,IAAI,CAAC,YAC9B,OAAO,QAAQ,eAAe,WAAW,QAAQ,aAAa;AAAA,EAChE;AACA,QAAM,IAAI;AAAA,IACR,6FACM,YAAY,KAAK,IAAI,CAAC;AAAA,EAC9B;AACF;","names":[]}
@@ -9,11 +9,11 @@ import {
9
9
  InMemoryResultBlobStore,
10
10
  InMemorySpawnJournal,
11
11
  contentAddress
12
- } from "./chunk-WIPGQ4GT.js";
12
+ } from "./chunk-IMSNJSXH.js";
13
13
  import {
14
14
  providerAsExecutor,
15
15
  resolveAgentEnvironmentProvider
16
- } from "./chunk-VSWBYWFK.js";
16
+ } from "./chunk-M6MD6JBS.js";
17
17
  import {
18
18
  addTokenUsage,
19
19
  deleteBoxSafe,
@@ -2030,6 +2030,7 @@ async function runWorktreeHarness(opts) {
2030
2030
  });
2031
2031
  try {
2032
2032
  assertSupportedWorktreeProfile(opts.profile, opts.harness);
2033
+ assertSafeProfileResourcePaths(opts.profile);
2033
2034
  const resourceInstructions = resolveResourceInstructions(opts.profile);
2034
2035
  const workspaceProfile = materializationOnlyProfile(opts.profile);
2035
2036
  const plan = materializeProfile(workspaceProfile, opts.harness);
@@ -2039,7 +2040,7 @@ async function runWorktreeHarness(opts) {
2039
2040
  );
2040
2041
  }
2041
2042
  assertSafeMaterializedPaths(plan);
2042
- const applied = applyWorkspacePlan(plan, worktree.path);
2043
+ const applied = applyWorkspacePlan(plan, worktree.path, { existingFiles: "reject" });
2043
2044
  if (applied.unsupported.length > 0) {
2044
2045
  throw new Error("runWorktreeHarness: applied profile unexpectedly retained unsupported rows");
2045
2046
  }
@@ -2222,6 +2223,15 @@ function assertSafeMaterializedPaths(plan) {
2222
2223
  }
2223
2224
  }
2224
2225
  }
2226
+ function assertSafeProfileResourcePaths(profile) {
2227
+ for (const file of profile.resources?.files ?? []) {
2228
+ if (file.path.split("/").some(isGitMetadataSegment)) {
2229
+ throw new Error(
2230
+ `runWorktreeHarness: profile file cannot target reserved Git metadata: ${file.path}`
2231
+ );
2232
+ }
2233
+ }
2234
+ }
2225
2235
  function isGitMetadataSegment(segment) {
2226
2236
  const windowsCanonical = segment.replace(/[ .]+$/u, "").toLowerCase();
2227
2237
  return windowsCanonical === ".git" || windowsCanonical.startsWith(".git:");
@@ -6826,4 +6836,4 @@ export {
6826
6836
  workerFromBackend,
6827
6837
  supervise
6828
6838
  };
6829
- //# sourceMappingURL=chunk-C3UKLQ54.js.map
6839
+ //# sourceMappingURL=chunk-IADLKE7I.js.map