@tangle-network/agent-runtime 0.134.9 → 0.135.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +80 -538
  2. package/dist/{activation-CAexDnXt.js → activation-n_QCjFyg.js} +2 -2
  3. package/dist/{activation-CAexDnXt.js.map → activation-n_QCjFyg.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/analyst-loop.d.ts +1 -1
  7. package/dist/{authoring-DHVHhbJO.js → authoring-Cl5xwuKl.js} +2 -2
  8. package/dist/{authoring-DHVHhbJO.js.map → authoring-Cl5xwuKl.js.map} +1 -1
  9. package/dist/conversation.d.ts +1 -1
  10. package/dist/{environment-provider-BIZMHOQw.d.ts → environment-provider-DA8LqBV-.d.ts} +3 -3
  11. package/dist/environment-provider.d.ts +1 -1
  12. package/dist/{graph-BWsEZmDL.js → graph-NKOjYL1z.js} +12 -8
  13. package/dist/graph-NKOjYL1z.js.map +1 -0
  14. package/dist/{improvement-cycle-DN0QhoCi.js → improvement-cycle-B8KrGlT4.js} +3 -3
  15. package/dist/{improvement-cycle-DN0QhoCi.js.map → improvement-cycle-B8KrGlT4.js.map} +1 -1
  16. package/dist/{index-RYbM0cUo.d.ts → index-CETQJlqT.d.ts} +3 -3
  17. package/dist/{index-DC7CNU9n.d.ts → index-CP1RvdOw.d.ts} +4 -4
  18. package/dist/{index-CRauzLFH.d.ts → index-DjPLpg7-.d.ts} +47 -9
  19. package/dist/index.d.ts +9 -9
  20. package/dist/index.js +7 -7
  21. package/dist/intelligence.d.ts +5 -5
  22. package/dist/intelligence.js +3 -3
  23. package/dist/kernel.d.ts +7 -7
  24. package/dist/kernel.js +7 -7
  25. package/dist/{knowledge-DDhcxfdu.js → knowledge-_7FWqPwl.js} +3 -3
  26. package/dist/{knowledge-DDhcxfdu.js.map → knowledge-_7FWqPwl.js.map} +1 -1
  27. package/dist/knowledge.d.ts +1 -1
  28. package/dist/knowledge.js +1 -1
  29. package/dist/{loop-runner-bin-bnDuiEQU.js → loop-runner-bin-CnlVnCM1.js} +3 -3
  30. package/dist/{loop-runner-bin-bnDuiEQU.js.map → loop-runner-bin-CnlVnCM1.js.map} +1 -1
  31. package/dist/{loop-runner-bin-Yp4T-tUJ.d.ts → loop-runner-bin-DndNkp6D.d.ts} +3 -3
  32. package/dist/loop-runner-bin.d.ts +1 -1
  33. package/dist/loop-runner-bin.js +1 -1
  34. package/dist/mcp/bin.js +3 -3
  35. package/dist/mcp/index.d.ts +5 -5
  36. package/dist/mcp/index.js +4 -4
  37. package/dist/{openai-tools-BulrPqjW.d.ts → openai-tools-DU3TZvFY.d.ts} +2 -2
  38. package/dist/{openai-tools-ne97uXo0.js → openai-tools-o7jw10Fn.js} +2 -2
  39. package/dist/{openai-tools-ne97uXo0.js.map → openai-tools-o7jw10Fn.js.map} +1 -1
  40. package/dist/primeintellect/index.d.ts +1 -1
  41. package/dist/profiles.d.ts +1 -1
  42. package/dist/{redact-Bojh05mQ.d.ts → redact--KfuCwwo.d.ts} +3 -3
  43. package/dist/{runtime-CwY043ZD.js → runtime-BQTE0RJS.js} +6 -6
  44. package/dist/{runtime-CwY043ZD.js.map → runtime-BQTE0RJS.js.map} +1 -1
  45. package/dist/{runtime-DHrzFy2v.d.ts → runtime-WugWo__W.d.ts} +4 -4
  46. package/dist/{stream-agent-turn-BEv31Log.d.ts → stream-agent-turn-DhPlvHwp.d.ts} +3 -3
  47. package/dist/{structural-rollout-BMnPPcJP.js → structural-rollout-keBf4YEc.js} +2 -2
  48. package/dist/{structural-rollout-BMnPPcJP.js.map → structural-rollout-keBf4YEc.js.map} +1 -1
  49. package/dist/{supervise-B-nTWUCK.js → supervise-CVP9ku5U.js} +36 -4
  50. package/dist/{supervise-B-nTWUCK.js.map → supervise-CVP9ku5U.js.map} +1 -1
  51. package/dist/{supervisor-Dl9Fk7g5.js → supervisor-mZ9Glkz7.js} +18 -3
  52. package/dist/supervisor-mZ9Glkz7.js.map +1 -0
  53. package/dist/testing.d.ts +2 -2
  54. package/dist/testing.js +11 -11
  55. package/dist/{types-DzZCZcwI.d.ts → types-BBwGSiAj.d.ts} +8 -5
  56. package/dist/{types-C7UNjVce.d.ts → types-BCkweg3w.d.ts} +2 -2
  57. package/package.json +1 -1
  58. package/dist/graph-BWsEZmDL.js.map +0 -1
  59. package/dist/supervisor-Dl9Fk7g5.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"improvement-cycle-DN0QhoCi.js","names":["truncate","canonicalCandidateDigest","approximatelyEqual","canonicalCandidateDigest","interfaceCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest"],"sources":["../src/improvement/agentic-generator.ts","../src/improvement/cleanup.ts","../src/improvement/improve-result.ts","../src/improvement/improvement-driver.ts","../src/improvement/rollout-policy.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/method-identity.ts","../src/improvement/method-execution.ts","../src/improvement/improve.ts","../src/intelligence/improvement-surfaces.ts","../src/intelligence/optimization-receipt.ts","../src/intelligence/improvement-cycle.ts"],"sourcesContent":["/**\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. A\n * cli-bridge placement sets `cwd` to the supplied worktree so Pi and other\n * supported harnesses edit the existing candidate directly.\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 * 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 * @stable\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type {\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n ProposalFinding,\n} 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 type { CandidateGenerator } from './improvement-driver'\nimport { optimizerMethod } from './optimizer-prompt'\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/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\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 readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\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 Pi author normally returns `{ backend:'bridge', cwd: worktreePath, ...transport }`. */\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. Omitted means the first dirty\n * shot is the candidate. See `commandVerifier`. */\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 provider = profile.model!.provider!.trim()\n const model = concreteProfileModel(profile)!\n const profileDigest = canonicalAgentProfileDigest(profile)\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\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 async generate({\n worktreePath,\n findings,\n maxShots,\n signal,\n generation,\n candidateIndex,\n costLedger,\n costPhase,\n }) {\n signal.throwIfAborted()\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' && executorConfig.cwd !== worktreePath) {\n throw new Error(\n 'agenticGenerator: bridge executor cwd must equal the candidate worktree path',\n )\n }\n const factory = createExecutor(executorConfig)\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n signal.throwIfAborted()\n const taskPrompt = attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt\n const startedAt = new Date()\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({ kind: 'executor', profile, factory }, taskPrompt, {\n signal: executionSignal,\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(callId ? { callId } : {}),\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 const execution = turn ? detachedSnapshot(turn, 'agenticGenerator shot execution') : 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,\n costReceipt,\n error: shotError,\n })\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError)\n signal.throwIfAborted()\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a Runtime turn')\n }\n\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, {\n kind: 'clean',\n worktreePath,\n })\n signal.throwIfAborted()\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n if (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 attemptNote = problem\n continue\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 (!verify) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\n }\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 signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\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 attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\nasync 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\nasync function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nasync 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\nfunction 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(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\nfunction 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\nfunction 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\nfunction sha256(value: string): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\n/** Turn proposal findings into a concrete coder task —\n * the senior scientific-method framing shared with the tool/MCP build prompts. */\nexport function defaultBuildPrompt(args: { findings: ReadonlyArray<ProposalFinding> }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis: real runs failed, an',\n 'analyst distilled the findings below, and your change will be measured on held-out tasks',\n 'against the unchanged baseline — only a real lift promotes it.',\n '',\n optimizerMethod,\n '',\n 'THE SURFACE — what a deliverable change looks like here:',\n '- edit this codebase in place: the smallest coherent change set that fully tests your',\n ' hypothesis about the dominant failure mode (see the method above — no unrelated edits,',\n ' they confound the measurement),',\n '- keep the diff reviewable: a reviewer should be able to trace every hunk back to a finding,',\n '- do not commit — leave changes in the working tree.',\n '',\n 'FINDINGS — ranked evidence from real failed runs:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n if (requiresRawTraceEvidence(args.findings)) {\n lines.push(\n '',\n 'Raw trace evidence requirement:',\n `- Inspect at least one raw trace path named above before editing.`,\n `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,\n '- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.',\n '- A candidate without this file, or with only this file changed, is discarded.',\n )\n }\n return lines.join('\\n')\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\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/** 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\nfunction worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain', '--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 return result.stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => line.slice(3).trim())\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\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<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","/** Serialize and apply Runtime's structural rollout profile coordinate. */\n\nimport type { MutableSurface } from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Returns `undefined` for non-strings,\n * malformed JSON, or values outside the policy invariants. Unknown fields are\n * dropped; supported optional fields are preserved. */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n }\n}\n\n/** Stable serialization with fixed field order. */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout. */\nexport function structuralRolloutPolicyFromProfile(\n profile: ReadonlyAgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a detached policy under the profile extension without mutating the input. */\nexport function applyRolloutPolicyToProfile(\n profile: ReadonlyAgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const candidate = structuredClone(profile) as AgentProfile\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n }\n return {\n ...candidate,\n extensions: { ...candidate.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\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 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\nexport interface 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 const value = profileComponents.read(profile)\n return {\n surface: componentSurface(value, 'profileComponents.read'),\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 = validateProfileCandidate(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 validateProfileCandidate(candidate, surface)\n}\n\nfunction validateProfileCandidate(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 baselineDigest = canonicalCandidateDigest(baselineSurface)\n if (profileComponents) {\n const reappliedBaseline = materializeImprovementProfileCandidate(\n profile,\n surface,\n baselineSurface,\n skills,\n profileComponents,\n )\n if (canonicalCandidateDigest(reappliedBaseline) !== canonicalCandidateDigest(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 digest = canonicalCandidateDigest(candidateSurface)\n const existing = candidates.get(digest)\n if (existing) return existing\n const candidate = materializeImprovementProfileCandidate(\n profile,\n surface,\n immutableCandidateValue(candidateSurface),\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\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?: 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 { 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 SelfImproveResult,\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/** 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: 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 = 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: SelfImproveResult<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\nexport interface 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 {\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}\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): void {\n const { cost } = result\n const observed =\n costAttribution === 'optimizer-run' && result.provenance?.runId\n ? compatibleLedger.summary({ tags: { optimizerRun: result.provenance.runId } })\n : invocationLedger.summary()\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 }\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","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","import { randomUUID } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport {\n type CampaignStorage,\n compareOptimizationMethods,\n decodeExternalTextCandidate,\n type OptimizationMethod,\n type OptimizationMethodComparison,\n readExternalOptimizerObservationArtifact,\n readGepaCandidatePopulationArtifact,\n} from '@tangle-network/agent-eval/campaign'\nimport type { MutableSurface, Scenario } from '@tangle-network/agent-eval/contract'\nimport {\n type AgentProfile,\n applyAgentProfileDiff,\n diffAgentProfiles,\n canonicalCandidateDigest as interfaceCandidateDigest,\n type Sha256Digest,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveCandidateValidationInput,\n ImproveMethodContext,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementProfileCandidate,\n ImprovementProfileCandidatePopulation,\n ImprovementProfilePopulationCandidateSource,\n ImprovementProfilePopulationLineageNode,\n} from './improve-types'\nimport { methodRuntimeControlsOf } from './method-controls'\nimport {\n assertMethodCostRecorded,\n methodInputWithScopedCost,\n methodInvocationCostLedger,\n} from './method-cost'\nimport { buildMethodEvaluationIdentity } from './method-identity'\nimport {\n assertCandidateSurfaceKind,\n createProfileCandidateMaterializer,\n prepareProfileSurface,\n} 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\nfunction copyProvenance(\n provenance: NonNullable<OptimizationMethodComparison['best']['provenance']>,\n): NonNullable<OptimizationMethodComparison['best']['provenance']> {\n return immutableCandidateValue(provenance)\n}\n\nfunction validateExecutionRef(value: unknown): Sha256Digest {\n const parsed = sha256DigestSchema.safeParse(value)\n if (!parsed.success) {\n throw new ConfigError('improve(): executionRef must be a lowercase sha256:<64 hex> digest')\n }\n return parsed.data\n}\n\nfunction materializationError(error: unknown): { name: string; message: string } {\n if (error instanceof Error) {\n return { name: error.name, message: error.message }\n }\n return {\n name: 'Error',\n message:\n typeof error === 'string' ? error : 'candidate materialization threw a non-Error value',\n }\n}\n\nfunction profileCandidatePopulation(\n provenance: OptimizationMethodComparison['best']['provenance'],\n baselineProfile: AgentProfile,\n materializeProfile: (candidateSurface: MutableSurface) => AgentProfile,\n winnerSurface: MutableSurface,\n storage?: CampaignStorage,\n): ImprovementProfileCandidatePopulation {\n const observationSummary = provenance?.observations\n const graphSummary = provenance?.gepaCandidatePopulation\n if (!observationSummary && !graphSummary) {\n return Object.freeze({\n status: 'unavailable',\n reason: 'method-did-not-report-candidate-population',\n })\n }\n\n const observations = observationSummary\n ? readExternalOptimizerObservationArtifact({\n summary: observationSummary,\n ...(storage ? { storage } : {}),\n })\n : undefined\n const graph = graphSummary\n ? readGepaCandidatePopulationArtifact({\n summary: graphSummary,\n })\n : undefined\n if (!graph && (observations?.candidates.length ?? 0) === 0) {\n return Object.freeze({\n status: 'unavailable',\n reason: 'method-did-not-report-candidate-population',\n })\n }\n interface PopulationEntry {\n candidateDigest: Sha256Digest\n value: MutableSurface\n observation?: {\n proposalSequence: number\n artifact: { path: string; sha256: Sha256Digest }\n }\n lineageNodes: ImprovementProfilePopulationLineageNode[]\n }\n const entries = new Map<Sha256Digest, PopulationEntry>()\n const entryFor = (candidateDigest: Sha256Digest, value: MutableSurface): PopulationEntry => {\n const existing = entries.get(candidateDigest)\n if (existing) {\n if (!isDeepStrictEqual(existing.value, value)) {\n throw new ConfigError(\n `improve(): optimizer artifacts disagree on candidate ${candidateDigest}`,\n )\n }\n return existing\n }\n const entry: PopulationEntry = {\n candidateDigest,\n value: immutableCandidateValue(value),\n lineageNodes: [],\n }\n entries.set(candidateDigest, entry)\n return entry\n }\n\n for (const submitted of observations?.candidates ?? []) {\n const entry = entryFor(\n submitted.candidateDigest,\n decodeExternalTextCandidate(submitted.candidate),\n )\n entry.observation = {\n proposalSequence: submitted.proposalSequence,\n artifact: {\n path: submitted.provenance.path,\n sha256: submitted.provenance.sha256,\n },\n }\n }\n for (const graphCandidate of graph?.candidates ?? []) {\n const entry = entryFor(\n graphCandidate.candidateDigest,\n decodeExternalTextCandidate(graphCandidate.candidate),\n )\n entry.lineageNodes.push({\n index: graphCandidate.index,\n parentIndices: [...graphCandidate.parentIndices],\n aggregateScore: graphCandidate.aggregateScore,\n selectionScores: graphCandidate.selectionScores.map((score) => ({ ...score })),\n discoveryEvaluationCount: graphCandidate.discoveryEvaluationCount,\n })\n }\n\n if (graph) {\n const best = graph.candidates.find((candidate) => candidate.index === graph.bestIndex)\n if (!best) {\n throw new ConfigError(\n `improve(): GEPA candidate population has no bestIndex node ${graph.bestIndex}`,\n )\n }\n const verifiedBest = decodeExternalTextCandidate(best.candidate)\n if (!isDeepStrictEqual(verifiedBest, winnerSurface)) {\n throw new ConfigError(\n 'improve(): method winner does not equal the verified GEPA bestIndex candidate',\n )\n }\n } else if (\n ![...entries.values()].some((entry) => isDeepStrictEqual(entry.value, winnerSurface))\n ) {\n throw new ConfigError(\n 'improve(): method winner does not appear in the verified optimizer observations',\n )\n }\n\n let materializedCandidates = 0\n let refusedCandidates = 0\n const candidates = [...entries.values()].map((entry) => {\n const source: ImprovementProfilePopulationCandidateSource = {\n candidateDigest: entry.candidateDigest,\n ...(entry.observation ? { observation: entry.observation } : {}),\n lineage:\n entry.lineageNodes.length > 0 && graph\n ? {\n status: 'available',\n artifact: {\n path: graph.summary.path,\n sha256: graph.summary.sha256,\n },\n nodes: entry.lineageNodes,\n }\n : {\n status: 'unavailable',\n reason: 'optimizer-did-not-report-candidate-lineage',\n },\n }\n const surfaceDigest = interfaceCandidateDigest(entry.value)\n let candidateProfile: AgentProfile\n try {\n candidateProfile = materializeProfile(entry.value)\n } catch (error) {\n refusedCandidates += 1\n return {\n status: 'refused' as const,\n source,\n value: entry.value,\n surfaceDigest,\n error: materializationError(error),\n }\n }\n\n const profileDigest = interfaceCandidateDigest(candidateProfile)\n const diffs = diffAgentProfiles(baselineProfile, candidateProfile)\n const reproduced = diffs.reduce(applyAgentProfileDiff, baselineProfile)\n if (interfaceCandidateDigest(reproduced) !== profileDigest) {\n throw new ConfigError(\n `improve(): Interface profile diffs do not reproduce optimizer candidate ${entry.candidateDigest}`,\n )\n }\n materializedCandidates += 1\n return {\n status: 'materialized' as const,\n source,\n value: entry.value,\n surfaceDigest,\n profile: candidateProfile,\n profileDigest,\n diffs,\n diffDigests: diffs.map(interfaceCandidateDigest),\n }\n })\n\n return immutableCandidateValue({\n status: 'available',\n source: {\n ...(observations\n ? {\n observations: {\n path: observations.summary.path,\n sha256: observations.summary.sha256,\n },\n }\n : {}),\n ...(graph\n ? {\n gepaCandidateGraph: {\n path: graph.summary.path,\n sha256: graph.summary.sha256,\n bestIndex: graph.bestIndex,\n },\n }\n : {}),\n },\n uniqueCandidates: entries.size,\n observedCandidates: observations?.candidates.length ?? 0,\n gepaCandidateNodes: graph?.candidates.length ?? 0,\n materializedCandidates,\n refusedCandidates,\n candidates,\n })\n}\n\nexport async function runMethodImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult> {\n const {\n surface = 'prompt',\n executionRef: inputExecutionRef,\n method: methodSource,\n agent,\n validateCandidate,\n findings: inputFindings = [],\n skills,\n profileComponents,\n optimizationRunOptions,\n minimumLift = 0,\n ...comparisonOptions\n } = opts\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 const executionRef = validateExecutionRef(inputExecutionRef)\n const findings = immutableCandidateValue([\n ...assertProposalFindings(inputFindings, '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 = canonicalCandidateDigest(profile)\n const identity = buildMethodEvaluationIdentity({\n executionRef,\n baselineProfileDigest,\n baselineSurface,\n surface,\n skills,\n validateCandidate,\n findings,\n trainScenarios: comparisonOptions.trainScenarios,\n selectionScenarios: comparisonOptions.selectionScenarios,\n testScenarios: comparisonOptions.testScenarios,\n judges: comparisonOptions.judges,\n seed: comparisonOptions.seed,\n reps: comparisonOptions.reps,\n costCeiling: comparisonOptions.costCeiling,\n optimizationRunOptions,\n })\n const { evaluationRef, developmentSplitDigest, finalTestSplitDigest, scenarioPartitions } =\n identity\n const dispatchRef = `improve:${evaluationRef}`\n const identifiedJudges = comparisonOptions.judges.map((judge, index) =>\n Object.freeze({\n ...judge,\n judgeVersion: canonicalCandidateDigest({\n 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 runtimeInvocationId = `runtime-optimization:${randomUUID()}`\n const method = resolveOptimizationMethod(methodSource, {\n profile,\n evaluationRef,\n surface,\n baselineSurface,\n baselineValue,\n findings,\n })\n const methodControls = methodRuntimeControlsOf(method)\n const baselineSurfaceDigest = canonicalCandidateDigest(baselineSurface)\n const validatedCandidates = new Set<Sha256Digest>()\n const materializeProfile = (\n candidateSurface: Parameters<typeof rawMaterializeProfile>[0],\n ): ReturnType<typeof rawMaterializeProfile> => {\n const candidate = rawMaterializeProfile(candidateSurface)\n const candidateDigest = canonicalCandidateDigest(candidateSurface)\n if (!validatedCandidates.has(candidateDigest)) {\n const prepared = prepareProfileSurface(candidate, surface, skills, profileComponents)\n const validationInput: ImproveCandidateValidationInput = Object.freeze({\n profile: candidate,\n surface,\n candidateSurface: immutableCandidateValue(candidateSurface),\n value: immutableCandidateValue(prepared.value),\n isBaseline: candidateDigest === baselineSurfaceDigest,\n })\n methodControls?.validateCandidate(validationInput)\n validateCandidate?.(validationInput)\n validatedCandidates.add(candidateDigest)\n }\n return candidate\n }\n materializeProfile(baselineSurface)\n const measuredMethod: OptimizationMethod<TScenario, TArtifact> = {\n ...method,\n async optimize(input) {\n const costScope = {\n evaluationRef,\n invocationId: runtimeInvocationId,\n }\n const scopedInput = methodInputWithScopedCost(\n input,\n costScope,\n methodControls?.costAttribution,\n )\n const invocationLedger = methodInvocationCostLedger(input.costLedger, costScope)\n const result = await method.optimize(scopedInput)\n assertMethodCostRecorded(\n method.name,\n result,\n scopedInput.costLedger,\n invocationLedger,\n comparisonOptions.costCeiling,\n methodControls?.costAttribution,\n )\n materializeProfile(result.winnerSurface)\n return result\n },\n }\n const startedAt = Date.now()\n const raw = await compareOptimizationMethods<TScenario, TArtifact>({\n ...comparisonOptions,\n judges: identifiedJudges,\n dispatchRef,\n optimizationRunOptions: {\n ...(optimizationRunOptions ?? {}),\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 score = raw.best\n const winnerSurface = immutableCandidateValue(score.winnerSurface)\n assertCandidateSurfaceKind(surface, baselineSurface, winnerSurface)\n const candidateProfile = materializeProfile(winnerSurface)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface,\n value: winnerSurface,\n profile: candidateProfile,\n })\n const candidatePopulation = profileCandidatePopulation(\n score.provenance,\n profile,\n materializeProfile,\n winnerSurface,\n optimizationRunOptions?.storage,\n )\n\n const cost = copyImproveCost(raw.totalCost)\n return {\n mode: 'method',\n method: method.name,\n ...(score.provenance ? { provenance: copyProvenance(score.provenance) } : {}),\n candidate,\n decision: cost.accountingComplete && score.liftCi.low > minimumLift ? 'ship' : 'hold',\n lift: score.lift,\n liftInterval: { ...score.liftCi },\n candidatePopulation,\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId: runtimeInvocationId,\n runId: score.provenance?.runId ?? runtimeInvocationId,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n executionRef,\n baselineProfileDigest,\n }),\n raw,\n async dispose() {},\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 is the sole exception. It uses Runtime's isolated git worktrees because\n * checkout ownership and cleanup cannot cross a generic optimizer boundary.\n *\n * @stable\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/contract'\nimport { type AgentProfile, 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} from './improve-types'\nimport { runMethodImprovement } from './method-execution'\n\nexport type {\n ImproveCandidateValidationInput,\n ImproveCandidateValidator,\n ImproveCodeBaseOptions,\n ImproveCodeOptions,\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImproveCost,\n ImproveCustomCodeGeneratorOptions,\n ImproveLineage,\n ImproveMethodContext,\n ImproveMethodFactory,\n ImproveMethodLineage,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementCandidate,\n ImprovementCodeCandidate,\n ImprovementMaterializedProfilePopulationCandidate,\n ImprovementProfileCandidate,\n ImprovementProfileCandidatePopulation,\n ImprovementProfileCandidatePopulationAvailable,\n ImprovementProfileCandidatePopulationUnavailable,\n ImprovementProfilePopulationArtifactSource,\n ImprovementProfilePopulationCandidate,\n ImprovementProfilePopulationCandidateSource,\n ImprovementProfilePopulationLineage,\n ImprovementProfilePopulationLineageNode,\n ImprovementProfilePopulationObservationSource,\n ImprovementRefusedProfilePopulationCandidate,\n ImproveOptimizationRunOptions,\n ImproveOptions,\n ImproveProfileAgent,\n ImproveProfileComponents,\n ImproveProfileSurface,\n ImproveResult,\n ImproveRuntimeCodeGeneratorOptions,\n ImproveScenarioPartitions,\n ImproveSkillsOptions,\n ImproveSurface,\n} from './improve-types'\n\n/**\n * Optimize one exact profile surface with a complete method.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult>\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: AgentProfile | ImproveCodeRunOptions<TScenario, TArtifact>,\n opts?: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\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 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 return runMethodImprovement(immutableCandidateValue(parsedProfile.data), opts)\n}\n","import {\n type AgentCandidateBundle,\n type AgentCandidateExperiment,\n type AgentImprovementActivationIntent,\n type AgentImprovementActivationTarget,\n type AgentImprovementEvaluation,\n type AgentImprovementSurface,\n type AgentProfile,\n type AgentProfileDiff,\n type AgentProfileDiffRemoval,\n type AgentProfileImprovementChange,\n type AgentProfileImprovementExperiment,\n agentProfileDiffSchema,\n agentProfileSchema,\n changedProfileImprovementSurfaces,\n defineAgentProfileDiff,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n agentCandidateProfileAsAgentProfile,\n applyExactAgentProfileDiff,\n omitUndefinedObjectFields,\n parseExactAgentProfile,\n} from '../candidate-execution/profile'\n\nconst changedSurfaceOrder: 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\n/** Agent improvement surfaces delivered as exact `AgentProfileDiff` replacements. */\nexport const AGENT_IMPROVEMENT_PROFILE_SURFACES = [\n 'prompt',\n 'skills',\n 'tools',\n 'mcp',\n 'hooks',\n 'subagents',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentImprovementProfileSurface = (typeof AGENT_IMPROVEMENT_PROFILE_SURFACES)[number]\n\n/**\n * Profile changes eligible for the product-owned measured comparison path.\n * The six directly deliverable profile surfaces retain their granular labels;\n * any residual profile axis also adds the complete `agent-profile` surface.\n */\nexport const AGENT_PROFILE_MEASURED_SURFACES = [\n ...AGENT_IMPROVEMENT_PROFILE_SURFACES,\n 'agent-profile',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentProfileMeasuredSurface = (typeof AGENT_PROFILE_MEASURED_SURFACES)[number]\n\ntype ProfileDifferHandledField =\n | 'name'\n | 'description'\n | 'version'\n | 'tags'\n | 'prompt'\n | 'model'\n | 'harness'\n | 'permissions'\n | 'tools'\n | 'mcp'\n | 'connections'\n | 'subagents'\n | 'resources'\n | 'hooks'\n | 'modes'\n | 'confidential'\n | 'metadata'\n | 'extensions'\ntype MissingProfileDifferField = Exclude<keyof AgentProfile, ProfileDifferHandledField>\nconst profileDifferIsExhaustive: MissingProfileDifferField extends never ? true : never = true\nvoid profileDifferIsExhaustive\n\ntype ProfileResourceDifferHandledField =\n | 'files'\n | 'tools'\n | 'skills'\n | 'agents'\n | 'commands'\n | 'instructions'\n | 'failOnError'\ntype MissingProfileResourceDifferField = Exclude<\n keyof NonNullable<AgentProfile['resources']>,\n ProfileResourceDifferHandledField\n>\nconst profileResourceDifferIsExhaustive: MissingProfileResourceDifferField extends never\n ? true\n : never = true\nvoid profileResourceDifferIsExhaustive\n\nexport interface AgentImprovementTargetProfileDiffOptions {\n id: string\n source?: AgentProfileDiff['source']\n metadata?: Record<string, unknown>\n}\n\nexport type AgentImprovementActivationTargetIdentity = Pick<\n AgentImprovementActivationTarget,\n 'surface' | 'identity'\n>\n\nexport function deriveChangedSurfaces(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (baselineBundle.knowledge || candidateBundle.knowledge) {\n assertKnowledgeCandidatePair(baselineBundle, candidateBundle)\n }\n assertCodeCandidatePair(baselineBundle, candidateBundle)\n const baseline = improvementSurfaceValues(baselineBundle)\n const candidate = improvementSurfaceValues(candidateBundle)\n const changed = changedSurfaceOrder.filter(\n (surface) =>\n canonicalCandidateDigest(baseline[surface]) !== canonicalCandidateDigest(candidate[surface]),\n )\n if (changed.length === 0) throw new Error('candidate experiment does not change an agent surface')\n return changed as [AgentImprovementSurface, ...AgentImprovementSurface[]]\n}\n\nexport function assertAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n targets: readonly AgentImprovementActivationTarget[],\n): void {\n if (isProfileImprovementExperiment(experiment)) {\n assertProfileImprovementTargetsShareIdentity(targets)\n }\n const expected = new Set(surfaces)\n const actual = new Set(targets.map((target) => target.surface))\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n if (\n !(isProfileImprovementExperiment(experiment)\n ? sameAgentImprovementSurfaceSet(surfaces, activationExperimentChangedSurfaces(experiment))\n : sameOrderedSurfaces(surfaces, activationExperimentChangedSurfaces(experiment))) ||\n targets.some((target) => !target.identity.trim()) ||\n targets.some(\n (target) =>\n target.expectedBaseDigest !== activationTargetDigest(experiment, sourceArm, target.surface),\n ) ||\n targets.length !== surfaces.length ||\n expected.size !== actual.size ||\n [...expected].some((surface) => !actual.has(surface))\n ) {\n throw new Error('agent improvement activation targets must cover exactly the changed surfaces')\n }\n}\n\n/** One opaque profile-state transition can change only one complete profile record. */\nexport function assertProfileImprovementTargetsShareIdentity(\n targets: readonly Pick<AgentImprovementActivationTarget, 'identity'>[],\n): void {\n if (new Set(targets.map((target) => target.identity)).size !== 1) {\n throw new Error('profile improvement activation targets must name one profile identity')\n }\n}\n\n/** Bind caller-owned target identities to the exact source state Runtime measured. */\nexport function buildAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n identities: readonly AgentImprovementActivationTargetIdentity[],\n): [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]] {\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targets = identities.map((target) => ({\n ...target,\n expectedBaseDigest: activationTargetDigest(experiment, sourceArm, target.surface),\n }))\n assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets)\n return targets as [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]]\n}\n\n/** Exact host-owned profile state for every changed profile surface. */\nexport function agentProfileImprovementStateDigest(\n experiment: AgentProfileImprovementExperiment,\n arm: 'baseline' | 'candidate',\n): Sha256Digest {\n return experiment[arm].stateDigest\n}\n\n/** Map Interface's current profile-improvement contract to Runtime-deliverable surfaces. */\nexport function profileImprovementChangedSurfaces(\n change: AgentProfileImprovementChange,\n): [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]] {\n const surfaces = changedProfileImprovementSurfaces(change)\n if (\n surfaces.length === 0 ||\n !surfaces.every((surface): surface is AgentProfileMeasuredSurface =>\n isAgentProfileMeasuredSurface(surface),\n )\n ) {\n throw new Error('profile improvement experiment does not change a supported surface')\n }\n return surfaces as [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]]\n}\n\nexport function agentImprovementTargetDigest(\n experiment: AgentCandidateExperiment,\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (surface === 'knowledge') {\n const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate)\n return arm === 'baseline' ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash\n }\n if (surface === 'code') assertCodeCandidatePair(experiment.baseline, experiment.candidate)\n return canonicalCandidateDigest(improvementSurfaceValues(experiment[arm])[surface])\n}\n\nexport function agentImprovementTargetInput(\n bundle: AgentCandidateBundle,\n surface: AgentImprovementSurface,\n): unknown {\n return improvementSurfaceValues(bundle)[surface]\n}\n\nfunction activationTargetDigest(\n experiment: AgentImprovementEvaluation['experiment'],\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (isProfileImprovementExperiment(experiment)) {\n if (!activationExperimentChangedSurfaces(experiment).includes(surface)) {\n throw new Error('profile improvement activation targets an unchanged surface')\n }\n return agentProfileImprovementStateDigest(experiment, arm)\n }\n return agentImprovementTargetDigest(experiment, arm, surface)\n}\n\nfunction activationExperimentChangedSurfaces(\n experiment: AgentImprovementEvaluation['experiment'],\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (!isProfileImprovementExperiment(experiment)) {\n return deriveChangedSurfaces(experiment.baseline, experiment.candidate)\n }\n return profileImprovementChangedSurfaces(experiment.change)\n}\n\nfunction isProfileImprovementExperiment(\n experiment: AgentImprovementEvaluation['experiment'],\n): experiment is AgentProfileImprovementExperiment {\n return experiment.kind === 'agent-profile-improvement-experiment'\n}\n\nfunction sameOrderedSurfaces(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface, index) => surface === right[index])\n}\n\n/** Profile-change surface order is presentation only; its measured contract is set-based. */\nexport function sameAgentImprovementSurfaceSet(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface) => right.includes(surface))\n}\n\n/** Return whether a measured surface can be delivered through an agent profile. */\nexport function isAgentImprovementProfileSurface(\n surface: AgentImprovementSurface,\n): surface is AgentImprovementProfileSurface {\n return (AGENT_IMPROVEMENT_PROFILE_SURFACES as readonly string[]).includes(surface)\n}\n\n/** Return whether a surface is eligible for shared profile measurement. */\nexport function isAgentProfileMeasuredSurface(\n surface: string,\n): surface is AgentProfileMeasuredSurface {\n return (AGENT_PROFILE_MEASURED_SURFACES as readonly string[]).includes(surface)\n}\n\n/**\n * Return the canonical current-state input for one profile-deliverable improvement target.\n * Missing slots become `null`; tools and subagents include both their direct and resource slots.\n * Unrelated profile fields are excluded. The result matches `agentImprovementTargetInput` for the\n * same profile inside a candidate bundle.\n */\nexport function agentImprovementProfileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n const parsed = parseExactAgentProfile(\n omitUndefinedObjectFields(profile, 'agent improvement profile'),\n 'agent improvement profile',\n )\n return immutableCandidateValue(profileSurfaceInput(parsed, surface))\n}\n\nfunction profileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n switch (surface) {\n case 'prompt':\n return { prompt: profile.prompt ?? null }\n case 'skills':\n return profile.resources?.skills ?? null\n case 'tools':\n return {\n tools: profile.tools ?? null,\n resources: profile.resources?.tools ?? null,\n }\n case 'mcp':\n return profile.mcp ?? null\n case 'hooks':\n return profile.hooks ?? null\n case 'subagents':\n return {\n subagents: profile.subagents ?? null,\n resources: profile.resources?.agents ?? null,\n }\n }\n}\n\n/** Return the `Sha256Digest` of one profile surface using Runtime's canonical candidate digest. */\nexport function agentImprovementProfileSurfaceDigest(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): Sha256Digest {\n return canonicalCandidateDigest(agentImprovementProfileSurfaceInput(profile, surface))\n}\n\n/**\n * Replace one measured profile surface exactly, including array-valued resources.\n * Apply the returned diffs in order: a diff applies its set before its removal,\n * so exact replacement requires a reset record followed by a set record.\n */\nexport function agentImprovementTargetProfileDiffs(\n target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n },\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const { remove, set } = improvementSurfaceReplacement(target)\n const common = {\n kind: 'agent-profile-diff' as const,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: target.surface,\n },\n }\n const reset = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:reset`,\n title: `Replace active ${target.surface}`,\n remove,\n }),\n ) as AgentProfileDiff\n if (!set) return [reset]\n const replacement = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:set`,\n title: `Activate measured ${target.surface}`,\n set,\n }),\n ) as AgentProfileDiff\n return [reset, replacement]\n}\n\n/**\n * Derive the ordered profile patch that changes one executable profile into\n * another, then prove the patch preserves the complete candidate state.\n */\nexport function agentImprovementProfileDiffs(\n baselineInput: AgentProfile,\n candidateInput: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const baseline = parseExactAgentProfile(\n omitUndefinedObjectFields(baselineInput, 'profile improvement baseline'),\n 'profile improvement baseline',\n )\n const candidate = parseExactAgentProfile(\n omitUndefinedObjectFields(candidateInput, 'profile improvement candidate'),\n 'profile improvement candidate',\n )\n if (canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate)) {\n throw new Error('profile improvement candidate does not change the profile')\n }\n const completeChanges = completeAgentProfileReplacementDiffs(baseline, candidate, options)\n const applied = completeChanges.reduce(\n (profile, change) =>\n applyExactAgentProfileDiff(profile, change, 'complete profile improvement candidate change'),\n baseline,\n )\n if (canonicalCandidateDigest(applied) !== canonicalCandidateDigest(candidate)) {\n throw new Error('complete profile improvement change did not reproduce the candidate')\n }\n return completeChanges\n}\n\nfunction completeAgentProfileReplacementDiffs(\n baseline: AgentProfile,\n candidate: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const remove: AgentProfileDiffRemoval = {}\n const set: AgentProfile = {}\n if (\n profileValuesDiffer(baseline.name, candidate.name) ||\n profileValuesDiffer(baseline.description, candidate.description) ||\n profileValuesDiffer(baseline.version, candidate.version)\n ) {\n remove.identity = true\n if (candidate.name !== undefined) set.name = candidate.name\n if (candidate.description !== undefined) set.description = candidate.description\n if (candidate.version !== undefined) set.version = candidate.version\n }\n if (profileValuesDiffer(baseline.tags, candidate.tags)) {\n remove.tags = true\n if (candidate.tags !== undefined) set.tags = candidate.tags\n }\n if (profileValuesDiffer(baseline.prompt, candidate.prompt)) {\n remove.prompt = true\n if (candidate.prompt !== undefined) set.prompt = candidate.prompt\n }\n if (profileValuesDiffer(baseline.model, candidate.model)) {\n remove.model = true\n if (candidate.model !== undefined) set.model = candidate.model\n }\n if (profileValuesDiffer(baseline.harness, candidate.harness)) {\n remove.harness = true\n if (candidate.harness !== undefined) set.harness = candidate.harness\n }\n if (profileValuesDiffer(baseline.permissions, candidate.permissions)) {\n remove.permissions = true\n if (candidate.permissions !== undefined) set.permissions = candidate.permissions\n }\n if (profileValuesDiffer(baseline.tools, candidate.tools)) {\n remove.tools = true\n if (candidate.tools !== undefined) set.tools = candidate.tools\n }\n if (profileValuesDiffer(baseline.mcp, candidate.mcp)) {\n remove.mcp = true\n if (candidate.mcp !== undefined) set.mcp = candidate.mcp\n }\n if (profileValuesDiffer(baseline.connections, candidate.connections)) {\n remove.connections = true\n if (candidate.connections !== undefined) set.connections = candidate.connections\n }\n if (profileValuesDiffer(baseline.subagents, candidate.subagents)) {\n remove.subagents = true\n if (candidate.subagents !== undefined) set.subagents = candidate.subagents\n }\n replaceChangedProfileResources(baseline.resources, candidate.resources, remove, set)\n if (profileValuesDiffer(baseline.hooks, candidate.hooks)) {\n remove.hooks = true\n if (candidate.hooks !== undefined) set.hooks = candidate.hooks\n }\n if (profileValuesDiffer(baseline.modes, candidate.modes)) {\n remove.modes = true\n if (candidate.modes !== undefined) set.modes = candidate.modes\n }\n if (profileValuesDiffer(baseline.confidential, candidate.confidential)) {\n remove.confidential = true\n if (candidate.confidential !== undefined) set.confidential = candidate.confidential\n }\n if (profileValuesDiffer(baseline.metadata, candidate.metadata)) {\n remove.metadata = true\n if (candidate.metadata !== undefined) set.metadata = candidate.metadata\n }\n if (profileValuesDiffer(baseline.extensions, candidate.extensions)) {\n remove.extensions = true\n if (candidate.extensions !== undefined) set.extensions = candidate.extensions\n }\n if (Object.keys(remove).length === 0) {\n throw new Error('complete profile differ found no changed fields')\n }\n const common = {\n kind: 'agent-profile-diff' as const,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: 'agent-profile',\n },\n }\n const reset = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:agent-profile:reset`,\n title: 'Reset changed agent profile fields',\n remove,\n }),\n ) as AgentProfileDiff\n if (Object.keys(set).length === 0) return [reset]\n const replacement = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:agent-profile:set`,\n title: 'Set changed agent profile fields',\n set,\n }),\n ) as AgentProfileDiff\n return [reset, replacement]\n}\n\nfunction replaceChangedProfileResources(\n baseline: AgentProfile['resources'],\n candidate: AgentProfile['resources'],\n remove: AgentProfileDiffRemoval,\n set: AgentProfile,\n): void {\n if (!profileValuesDiffer(baseline, candidate)) return\n const resourceRemoval: Exclude<AgentProfileDiffRemoval['resources'], true | undefined> = {}\n const resourceSet: NonNullable<AgentProfile['resources']> = {}\n let changedSubfields = 0\n\n if (profileValuesDiffer(baseline?.files, candidate?.files)) {\n changedSubfields += 1\n resourceRemoval.files = true\n if (candidate?.files !== undefined) resourceSet.files = candidate.files\n }\n if (profileValuesDiffer(baseline?.tools, candidate?.tools)) {\n changedSubfields += 1\n resourceRemoval.tools = true\n if (candidate?.tools !== undefined) resourceSet.tools = candidate.tools\n }\n if (profileValuesDiffer(baseline?.skills, candidate?.skills)) {\n changedSubfields += 1\n resourceRemoval.skills = true\n if (candidate?.skills !== undefined) resourceSet.skills = candidate.skills\n }\n if (profileValuesDiffer(baseline?.agents, candidate?.agents)) {\n changedSubfields += 1\n resourceRemoval.agents = true\n if (candidate?.agents !== undefined) resourceSet.agents = candidate.agents\n }\n if (profileValuesDiffer(baseline?.commands, candidate?.commands)) {\n changedSubfields += 1\n resourceRemoval.commands = true\n if (candidate?.commands !== undefined) resourceSet.commands = candidate.commands\n }\n if (profileValuesDiffer(baseline?.instructions, candidate?.instructions)) {\n changedSubfields += 1\n resourceRemoval.instructions = true\n if (candidate?.instructions !== undefined) resourceSet.instructions = candidate.instructions\n }\n if (profileValuesDiffer(baseline?.failOnError, candidate?.failOnError)) {\n changedSubfields += 1\n resourceRemoval.failOnError = true\n if (candidate?.failOnError !== undefined) resourceSet.failOnError = candidate.failOnError\n }\n\n if (changedSubfields === 0) {\n remove.resources = true\n if (candidate !== undefined) set.resources = candidate\n return\n }\n remove.resources = resourceRemoval\n if (Object.keys(resourceSet).length > 0) set.resources = resourceSet\n}\n\nfunction profileValuesDiffer(baseline: unknown, candidate: unknown): boolean {\n const comparable = (value: unknown) =>\n value === undefined ? { present: false } : { present: true, value }\n return (\n canonicalCandidateDigest(comparable(baseline)) !==\n canonicalCandidateDigest(comparable(candidate))\n )\n}\n\nfunction improvementSurfaceReplacement(target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n}): { remove: AgentProfileDiffRemoval; set?: AgentProfile } {\n const value = target.desiredInput\n switch (target.surface) {\n case 'prompt': {\n const prompt = exactObject(value, ['prompt'], 'prompt activation input').prompt\n assertDefined(prompt, 'prompt activation input.prompt')\n return {\n remove: { prompt: true },\n ...(prompt === null ? {} : { set: parseProfileSet({ prompt }) }),\n }\n }\n case 'skills':\n assertDefined(value, 'skills activation input')\n return {\n remove: { resources: { skills: true } },\n ...(value === null ? {} : { set: parseProfileSet({ resources: { skills: value } }) }),\n }\n case 'tools': {\n const parsed = exactObject(value, ['tools', 'resources'], 'tools activation input')\n assertDefined(parsed.tools, 'tools activation input.tools')\n assertDefined(parsed.resources, 'tools activation input.resources')\n const set = {\n ...(parsed.tools === null ? {} : { tools: parsed.tools }),\n ...(parsed.resources === null ? {} : { resources: { tools: parsed.resources } }),\n }\n return {\n remove: { tools: true, resources: { tools: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n case 'mcp':\n assertDefined(value, 'mcp activation input')\n return {\n remove: { mcp: true },\n ...(value === null ? {} : { set: parseProfileSet({ mcp: value }) }),\n }\n case 'hooks':\n assertDefined(value, 'hooks activation input')\n return {\n remove: { hooks: true },\n ...(value === null ? {} : { set: parseProfileSet({ hooks: value }) }),\n }\n case 'subagents': {\n const parsed = exactObject(value, ['subagents', 'resources'], 'subagents activation input')\n assertDefined(parsed.subagents, 'subagents activation input.subagents')\n assertDefined(parsed.resources, 'subagents activation input.resources')\n const set = {\n ...(parsed.subagents === null ? {} : { subagents: parsed.subagents }),\n ...(parsed.resources === null ? {} : { resources: { agents: parsed.resources } }),\n }\n return {\n remove: { subagents: true, resources: { agents: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n }\n}\n\nfunction assertDefined(value: unknown, label: string): void {\n if (value === undefined) throw new Error(`${label} must not be undefined`)\n}\n\nfunction exactObject(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const record = value as Record<string, unknown>\n const actual = Object.keys(record).sort()\n const expected = [...keys].sort()\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {\n throw new Error(`${label} must contain exactly: ${expected.join(', ')}`)\n }\n return record\n}\n\nfunction parseProfileSet(value: unknown): AgentProfile {\n return agentProfileSchema.parse(value) as AgentProfile\n}\n\nfunction assertKnowledgeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): NonNullable<AgentCandidateBundle['knowledge']> {\n const baseline = baselineBundle.knowledge\n const candidate = candidateBundle.knowledge\n if (!baseline && !candidate) {\n throw new Error('knowledge candidate pair is not present')\n }\n if (\n !baseline ||\n !candidate ||\n canonicalCandidateDigest({ candidate: baseline.candidate, evaluation: baseline.evaluation }) !==\n canonicalCandidateDigest({ candidate: candidate.candidate, evaluation: candidate.evaluation })\n ) {\n throw new Error(\n 'knowledge experiment arms must share one measured candidate and evaluation identity',\n )\n }\n return candidate\n}\n\nfunction assertCodeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): void {\n const baseline = baselineBundle.code\n const candidate = candidateBundle.code\n if (\n canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate) ||\n candidate.kind !== 'git-patch'\n ) {\n return\n }\n const baselineTree =\n baseline.kind === 'no-op'\n ? baseline.baseTree\n : baseline.kind === 'git-patch'\n ? baseline.candidateTree\n : undefined\n const baselineRepository = baseline.kind === 'disabled' ? undefined : baseline.repository\n if (\n baselineTree !== candidate.baseTree ||\n !baselineRepository ||\n canonicalCandidateDigest(baselineRepository) !== canonicalCandidateDigest(candidate.repository)\n ) {\n throw new Error(\n 'code candidate must be based on the exact repository tree measured by the baseline arm',\n )\n }\n}\n\nfunction improvementSurfaceValues(\n bundle: AgentCandidateBundle,\n): Record<AgentImprovementSurface, unknown> {\n const profile = agentCandidateProfileAsAgentProfile(bundle.profile)\n return {\n prompt: agentImprovementProfileSurfaceInput(profile, 'prompt'),\n skills: agentImprovementProfileSurfaceInput(profile, 'skills'),\n tools: agentImprovementProfileSurfaceInput(profile, 'tools'),\n mcp: agentImprovementProfileSurfaceInput(profile, 'mcp'),\n hooks: agentImprovementProfileSurfaceInput(profile, 'hooks'),\n subagents: agentImprovementProfileSurfaceInput(profile, 'subagents'),\n 'agent-profile': { profile: opaqueProfileSlice(profile), execution: bundle.execution },\n memory: {\n instructions: profile.resources?.instructions ?? null,\n executionPolicy: bundle.memory,\n },\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","import type {\n CampaignScenarioIdentity,\n OptimizationMethodComparison,\n OptimizationPackageSource,\n OptimizationTokenUsage,\n} from '@tangle-network/agent-eval/campaign'\nimport { campaignSplitDigestFromIdentities } from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentCandidateJsonValue,\n type AgentImprovementMeasuredComparison,\n type AgentProfile,\n agentProfileModelHintsSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport type { ImproveMethodResult, ImproveScenarioPartitions } from '../improvement/improve'\n\ntype OptimizationProvenance = NonNullable<OptimizationMethodComparison['best']['provenance']>\n\nexport interface OptimizationActivationReceipt {\n kind: 'optimization-activation-receipt'\n method: string\n source: OptimizationPackageSource\n bridge?: OptimizationPackageSource\n modules?: OptimizationProvenance['modules']\n python?: OptimizationProvenance['python']\n models?: {\n candidate?: NonNullable<AgentProfile['model']>\n optimizer?: string\n }\n usage: {\n optimizerEvaluations: number\n optimizerTokens?: OptimizationTokenUsage\n }\n cost: {\n optimization: OptimizationReceiptCost\n finalTest: OptimizationReceiptCost\n total: OptimizationReceiptCost\n }\n invocation: {\n runtimeInvocationId: string\n optimizerRunId: string\n compatibleOptimizerRunId?: string\n resumed: boolean\n artifactDir: string\n }\n developmentDataDigest: Sha256Digest\n finalTestDataDigest: Sha256Digest\n scenarioPartitions: ImproveScenarioPartitions\n digest: Sha256Digest\n}\n\nexport interface OptimizationReceiptCost {\n totalUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport const optimizationReceiptMetadataKey = 'optimizationReceipt'\n\n/** Build a detached receipt only for methods backed by an identified external optimizer. */\nexport function createOptimizationActivationReceipt(\n improvement: ImproveMethodResult,\n): OptimizationActivationReceipt | undefined {\n const provenance = improvement.provenance\n if (!provenance) return undefined\n const finalTestDataDigest = improvement.lineage.finalTestSplitDigest\n if (!finalTestDataDigest) {\n throw new Error('method improvement does not retain its final-test split digest')\n }\n const optimizerModel = provenance.optimizerModel\n const candidateModel = improvement.candidate.profile.model\n\n return canonicalCandidateDocument<OptimizationActivationReceipt>({\n kind: 'optimization-activation-receipt',\n method: improvement.method,\n source: provenance.source,\n ...(provenance.bridge ? { bridge: provenance.bridge } : {}),\n ...(provenance.modules ? { modules: provenance.modules } : {}),\n ...(provenance.python ? { python: provenance.python } : {}),\n ...(candidateModel || optimizerModel\n ? {\n models: {\n ...(candidateModel ? { candidate: candidateModel } : {}),\n ...(optimizerModel ? { optimizer: optimizerModel } : {}),\n },\n }\n : {}),\n usage: {\n optimizerEvaluations: provenance.evaluationCount,\n ...(provenance.tokenUsage ? { optimizerTokens: provenance.tokenUsage } : {}),\n },\n cost: {\n optimization: receiptCost(improvement.raw.optimizationCost),\n finalTest: receiptCost(improvement.raw.testCost),\n total: receiptCost(improvement.raw.totalCost),\n },\n invocation: {\n runtimeInvocationId: improvement.lineage.invocationId,\n optimizerRunId: provenance.runId,\n ...(provenance.compatibleRunId\n ? { compatibleOptimizerRunId: provenance.compatibleRunId }\n : {}),\n resumed: provenance.resumed,\n artifactDir: provenance.artifactDir,\n },\n developmentDataDigest: improvement.lineage.developmentSplitDigest,\n finalTestDataDigest,\n scenarioPartitions: improvement.lineage.scenarioPartitions,\n }).value\n}\n\n/** Add Runtime-owned optimizer evidence without aliasing caller metadata. */\nexport function attachOptimizationActivationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n receipt: OptimizationActivationReceipt,\n): NonNullable<AgentImprovementMeasuredComparison['metadata']> {\n assertNoCallerOptimizationReceipt(metadata)\n return immutableCandidateValue({\n ...(metadata ?? {}),\n [optimizationReceiptMetadataKey]: receipt as unknown as AgentCandidateJsonValue,\n })\n}\n\nexport function assertNoCallerOptimizationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): void {\n if (metadata && Object.hasOwn(metadata, optimizationReceiptMetadataKey)) {\n throw new Error(`candidate metadata reserves '${optimizationReceiptMetadataKey}' for Runtime`)\n }\n}\n\n/** Read and verify the optimizer evidence carried by a measured proposal. */\nexport function optimizationActivationReceiptFromMetadata(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): OptimizationActivationReceipt | undefined {\n const value = metadata?.[optimizationReceiptMetadataKey]\n if (value === undefined) return undefined\n return immutableCandidateValue(parseOptimizationActivationReceipt(value))\n}\n\nfunction parseOptimizationActivationReceipt(\n value: AgentCandidateJsonValue,\n): OptimizationActivationReceipt {\n if (!isRecord(value) || value.kind !== 'optimization-activation-receipt') {\n throw new Error('optimization receipt must be an optimization-activation-receipt')\n }\n if (\n !isNonEmptyString(value.method) ||\n !isPackageSource(value.source) ||\n (value.bridge !== undefined && !isPackageSource(value.bridge)) ||\n !isModules(value.modules) ||\n !isPythonRuntime(value.python) ||\n !isModels(value.models) ||\n !isUsage(value.usage) ||\n !isCost(value.cost) ||\n !isInvocation(value.invocation) ||\n !isSha256Digest(value.developmentDataDigest) ||\n !isSha256Digest(value.finalTestDataDigest) ||\n !isScenarioPartitions(value.scenarioPartitions) ||\n !isSha256Digest(value.digest)\n ) {\n throw new Error('optimization receipt contains invalid evidence')\n }\n const receipt = value as unknown as OptimizationActivationReceipt\n if (!hasMatchingScenarioPartitionDigests(receipt)) {\n throw new Error('optimization receipt task identities do not match its split digests')\n }\n if (canonicalCandidateDigest(omitTopLevelDigest(receipt)) !== receipt.digest) {\n throw new Error('optimization receipt digest does not match its evidence')\n }\n return receipt\n}\n\nfunction isScenarioPartitions(value: unknown): value is ImproveScenarioPartitions {\n if (!isRecord(value)) return false\n return (\n isScenarioIdentityList(value.train) &&\n isScenarioIdentityList(value.selection) &&\n isScenarioIdentityList(value.finalTest) &&\n isPositiveSafeInteger(value.optimizationReps) &&\n isPositiveSafeInteger(value.finalTestReps)\n )\n}\n\nfunction isScenarioIdentityList(value: unknown): value is CampaignScenarioIdentity[] {\n return (\n Array.isArray(value) &&\n value.every(\n (scenario) =>\n isRecord(scenario) &&\n isNonEmptyString(scenario.id) &&\n isNonEmptyString(scenario.kind) &&\n isSha256Digest(scenario.scenarioDigest),\n )\n )\n}\n\nfunction hasMatchingScenarioPartitionDigests(receipt: OptimizationActivationReceipt): boolean {\n try {\n const { scenarioPartitions } = receipt\n const developmentDataDigest = canonicalCandidateDigest({\n train: campaignSplitDigestFromIdentities(\n scenarioPartitions.train,\n scenarioPartitions.optimizationReps,\n ),\n selection: campaignSplitDigestFromIdentities(\n scenarioPartitions.selection,\n scenarioPartitions.optimizationReps,\n ),\n })\n const finalTestDataDigest = campaignSplitDigestFromIdentities(\n scenarioPartitions.finalTest,\n scenarioPartitions.finalTestReps,\n )\n return (\n receipt.developmentDataDigest === developmentDataDigest &&\n receipt.finalTestDataDigest === finalTestDataDigest\n )\n } catch {\n return false\n }\n}\n\nfunction isPackageSource(value: unknown): value is OptimizationPackageSource {\n if (\n !isRecord(value) ||\n value.kind !== 'package' ||\n (value.evidence !== 'observed' && value.evidence !== 'declared') ||\n !isNonEmptyString(value.package) ||\n !isNonEmptyString(value.version)\n ) {\n return false\n }\n return (\n isOptionalNonEmptyString(value.sourceUrl) &&\n isOptionalNonEmptyString(value.revision) &&\n (value.sourceSha256 === undefined ||\n (typeof value.sourceSha256 === 'string' && /^[0-9a-f]{64}$/.test(value.sourceSha256)))\n )\n}\n\nfunction isModules(value: unknown): boolean {\n return (\n value === undefined ||\n (Array.isArray(value) &&\n value.every(\n (module) =>\n isRecord(module) &&\n isNonEmptyString(module.module) &&\n typeof module.sourceSha256 === 'string' &&\n /^[0-9a-f]{64}$/.test(module.sourceSha256),\n ))\n )\n}\n\nfunction isPythonRuntime(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) && isNonEmptyString(value.implementation) && isNonEmptyString(value.version))\n )\n}\n\nfunction isModels(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) &&\n (value.candidate === undefined ||\n agentProfileModelHintsSchema.safeParse(value.candidate).success) &&\n isOptionalNonEmptyString(value.optimizer) &&\n (value.candidate !== undefined || value.optimizer !== undefined))\n )\n}\n\nfunction isUsage(value: unknown): boolean {\n if (!isRecord(value) || !isNonNegativeInteger(value.optimizerEvaluations)) return false\n if (value.optimizerTokens === undefined) return true\n const tokens = value.optimizerTokens\n if (!isRecord(tokens)) return false\n const inputTokens = tokens.inputTokens\n const outputTokens = tokens.outputTokens\n const totalTokens = tokens.totalTokens\n const calls = tokens.calls\n if (\n !isNonNegativeInteger(inputTokens) ||\n !isNonNegativeInteger(outputTokens) ||\n !isNonNegativeInteger(totalTokens) ||\n !isNonNegativeInteger(calls)\n ) {\n return false\n }\n if (\n !isOptionalNonNegativeInteger(tokens.cachedInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.cacheWriteInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.reasoningTokens)\n ) {\n return false\n }\n const cachedInputTokens =\n typeof tokens.cachedInputTokens === 'number' ? tokens.cachedInputTokens : 0\n const cacheWriteInputTokens =\n typeof tokens.cacheWriteInputTokens === 'number' ? tokens.cacheWriteInputTokens : 0\n const reasoningTokens = typeof tokens.reasoningTokens === 'number' ? tokens.reasoningTokens : 0\n return (\n totalTokens === inputTokens + outputTokens &&\n cachedInputTokens + cacheWriteInputTokens <= inputTokens &&\n reasoningTokens <= outputTokens &&\n (totalTokens === 0 || calls > 0)\n )\n}\n\nfunction isCost(value: unknown): boolean {\n if (\n !isRecord(value) ||\n !isCostPart(value.optimization) ||\n !isCostPart(value.finalTest) ||\n !isCostPart(value.total)\n ) {\n return false\n }\n const optimization = value.optimization as unknown as OptimizationReceiptCost\n const finalTest = value.finalTest as unknown as OptimizationReceiptCost\n const total = value.total as unknown as OptimizationReceiptCost\n return (\n approximatelyEqual(total.totalUsd, optimization.totalUsd + finalTest.totalUsd) &&\n total.accountingComplete === (optimization.accountingComplete && finalTest.accountingComplete)\n )\n}\n\nfunction isCostPart(value: unknown): boolean {\n return (\n isRecord(value) &&\n typeof value.totalUsd === 'number' &&\n Number.isFinite(value.totalUsd) &&\n value.totalUsd >= 0 &&\n typeof value.accountingComplete === 'boolean' &&\n Array.isArray(value.incompleteReasons) &&\n value.incompleteReasons.every((reason) => typeof reason === 'string')\n )\n}\n\nfunction receiptCost(value: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}): OptimizationReceiptCost {\n return {\n totalUsd: value.totalCostUsd,\n accountingComplete: value.accountingComplete,\n incompleteReasons: [...value.incompleteReasons],\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 isInvocation(value: unknown): boolean {\n return (\n isRecord(value) &&\n isNonEmptyString(value.runtimeInvocationId) &&\n isNonEmptyString(value.optimizerRunId) &&\n isOptionalNonEmptyString(value.compatibleOptimizerRunId) &&\n typeof value.resumed === 'boolean' &&\n isNonEmptyString(value.artifactDir)\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, AgentCandidateJsonValue> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction isOptionalNonEmptyString(value: unknown): boolean {\n return value === undefined || isNonEmptyString(value)\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\nfunction isOptionalNonNegativeInteger(value: unknown): boolean {\n return value === undefined || isNonNegativeInteger(value)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value)\n}\n","import { CostLedger, type CostLedgerHandle } from '@tangle-network/agent-eval'\nimport { assertProposalFindings, type ProposalFinding } from '@tangle-network/agent-eval/analyst'\nimport {\n type CampaignScenarioIdentity,\n campaignSplitDigestFromIdentities,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfileImprovementExperimentExecutionInput,\n type CandidateExperimentExecutionInput,\n type CompareCandidateExperimentOptions,\n measuredComparisonFromAgentProfileImprovementExperiment,\n measuredComparisonFromCandidateExperiment,\n runAgentProfileImprovementExperiment,\n runCandidateExperiment,\n type Scenario,\n sealAgentProfileImprovementExperiment,\n sealAgentProfileImprovementSuite,\n sealAgentProfileImprovementTask,\n sealCandidateExperiment,\n verifyAgentProfileImprovementExperimentComparison,\n verifyCandidateExperiment,\n verifyCandidateExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateBenchmarkCellRef,\n AgentCandidateBundle,\n AgentCandidateEvaluationPolicy,\n AgentCandidateExperiment,\n AgentCandidateExperimentMaterial,\n AgentCandidateExperimentMeasurement,\n AgentCandidateLineage,\n AgentCandidateRunCell,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementCost,\n AgentImprovementEvaluation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n AgentImprovementSource,\n AgentProfile,\n AgentProfileImprovementExecutionRef,\n AgentProfileImprovementExperiment,\n AgentProfileImprovementMeasuredComparison,\n AgentProfileImprovementMeasurement,\n AgentProfileImprovementRunReceipt,\n AgentProfileImprovementSuiteInputs,\n AgentProfileImprovementTask,\n AgentProfileImprovementTaskMaterial,\n CandidateExecutionEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n AGENT_IMPROVEMENT_SOURCE_METADATA_KEY,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateRunReceiptSchema,\n agentImprovementActivationSchema,\n agentImprovementProposalSchema,\n agentImprovementReviewSchema,\n agentImprovementSourceMetadata,\n agentImprovementSourceSchema,\n agentProfileImprovementArmSchema,\n agentProfileImprovementExecutionRefSchema,\n candidateExecutionEvidenceSchema,\n numbersApproximatelyEqual,\n} from '@tangle-network/agent-interface'\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 assertCandidateProfileBinding,\n createAgentCandidateProfileActivation,\n materializeAgentCandidateProfilePlan,\n parseAgentCandidateProfileActivation,\n parseExactAgentProfile,\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 {\n type ImproveMethodOptions,\n type ImproveMethodResult,\n type ImproveOptions,\n type ImproveResult,\n improve,\n} from '../improvement/improve'\nimport {\n type AgentImprovementActivationTargetIdentity,\n type AgentProfileMeasuredSurface,\n agentImprovementProfileDiffs,\n assertAgentImprovementActivationTargets,\n buildAgentImprovementActivationTargets,\n deriveChangedSurfaces,\n isAgentProfileMeasuredSurface,\n profileImprovementChangedSurfaces,\n sameAgentImprovementSurfaceSet,\n} from './improvement-surfaces'\nimport {\n assertNoCallerOptimizationReceipt,\n attachOptimizationActivationReceipt,\n createOptimizationActivationReceipt,\n optimizationActivationReceiptFromMetadata,\n} from './optimization-receipt'\nimport type { AgentImprovementProfileStateDigest } from './profile-activation'\n\nexport type {\n AgentImprovementActivation,\n AgentImprovementEvaluation,\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<\n CompareCandidateExperimentOptions,\n 'experiment' | 'measurements' | 'measurement' | 'preparation'\n > {\n experiment: AgentCandidateExperiment\n placeCell: (\n input: CandidateExperimentExecutionInput,\n ) => AgentCandidateExperimentCellPlacement | Promise<AgentCandidateExperimentCellPlacement>\n maxConcurrency?: number\n /** Work before this call. Omit when this function is only measuring a sealed experiment. */\n preparation?: CompareCandidateExperimentOptions['preparation']\n /** Shared account when preparation and held-out work have one customer budget. */\n costLedger?: CostLedgerHandle\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 ProposalFinding[]\n evaluation: AgentImprovementEvaluation\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 intent: AgentImprovementActivationIntent\n /** Runtime derives each exact source digest; callers identify only the records to change. */\n targets: [AgentImprovementActivationTargetIdentity, ...AgentImprovementActivationTargetIdentity[]]\n fundingOwner: string\n authorizedBy: string\n expiresAt: string\n /** Required only when an activation targets the complete `agent-profile` surface. */\n executionRef?: AgentProfileImprovementExecutionRef\n now?: () => Date\n}\n\nexport type AgentImprovementAnalysisOptions = Omit<\n RunAnalystLoopOpts,\n | 'runId'\n | 'inputs'\n | 'improvementProposalSource'\n | 'knowledgeProposalSource'\n | 'onEvent'\n | 'log'\n | 'costLedger'\n | 'costPhase'\n | 'signal'\n> & {\n inputs: Omit<RunAnalystLoopOpts['inputs'], 'judgeInput'> & { judgeInput?: never }\n}\n\ntype WithProposalFindings<T> = T extends unknown\n ? Omit<T, 'findings'> & { findings?: readonly ProposalFinding[] }\n : never\n\nexport interface ProposeAgentImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n profile: AgentProfile\n analysis: AgentImprovementAnalysisOptions\n improvement: WithProposalFindings<ImproveOptions<TScenario, TArtifact>>\n buildExperiment: (input: {\n analysis: RunAnalystLoopResult\n improvement: ImproveResult<TScenario, TArtifact>\n }) => AgentImprovementExperimentMaterial | Promise<AgentImprovementExperimentMaterial>\n placeCell: RunAgentCandidateExperimentOptions['placeCell']\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentImprovementMeasuredComparison['candidate']\n metadata?: AgentImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\n/** Product-supplied experiment material. Runtime supplies optimizer ancestry and the final digest. */\nexport type AgentImprovementExperimentMaterial = Omit<\n AgentCandidateExperimentMaterial,\n 'candidateLineage'\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\n/** Product-owned task material that Runtime freezes before either profile state runs. */\nexport interface AgentProfileImprovementBenchmark {\n tasks: [AgentProfileImprovementTaskMaterial, ...AgentProfileImprovementTaskMaterial[]]\n reps: number\n seeds: [number, ...number[]]\n policy: AgentCandidateEvaluationPolicy\n}\n\n/**\n * One product execution adapter shared by optimizer search and exact profile\n * measurement. `executionRef` must identify both operations and their closure.\n */\nexport interface AgentProfileImprovementExecutor<TScenario extends Scenario, TArtifact> {\n executionRef: AgentProfileImprovementExecutionRef\n optimize: ImproveMethodOptions<TScenario, TArtifact>['agent']\n measure(\n input: AgentProfileImprovementExperimentExecutionInput & { profile: AgentProfile },\n ): Promise<AgentProfileImprovementRunReceipt>\n}\n\n/** The portable profile changes that the measured-profile contract permits. */\nexport type AgentProfileImprovementMethodOptions<TScenario extends Scenario, TArtifact> = Omit<\n ImproveMethodOptions<TScenario, TArtifact>,\n 'agent' | 'executionRef' | 'findings' | 'surface'\n> & {\n surface?: AgentProfileMeasuredSurface\n findings?: readonly ProposalFinding[]\n}\n\n/**\n * Complete profile-improvement path for a product-owned source.\n * Runtime owns analysis, search ancestry, profile diffs, experiment sealing,\n * paired evaluation, and the reviewable proposal. The product keeps its\n * profile bytes, task executor, billing, trace capture, and persistence.\n */\nexport interface ProposeAgentProfileImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n source: AgentImprovementSource\n profile: AgentProfile\n stateDigest: AgentImprovementProfileStateDigest\n analysis: AgentImprovementAnalysisOptions\n improvement: AgentProfileImprovementMethodOptions<TScenario, TArtifact>\n benchmark: AgentProfileImprovementBenchmark\n executor: AgentProfileImprovementExecutor<TScenario, TArtifact>\n /** One customer-approved maximum for analysis, optimization, and measurement. */\n budgetUsd: number\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\nexport interface ProposeAgentProfileImprovementResult {\n analysis: RunAnalystLoopResult\n improvement: ImproveMethodResult\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n proposal: AgentImprovementProposal\n}\n\nfunction sealAgentImprovementExperiment<TScenario extends Scenario, TArtifact>(\n material: AgentImprovementExperimentMaterial,\n improvement: ImproveResult<TScenario, TArtifact>,\n): AgentCandidateExperiment {\n assertRuntimeOwnedExperimentFieldsAbsent(material)\n // Bundle ancestry names the frozen proposal baseline; the optimizer run identifies its full search history.\n const candidateLineage: AgentCandidateLineage = {\n source: 'optimizer',\n parentDigests: [material.baseline.digest],\n runIds: [improvement.lineage.runId],\n developmentSplitDigest: improvement.lineage.developmentSplitDigest,\n }\n const experiment = sealCandidateExperiment({ ...material, candidateLineage })\n assertCandidateReleaseWorkIsFresh(experiment, improvement)\n return experiment\n}\n\nfunction assertRuntimeOwnedExperimentFieldsAbsent(\n material: AgentImprovementExperimentMaterial,\n): void {\n if (material === null || typeof material !== 'object' || Array.isArray(material)) {\n throw new Error('agent improvement experiment material must be an object')\n }\n const supplied = ['candidateLineage', 'digest'].filter((field) => Object.hasOwn(material, field))\n if (supplied.length > 0) {\n throw new Error(\n `agent improvement experiment material must not supply Runtime-owned fields: ${supplied.join(', ')}`,\n )\n }\n}\n\ntype ProposalFindingImprovementProposal = Omit<AgentImprovementProposal, 'findings'> & {\n findings: ProposalFinding[]\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 preparation = options.preparation ?? {\n wallDurationMs: 0,\n cost: { usd: 0, provenance: 'observed' as const },\n }\n const costLedger =\n options.costLedger ??\n (experiment.policy.budgetUsd === undefined\n ? undefined\n : new CostLedger({ costCeilingUsd: experiment.policy.budgetUsd }))\n const run = await runCandidateExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n ...(costLedger ? { costLedger } : {}),\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: run.measurements,\n preparation,\n measurement: run.measurement,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n ...(options.generationsExplored === undefined\n ? {}\n : { generationsExplored: options.generationsExplored }),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n return { experiment, measurements: run.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\nasync function analyzeAgentImprovement(\n runId: string,\n options: AgentImprovementAnalysisOptions,\n costLedger?: CostLedgerHandle,\n signal?: AbortSignal,\n): Promise<{ analysis: RunAnalystLoopResult; findings: ProposalFinding[] }> {\n assertMeasuredAnalysisOptions(options)\n const analysis = await runAnalystLoop({\n ...options,\n runId,\n ...(costLedger ? { costLedger, costPhase: 'profile-improvement-analysis' } : {}),\n ...(signal ? { signal } : {}),\n })\n if (costLedger) assertAnalysisCostRecorded(analysis, costLedger)\n const judgeDerived = analysis.analystResult.findings.filter(\n (finding) => finding.derived_from_judge === true,\n )\n if (judgeDerived.length > 0) {\n throw new Error(\n `agent improvement analysis must not produce judge-derived findings: [${judgeDerived\n .map((finding) => finding.finding_id)\n .join(', ')}]`,\n )\n }\n const findings = assertProposalFindings(\n analysis.analystResult.findings.map((finding) => ({\n ...finding,\n proposal_origin: 'production' as const,\n })),\n 'agent improvement findings',\n )\n return { analysis, findings: [...findings] }\n}\n\nfunction assertMeasuredAnalysisOptions(options: AgentImprovementAnalysisOptions): void {\n const rawOptions = options as RunAnalystLoopOpts\n if (\n rawOptions.knowledgeProposalSource !== undefined ||\n rawOptions.improvementProposalSource !== undefined\n ) {\n throw new Error('measured agent improvement analysis must not run proposal sources')\n }\n if (rawOptions.onEvent !== undefined || rawOptions.log !== undefined) {\n throw new Error('measured agent improvement analysis must not run callbacks')\n }\n if (rawOptions.inputs.judgeInput !== undefined) {\n throw new Error('measured agent improvement analysis must not receive judge input')\n }\n}\n\ninterface ImprovementSearchAccounting {\n costUsd: number\n durationMs: number\n}\n\nfunction completeAnalysisAccounting(analysis: RunAnalystLoopResult): ImprovementSearchAccounting {\n const analysisCost = analysis.analystResult.total_cost_provenance\n if (!analysisCost || analysisCost.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is uncaptured')\n }\n if (\n !Number.isFinite(analysis.analystResult.total_cost_usd) ||\n analysis.analystResult.total_cost_usd < 0\n ) {\n throw new Error('agent improvement analysis cost must be finite and non-negative')\n }\n if (analysisCost.usd !== analysis.analystResult.total_cost_usd) {\n throw new Error('agent improvement analysis cost does not match its provenance')\n }\n if (!Number.isFinite(analysis.durationMs) || analysis.durationMs < 0) {\n throw new Error('agent improvement analysis duration must be finite and non-negative')\n }\n return {\n costUsd: analysis.analystResult.total_cost_usd,\n durationMs: analysis.durationMs,\n }\n}\n\nfunction assertAnalysisCostRecorded(\n analysis: RunAnalystLoopResult,\n costLedger: CostLedgerHandle,\n): void {\n const reported = completeAnalysisAccounting(analysis)\n const summary = costLedger.summary()\n if (!summary.accountingComplete || summary.costProvenance.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is incomplete in the shared account')\n }\n const analysisCost = analysis.analystResult.total_cost_provenance\n if (!analysisCost || analysisCost.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is uncaptured')\n }\n if (\n !numbersApproximatelyEqual(summary.totalCostUsd, reported.costUsd) ||\n summary.costProvenance.kind !== analysisCost.kind\n ) {\n throw new Error('agent improvement analysis cost does not match the shared account')\n }\n}\n\nfunction createProfileImprovementCostLedger(budgetUsd: number): CostLedger {\n if (!Number.isFinite(budgetUsd) || budgetUsd < 0) {\n throw new Error('profile improvement budgetUsd must be a non-negative finite number')\n }\n return new CostLedger({ costCeilingUsd: budgetUsd })\n}\n\nfunction profilePolicyWithBudget(\n policy: AgentCandidateEvaluationPolicy,\n budgetUsd: number,\n): AgentCandidateEvaluationPolicy {\n if (policy.budgetUsd !== undefined && !numbersApproximatelyEqual(policy.budgetUsd, budgetUsd)) {\n throw new Error('profile improvement policy budgetUsd must equal the run budgetUsd')\n }\n return { ...policy, budgetUsd }\n}\n\nfunction profilePreparationAccounting(\n costLedger: CostLedgerHandle,\n startedAt: number,\n): { wallDurationMs: number; cost: AgentImprovementCost } {\n const summary = costLedger.summary()\n if (!summary.accountingComplete || summary.costProvenance.kind === 'uncaptured') {\n throw new Error('profile improvement preparation cost is incomplete')\n }\n return {\n wallDurationMs: Math.max(0, performance.now() - startedAt),\n cost: {\n usd: summary.costProvenance.usd,\n provenance: summary.costProvenance.kind,\n },\n }\n}\n\nfunction completeImprovementSearchAccounting(\n analysis: ImprovementSearchAccounting,\n improvement: {\n cost: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: readonly string[]\n }\n durationMs: number\n },\n): { searchCostUsd: number; searchDurationMs: number } {\n if (!improvement.cost.accountingComplete) {\n throw new Error(\n `agent improvement optimization cost is incomplete: ${improvement.cost.incompleteReasons.join(', ') || 'unspecified'}`,\n )\n }\n if (!Number.isFinite(improvement.cost.totalCostUsd) || improvement.cost.totalCostUsd < 0) {\n throw new Error('agent improvement optimization cost must be finite and non-negative')\n }\n if (!Number.isFinite(improvement.durationMs) || improvement.durationMs < 0) {\n throw new Error('agent improvement optimization duration must be finite and non-negative')\n }\n return {\n searchCostUsd: analysis.costUsd + improvement.cost.totalCostUsd,\n searchDurationMs: analysis.durationMs + improvement.durationMs,\n }\n}\n\nfunction profileStateDigest(\n stateDigest: AgentImprovementProfileStateDigest,\n identity: string,\n profile: AgentProfile,\n): Sha256Digest {\n return agentProfileImprovementArmSchema.parse({\n stateDigest: stateDigest({ identity, profile }),\n }).stateDigest\n}\n\nfunction sealProfileImprovementBenchmark(\n input: AgentProfileImprovementBenchmark,\n): AgentProfileImprovementSuiteInputs {\n const tasks = input.tasks.map((task) => sealAgentProfileImprovementTask(task)) as [\n AgentProfileImprovementTask,\n ...AgentProfileImprovementTask[],\n ]\n return sealAgentProfileImprovementSuite({\n splitDigest: campaignSplitDigestFromIdentities(\n tasks.map(profileTaskScenarioIdentity),\n input.reps,\n ),\n tasks,\n reps: input.reps,\n seeds: input.seeds,\n })\n}\n\nfunction profileTaskScenarioIdentity(task: AgentProfileImprovementTask): CampaignScenarioIdentity {\n return {\n id: task.scenario.id,\n kind: task.scenario.kind,\n scenarioDigest: task.scenario.digest,\n }\n}\n\nfunction assertReleaseSplitIsFresh<TScenario extends Scenario, TArtifact>(\n heldOutSplitDigest: Sha256Digest,\n improvement: ImproveResult<TScenario, TArtifact>,\n): void {\n const consumedSplits = [improvement.lineage.developmentSplitDigest]\n if (improvement.mode === 'method') {\n const finalTestSplitDigest = improvement.lineage.finalTestSplitDigest\n if (!finalTestSplitDigest) {\n throw new Error('method improvement does not retain its final-test split digest')\n }\n consumedSplits.push(finalTestSplitDigest)\n }\n if (consumedSplits.includes(heldOutSplitDigest)) {\n throw new Error('release benchmark reuses an optimizer development or final-test split')\n }\n}\n\nfunction assertReleaseScenariosAreFresh(\n improvement: ImproveMethodResult,\n heldOutScenarios: readonly CampaignScenarioIdentity[],\n): void {\n const optimizerScenarios = new Map<string, string>()\n for (const [partition, scenarios] of [\n ['train', improvement.lineage.scenarioPartitions.train],\n ['selection', improvement.lineage.scenarioPartitions.selection],\n ['final-test', improvement.lineage.scenarioPartitions.finalTest],\n ] as const) {\n for (const scenario of scenarios) {\n optimizerScenarios.set(canonicalCandidateDigest(scenario), partition)\n }\n }\n const reused = heldOutScenarios\n .filter((scenario) => optimizerScenarios.has(canonicalCandidateDigest(scenario)))\n .map(\n (scenario) =>\n `${scenario.id} (${optimizerScenarios.get(canonicalCandidateDigest(scenario))})`,\n )\n if (reused.length > 0) {\n throw new Error(`release benchmark reuses optimizer scenario(s): [${reused.join(', ')}]`)\n }\n}\n\nfunction assertCandidateReleaseWorkIsFresh<TScenario extends Scenario, TArtifact>(\n experiment: AgentCandidateExperiment,\n improvement: ImproveResult<TScenario, TArtifact>,\n): void {\n for (const splitDigest of new Set(\n experiment.benchmark.tasks.map((task) => task.benchmark.splitDigest),\n )) {\n assertReleaseSplitIsFresh(splitDigest, improvement)\n }\n if (improvement.mode !== 'method') return\n assertReleaseScenariosAreFresh(\n improvement,\n experiment.benchmark.tasks.map((task) => task.scenario),\n )\n}\n\nfunction assertProfileReleaseWorkIsFresh(\n benchmark: AgentProfileImprovementSuiteInputs,\n improvement: ImproveMethodResult,\n): void {\n assertReleaseSplitIsFresh(benchmark.suite.splitDigest, improvement)\n assertReleaseScenariosAreFresh(improvement, benchmark.tasks.map(profileTaskScenarioIdentity))\n}\n\nfunction profileImprovementMetadata(\n metadata: AgentProfileImprovementMeasuredComparison['metadata'],\n source: AgentImprovementSource,\n optimizationReceipt: ReturnType<typeof createOptimizationActivationReceipt>,\n): NonNullable<AgentProfileImprovementMeasuredComparison['metadata']> {\n assertNoCallerOptimizationReceipt(metadata)\n if (metadata && Object.hasOwn(metadata, AGENT_IMPROVEMENT_SOURCE_METADATA_KEY)) {\n throw new Error(\n `candidate metadata reserves '${AGENT_IMPROVEMENT_SOURCE_METADATA_KEY}' for Runtime`,\n )\n }\n const sourceMetadata = agentImprovementSourceMetadata(source)\n const merged = { ...(metadata ?? {}), ...sourceMetadata }\n return optimizationReceipt\n ? attachOptimizationActivationReceipt(merged, optimizationReceipt)\n : immutableCandidateValue(merged)\n}\n\n/**\n * Analyze a product-owned profile, search one profile surface, then run the\n * exact baseline and candidate through the product executor before proposing.\n */\nexport async function proposeAgentProfileImprovement<TScenario extends Scenario, TArtifact>(\n options: ProposeAgentProfileImprovementOptions<TScenario, TArtifact>,\n): Promise<ProposeAgentProfileImprovementResult> {\n const source = agentImprovementSourceSchema.parse(options.source)\n const surface = options.improvement.surface ?? 'prompt'\n if (!isAgentProfileMeasuredSurface(surface)) {\n throw new Error(\n 'measured profile improvement supports profile surfaces or a complete agent profile; use the sealed-candidate path for this surface',\n )\n }\n assertMeasuredAnalysisOptions(options.analysis)\n const inputFindings = assertProposalFindings(\n options.improvement.findings ?? [],\n 'profile improvement input findings',\n )\n const costLedger = createProfileImprovementCostLedger(options.budgetUsd)\n const preparationStartedAt = performance.now()\n const profile = parseExactAgentProfile(options.profile, 'profile improvement source')\n const baselineStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n profile,\n )\n if (baselineStateDigest !== source.sourceDigest) {\n throw new Error('profile improvement source digest does not match the measured profile state')\n }\n const policy = profilePolicyWithBudget(options.benchmark.policy, options.budgetUsd)\n if (\n options.improvement.costCeiling !== undefined &&\n !numbersApproximatelyEqual(options.improvement.costCeiling, options.budgetUsd)\n ) {\n throw new Error('profile improvement costCeiling must equal the run budgetUsd')\n }\n const { analysis, findings } = await analyzeAgentImprovement(\n options.runId,\n options.analysis,\n costLedger,\n options.signal,\n )\n const proposalFindings = immutableCandidateValue([...inputFindings, ...findings])\n const improvement = await improve(profile, {\n ...options.improvement,\n executionRef: options.executor.executionRef.digest,\n agent: options.executor.optimize,\n costLedger,\n costCeiling: options.budgetUsd,\n findings: proposalFindings,\n })\n try {\n if (improvement.decision !== 'ship') {\n throw new Error('agent profile improvement search did not produce a promotable candidate')\n }\n const candidateProfile = parseExactAgentProfile(\n improvement.candidate.profile,\n 'profile improvement candidate',\n )\n const candidateStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n candidateProfile,\n )\n if (candidateStateDigest === baselineStateDigest) {\n throw new Error('profile improvement candidate state digest matches the baseline')\n }\n const change = agentImprovementProfileDiffs(profile, candidateProfile, {\n id: `profile-improvement:${candidateStateDigest}`,\n metadata: {\n sourceIdentity: source.sourceIdentity,\n sourceRevision: source.sourceRevision,\n },\n })\n const profileDiffIds = change.map((step) => {\n if (!step.id) throw new Error('profile improvement change requires an exact diff id')\n return step.id\n })\n const benchmark = sealProfileImprovementBenchmark({ ...options.benchmark, policy })\n assertProfileReleaseWorkIsFresh(benchmark, improvement)\n const experiment = sealAgentProfileImprovementExperiment({\n kind: 'agent-profile-improvement-experiment',\n digestAlgorithm: 'rfc8785-sha256',\n source,\n executionRef: options.executor.executionRef,\n baseline: { stateDigest: baselineStateDigest },\n candidate: { stateDigest: candidateStateDigest },\n change,\n candidateLineage: {\n source: 'optimizer',\n parentDigests: [source.sourceDigest],\n runIds: [improvement.lineage.runId],\n profileDiffIds,\n developmentSplitDigest: improvement.lineage.developmentSplitDigest,\n },\n benchmark,\n policy,\n })\n const profilesByStateDigest = new Map<Sha256Digest, AgentProfile>([\n [baselineStateDigest, profile],\n [candidateStateDigest, candidateProfile],\n ])\n const preparation = profilePreparationAccounting(costLedger, preparationStartedAt)\n const run = await runAgentProfileImprovementExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n costLedger,\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const measuredProfile = profilesByStateDigest.get(input.stateDigest)\n if (!measuredProfile) {\n throw new Error('profile improvement execution requested an unknown profile state')\n }\n return options.executor.measure({ ...input, profile: measuredProfile })\n },\n })\n const optimizationReceipt = createOptimizationActivationReceipt(improvement)\n const evaluation = verifyAgentProfileImprovementExperimentComparison(\n measuredComparisonFromAgentProfileImprovementExperiment({\n experiment,\n measurements: run.measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n generationsExplored: improvement.generationsExplored ?? 0,\n preparation,\n measurement: run.measurement,\n metadata: profileImprovementMetadata(options.metadata, source, optimizationReceipt),\n }),\n )\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings: proposalFindings,\n evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return { analysis, improvement, experiment, measurements: run.measurements, proposal }\n } catch (cause) {\n return rethrowAfterCleanup(\n cause,\n () => improvement.dispose(),\n 'proposeAgentProfileImprovement failed',\n )\n }\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 assertNoCallerOptimizationReceipt(options.metadata)\n assertMeasuredAnalysisOptions(options.analysis)\n const inputFindings = assertProposalFindings(\n options.improvement.findings ?? [],\n 'agent improvement input findings',\n )\n const { analysis, findings } = await analyzeAgentImprovement(options.runId, options.analysis)\n const analysisAccounting = completeAnalysisAccounting(analysis)\n const proposalFindings = immutableCandidateValue([...inputFindings, ...findings])\n const improvementInput = {\n ...options.improvement,\n findings: proposalFindings,\n }\n const improvement =\n improvementInput.surface === 'code'\n ? await improve(improvementInput)\n : await improve(options.profile, improvementInput)\n try {\n if (improvement.decision !== 'ship') {\n throw new Error('agent improvement search did not produce a promotable candidate')\n }\n const searchAccounting = completeImprovementSearchAccounting(analysisAccounting, improvement)\n const preparation = {\n wallDurationMs: searchAccounting.searchDurationMs,\n cost: {\n usd: searchAccounting.searchCostUsd,\n provenance: 'estimated' as const,\n },\n }\n const optimizationReceipt =\n improvement.mode === 'method' ? createOptimizationActivationReceipt(improvement) : undefined\n const experiment = sealAgentImprovementExperiment(\n await options.buildExperiment({ analysis, improvement }),\n improvement,\n )\n assertCandidateProfileBinding(options.profile, experiment.baseline.profile)\n assertImprovementCandidateBinding(improvement, experiment)\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 ...(optimizationReceipt\n ? {\n metadata: attachOptimizationActivationReceipt(options.metadata, optimizationReceipt),\n }\n : options.metadata\n ? { metadata: options.metadata }\n : {}),\n ...(improvement.generationsExplored === undefined\n ? {}\n : { generationsExplored: improvement.generationsExplored }),\n preparation,\n })\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings: proposalFindings,\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\nfunction assertImprovementCandidateBinding<TScenario extends Scenario, TArtifact>(\n improvement: ImproveResult<TScenario, TArtifact>,\n experiment: AgentCandidateExperiment,\n): void {\n const candidate = improvement.candidate\n if (candidate.surface !== 'code') {\n try {\n assertCandidateProfileBinding(candidate.profile, experiment.candidate.profile)\n } catch (cause) {\n throw new Error('candidate experiment does not contain the improvement winner', { cause })\n }\n return\n }\n\n const surface = candidate.value\n const code = experiment.candidate.code\n if (\n typeof surface !== 'object' ||\n surface === null ||\n surface.kind !== 'code' ||\n code.kind !== 'git-patch' ||\n code.baseCommit !== surface.baseCommit ||\n code.baseTree !== surface.baseTree ||\n code.candidateTree !== surface.candidateTree ||\n code.patch.artifact.sha256 !== surface.patch.sha256 ||\n code.patch.artifact.byteLength !== surface.patch.byteLength\n ) {\n throw new Error('candidate experiment does not contain the improvement winner')\n }\n if (\n canonicalCandidateDigest(experiment.baseline.profile) !==\n canonicalCandidateDigest(experiment.candidate.profile)\n ) {\n throw new Error('code improvement candidate changed the agent profile')\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 = assertProposalFindings(\n options.findings,\n 'createAgentImprovementProposal findings',\n )\n const { evaluation, changedSurfaces } = validateShippableAgentImprovementEvaluation(\n options.evaluation,\n options.runId,\n 'agent improvement proposal',\n )\n return agentImprovementProposalSchema.parse(\n canonicalCandidateDocument<ProposalFindingImprovementProposal>({\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 const reviewedAt = (input.now ?? (() => new Date()))().toISOString()\n if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) {\n throw new Error('candidate review cannot predate its proposal')\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,\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 const authorizedAt = (options.now ?? (() => new Date()))().toISOString()\n if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) {\n throw new Error('candidate activation cannot predate its approval')\n }\n const targets = buildAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n options.intent,\n options.targets,\n )\n const executionRef = profileActivationExecutionRef(experiment, targets, options.executionRef)\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 candidateDigest: measuredCandidateDigest(proposal),\n ...(executionRef ? { executionRef } : {}),\n intent: options.intent,\n targets,\n fundingOwner: options.fundingOwner,\n authorizedBy: options.authorizedBy,\n authorizedAt,\n expiresAt: options.expiresAt,\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 { changedSurfaces } = validateShippableAgentImprovementEvaluation(\n proposal.evaluation,\n proposal.runId,\n 'agent improvement proposal',\n )\n const changedSurfacesMatch =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? sameAgentImprovementSurfaceSet(proposal.changedSurfaces, changedSurfaces)\n : sameOrderedValues(proposal.changedSurfaces, changedSurfaces)\n if (!changedSurfacesMatch) {\n throw new Error('proposal changed surfaces do not match its exact experiment')\n }\n assertProposalFindings(proposal.findings, 'agent improvement proposal findings')\n return proposal\n}\n\n/** Return a sealed bundle experiment; ordinary profile changes need a product-owned executor. */\nexport function requireSealedCandidateExperiment(\n proposal: AgentImprovementProposal,\n): AgentCandidateExperiment {\n if (proposal.evaluation.kind !== 'agent-improvement-measured-comparison') {\n throw new Error(\n 'agent profile improvement activation requires a product profile-diff executor, not a sealed candidate bundle',\n )\n }\n return proposal.evaluation.experiment\n}\n\nfunction measuredCandidateDigest(proposal: AgentImprovementProposal): Sha256Digest {\n return proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? proposal.evaluation.experiment.candidate.stateDigest\n : proposal.evaluation.experiment.candidate.digest\n}\n\nfunction profileActivationExecutionRef(\n experiment: AgentImprovementEvaluation['experiment'],\n targets: AgentImprovementActivation['targets'],\n executionRef: AgentProfileImprovementExecutionRef | undefined,\n): AgentProfileImprovementExecutionRef | undefined {\n const targetsAgentProfile = targets.some((target) => target.surface === 'agent-profile')\n if (!targetsAgentProfile) {\n if (executionRef !== undefined) {\n throw new Error('profile activation executionRef is valid only for agent-profile targets')\n }\n return undefined\n }\n if (experiment.kind !== 'agent-profile-improvement-experiment') {\n throw new Error('agent-profile activation requires a measured profile experiment')\n }\n if (executionRef === undefined) {\n throw new Error('profile improvement activation requires the measured executor')\n }\n const parsed = agentProfileImprovementExecutionRefSchema.parse(executionRef)\n if (canonicalCandidateDigest(parsed) !== canonicalCandidateDigest(experiment.executionRef)) {\n throw new Error('profile improvement activation executor does not match the measurement')\n }\n return parsed\n}\n\nfunction validateShippableAgentImprovementEvaluation(\n input: unknown,\n runId: string,\n subject: string,\n): {\n evaluation: AgentImprovementEvaluation\n changedSurfaces: AgentImprovementProposal['changedSurfaces']\n} {\n const evaluation = verifyAgentImprovementEvaluation(input)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error(`${subject} requires a passing experiment`)\n }\n if (runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces =\n evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? profileImprovementChangedSurfaces(evaluation.experiment.change)\n : deriveChangedSurfaces(evaluation.experiment.baseline, evaluation.experiment.candidate)\n return { evaluation, changedSurfaces }\n}\n\n/** Use each owning package's complete measurement validator before a proposal is persisted. */\nfunction verifyAgentImprovementEvaluation(input: unknown): AgentImprovementEvaluation {\n if (\n typeof input === 'object' &&\n input !== null &&\n 'kind' in input &&\n input.kind === 'agent-profile-improvement-measured-comparison'\n ) {\n const evaluation = verifyAgentProfileImprovementExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\n }\n const evaluation = verifyCandidateExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\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.candidateDigest !== measuredCandidateDigest(proposal) ||\n Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) ||\n Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)\n ) {\n throw new Error('candidate activation does not bind the measured and approved candidate')\n }\n if (\n activation.targets.some((target) => target.surface === 'agent-profile') &&\n (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison' ||\n activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(proposal.evaluation.experiment.executionRef))\n ) {\n throw new Error('profile activation does not bind the measured executor')\n }\n assertAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n activation.intent,\n activation.targets,\n )\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 = materializeAgentCandidateProfilePlan({\n profile: bundle.profile,\n harness: bundle.execution.harness,\n launch: bundle.execution.launch,\n workspace: bundle.execution.cwd.workspace,\n workspaces: plan.material.workspaces,\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\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;;AAkHjC,SAAgB,iBAAiB,MAAmD;CAClF,MAAM,UAAU,iBACd,mBAAmB,MAAM,KAAK,OAAO,GACrC,0BACF;CACA,6BAA6B,SAAS,kBAAkB;CACxD,MAAM,UAAU,QAAQ;CACxB,MAAM,WAAW,QAAQ,MAAO,SAAU,KAAK;CAC/C,MAAM,QAAQ,qBAAqB,OAAO;CAC1C,MAAM,gBAAgB,4BAA4B,OAAO;CACzD,MAAM,QAAQ,KAAK,WAAW;CAC9B,MAAM,SAAS,KAAK;CAEpB,OAAO;EACL,MAAM,WAAW;EAMjB,yBAAyB;EACzB,MAAM,SAAS,EACb,cACA,UACA,UACA,QACA,YACA,gBACA,YACA,aACC;GACD,OAAO,eAAe;GACtB,IAAI,KAAK,iBAAiB,CAAC,YACzB,MAAM,IAAI,MACR,yFACF;GAEF,MAAM,aAAa,KAAK,YAAY,EAAE,SAAS,CAAC;GAChD,IAAI,OAAO,eAAe,YAAY,WAAW,KAAK,CAAC,CAAC,WAAW,GACjE,MAAM,IAAI,MAAM,8DAA8D;GAEhF,MAAM,iBAAiB,KAAK,oBAAoB,YAAY;GAC5D,IAAI,eAAe,YAAY,YAAY,eAAe,QAAQ,cAChE,MAAM,IAAI,MACR,8EACF;GAEF,MAAM,UAAU,eAAe,cAAc;GAC7C,MAAM,wBAAwB,yBAAyB,QAAQ;GAC/D,MAAM,QAAQ,KAAK,IAAI,GAAG,QAAQ;GAElC,IAAI,cAAc;GAElB,KAAK,IAAI,OAAO,GAAG,OAAO,OAAO,QAAQ;IACvC,OAAO,eAAe;IACtB,MAAM,aAAa,cA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AM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,oBACP,UACA,UACA,OACM;CACN,MAAM,QAAQ,wBAAwB,mBAAmB,QAAQ,CAAC;CAClE,IACE,SAAS,WAAW,SAAS,UAC7B,SAAS,SAAS,WAAW,SAAS,UACtC,SAAS,SAAS,eAAe,MAAM,YAEvC,MAAM,IAAI,MAAM,6CAA6C,OAAO;AAExE;AAEA,SAAS,6BACP,UAKA,OACM;CACN,MAAM,QAAQ,wBAAwB,SAAS,QAAQ;CACvD,IACEA,2BAAyB,SAAS,QAAQ,MAAM,SAAS,UACzD,SAAS,SAAS,WAAW,SAAS,UACtC,SAAS,SAAS,eAAe,MAAM,YAEvC,MAAM,IAAI,MAAM,GAAG,MAAM,8CAA8C;AAE3E;AAEA,SAAS,kBAAqB,MAAoB,OAA8B;CAC9E,OAAO,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,OAAO,UAAU,UAAU,MAAM,MAAM;AAC5F"}
1
+ {"version":3,"file":"improvement-cycle-B8KrGlT4.js","names":["truncate","canonicalCandidateDigest","approximatelyEqual","canonicalCandidateDigest","interfaceCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest"],"sources":["../src/improvement/agentic-generator.ts","../src/improvement/cleanup.ts","../src/improvement/improve-result.ts","../src/improvement/improvement-driver.ts","../src/improvement/rollout-policy.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/method-identity.ts","../src/improvement/method-execution.ts","../src/improvement/improve.ts","../src/intelligence/improvement-surfaces.ts","../src/intelligence/optimization-receipt.ts","../src/intelligence/improvement-cycle.ts"],"sourcesContent":["/**\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. A\n * cli-bridge placement sets `cwd` to the supplied worktree so Pi and other\n * supported harnesses edit the existing candidate directly.\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 * 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 * @stable\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type {\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n ProposalFinding,\n} 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 type { CandidateGenerator } from './improvement-driver'\nimport { optimizerMethod } from './optimizer-prompt'\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/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\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 readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\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 Pi author normally returns `{ backend:'bridge', cwd: worktreePath, ...transport }`. */\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. Omitted means the first dirty\n * shot is the candidate. See `commandVerifier`. */\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 provider = profile.model!.provider!.trim()\n const model = concreteProfileModel(profile)!\n const profileDigest = canonicalAgentProfileDigest(profile)\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\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 async generate({\n worktreePath,\n findings,\n maxShots,\n signal,\n generation,\n candidateIndex,\n costLedger,\n costPhase,\n }) {\n signal.throwIfAborted()\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' && executorConfig.cwd !== worktreePath) {\n throw new Error(\n 'agenticGenerator: bridge executor cwd must equal the candidate worktree path',\n )\n }\n const factory = createExecutor(executorConfig)\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n signal.throwIfAborted()\n const taskPrompt = attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt\n const startedAt = new Date()\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({ kind: 'executor', profile, factory }, taskPrompt, {\n signal: executionSignal,\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(callId ? { callId } : {}),\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 const execution = turn ? detachedSnapshot(turn, 'agenticGenerator shot execution') : 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,\n costReceipt,\n error: shotError,\n })\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError)\n signal.throwIfAborted()\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a Runtime turn')\n }\n\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, {\n kind: 'clean',\n worktreePath,\n })\n signal.throwIfAborted()\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n if (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 attemptNote = problem\n continue\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 (!verify) {\n signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\n }\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 signal.throwIfAborted()\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n })\n signal.throwIfAborted()\n return acceptedCandidate(findings)\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 attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\nasync 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\nasync function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nasync 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\nfunction 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(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\nfunction 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\nfunction 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\nfunction sha256(value: string): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\n/** Turn proposal findings into a concrete coder task —\n * the senior scientific-method framing shared with the tool/MCP build prompts. */\nexport function defaultBuildPrompt(args: { findings: ReadonlyArray<ProposalFinding> }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis: real runs failed, an',\n 'analyst distilled the findings below, and your change will be measured on held-out tasks',\n 'against the unchanged baseline — only a real lift promotes it.',\n '',\n optimizerMethod,\n '',\n 'THE SURFACE — what a deliverable change looks like here:',\n '- edit this codebase in place: the smallest coherent change set that fully tests your',\n ' hypothesis about the dominant failure mode (see the method above — no unrelated edits,',\n ' they confound the measurement),',\n '- keep the diff reviewable: a reviewer should be able to trace every hunk back to a finding,',\n '- do not commit — leave changes in the working tree.',\n '',\n 'FINDINGS — ranked evidence from real failed runs:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n if (requiresRawTraceEvidence(args.findings)) {\n lines.push(\n '',\n 'Raw trace evidence requirement:',\n `- Inspect at least one raw trace path named above before editing.`,\n `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,\n '- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.',\n '- A candidate without this file, or with only this file changed, is discarded.',\n )\n }\n return lines.join('\\n')\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\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/** 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\nfunction worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain', '--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 return result.stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => line.slice(3).trim())\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\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<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","/** Serialize and apply Runtime's structural rollout profile coordinate. */\n\nimport type { MutableSurface } from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Returns `undefined` for non-strings,\n * malformed JSON, or values outside the policy invariants. Unknown fields are\n * dropped; supported optional fields are preserved. */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n }\n}\n\n/** Stable serialization with fixed field order. */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout. */\nexport function structuralRolloutPolicyFromProfile(\n profile: ReadonlyAgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a detached policy under the profile extension without mutating the input. */\nexport function applyRolloutPolicyToProfile(\n profile: ReadonlyAgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const candidate = structuredClone(profile) as AgentProfile\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n }\n return {\n ...candidate,\n extensions: { ...candidate.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\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 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\nexport interface 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 const value = profileComponents.read(profile)\n return {\n surface: componentSurface(value, 'profileComponents.read'),\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 = validateProfileCandidate(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 validateProfileCandidate(candidate, surface)\n}\n\nfunction validateProfileCandidate(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 baselineDigest = canonicalCandidateDigest(baselineSurface)\n if (profileComponents) {\n const reappliedBaseline = materializeImprovementProfileCandidate(\n profile,\n surface,\n baselineSurface,\n skills,\n profileComponents,\n )\n if (canonicalCandidateDigest(reappliedBaseline) !== canonicalCandidateDigest(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 digest = canonicalCandidateDigest(candidateSurface)\n const existing = candidates.get(digest)\n if (existing) return existing\n const candidate = materializeImprovementProfileCandidate(\n profile,\n surface,\n immutableCandidateValue(candidateSurface),\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\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?: 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 { 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 SelfImproveResult,\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/** 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: 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 = 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: SelfImproveResult<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\nexport interface 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 {\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}\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): void {\n const { cost } = result\n const observed =\n costAttribution === 'optimizer-run' && result.provenance?.runId\n ? compatibleLedger.summary({ tags: { optimizerRun: result.provenance.runId } })\n : invocationLedger.summary()\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 }\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","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","import { randomUUID } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport {\n type CampaignStorage,\n compareOptimizationMethods,\n decodeExternalTextCandidate,\n type OptimizationMethod,\n type OptimizationMethodComparison,\n readExternalOptimizerObservationArtifact,\n readGepaCandidatePopulationArtifact,\n} from '@tangle-network/agent-eval/campaign'\nimport type { MutableSurface, Scenario } from '@tangle-network/agent-eval/contract'\nimport {\n type AgentProfile,\n applyAgentProfileDiff,\n diffAgentProfiles,\n canonicalCandidateDigest as interfaceCandidateDigest,\n type Sha256Digest,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport { copyImproveCost } from './improve-result'\nimport type {\n ImproveCandidateValidationInput,\n ImproveMethodContext,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementProfileCandidate,\n ImprovementProfileCandidatePopulation,\n ImprovementProfilePopulationCandidateSource,\n ImprovementProfilePopulationLineageNode,\n} from './improve-types'\nimport { methodRuntimeControlsOf } from './method-controls'\nimport {\n assertMethodCostRecorded,\n methodInputWithScopedCost,\n methodInvocationCostLedger,\n} from './method-cost'\nimport { buildMethodEvaluationIdentity } from './method-identity'\nimport {\n assertCandidateSurfaceKind,\n createProfileCandidateMaterializer,\n prepareProfileSurface,\n} 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\nfunction copyProvenance(\n provenance: NonNullable<OptimizationMethodComparison['best']['provenance']>,\n): NonNullable<OptimizationMethodComparison['best']['provenance']> {\n return immutableCandidateValue(provenance)\n}\n\nfunction validateExecutionRef(value: unknown): Sha256Digest {\n const parsed = sha256DigestSchema.safeParse(value)\n if (!parsed.success) {\n throw new ConfigError('improve(): executionRef must be a lowercase sha256:<64 hex> digest')\n }\n return parsed.data\n}\n\nfunction materializationError(error: unknown): { name: string; message: string } {\n if (error instanceof Error) {\n return { name: error.name, message: error.message }\n }\n return {\n name: 'Error',\n message:\n typeof error === 'string' ? error : 'candidate materialization threw a non-Error value',\n }\n}\n\nfunction profileCandidatePopulation(\n provenance: OptimizationMethodComparison['best']['provenance'],\n baselineProfile: AgentProfile,\n materializeProfile: (candidateSurface: MutableSurface) => AgentProfile,\n winnerSurface: MutableSurface,\n storage?: CampaignStorage,\n): ImprovementProfileCandidatePopulation {\n const observationSummary = provenance?.observations\n const graphSummary = provenance?.gepaCandidatePopulation\n if (!observationSummary && !graphSummary) {\n return Object.freeze({\n status: 'unavailable',\n reason: 'method-did-not-report-candidate-population',\n })\n }\n\n const observations = observationSummary\n ? readExternalOptimizerObservationArtifact({\n summary: observationSummary,\n ...(storage ? { storage } : {}),\n })\n : undefined\n const graph = graphSummary\n ? readGepaCandidatePopulationArtifact({\n summary: graphSummary,\n })\n : undefined\n if (!graph && (observations?.candidates.length ?? 0) === 0) {\n return Object.freeze({\n status: 'unavailable',\n reason: 'method-did-not-report-candidate-population',\n })\n }\n interface PopulationEntry {\n candidateDigest: Sha256Digest\n value: MutableSurface\n observation?: {\n proposalSequence: number\n artifact: { path: string; sha256: Sha256Digest }\n }\n lineageNodes: ImprovementProfilePopulationLineageNode[]\n }\n const entries = new Map<Sha256Digest, PopulationEntry>()\n const entryFor = (candidateDigest: Sha256Digest, value: MutableSurface): PopulationEntry => {\n const existing = entries.get(candidateDigest)\n if (existing) {\n if (!isDeepStrictEqual(existing.value, value)) {\n throw new ConfigError(\n `improve(): optimizer artifacts disagree on candidate ${candidateDigest}`,\n )\n }\n return existing\n }\n const entry: PopulationEntry = {\n candidateDigest,\n value: immutableCandidateValue(value),\n lineageNodes: [],\n }\n entries.set(candidateDigest, entry)\n return entry\n }\n\n for (const submitted of observations?.candidates ?? []) {\n const entry = entryFor(\n submitted.candidateDigest,\n decodeExternalTextCandidate(submitted.candidate),\n )\n entry.observation = {\n proposalSequence: submitted.proposalSequence,\n artifact: {\n path: submitted.provenance.path,\n sha256: submitted.provenance.sha256,\n },\n }\n }\n for (const graphCandidate of graph?.candidates ?? []) {\n const entry = entryFor(\n graphCandidate.candidateDigest,\n decodeExternalTextCandidate(graphCandidate.candidate),\n )\n entry.lineageNodes.push({\n index: graphCandidate.index,\n parentIndices: [...graphCandidate.parentIndices],\n aggregateScore: graphCandidate.aggregateScore,\n selectionScores: graphCandidate.selectionScores.map((score) => ({ ...score })),\n discoveryEvaluationCount: graphCandidate.discoveryEvaluationCount,\n })\n }\n\n if (graph) {\n const best = graph.candidates.find((candidate) => candidate.index === graph.bestIndex)\n if (!best) {\n throw new ConfigError(\n `improve(): GEPA candidate population has no bestIndex node ${graph.bestIndex}`,\n )\n }\n const verifiedBest = decodeExternalTextCandidate(best.candidate)\n if (!isDeepStrictEqual(verifiedBest, winnerSurface)) {\n throw new ConfigError(\n 'improve(): method winner does not equal the verified GEPA bestIndex candidate',\n )\n }\n } else if (\n ![...entries.values()].some((entry) => isDeepStrictEqual(entry.value, winnerSurface))\n ) {\n throw new ConfigError(\n 'improve(): method winner does not appear in the verified optimizer observations',\n )\n }\n\n let materializedCandidates = 0\n let refusedCandidates = 0\n const candidates = [...entries.values()].map((entry) => {\n const source: ImprovementProfilePopulationCandidateSource = {\n candidateDigest: entry.candidateDigest,\n ...(entry.observation ? { observation: entry.observation } : {}),\n lineage:\n entry.lineageNodes.length > 0 && graph\n ? {\n status: 'available',\n artifact: {\n path: graph.summary.path,\n sha256: graph.summary.sha256,\n },\n nodes: entry.lineageNodes,\n }\n : {\n status: 'unavailable',\n reason: 'optimizer-did-not-report-candidate-lineage',\n },\n }\n const surfaceDigest = interfaceCandidateDigest(entry.value)\n let candidateProfile: AgentProfile\n try {\n candidateProfile = materializeProfile(entry.value)\n } catch (error) {\n refusedCandidates += 1\n return {\n status: 'refused' as const,\n source,\n value: entry.value,\n surfaceDigest,\n error: materializationError(error),\n }\n }\n\n const profileDigest = interfaceCandidateDigest(candidateProfile)\n const diffs = diffAgentProfiles(baselineProfile, candidateProfile)\n const reproduced = diffs.reduce(applyAgentProfileDiff, baselineProfile)\n if (interfaceCandidateDigest(reproduced) !== profileDigest) {\n throw new ConfigError(\n `improve(): Interface profile diffs do not reproduce optimizer candidate ${entry.candidateDigest}`,\n )\n }\n materializedCandidates += 1\n return {\n status: 'materialized' as const,\n source,\n value: entry.value,\n surfaceDigest,\n profile: candidateProfile,\n profileDigest,\n diffs,\n diffDigests: diffs.map(interfaceCandidateDigest),\n }\n })\n\n return immutableCandidateValue({\n status: 'available',\n source: {\n ...(observations\n ? {\n observations: {\n path: observations.summary.path,\n sha256: observations.summary.sha256,\n },\n }\n : {}),\n ...(graph\n ? {\n gepaCandidateGraph: {\n path: graph.summary.path,\n sha256: graph.summary.sha256,\n bestIndex: graph.bestIndex,\n },\n }\n : {}),\n },\n uniqueCandidates: entries.size,\n observedCandidates: observations?.candidates.length ?? 0,\n gepaCandidateNodes: graph?.candidates.length ?? 0,\n materializedCandidates,\n refusedCandidates,\n candidates,\n })\n}\n\nexport async function runMethodImprovement<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult> {\n const {\n surface = 'prompt',\n executionRef: inputExecutionRef,\n method: methodSource,\n agent,\n validateCandidate,\n findings: inputFindings = [],\n skills,\n profileComponents,\n optimizationRunOptions,\n minimumLift = 0,\n ...comparisonOptions\n } = opts\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 const executionRef = validateExecutionRef(inputExecutionRef)\n const findings = immutableCandidateValue([\n ...assertProposalFindings(inputFindings, '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 = canonicalCandidateDigest(profile)\n const identity = buildMethodEvaluationIdentity({\n executionRef,\n baselineProfileDigest,\n baselineSurface,\n surface,\n skills,\n validateCandidate,\n findings,\n trainScenarios: comparisonOptions.trainScenarios,\n selectionScenarios: comparisonOptions.selectionScenarios,\n testScenarios: comparisonOptions.testScenarios,\n judges: comparisonOptions.judges,\n seed: comparisonOptions.seed,\n reps: comparisonOptions.reps,\n costCeiling: comparisonOptions.costCeiling,\n optimizationRunOptions,\n })\n const { evaluationRef, developmentSplitDigest, finalTestSplitDigest, scenarioPartitions } =\n identity\n const dispatchRef = `improve:${evaluationRef}`\n const identifiedJudges = comparisonOptions.judges.map((judge, index) =>\n Object.freeze({\n ...judge,\n judgeVersion: canonicalCandidateDigest({\n 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 runtimeInvocationId = `runtime-optimization:${randomUUID()}`\n const method = resolveOptimizationMethod(methodSource, {\n profile,\n evaluationRef,\n surface,\n baselineSurface,\n baselineValue,\n findings,\n })\n const methodControls = methodRuntimeControlsOf(method)\n const baselineSurfaceDigest = canonicalCandidateDigest(baselineSurface)\n const validatedCandidates = new Set<Sha256Digest>()\n const materializeProfile = (\n candidateSurface: Parameters<typeof rawMaterializeProfile>[0],\n ): ReturnType<typeof rawMaterializeProfile> => {\n const candidate = rawMaterializeProfile(candidateSurface)\n const candidateDigest = canonicalCandidateDigest(candidateSurface)\n if (!validatedCandidates.has(candidateDigest)) {\n const prepared = prepareProfileSurface(candidate, surface, skills, profileComponents)\n const validationInput: ImproveCandidateValidationInput = Object.freeze({\n profile: candidate,\n surface,\n candidateSurface: immutableCandidateValue(candidateSurface),\n value: immutableCandidateValue(prepared.value),\n isBaseline: candidateDigest === baselineSurfaceDigest,\n })\n methodControls?.validateCandidate(validationInput)\n validateCandidate?.(validationInput)\n validatedCandidates.add(candidateDigest)\n }\n return candidate\n }\n materializeProfile(baselineSurface)\n const measuredMethod: OptimizationMethod<TScenario, TArtifact> = {\n ...method,\n async optimize(input) {\n const costScope = {\n evaluationRef,\n invocationId: runtimeInvocationId,\n }\n const scopedInput = methodInputWithScopedCost(\n input,\n costScope,\n methodControls?.costAttribution,\n )\n const invocationLedger = methodInvocationCostLedger(input.costLedger, costScope)\n const result = await method.optimize(scopedInput)\n assertMethodCostRecorded(\n method.name,\n result,\n scopedInput.costLedger,\n invocationLedger,\n comparisonOptions.costCeiling,\n methodControls?.costAttribution,\n )\n materializeProfile(result.winnerSurface)\n return result\n },\n }\n const startedAt = Date.now()\n const raw = await compareOptimizationMethods<TScenario, TArtifact>({\n ...comparisonOptions,\n judges: identifiedJudges,\n dispatchRef,\n optimizationRunOptions: {\n ...(optimizationRunOptions ?? {}),\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 score = raw.best\n const winnerSurface = immutableCandidateValue(score.winnerSurface)\n assertCandidateSurfaceKind(surface, baselineSurface, winnerSurface)\n const candidateProfile = materializeProfile(winnerSurface)\n const candidate: ImprovementProfileCandidate = Object.freeze({\n surface,\n value: winnerSurface,\n profile: candidateProfile,\n })\n const candidatePopulation = profileCandidatePopulation(\n score.provenance,\n profile,\n materializeProfile,\n winnerSurface,\n optimizationRunOptions?.storage,\n )\n\n const cost = copyImproveCost(raw.totalCost)\n return {\n mode: 'method',\n method: method.name,\n ...(score.provenance ? { provenance: copyProvenance(score.provenance) } : {}),\n candidate,\n decision: cost.accountingComplete && score.liftCi.low > minimumLift ? 'ship' : 'hold',\n lift: score.lift,\n liftInterval: { ...score.liftCi },\n candidatePopulation,\n cost,\n durationMs: Date.now() - startedAt,\n lineage: Object.freeze({\n invocationId: runtimeInvocationId,\n runId: score.provenance?.runId ?? runtimeInvocationId,\n developmentSplitDigest,\n finalTestSplitDigest,\n scenarioPartitions,\n executionRef,\n baselineProfileDigest,\n }),\n raw,\n async dispose() {},\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 is the sole exception. It uses Runtime's isolated git worktrees because\n * checkout ownership and cleanup cannot cross a generic optimizer boundary.\n *\n * @stable\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/contract'\nimport { type AgentProfile, 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} from './improve-types'\nimport { runMethodImprovement } from './method-execution'\n\nexport type {\n ImproveCandidateValidationInput,\n ImproveCandidateValidator,\n ImproveCodeBaseOptions,\n ImproveCodeOptions,\n ImproveCodeResult,\n ImproveCodeRunOptions,\n ImproveCost,\n ImproveCustomCodeGeneratorOptions,\n ImproveLineage,\n ImproveMethodContext,\n ImproveMethodFactory,\n ImproveMethodLineage,\n ImproveMethodOptions,\n ImproveMethodResult,\n ImproveMethodSource,\n ImprovementCandidate,\n ImprovementCodeCandidate,\n ImprovementMaterializedProfilePopulationCandidate,\n ImprovementProfileCandidate,\n ImprovementProfileCandidatePopulation,\n ImprovementProfileCandidatePopulationAvailable,\n ImprovementProfileCandidatePopulationUnavailable,\n ImprovementProfilePopulationArtifactSource,\n ImprovementProfilePopulationCandidate,\n ImprovementProfilePopulationCandidateSource,\n ImprovementProfilePopulationLineage,\n ImprovementProfilePopulationLineageNode,\n ImprovementProfilePopulationObservationSource,\n ImprovementRefusedProfilePopulationCandidate,\n ImproveOptimizationRunOptions,\n ImproveOptions,\n ImproveProfileAgent,\n ImproveProfileComponents,\n ImproveProfileSurface,\n ImproveResult,\n ImproveRuntimeCodeGeneratorOptions,\n ImproveScenarioPartitions,\n ImproveSkillsOptions,\n ImproveSurface,\n} from './improve-types'\n\n/**\n * Optimize one exact profile surface with a complete method.\n */\nexport function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n opts: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveMethodResult>\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: AgentProfile | ImproveCodeRunOptions<TScenario, TArtifact>,\n opts?: ImproveMethodOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\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 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 return runMethodImprovement(immutableCandidateValue(parsedProfile.data), opts)\n}\n","import {\n type AgentCandidateBundle,\n type AgentCandidateExperiment,\n type AgentImprovementActivationIntent,\n type AgentImprovementActivationTarget,\n type AgentImprovementEvaluation,\n type AgentImprovementSurface,\n type AgentProfile,\n type AgentProfileDiff,\n type AgentProfileDiffRemoval,\n type AgentProfileImprovementChange,\n type AgentProfileImprovementExperiment,\n agentProfileDiffSchema,\n agentProfileSchema,\n changedProfileImprovementSurfaces,\n defineAgentProfileDiff,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n agentCandidateProfileAsAgentProfile,\n applyExactAgentProfileDiff,\n omitUndefinedObjectFields,\n parseExactAgentProfile,\n} from '../candidate-execution/profile'\n\nconst changedSurfaceOrder: 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\n/** Agent improvement surfaces delivered as exact `AgentProfileDiff` replacements. */\nexport const AGENT_IMPROVEMENT_PROFILE_SURFACES = [\n 'prompt',\n 'skills',\n 'tools',\n 'mcp',\n 'hooks',\n 'subagents',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentImprovementProfileSurface = (typeof AGENT_IMPROVEMENT_PROFILE_SURFACES)[number]\n\n/**\n * Profile changes eligible for the product-owned measured comparison path.\n * The six directly deliverable profile surfaces retain their granular labels;\n * any residual profile axis also adds the complete `agent-profile` surface.\n */\nexport const AGENT_PROFILE_MEASURED_SURFACES = [\n ...AGENT_IMPROVEMENT_PROFILE_SURFACES,\n 'agent-profile',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentProfileMeasuredSurface = (typeof AGENT_PROFILE_MEASURED_SURFACES)[number]\n\ntype ProfileDifferHandledField =\n | 'name'\n | 'description'\n | 'version'\n | 'tags'\n | 'prompt'\n | 'model'\n | 'harness'\n | 'permissions'\n | 'tools'\n | 'mcp'\n | 'connections'\n | 'subagents'\n | 'resources'\n | 'hooks'\n | 'modes'\n | 'confidential'\n | 'metadata'\n | 'extensions'\ntype MissingProfileDifferField = Exclude<keyof AgentProfile, ProfileDifferHandledField>\nconst profileDifferIsExhaustive: MissingProfileDifferField extends never ? true : never = true\nvoid profileDifferIsExhaustive\n\ntype ProfileResourceDifferHandledField =\n | 'files'\n | 'tools'\n | 'skills'\n | 'agents'\n | 'commands'\n | 'instructions'\n | 'failOnError'\ntype MissingProfileResourceDifferField = Exclude<\n keyof NonNullable<AgentProfile['resources']>,\n ProfileResourceDifferHandledField\n>\nconst profileResourceDifferIsExhaustive: MissingProfileResourceDifferField extends never\n ? true\n : never = true\nvoid profileResourceDifferIsExhaustive\n\nexport interface AgentImprovementTargetProfileDiffOptions {\n id: string\n source?: AgentProfileDiff['source']\n metadata?: Record<string, unknown>\n}\n\nexport type AgentImprovementActivationTargetIdentity = Pick<\n AgentImprovementActivationTarget,\n 'surface' | 'identity'\n>\n\nexport function deriveChangedSurfaces(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (baselineBundle.knowledge || candidateBundle.knowledge) {\n assertKnowledgeCandidatePair(baselineBundle, candidateBundle)\n }\n assertCodeCandidatePair(baselineBundle, candidateBundle)\n const baseline = improvementSurfaceValues(baselineBundle)\n const candidate = improvementSurfaceValues(candidateBundle)\n const changed = changedSurfaceOrder.filter(\n (surface) =>\n canonicalCandidateDigest(baseline[surface]) !== canonicalCandidateDigest(candidate[surface]),\n )\n if (changed.length === 0) throw new Error('candidate experiment does not change an agent surface')\n return changed as [AgentImprovementSurface, ...AgentImprovementSurface[]]\n}\n\nexport function assertAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n targets: readonly AgentImprovementActivationTarget[],\n): void {\n if (isProfileImprovementExperiment(experiment)) {\n assertProfileImprovementTargetsShareIdentity(targets)\n }\n const expected = new Set(surfaces)\n const actual = new Set(targets.map((target) => target.surface))\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n if (\n !(isProfileImprovementExperiment(experiment)\n ? sameAgentImprovementSurfaceSet(surfaces, activationExperimentChangedSurfaces(experiment))\n : sameOrderedSurfaces(surfaces, activationExperimentChangedSurfaces(experiment))) ||\n targets.some((target) => !target.identity.trim()) ||\n targets.some(\n (target) =>\n target.expectedBaseDigest !== activationTargetDigest(experiment, sourceArm, target.surface),\n ) ||\n targets.length !== surfaces.length ||\n expected.size !== actual.size ||\n [...expected].some((surface) => !actual.has(surface))\n ) {\n throw new Error('agent improvement activation targets must cover exactly the changed surfaces')\n }\n}\n\n/** One opaque profile-state transition can change only one complete profile record. */\nexport function assertProfileImprovementTargetsShareIdentity(\n targets: readonly Pick<AgentImprovementActivationTarget, 'identity'>[],\n): void {\n if (new Set(targets.map((target) => target.identity)).size !== 1) {\n throw new Error('profile improvement activation targets must name one profile identity')\n }\n}\n\n/** Bind caller-owned target identities to the exact source state Runtime measured. */\nexport function buildAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n identities: readonly AgentImprovementActivationTargetIdentity[],\n): [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]] {\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targets = identities.map((target) => ({\n ...target,\n expectedBaseDigest: activationTargetDigest(experiment, sourceArm, target.surface),\n }))\n assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets)\n return targets as [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]]\n}\n\n/** Exact host-owned profile state for every changed profile surface. */\nexport function agentProfileImprovementStateDigest(\n experiment: AgentProfileImprovementExperiment,\n arm: 'baseline' | 'candidate',\n): Sha256Digest {\n return experiment[arm].stateDigest\n}\n\n/** Map Interface's current profile-improvement contract to Runtime-deliverable surfaces. */\nexport function profileImprovementChangedSurfaces(\n change: AgentProfileImprovementChange,\n): [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]] {\n const surfaces = changedProfileImprovementSurfaces(change)\n if (\n surfaces.length === 0 ||\n !surfaces.every((surface): surface is AgentProfileMeasuredSurface =>\n isAgentProfileMeasuredSurface(surface),\n )\n ) {\n throw new Error('profile improvement experiment does not change a supported surface')\n }\n return surfaces as [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]]\n}\n\nexport function agentImprovementTargetDigest(\n experiment: AgentCandidateExperiment,\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (surface === 'knowledge') {\n const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate)\n return arm === 'baseline' ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash\n }\n if (surface === 'code') assertCodeCandidatePair(experiment.baseline, experiment.candidate)\n return canonicalCandidateDigest(improvementSurfaceValues(experiment[arm])[surface])\n}\n\nexport function agentImprovementTargetInput(\n bundle: AgentCandidateBundle,\n surface: AgentImprovementSurface,\n): unknown {\n return improvementSurfaceValues(bundle)[surface]\n}\n\nfunction activationTargetDigest(\n experiment: AgentImprovementEvaluation['experiment'],\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (isProfileImprovementExperiment(experiment)) {\n if (!activationExperimentChangedSurfaces(experiment).includes(surface)) {\n throw new Error('profile improvement activation targets an unchanged surface')\n }\n return agentProfileImprovementStateDigest(experiment, arm)\n }\n return agentImprovementTargetDigest(experiment, arm, surface)\n}\n\nfunction activationExperimentChangedSurfaces(\n experiment: AgentImprovementEvaluation['experiment'],\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (!isProfileImprovementExperiment(experiment)) {\n return deriveChangedSurfaces(experiment.baseline, experiment.candidate)\n }\n return profileImprovementChangedSurfaces(experiment.change)\n}\n\nfunction isProfileImprovementExperiment(\n experiment: AgentImprovementEvaluation['experiment'],\n): experiment is AgentProfileImprovementExperiment {\n return experiment.kind === 'agent-profile-improvement-experiment'\n}\n\nfunction sameOrderedSurfaces(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface, index) => surface === right[index])\n}\n\n/** Profile-change surface order is presentation only; its measured contract is set-based. */\nexport function sameAgentImprovementSurfaceSet(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface) => right.includes(surface))\n}\n\n/** Return whether a measured surface can be delivered through an agent profile. */\nexport function isAgentImprovementProfileSurface(\n surface: AgentImprovementSurface,\n): surface is AgentImprovementProfileSurface {\n return (AGENT_IMPROVEMENT_PROFILE_SURFACES as readonly string[]).includes(surface)\n}\n\n/** Return whether a surface is eligible for shared profile measurement. */\nexport function isAgentProfileMeasuredSurface(\n surface: string,\n): surface is AgentProfileMeasuredSurface {\n return (AGENT_PROFILE_MEASURED_SURFACES as readonly string[]).includes(surface)\n}\n\n/**\n * Return the canonical current-state input for one profile-deliverable improvement target.\n * Missing slots become `null`; tools and subagents include both their direct and resource slots.\n * Unrelated profile fields are excluded. The result matches `agentImprovementTargetInput` for the\n * same profile inside a candidate bundle.\n */\nexport function agentImprovementProfileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n const parsed = parseExactAgentProfile(\n omitUndefinedObjectFields(profile, 'agent improvement profile'),\n 'agent improvement profile',\n )\n return immutableCandidateValue(profileSurfaceInput(parsed, surface))\n}\n\nfunction profileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n switch (surface) {\n case 'prompt':\n return { prompt: profile.prompt ?? null }\n case 'skills':\n return profile.resources?.skills ?? null\n case 'tools':\n return {\n tools: profile.tools ?? null,\n resources: profile.resources?.tools ?? null,\n }\n case 'mcp':\n return profile.mcp ?? null\n case 'hooks':\n return profile.hooks ?? null\n case 'subagents':\n return {\n subagents: profile.subagents ?? null,\n resources: profile.resources?.agents ?? null,\n }\n }\n}\n\n/** Return the `Sha256Digest` of one profile surface using Runtime's canonical candidate digest. */\nexport function agentImprovementProfileSurfaceDigest(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): Sha256Digest {\n return canonicalCandidateDigest(agentImprovementProfileSurfaceInput(profile, surface))\n}\n\n/**\n * Replace one measured profile surface exactly, including array-valued resources.\n * Apply the returned diffs in order: a diff applies its set before its removal,\n * so exact replacement requires a reset record followed by a set record.\n */\nexport function agentImprovementTargetProfileDiffs(\n target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n },\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const { remove, set } = improvementSurfaceReplacement(target)\n const common = {\n kind: 'agent-profile-diff' as const,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: target.surface,\n },\n }\n const reset = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:reset`,\n title: `Replace active ${target.surface}`,\n remove,\n }),\n ) as AgentProfileDiff\n if (!set) return [reset]\n const replacement = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:set`,\n title: `Activate measured ${target.surface}`,\n set,\n }),\n ) as AgentProfileDiff\n return [reset, replacement]\n}\n\n/**\n * Derive the ordered profile patch that changes one executable profile into\n * another, then prove the patch preserves the complete candidate state.\n */\nexport function agentImprovementProfileDiffs(\n baselineInput: AgentProfile,\n candidateInput: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const baseline = parseExactAgentProfile(\n omitUndefinedObjectFields(baselineInput, 'profile improvement baseline'),\n 'profile improvement baseline',\n )\n const candidate = parseExactAgentProfile(\n omitUndefinedObjectFields(candidateInput, 'profile improvement candidate'),\n 'profile improvement candidate',\n )\n if (canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate)) {\n throw new Error('profile improvement candidate does not change the profile')\n }\n const completeChanges = completeAgentProfileReplacementDiffs(baseline, candidate, options)\n const applied = completeChanges.reduce(\n (profile, change) =>\n applyExactAgentProfileDiff(profile, change, 'complete profile improvement candidate change'),\n baseline,\n )\n if (canonicalCandidateDigest(applied) !== canonicalCandidateDigest(candidate)) {\n throw new Error('complete profile improvement change did not reproduce the candidate')\n }\n return completeChanges\n}\n\nfunction completeAgentProfileReplacementDiffs(\n baseline: AgentProfile,\n candidate: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const remove: AgentProfileDiffRemoval = {}\n const set: AgentProfile = {}\n if (\n profileValuesDiffer(baseline.name, candidate.name) ||\n profileValuesDiffer(baseline.description, candidate.description) ||\n profileValuesDiffer(baseline.version, candidate.version)\n ) {\n remove.identity = true\n if (candidate.name !== undefined) set.name = candidate.name\n if (candidate.description !== undefined) set.description = candidate.description\n if (candidate.version !== undefined) set.version = candidate.version\n }\n if (profileValuesDiffer(baseline.tags, candidate.tags)) {\n remove.tags = true\n if (candidate.tags !== undefined) set.tags = candidate.tags\n }\n if (profileValuesDiffer(baseline.prompt, candidate.prompt)) {\n remove.prompt = true\n if (candidate.prompt !== undefined) set.prompt = candidate.prompt\n }\n if (profileValuesDiffer(baseline.model, candidate.model)) {\n remove.model = true\n if (candidate.model !== undefined) set.model = candidate.model\n }\n if (profileValuesDiffer(baseline.harness, candidate.harness)) {\n remove.harness = true\n if (candidate.harness !== undefined) set.harness = candidate.harness\n }\n if (profileValuesDiffer(baseline.permissions, candidate.permissions)) {\n remove.permissions = true\n if (candidate.permissions !== undefined) set.permissions = candidate.permissions\n }\n if (profileValuesDiffer(baseline.tools, candidate.tools)) {\n remove.tools = true\n if (candidate.tools !== undefined) set.tools = candidate.tools\n }\n if (profileValuesDiffer(baseline.mcp, candidate.mcp)) {\n remove.mcp = true\n if (candidate.mcp !== undefined) set.mcp = candidate.mcp\n }\n if (profileValuesDiffer(baseline.connections, candidate.connections)) {\n remove.connections = true\n if (candidate.connections !== undefined) set.connections = candidate.connections\n }\n if (profileValuesDiffer(baseline.subagents, candidate.subagents)) {\n remove.subagents = true\n if (candidate.subagents !== undefined) set.subagents = candidate.subagents\n }\n replaceChangedProfileResources(baseline.resources, candidate.resources, remove, set)\n if (profileValuesDiffer(baseline.hooks, candidate.hooks)) {\n remove.hooks = true\n if (candidate.hooks !== undefined) set.hooks = candidate.hooks\n }\n if (profileValuesDiffer(baseline.modes, candidate.modes)) {\n remove.modes = true\n if (candidate.modes !== undefined) set.modes = candidate.modes\n }\n if (profileValuesDiffer(baseline.confidential, candidate.confidential)) {\n remove.confidential = true\n if (candidate.confidential !== undefined) set.confidential = candidate.confidential\n }\n if (profileValuesDiffer(baseline.metadata, candidate.metadata)) {\n remove.metadata = true\n if (candidate.metadata !== undefined) set.metadata = candidate.metadata\n }\n if (profileValuesDiffer(baseline.extensions, candidate.extensions)) {\n remove.extensions = true\n if (candidate.extensions !== undefined) set.extensions = candidate.extensions\n }\n if (Object.keys(remove).length === 0) {\n throw new Error('complete profile differ found no changed fields')\n }\n const common = {\n kind: 'agent-profile-diff' as const,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: 'agent-profile',\n },\n }\n const reset = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:agent-profile:reset`,\n title: 'Reset changed agent profile fields',\n remove,\n }),\n ) as AgentProfileDiff\n if (Object.keys(set).length === 0) return [reset]\n const replacement = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:agent-profile:set`,\n title: 'Set changed agent profile fields',\n set,\n }),\n ) as AgentProfileDiff\n return [reset, replacement]\n}\n\nfunction replaceChangedProfileResources(\n baseline: AgentProfile['resources'],\n candidate: AgentProfile['resources'],\n remove: AgentProfileDiffRemoval,\n set: AgentProfile,\n): void {\n if (!profileValuesDiffer(baseline, candidate)) return\n const resourceRemoval: Exclude<AgentProfileDiffRemoval['resources'], true | undefined> = {}\n const resourceSet: NonNullable<AgentProfile['resources']> = {}\n let changedSubfields = 0\n\n if (profileValuesDiffer(baseline?.files, candidate?.files)) {\n changedSubfields += 1\n resourceRemoval.files = true\n if (candidate?.files !== undefined) resourceSet.files = candidate.files\n }\n if (profileValuesDiffer(baseline?.tools, candidate?.tools)) {\n changedSubfields += 1\n resourceRemoval.tools = true\n if (candidate?.tools !== undefined) resourceSet.tools = candidate.tools\n }\n if (profileValuesDiffer(baseline?.skills, candidate?.skills)) {\n changedSubfields += 1\n resourceRemoval.skills = true\n if (candidate?.skills !== undefined) resourceSet.skills = candidate.skills\n }\n if (profileValuesDiffer(baseline?.agents, candidate?.agents)) {\n changedSubfields += 1\n resourceRemoval.agents = true\n if (candidate?.agents !== undefined) resourceSet.agents = candidate.agents\n }\n if (profileValuesDiffer(baseline?.commands, candidate?.commands)) {\n changedSubfields += 1\n resourceRemoval.commands = true\n if (candidate?.commands !== undefined) resourceSet.commands = candidate.commands\n }\n if (profileValuesDiffer(baseline?.instructions, candidate?.instructions)) {\n changedSubfields += 1\n resourceRemoval.instructions = true\n if (candidate?.instructions !== undefined) resourceSet.instructions = candidate.instructions\n }\n if (profileValuesDiffer(baseline?.failOnError, candidate?.failOnError)) {\n changedSubfields += 1\n resourceRemoval.failOnError = true\n if (candidate?.failOnError !== undefined) resourceSet.failOnError = candidate.failOnError\n }\n\n if (changedSubfields === 0) {\n remove.resources = true\n if (candidate !== undefined) set.resources = candidate\n return\n }\n remove.resources = resourceRemoval\n if (Object.keys(resourceSet).length > 0) set.resources = resourceSet\n}\n\nfunction profileValuesDiffer(baseline: unknown, candidate: unknown): boolean {\n const comparable = (value: unknown) =>\n value === undefined ? { present: false } : { present: true, value }\n return (\n canonicalCandidateDigest(comparable(baseline)) !==\n canonicalCandidateDigest(comparable(candidate))\n )\n}\n\nfunction improvementSurfaceReplacement(target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n}): { remove: AgentProfileDiffRemoval; set?: AgentProfile } {\n const value = target.desiredInput\n switch (target.surface) {\n case 'prompt': {\n const prompt = exactObject(value, ['prompt'], 'prompt activation input').prompt\n assertDefined(prompt, 'prompt activation input.prompt')\n return {\n remove: { prompt: true },\n ...(prompt === null ? {} : { set: parseProfileSet({ prompt }) }),\n }\n }\n case 'skills':\n assertDefined(value, 'skills activation input')\n return {\n remove: { resources: { skills: true } },\n ...(value === null ? {} : { set: parseProfileSet({ resources: { skills: value } }) }),\n }\n case 'tools': {\n const parsed = exactObject(value, ['tools', 'resources'], 'tools activation input')\n assertDefined(parsed.tools, 'tools activation input.tools')\n assertDefined(parsed.resources, 'tools activation input.resources')\n const set = {\n ...(parsed.tools === null ? {} : { tools: parsed.tools }),\n ...(parsed.resources === null ? {} : { resources: { tools: parsed.resources } }),\n }\n return {\n remove: { tools: true, resources: { tools: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n case 'mcp':\n assertDefined(value, 'mcp activation input')\n return {\n remove: { mcp: true },\n ...(value === null ? {} : { set: parseProfileSet({ mcp: value }) }),\n }\n case 'hooks':\n assertDefined(value, 'hooks activation input')\n return {\n remove: { hooks: true },\n ...(value === null ? {} : { set: parseProfileSet({ hooks: value }) }),\n }\n case 'subagents': {\n const parsed = exactObject(value, ['subagents', 'resources'], 'subagents activation input')\n assertDefined(parsed.subagents, 'subagents activation input.subagents')\n assertDefined(parsed.resources, 'subagents activation input.resources')\n const set = {\n ...(parsed.subagents === null ? {} : { subagents: parsed.subagents }),\n ...(parsed.resources === null ? {} : { resources: { agents: parsed.resources } }),\n }\n return {\n remove: { subagents: true, resources: { agents: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n }\n}\n\nfunction assertDefined(value: unknown, label: string): void {\n if (value === undefined) throw new Error(`${label} must not be undefined`)\n}\n\nfunction exactObject(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const record = value as Record<string, unknown>\n const actual = Object.keys(record).sort()\n const expected = [...keys].sort()\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {\n throw new Error(`${label} must contain exactly: ${expected.join(', ')}`)\n }\n return record\n}\n\nfunction parseProfileSet(value: unknown): AgentProfile {\n return agentProfileSchema.parse(value) as AgentProfile\n}\n\nfunction assertKnowledgeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): NonNullable<AgentCandidateBundle['knowledge']> {\n const baseline = baselineBundle.knowledge\n const candidate = candidateBundle.knowledge\n if (!baseline && !candidate) {\n throw new Error('knowledge candidate pair is not present')\n }\n if (\n !baseline ||\n !candidate ||\n canonicalCandidateDigest({ candidate: baseline.candidate, evaluation: baseline.evaluation }) !==\n canonicalCandidateDigest({ candidate: candidate.candidate, evaluation: candidate.evaluation })\n ) {\n throw new Error(\n 'knowledge experiment arms must share one measured candidate and evaluation identity',\n )\n }\n return candidate\n}\n\nfunction assertCodeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): void {\n const baseline = baselineBundle.code\n const candidate = candidateBundle.code\n if (\n canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate) ||\n candidate.kind !== 'git-patch'\n ) {\n return\n }\n const baselineTree =\n baseline.kind === 'no-op'\n ? baseline.baseTree\n : baseline.kind === 'git-patch'\n ? baseline.candidateTree\n : undefined\n const baselineRepository = baseline.kind === 'disabled' ? undefined : baseline.repository\n if (\n baselineTree !== candidate.baseTree ||\n !baselineRepository ||\n canonicalCandidateDigest(baselineRepository) !== canonicalCandidateDigest(candidate.repository)\n ) {\n throw new Error(\n 'code candidate must be based on the exact repository tree measured by the baseline arm',\n )\n }\n}\n\nfunction improvementSurfaceValues(\n bundle: AgentCandidateBundle,\n): Record<AgentImprovementSurface, unknown> {\n const profile = agentCandidateProfileAsAgentProfile(bundle.profile)\n return {\n prompt: agentImprovementProfileSurfaceInput(profile, 'prompt'),\n skills: agentImprovementProfileSurfaceInput(profile, 'skills'),\n tools: agentImprovementProfileSurfaceInput(profile, 'tools'),\n mcp: agentImprovementProfileSurfaceInput(profile, 'mcp'),\n hooks: agentImprovementProfileSurfaceInput(profile, 'hooks'),\n subagents: agentImprovementProfileSurfaceInput(profile, 'subagents'),\n 'agent-profile': { profile: opaqueProfileSlice(profile), execution: bundle.execution },\n memory: {\n instructions: profile.resources?.instructions ?? null,\n executionPolicy: bundle.memory,\n },\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","import type {\n CampaignScenarioIdentity,\n OptimizationMethodComparison,\n OptimizationPackageSource,\n OptimizationTokenUsage,\n} from '@tangle-network/agent-eval/campaign'\nimport { campaignSplitDigestFromIdentities } from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentCandidateJsonValue,\n type AgentImprovementMeasuredComparison,\n type AgentProfile,\n agentProfileModelHintsSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport type { ImproveMethodResult, ImproveScenarioPartitions } from '../improvement/improve'\n\ntype OptimizationProvenance = NonNullable<OptimizationMethodComparison['best']['provenance']>\n\nexport interface OptimizationActivationReceipt {\n kind: 'optimization-activation-receipt'\n method: string\n source: OptimizationPackageSource\n bridge?: OptimizationPackageSource\n modules?: OptimizationProvenance['modules']\n python?: OptimizationProvenance['python']\n models?: {\n candidate?: NonNullable<AgentProfile['model']>\n optimizer?: string\n }\n usage: {\n optimizerEvaluations: number\n optimizerTokens?: OptimizationTokenUsage\n }\n cost: {\n optimization: OptimizationReceiptCost\n finalTest: OptimizationReceiptCost\n total: OptimizationReceiptCost\n }\n invocation: {\n runtimeInvocationId: string\n optimizerRunId: string\n compatibleOptimizerRunId?: string\n resumed: boolean\n artifactDir: string\n }\n developmentDataDigest: Sha256Digest\n finalTestDataDigest: Sha256Digest\n scenarioPartitions: ImproveScenarioPartitions\n digest: Sha256Digest\n}\n\nexport interface OptimizationReceiptCost {\n totalUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport const optimizationReceiptMetadataKey = 'optimizationReceipt'\n\n/** Build a detached receipt only for methods backed by an identified external optimizer. */\nexport function createOptimizationActivationReceipt(\n improvement: ImproveMethodResult,\n): OptimizationActivationReceipt | undefined {\n const provenance = improvement.provenance\n if (!provenance) return undefined\n const finalTestDataDigest = improvement.lineage.finalTestSplitDigest\n if (!finalTestDataDigest) {\n throw new Error('method improvement does not retain its final-test split digest')\n }\n const optimizerModel = provenance.optimizerModel\n const candidateModel = improvement.candidate.profile.model\n\n return canonicalCandidateDocument<OptimizationActivationReceipt>({\n kind: 'optimization-activation-receipt',\n method: improvement.method,\n source: provenance.source,\n ...(provenance.bridge ? { bridge: provenance.bridge } : {}),\n ...(provenance.modules ? { modules: provenance.modules } : {}),\n ...(provenance.python ? { python: provenance.python } : {}),\n ...(candidateModel || optimizerModel\n ? {\n models: {\n ...(candidateModel ? { candidate: candidateModel } : {}),\n ...(optimizerModel ? { optimizer: optimizerModel } : {}),\n },\n }\n : {}),\n usage: {\n optimizerEvaluations: provenance.evaluationCount,\n ...(provenance.tokenUsage ? { optimizerTokens: provenance.tokenUsage } : {}),\n },\n cost: {\n optimization: receiptCost(improvement.raw.optimizationCost),\n finalTest: receiptCost(improvement.raw.testCost),\n total: receiptCost(improvement.raw.totalCost),\n },\n invocation: {\n runtimeInvocationId: improvement.lineage.invocationId,\n optimizerRunId: provenance.runId,\n ...(provenance.compatibleRunId\n ? { compatibleOptimizerRunId: provenance.compatibleRunId }\n : {}),\n resumed: provenance.resumed,\n artifactDir: provenance.artifactDir,\n },\n developmentDataDigest: improvement.lineage.developmentSplitDigest,\n finalTestDataDigest,\n scenarioPartitions: improvement.lineage.scenarioPartitions,\n }).value\n}\n\n/** Add Runtime-owned optimizer evidence without aliasing caller metadata. */\nexport function attachOptimizationActivationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n receipt: OptimizationActivationReceipt,\n): NonNullable<AgentImprovementMeasuredComparison['metadata']> {\n assertNoCallerOptimizationReceipt(metadata)\n return immutableCandidateValue({\n ...(metadata ?? {}),\n [optimizationReceiptMetadataKey]: receipt as unknown as AgentCandidateJsonValue,\n })\n}\n\nexport function assertNoCallerOptimizationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): void {\n if (metadata && Object.hasOwn(metadata, optimizationReceiptMetadataKey)) {\n throw new Error(`candidate metadata reserves '${optimizationReceiptMetadataKey}' for Runtime`)\n }\n}\n\n/** Read and verify the optimizer evidence carried by a measured proposal. */\nexport function optimizationActivationReceiptFromMetadata(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): OptimizationActivationReceipt | undefined {\n const value = metadata?.[optimizationReceiptMetadataKey]\n if (value === undefined) return undefined\n return immutableCandidateValue(parseOptimizationActivationReceipt(value))\n}\n\nfunction parseOptimizationActivationReceipt(\n value: AgentCandidateJsonValue,\n): OptimizationActivationReceipt {\n if (!isRecord(value) || value.kind !== 'optimization-activation-receipt') {\n throw new Error('optimization receipt must be an optimization-activation-receipt')\n }\n if (\n !isNonEmptyString(value.method) ||\n !isPackageSource(value.source) ||\n (value.bridge !== undefined && !isPackageSource(value.bridge)) ||\n !isModules(value.modules) ||\n !isPythonRuntime(value.python) ||\n !isModels(value.models) ||\n !isUsage(value.usage) ||\n !isCost(value.cost) ||\n !isInvocation(value.invocation) ||\n !isSha256Digest(value.developmentDataDigest) ||\n !isSha256Digest(value.finalTestDataDigest) ||\n !isScenarioPartitions(value.scenarioPartitions) ||\n !isSha256Digest(value.digest)\n ) {\n throw new Error('optimization receipt contains invalid evidence')\n }\n const receipt = value as unknown as OptimizationActivationReceipt\n if (!hasMatchingScenarioPartitionDigests(receipt)) {\n throw new Error('optimization receipt task identities do not match its split digests')\n }\n if (canonicalCandidateDigest(omitTopLevelDigest(receipt)) !== receipt.digest) {\n throw new Error('optimization receipt digest does not match its evidence')\n }\n return receipt\n}\n\nfunction isScenarioPartitions(value: unknown): value is ImproveScenarioPartitions {\n if (!isRecord(value)) return false\n return (\n isScenarioIdentityList(value.train) &&\n isScenarioIdentityList(value.selection) &&\n isScenarioIdentityList(value.finalTest) &&\n isPositiveSafeInteger(value.optimizationReps) &&\n isPositiveSafeInteger(value.finalTestReps)\n )\n}\n\nfunction isScenarioIdentityList(value: unknown): value is CampaignScenarioIdentity[] {\n return (\n Array.isArray(value) &&\n value.every(\n (scenario) =>\n isRecord(scenario) &&\n isNonEmptyString(scenario.id) &&\n isNonEmptyString(scenario.kind) &&\n isSha256Digest(scenario.scenarioDigest),\n )\n )\n}\n\nfunction hasMatchingScenarioPartitionDigests(receipt: OptimizationActivationReceipt): boolean {\n try {\n const { scenarioPartitions } = receipt\n const developmentDataDigest = canonicalCandidateDigest({\n train: campaignSplitDigestFromIdentities(\n scenarioPartitions.train,\n scenarioPartitions.optimizationReps,\n ),\n selection: campaignSplitDigestFromIdentities(\n scenarioPartitions.selection,\n scenarioPartitions.optimizationReps,\n ),\n })\n const finalTestDataDigest = campaignSplitDigestFromIdentities(\n scenarioPartitions.finalTest,\n scenarioPartitions.finalTestReps,\n )\n return (\n receipt.developmentDataDigest === developmentDataDigest &&\n receipt.finalTestDataDigest === finalTestDataDigest\n )\n } catch {\n return false\n }\n}\n\nfunction isPackageSource(value: unknown): value is OptimizationPackageSource {\n if (\n !isRecord(value) ||\n value.kind !== 'package' ||\n (value.evidence !== 'observed' && value.evidence !== 'declared') ||\n !isNonEmptyString(value.package) ||\n !isNonEmptyString(value.version)\n ) {\n return false\n }\n return (\n isOptionalNonEmptyString(value.sourceUrl) &&\n isOptionalNonEmptyString(value.revision) &&\n (value.sourceSha256 === undefined ||\n (typeof value.sourceSha256 === 'string' && /^[0-9a-f]{64}$/.test(value.sourceSha256)))\n )\n}\n\nfunction isModules(value: unknown): boolean {\n return (\n value === undefined ||\n (Array.isArray(value) &&\n value.every(\n (module) =>\n isRecord(module) &&\n isNonEmptyString(module.module) &&\n typeof module.sourceSha256 === 'string' &&\n /^[0-9a-f]{64}$/.test(module.sourceSha256),\n ))\n )\n}\n\nfunction isPythonRuntime(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) && isNonEmptyString(value.implementation) && isNonEmptyString(value.version))\n )\n}\n\nfunction isModels(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) &&\n (value.candidate === undefined ||\n agentProfileModelHintsSchema.safeParse(value.candidate).success) &&\n isOptionalNonEmptyString(value.optimizer) &&\n (value.candidate !== undefined || value.optimizer !== undefined))\n )\n}\n\nfunction isUsage(value: unknown): boolean {\n if (!isRecord(value) || !isNonNegativeInteger(value.optimizerEvaluations)) return false\n if (value.optimizerTokens === undefined) return true\n const tokens = value.optimizerTokens\n if (!isRecord(tokens)) return false\n const inputTokens = tokens.inputTokens\n const outputTokens = tokens.outputTokens\n const totalTokens = tokens.totalTokens\n const calls = tokens.calls\n if (\n !isNonNegativeInteger(inputTokens) ||\n !isNonNegativeInteger(outputTokens) ||\n !isNonNegativeInteger(totalTokens) ||\n !isNonNegativeInteger(calls)\n ) {\n return false\n }\n if (\n !isOptionalNonNegativeInteger(tokens.cachedInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.cacheWriteInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.reasoningTokens)\n ) {\n return false\n }\n const cachedInputTokens =\n typeof tokens.cachedInputTokens === 'number' ? tokens.cachedInputTokens : 0\n const cacheWriteInputTokens =\n typeof tokens.cacheWriteInputTokens === 'number' ? tokens.cacheWriteInputTokens : 0\n const reasoningTokens = typeof tokens.reasoningTokens === 'number' ? tokens.reasoningTokens : 0\n return (\n totalTokens === inputTokens + outputTokens &&\n cachedInputTokens + cacheWriteInputTokens <= inputTokens &&\n reasoningTokens <= outputTokens &&\n (totalTokens === 0 || calls > 0)\n )\n}\n\nfunction isCost(value: unknown): boolean {\n if (\n !isRecord(value) ||\n !isCostPart(value.optimization) ||\n !isCostPart(value.finalTest) ||\n !isCostPart(value.total)\n ) {\n return false\n }\n const optimization = value.optimization as unknown as OptimizationReceiptCost\n const finalTest = value.finalTest as unknown as OptimizationReceiptCost\n const total = value.total as unknown as OptimizationReceiptCost\n return (\n approximatelyEqual(total.totalUsd, optimization.totalUsd + finalTest.totalUsd) &&\n total.accountingComplete === (optimization.accountingComplete && finalTest.accountingComplete)\n )\n}\n\nfunction isCostPart(value: unknown): boolean {\n return (\n isRecord(value) &&\n typeof value.totalUsd === 'number' &&\n Number.isFinite(value.totalUsd) &&\n value.totalUsd >= 0 &&\n typeof value.accountingComplete === 'boolean' &&\n Array.isArray(value.incompleteReasons) &&\n value.incompleteReasons.every((reason) => typeof reason === 'string')\n )\n}\n\nfunction receiptCost(value: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}): OptimizationReceiptCost {\n return {\n totalUsd: value.totalCostUsd,\n accountingComplete: value.accountingComplete,\n incompleteReasons: [...value.incompleteReasons],\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 isInvocation(value: unknown): boolean {\n return (\n isRecord(value) &&\n isNonEmptyString(value.runtimeInvocationId) &&\n isNonEmptyString(value.optimizerRunId) &&\n isOptionalNonEmptyString(value.compatibleOptimizerRunId) &&\n typeof value.resumed === 'boolean' &&\n isNonEmptyString(value.artifactDir)\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, AgentCandidateJsonValue> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction isOptionalNonEmptyString(value: unknown): boolean {\n return value === undefined || isNonEmptyString(value)\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\nfunction isOptionalNonNegativeInteger(value: unknown): boolean {\n return value === undefined || isNonNegativeInteger(value)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value)\n}\n","import { CostLedger, type CostLedgerHandle } from '@tangle-network/agent-eval'\nimport { assertProposalFindings, type ProposalFinding } from '@tangle-network/agent-eval/analyst'\nimport {\n type CampaignScenarioIdentity,\n campaignSplitDigestFromIdentities,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfileImprovementExperimentExecutionInput,\n type CandidateExperimentExecutionInput,\n type CompareCandidateExperimentOptions,\n measuredComparisonFromAgentProfileImprovementExperiment,\n measuredComparisonFromCandidateExperiment,\n runAgentProfileImprovementExperiment,\n runCandidateExperiment,\n type Scenario,\n sealAgentProfileImprovementExperiment,\n sealAgentProfileImprovementSuite,\n sealAgentProfileImprovementTask,\n sealCandidateExperiment,\n verifyAgentProfileImprovementExperimentComparison,\n verifyCandidateExperiment,\n verifyCandidateExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateBenchmarkCellRef,\n AgentCandidateBundle,\n AgentCandidateEvaluationPolicy,\n AgentCandidateExperiment,\n AgentCandidateExperimentMaterial,\n AgentCandidateExperimentMeasurement,\n AgentCandidateLineage,\n AgentCandidateRunCell,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementCost,\n AgentImprovementEvaluation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n AgentImprovementSource,\n AgentProfile,\n AgentProfileImprovementExecutionRef,\n AgentProfileImprovementExperiment,\n AgentProfileImprovementMeasuredComparison,\n AgentProfileImprovementMeasurement,\n AgentProfileImprovementRunReceipt,\n AgentProfileImprovementSuiteInputs,\n AgentProfileImprovementTask,\n AgentProfileImprovementTaskMaterial,\n CandidateExecutionEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n AGENT_IMPROVEMENT_SOURCE_METADATA_KEY,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateRunReceiptSchema,\n agentImprovementActivationSchema,\n agentImprovementProposalSchema,\n agentImprovementReviewSchema,\n agentImprovementSourceMetadata,\n agentImprovementSourceSchema,\n agentProfileImprovementArmSchema,\n agentProfileImprovementExecutionRefSchema,\n candidateExecutionEvidenceSchema,\n numbersApproximatelyEqual,\n} from '@tangle-network/agent-interface'\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 assertCandidateProfileBinding,\n createAgentCandidateProfileActivation,\n materializeAgentCandidateProfilePlan,\n parseAgentCandidateProfileActivation,\n parseExactAgentProfile,\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 {\n type ImproveMethodOptions,\n type ImproveMethodResult,\n type ImproveOptions,\n type ImproveResult,\n improve,\n} from '../improvement/improve'\nimport {\n type AgentImprovementActivationTargetIdentity,\n type AgentProfileMeasuredSurface,\n agentImprovementProfileDiffs,\n assertAgentImprovementActivationTargets,\n buildAgentImprovementActivationTargets,\n deriveChangedSurfaces,\n isAgentProfileMeasuredSurface,\n profileImprovementChangedSurfaces,\n sameAgentImprovementSurfaceSet,\n} from './improvement-surfaces'\nimport {\n assertNoCallerOptimizationReceipt,\n attachOptimizationActivationReceipt,\n createOptimizationActivationReceipt,\n optimizationActivationReceiptFromMetadata,\n} from './optimization-receipt'\nimport type { AgentImprovementProfileStateDigest } from './profile-activation'\n\nexport type {\n AgentImprovementActivation,\n AgentImprovementEvaluation,\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<\n CompareCandidateExperimentOptions,\n 'experiment' | 'measurements' | 'measurement' | 'preparation'\n > {\n experiment: AgentCandidateExperiment\n placeCell: (\n input: CandidateExperimentExecutionInput,\n ) => AgentCandidateExperimentCellPlacement | Promise<AgentCandidateExperimentCellPlacement>\n maxConcurrency?: number\n /** Work before this call. Omit when this function is only measuring a sealed experiment. */\n preparation?: CompareCandidateExperimentOptions['preparation']\n /** Shared account when preparation and held-out work have one customer budget. */\n costLedger?: CostLedgerHandle\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 ProposalFinding[]\n evaluation: AgentImprovementEvaluation\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 intent: AgentImprovementActivationIntent\n /** Runtime derives each exact source digest; callers identify only the records to change. */\n targets: [AgentImprovementActivationTargetIdentity, ...AgentImprovementActivationTargetIdentity[]]\n fundingOwner: string\n authorizedBy: string\n expiresAt: string\n /** Required only when an activation targets the complete `agent-profile` surface. */\n executionRef?: AgentProfileImprovementExecutionRef\n now?: () => Date\n}\n\nexport type AgentImprovementAnalysisOptions = Omit<\n RunAnalystLoopOpts,\n | 'runId'\n | 'inputs'\n | 'improvementProposalSource'\n | 'knowledgeProposalSource'\n | 'onEvent'\n | 'log'\n | 'costLedger'\n | 'costPhase'\n | 'signal'\n> & {\n inputs: Omit<RunAnalystLoopOpts['inputs'], 'judgeInput'> & { judgeInput?: never }\n}\n\ntype WithProposalFindings<T> = T extends unknown\n ? Omit<T, 'findings'> & { findings?: readonly ProposalFinding[] }\n : never\n\nexport interface ProposeAgentImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n profile: AgentProfile\n analysis: AgentImprovementAnalysisOptions\n improvement: WithProposalFindings<ImproveOptions<TScenario, TArtifact>>\n buildExperiment: (input: {\n analysis: RunAnalystLoopResult\n improvement: ImproveResult<TScenario, TArtifact>\n }) => AgentImprovementExperimentMaterial | Promise<AgentImprovementExperimentMaterial>\n placeCell: RunAgentCandidateExperimentOptions['placeCell']\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentImprovementMeasuredComparison['candidate']\n metadata?: AgentImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\n/** Product-supplied experiment material. Runtime supplies optimizer ancestry and the final digest. */\nexport type AgentImprovementExperimentMaterial = Omit<\n AgentCandidateExperimentMaterial,\n 'candidateLineage'\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\n/** Product-owned task material that Runtime freezes before either profile state runs. */\nexport interface AgentProfileImprovementBenchmark {\n tasks: [AgentProfileImprovementTaskMaterial, ...AgentProfileImprovementTaskMaterial[]]\n reps: number\n seeds: [number, ...number[]]\n policy: AgentCandidateEvaluationPolicy\n}\n\n/**\n * One product execution adapter shared by optimizer search and exact profile\n * measurement. `executionRef` must identify both operations and their closure.\n */\nexport interface AgentProfileImprovementExecutor<TScenario extends Scenario, TArtifact> {\n executionRef: AgentProfileImprovementExecutionRef\n optimize: ImproveMethodOptions<TScenario, TArtifact>['agent']\n measure(\n input: AgentProfileImprovementExperimentExecutionInput & { profile: AgentProfile },\n ): Promise<AgentProfileImprovementRunReceipt>\n}\n\n/** The portable profile changes that the measured-profile contract permits. */\nexport type AgentProfileImprovementMethodOptions<TScenario extends Scenario, TArtifact> = Omit<\n ImproveMethodOptions<TScenario, TArtifact>,\n 'agent' | 'executionRef' | 'findings' | 'surface'\n> & {\n surface?: AgentProfileMeasuredSurface\n findings?: readonly ProposalFinding[]\n}\n\n/**\n * Complete profile-improvement path for a product-owned source.\n * Runtime owns analysis, search ancestry, profile diffs, experiment sealing,\n * paired evaluation, and the reviewable proposal. The product keeps its\n * profile bytes, task executor, billing, trace capture, and persistence.\n */\nexport interface ProposeAgentProfileImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n source: AgentImprovementSource\n profile: AgentProfile\n stateDigest: AgentImprovementProfileStateDigest\n analysis: AgentImprovementAnalysisOptions\n improvement: AgentProfileImprovementMethodOptions<TScenario, TArtifact>\n benchmark: AgentProfileImprovementBenchmark\n executor: AgentProfileImprovementExecutor<TScenario, TArtifact>\n /** One customer-approved maximum for analysis, optimization, and measurement. */\n budgetUsd: number\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\nexport interface ProposeAgentProfileImprovementResult {\n analysis: RunAnalystLoopResult\n improvement: ImproveMethodResult\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n proposal: AgentImprovementProposal\n}\n\nfunction sealAgentImprovementExperiment<TScenario extends Scenario, TArtifact>(\n material: AgentImprovementExperimentMaterial,\n improvement: ImproveResult<TScenario, TArtifact>,\n): AgentCandidateExperiment {\n assertRuntimeOwnedExperimentFieldsAbsent(material)\n // Bundle ancestry names the frozen proposal baseline; the optimizer run identifies its full search history.\n const candidateLineage: AgentCandidateLineage = {\n source: 'optimizer',\n parentDigests: [material.baseline.digest],\n runIds: [improvement.lineage.runId],\n developmentSplitDigest: improvement.lineage.developmentSplitDigest,\n }\n const experiment = sealCandidateExperiment({ ...material, candidateLineage })\n assertCandidateReleaseWorkIsFresh(experiment, improvement)\n return experiment\n}\n\nfunction assertRuntimeOwnedExperimentFieldsAbsent(\n material: AgentImprovementExperimentMaterial,\n): void {\n if (material === null || typeof material !== 'object' || Array.isArray(material)) {\n throw new Error('agent improvement experiment material must be an object')\n }\n const supplied = ['candidateLineage', 'digest'].filter((field) => Object.hasOwn(material, field))\n if (supplied.length > 0) {\n throw new Error(\n `agent improvement experiment material must not supply Runtime-owned fields: ${supplied.join(', ')}`,\n )\n }\n}\n\ntype ProposalFindingImprovementProposal = Omit<AgentImprovementProposal, 'findings'> & {\n findings: ProposalFinding[]\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 preparation = options.preparation ?? {\n wallDurationMs: 0,\n cost: { usd: 0, provenance: 'observed' as const },\n }\n const costLedger =\n options.costLedger ??\n (experiment.policy.budgetUsd === undefined\n ? undefined\n : new CostLedger({ costCeilingUsd: experiment.policy.budgetUsd }))\n const run = await runCandidateExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n ...(costLedger ? { costLedger } : {}),\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: run.measurements,\n preparation,\n measurement: run.measurement,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n ...(options.generationsExplored === undefined\n ? {}\n : { generationsExplored: options.generationsExplored }),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n return { experiment, measurements: run.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\nasync function analyzeAgentImprovement(\n runId: string,\n options: AgentImprovementAnalysisOptions,\n costLedger?: CostLedgerHandle,\n signal?: AbortSignal,\n): Promise<{ analysis: RunAnalystLoopResult; findings: ProposalFinding[] }> {\n assertMeasuredAnalysisOptions(options)\n const analysis = await runAnalystLoop({\n ...options,\n runId,\n ...(costLedger ? { costLedger, costPhase: 'profile-improvement-analysis' } : {}),\n ...(signal ? { signal } : {}),\n })\n if (costLedger) assertAnalysisCostRecorded(analysis, costLedger)\n const judgeDerived = analysis.analystResult.findings.filter(\n (finding) => finding.derived_from_judge === true,\n )\n if (judgeDerived.length > 0) {\n throw new Error(\n `agent improvement analysis must not produce judge-derived findings: [${judgeDerived\n .map((finding) => finding.finding_id)\n .join(', ')}]`,\n )\n }\n const findings = assertProposalFindings(\n analysis.analystResult.findings.map((finding) => ({\n ...finding,\n proposal_origin: 'production' as const,\n })),\n 'agent improvement findings',\n )\n return { analysis, findings: [...findings] }\n}\n\nfunction assertMeasuredAnalysisOptions(options: AgentImprovementAnalysisOptions): void {\n const rawOptions = options as RunAnalystLoopOpts\n if (\n rawOptions.knowledgeProposalSource !== undefined ||\n rawOptions.improvementProposalSource !== undefined\n ) {\n throw new Error('measured agent improvement analysis must not run proposal sources')\n }\n if (rawOptions.onEvent !== undefined || rawOptions.log !== undefined) {\n throw new Error('measured agent improvement analysis must not run callbacks')\n }\n if (rawOptions.inputs.judgeInput !== undefined) {\n throw new Error('measured agent improvement analysis must not receive judge input')\n }\n}\n\ninterface ImprovementSearchAccounting {\n costUsd: number\n durationMs: number\n}\n\nfunction completeAnalysisAccounting(analysis: RunAnalystLoopResult): ImprovementSearchAccounting {\n const analysisCost = analysis.analystResult.total_cost_provenance\n if (!analysisCost || analysisCost.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is uncaptured')\n }\n if (\n !Number.isFinite(analysis.analystResult.total_cost_usd) ||\n analysis.analystResult.total_cost_usd < 0\n ) {\n throw new Error('agent improvement analysis cost must be finite and non-negative')\n }\n if (analysisCost.usd !== analysis.analystResult.total_cost_usd) {\n throw new Error('agent improvement analysis cost does not match its provenance')\n }\n if (!Number.isFinite(analysis.durationMs) || analysis.durationMs < 0) {\n throw new Error('agent improvement analysis duration must be finite and non-negative')\n }\n return {\n costUsd: analysis.analystResult.total_cost_usd,\n durationMs: analysis.durationMs,\n }\n}\n\nfunction assertAnalysisCostRecorded(\n analysis: RunAnalystLoopResult,\n costLedger: CostLedgerHandle,\n): void {\n const reported = completeAnalysisAccounting(analysis)\n const summary = costLedger.summary()\n if (!summary.accountingComplete || summary.costProvenance.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is incomplete in the shared account')\n }\n const analysisCost = analysis.analystResult.total_cost_provenance\n if (!analysisCost || analysisCost.kind === 'uncaptured') {\n throw new Error('agent improvement analysis cost is uncaptured')\n }\n if (\n !numbersApproximatelyEqual(summary.totalCostUsd, reported.costUsd) ||\n summary.costProvenance.kind !== analysisCost.kind\n ) {\n throw new Error('agent improvement analysis cost does not match the shared account')\n }\n}\n\nfunction createProfileImprovementCostLedger(budgetUsd: number): CostLedger {\n if (!Number.isFinite(budgetUsd) || budgetUsd < 0) {\n throw new Error('profile improvement budgetUsd must be a non-negative finite number')\n }\n return new CostLedger({ costCeilingUsd: budgetUsd })\n}\n\nfunction profilePolicyWithBudget(\n policy: AgentCandidateEvaluationPolicy,\n budgetUsd: number,\n): AgentCandidateEvaluationPolicy {\n if (policy.budgetUsd !== undefined && !numbersApproximatelyEqual(policy.budgetUsd, budgetUsd)) {\n throw new Error('profile improvement policy budgetUsd must equal the run budgetUsd')\n }\n return { ...policy, budgetUsd }\n}\n\nfunction profilePreparationAccounting(\n costLedger: CostLedgerHandle,\n startedAt: number,\n): { wallDurationMs: number; cost: AgentImprovementCost } {\n const summary = costLedger.summary()\n if (!summary.accountingComplete || summary.costProvenance.kind === 'uncaptured') {\n throw new Error('profile improvement preparation cost is incomplete')\n }\n return {\n wallDurationMs: Math.max(0, performance.now() - startedAt),\n cost: {\n usd: summary.costProvenance.usd,\n provenance: summary.costProvenance.kind,\n },\n }\n}\n\nfunction completeImprovementSearchAccounting(\n analysis: ImprovementSearchAccounting,\n improvement: {\n cost: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: readonly string[]\n }\n durationMs: number\n },\n): { searchCostUsd: number; searchDurationMs: number } {\n if (!improvement.cost.accountingComplete) {\n throw new Error(\n `agent improvement optimization cost is incomplete: ${improvement.cost.incompleteReasons.join(', ') || 'unspecified'}`,\n )\n }\n if (!Number.isFinite(improvement.cost.totalCostUsd) || improvement.cost.totalCostUsd < 0) {\n throw new Error('agent improvement optimization cost must be finite and non-negative')\n }\n if (!Number.isFinite(improvement.durationMs) || improvement.durationMs < 0) {\n throw new Error('agent improvement optimization duration must be finite and non-negative')\n }\n return {\n searchCostUsd: analysis.costUsd + improvement.cost.totalCostUsd,\n searchDurationMs: analysis.durationMs + improvement.durationMs,\n }\n}\n\nfunction profileStateDigest(\n stateDigest: AgentImprovementProfileStateDigest,\n identity: string,\n profile: AgentProfile,\n): Sha256Digest {\n return agentProfileImprovementArmSchema.parse({\n stateDigest: stateDigest({ identity, profile }),\n }).stateDigest\n}\n\nfunction sealProfileImprovementBenchmark(\n input: AgentProfileImprovementBenchmark,\n): AgentProfileImprovementSuiteInputs {\n const tasks = input.tasks.map((task) => sealAgentProfileImprovementTask(task)) as [\n AgentProfileImprovementTask,\n ...AgentProfileImprovementTask[],\n ]\n return sealAgentProfileImprovementSuite({\n splitDigest: campaignSplitDigestFromIdentities(\n tasks.map(profileTaskScenarioIdentity),\n input.reps,\n ),\n tasks,\n reps: input.reps,\n seeds: input.seeds,\n })\n}\n\nfunction profileTaskScenarioIdentity(task: AgentProfileImprovementTask): CampaignScenarioIdentity {\n return {\n id: task.scenario.id,\n kind: task.scenario.kind,\n scenarioDigest: task.scenario.digest,\n }\n}\n\nfunction assertReleaseSplitIsFresh<TScenario extends Scenario, TArtifact>(\n heldOutSplitDigest: Sha256Digest,\n improvement: ImproveResult<TScenario, TArtifact>,\n): void {\n const consumedSplits = [improvement.lineage.developmentSplitDigest]\n if (improvement.mode === 'method') {\n const finalTestSplitDigest = improvement.lineage.finalTestSplitDigest\n if (!finalTestSplitDigest) {\n throw new Error('method improvement does not retain its final-test split digest')\n }\n consumedSplits.push(finalTestSplitDigest)\n }\n if (consumedSplits.includes(heldOutSplitDigest)) {\n throw new Error('release benchmark reuses an optimizer development or final-test split')\n }\n}\n\nfunction assertReleaseScenariosAreFresh(\n improvement: ImproveMethodResult,\n heldOutScenarios: readonly CampaignScenarioIdentity[],\n): void {\n const optimizerScenarios = new Map<string, string>()\n for (const [partition, scenarios] of [\n ['train', improvement.lineage.scenarioPartitions.train],\n ['selection', improvement.lineage.scenarioPartitions.selection],\n ['final-test', improvement.lineage.scenarioPartitions.finalTest],\n ] as const) {\n for (const scenario of scenarios) {\n optimizerScenarios.set(canonicalCandidateDigest(scenario), partition)\n }\n }\n const reused = heldOutScenarios\n .filter((scenario) => optimizerScenarios.has(canonicalCandidateDigest(scenario)))\n .map(\n (scenario) =>\n `${scenario.id} (${optimizerScenarios.get(canonicalCandidateDigest(scenario))})`,\n )\n if (reused.length > 0) {\n throw new Error(`release benchmark reuses optimizer scenario(s): [${reused.join(', ')}]`)\n }\n}\n\nfunction assertCandidateReleaseWorkIsFresh<TScenario extends Scenario, TArtifact>(\n experiment: AgentCandidateExperiment,\n improvement: ImproveResult<TScenario, TArtifact>,\n): void {\n for (const splitDigest of new Set(\n experiment.benchmark.tasks.map((task) => task.benchmark.splitDigest),\n )) {\n assertReleaseSplitIsFresh(splitDigest, improvement)\n }\n if (improvement.mode !== 'method') return\n assertReleaseScenariosAreFresh(\n improvement,\n experiment.benchmark.tasks.map((task) => task.scenario),\n )\n}\n\nfunction assertProfileReleaseWorkIsFresh(\n benchmark: AgentProfileImprovementSuiteInputs,\n improvement: ImproveMethodResult,\n): void {\n assertReleaseSplitIsFresh(benchmark.suite.splitDigest, improvement)\n assertReleaseScenariosAreFresh(improvement, benchmark.tasks.map(profileTaskScenarioIdentity))\n}\n\nfunction profileImprovementMetadata(\n metadata: AgentProfileImprovementMeasuredComparison['metadata'],\n source: AgentImprovementSource,\n optimizationReceipt: ReturnType<typeof createOptimizationActivationReceipt>,\n): NonNullable<AgentProfileImprovementMeasuredComparison['metadata']> {\n assertNoCallerOptimizationReceipt(metadata)\n if (metadata && Object.hasOwn(metadata, AGENT_IMPROVEMENT_SOURCE_METADATA_KEY)) {\n throw new Error(\n `candidate metadata reserves '${AGENT_IMPROVEMENT_SOURCE_METADATA_KEY}' for Runtime`,\n )\n }\n const sourceMetadata = agentImprovementSourceMetadata(source)\n const merged = { ...(metadata ?? {}), ...sourceMetadata }\n return optimizationReceipt\n ? attachOptimizationActivationReceipt(merged, optimizationReceipt)\n : immutableCandidateValue(merged)\n}\n\n/**\n * Analyze a product-owned profile, search one profile surface, then run the\n * exact baseline and candidate through the product executor before proposing.\n */\nexport async function proposeAgentProfileImprovement<TScenario extends Scenario, TArtifact>(\n options: ProposeAgentProfileImprovementOptions<TScenario, TArtifact>,\n): Promise<ProposeAgentProfileImprovementResult> {\n const source = agentImprovementSourceSchema.parse(options.source)\n const surface = options.improvement.surface ?? 'prompt'\n if (!isAgentProfileMeasuredSurface(surface)) {\n throw new Error(\n 'measured profile improvement supports profile surfaces or a complete agent profile; use the sealed-candidate path for this surface',\n )\n }\n assertMeasuredAnalysisOptions(options.analysis)\n const inputFindings = assertProposalFindings(\n options.improvement.findings ?? [],\n 'profile improvement input findings',\n )\n const costLedger = createProfileImprovementCostLedger(options.budgetUsd)\n const preparationStartedAt = performance.now()\n const profile = parseExactAgentProfile(options.profile, 'profile improvement source')\n const baselineStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n profile,\n )\n if (baselineStateDigest !== source.sourceDigest) {\n throw new Error('profile improvement source digest does not match the measured profile state')\n }\n const policy = profilePolicyWithBudget(options.benchmark.policy, options.budgetUsd)\n if (\n options.improvement.costCeiling !== undefined &&\n !numbersApproximatelyEqual(options.improvement.costCeiling, options.budgetUsd)\n ) {\n throw new Error('profile improvement costCeiling must equal the run budgetUsd')\n }\n const { analysis, findings } = await analyzeAgentImprovement(\n options.runId,\n options.analysis,\n costLedger,\n options.signal,\n )\n const proposalFindings = immutableCandidateValue([...inputFindings, ...findings])\n const improvement = await improve(profile, {\n ...options.improvement,\n executionRef: options.executor.executionRef.digest,\n agent: options.executor.optimize,\n costLedger,\n costCeiling: options.budgetUsd,\n findings: proposalFindings,\n })\n try {\n if (improvement.decision !== 'ship') {\n throw new Error('agent profile improvement search did not produce a promotable candidate')\n }\n const candidateProfile = parseExactAgentProfile(\n improvement.candidate.profile,\n 'profile improvement candidate',\n )\n const candidateStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n candidateProfile,\n )\n if (candidateStateDigest === baselineStateDigest) {\n throw new Error('profile improvement candidate state digest matches the baseline')\n }\n const change = agentImprovementProfileDiffs(profile, candidateProfile, {\n id: `profile-improvement:${candidateStateDigest}`,\n metadata: {\n sourceIdentity: source.sourceIdentity,\n sourceRevision: source.sourceRevision,\n },\n })\n const profileDiffIds = change.map((step) => {\n if (!step.id) throw new Error('profile improvement change requires an exact diff id')\n return step.id\n })\n const benchmark = sealProfileImprovementBenchmark({ ...options.benchmark, policy })\n assertProfileReleaseWorkIsFresh(benchmark, improvement)\n const experiment = sealAgentProfileImprovementExperiment({\n kind: 'agent-profile-improvement-experiment',\n digestAlgorithm: 'rfc8785-sha256',\n source,\n executionRef: options.executor.executionRef,\n baseline: { stateDigest: baselineStateDigest },\n candidate: { stateDigest: candidateStateDigest },\n change,\n candidateLineage: {\n source: 'optimizer',\n parentDigests: [source.sourceDigest],\n runIds: [improvement.lineage.runId],\n profileDiffIds,\n developmentSplitDigest: improvement.lineage.developmentSplitDigest,\n },\n benchmark,\n policy,\n })\n const profilesByStateDigest = new Map<Sha256Digest, AgentProfile>([\n [baselineStateDigest, profile],\n [candidateStateDigest, candidateProfile],\n ])\n const preparation = profilePreparationAccounting(costLedger, preparationStartedAt)\n const run = await runAgentProfileImprovementExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n costLedger,\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const measuredProfile = profilesByStateDigest.get(input.stateDigest)\n if (!measuredProfile) {\n throw new Error('profile improvement execution requested an unknown profile state')\n }\n return options.executor.measure({ ...input, profile: measuredProfile })\n },\n })\n const optimizationReceipt = createOptimizationActivationReceipt(improvement)\n const evaluation = verifyAgentProfileImprovementExperimentComparison(\n measuredComparisonFromAgentProfileImprovementExperiment({\n experiment,\n measurements: run.measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n generationsExplored: improvement.generationsExplored ?? 0,\n preparation,\n measurement: run.measurement,\n metadata: profileImprovementMetadata(options.metadata, source, optimizationReceipt),\n }),\n )\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings: proposalFindings,\n evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return { analysis, improvement, experiment, measurements: run.measurements, proposal }\n } catch (cause) {\n return rethrowAfterCleanup(\n cause,\n () => improvement.dispose(),\n 'proposeAgentProfileImprovement failed',\n )\n }\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 assertNoCallerOptimizationReceipt(options.metadata)\n assertMeasuredAnalysisOptions(options.analysis)\n const inputFindings = assertProposalFindings(\n options.improvement.findings ?? [],\n 'agent improvement input findings',\n )\n const { analysis, findings } = await analyzeAgentImprovement(options.runId, options.analysis)\n const analysisAccounting = completeAnalysisAccounting(analysis)\n const proposalFindings = immutableCandidateValue([...inputFindings, ...findings])\n const improvementInput = {\n ...options.improvement,\n findings: proposalFindings,\n }\n const improvement =\n improvementInput.surface === 'code'\n ? await improve(improvementInput)\n : await improve(options.profile, improvementInput)\n try {\n if (improvement.decision !== 'ship') {\n throw new Error('agent improvement search did not produce a promotable candidate')\n }\n const searchAccounting = completeImprovementSearchAccounting(analysisAccounting, improvement)\n const preparation = {\n wallDurationMs: searchAccounting.searchDurationMs,\n cost: {\n usd: searchAccounting.searchCostUsd,\n provenance: 'estimated' as const,\n },\n }\n const optimizationReceipt =\n improvement.mode === 'method' ? createOptimizationActivationReceipt(improvement) : undefined\n const experiment = sealAgentImprovementExperiment(\n await options.buildExperiment({ analysis, improvement }),\n improvement,\n )\n assertCandidateProfileBinding(options.profile, experiment.baseline.profile)\n assertImprovementCandidateBinding(improvement, experiment)\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 ...(optimizationReceipt\n ? {\n metadata: attachOptimizationActivationReceipt(options.metadata, optimizationReceipt),\n }\n : options.metadata\n ? { metadata: options.metadata }\n : {}),\n ...(improvement.generationsExplored === undefined\n ? {}\n : { generationsExplored: improvement.generationsExplored }),\n preparation,\n })\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings: proposalFindings,\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\nfunction assertImprovementCandidateBinding<TScenario extends Scenario, TArtifact>(\n improvement: ImproveResult<TScenario, TArtifact>,\n experiment: AgentCandidateExperiment,\n): void {\n const candidate = improvement.candidate\n if (candidate.surface !== 'code') {\n try {\n assertCandidateProfileBinding(candidate.profile, experiment.candidate.profile)\n } catch (cause) {\n throw new Error('candidate experiment does not contain the improvement winner', { cause })\n }\n return\n }\n\n const surface = candidate.value\n const code = experiment.candidate.code\n if (\n typeof surface !== 'object' ||\n surface === null ||\n surface.kind !== 'code' ||\n code.kind !== 'git-patch' ||\n code.baseCommit !== surface.baseCommit ||\n code.baseTree !== surface.baseTree ||\n code.candidateTree !== surface.candidateTree ||\n code.patch.artifact.sha256 !== surface.patch.sha256 ||\n code.patch.artifact.byteLength !== surface.patch.byteLength\n ) {\n throw new Error('candidate experiment does not contain the improvement winner')\n }\n if (\n canonicalCandidateDigest(experiment.baseline.profile) !==\n canonicalCandidateDigest(experiment.candidate.profile)\n ) {\n throw new Error('code improvement candidate changed the agent profile')\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 = assertProposalFindings(\n options.findings,\n 'createAgentImprovementProposal findings',\n )\n const { evaluation, changedSurfaces } = validateShippableAgentImprovementEvaluation(\n options.evaluation,\n options.runId,\n 'agent improvement proposal',\n )\n return agentImprovementProposalSchema.parse(\n canonicalCandidateDocument<ProposalFindingImprovementProposal>({\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 const reviewedAt = (input.now ?? (() => new Date()))().toISOString()\n if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) {\n throw new Error('candidate review cannot predate its proposal')\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,\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 const authorizedAt = (options.now ?? (() => new Date()))().toISOString()\n if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) {\n throw new Error('candidate activation cannot predate its approval')\n }\n const targets = buildAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n options.intent,\n options.targets,\n )\n const executionRef = profileActivationExecutionRef(experiment, targets, options.executionRef)\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 candidateDigest: measuredCandidateDigest(proposal),\n ...(executionRef ? { executionRef } : {}),\n intent: options.intent,\n targets,\n fundingOwner: options.fundingOwner,\n authorizedBy: options.authorizedBy,\n authorizedAt,\n expiresAt: options.expiresAt,\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 { changedSurfaces } = validateShippableAgentImprovementEvaluation(\n proposal.evaluation,\n proposal.runId,\n 'agent improvement proposal',\n )\n const changedSurfacesMatch =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? sameAgentImprovementSurfaceSet(proposal.changedSurfaces, changedSurfaces)\n : sameOrderedValues(proposal.changedSurfaces, changedSurfaces)\n if (!changedSurfacesMatch) {\n throw new Error('proposal changed surfaces do not match its exact experiment')\n }\n assertProposalFindings(proposal.findings, 'agent improvement proposal findings')\n return proposal\n}\n\n/** Return a sealed bundle experiment; ordinary profile changes need a product-owned executor. */\nexport function requireSealedCandidateExperiment(\n proposal: AgentImprovementProposal,\n): AgentCandidateExperiment {\n if (proposal.evaluation.kind !== 'agent-improvement-measured-comparison') {\n throw new Error(\n 'agent profile improvement activation requires a product profile-diff executor, not a sealed candidate bundle',\n )\n }\n return proposal.evaluation.experiment\n}\n\nfunction measuredCandidateDigest(proposal: AgentImprovementProposal): Sha256Digest {\n return proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? proposal.evaluation.experiment.candidate.stateDigest\n : proposal.evaluation.experiment.candidate.digest\n}\n\nfunction profileActivationExecutionRef(\n experiment: AgentImprovementEvaluation['experiment'],\n targets: AgentImprovementActivation['targets'],\n executionRef: AgentProfileImprovementExecutionRef | undefined,\n): AgentProfileImprovementExecutionRef | undefined {\n const targetsAgentProfile = targets.some((target) => target.surface === 'agent-profile')\n if (!targetsAgentProfile) {\n if (executionRef !== undefined) {\n throw new Error('profile activation executionRef is valid only for agent-profile targets')\n }\n return undefined\n }\n if (experiment.kind !== 'agent-profile-improvement-experiment') {\n throw new Error('agent-profile activation requires a measured profile experiment')\n }\n if (executionRef === undefined) {\n throw new Error('profile improvement activation requires the measured executor')\n }\n const parsed = agentProfileImprovementExecutionRefSchema.parse(executionRef)\n if (canonicalCandidateDigest(parsed) !== canonicalCandidateDigest(experiment.executionRef)) {\n throw new Error('profile improvement activation executor does not match the measurement')\n }\n return parsed\n}\n\nfunction validateShippableAgentImprovementEvaluation(\n input: unknown,\n runId: string,\n subject: string,\n): {\n evaluation: AgentImprovementEvaluation\n changedSurfaces: AgentImprovementProposal['changedSurfaces']\n} {\n const evaluation = verifyAgentImprovementEvaluation(input)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error(`${subject} requires a passing experiment`)\n }\n if (runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces =\n evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? profileImprovementChangedSurfaces(evaluation.experiment.change)\n : deriveChangedSurfaces(evaluation.experiment.baseline, evaluation.experiment.candidate)\n return { evaluation, changedSurfaces }\n}\n\n/** Use each owning package's complete measurement validator before a proposal is persisted. */\nfunction verifyAgentImprovementEvaluation(input: unknown): AgentImprovementEvaluation {\n if (\n typeof input === 'object' &&\n input !== null &&\n 'kind' in input &&\n input.kind === 'agent-profile-improvement-measured-comparison'\n ) {\n const evaluation = verifyAgentProfileImprovementExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\n }\n const evaluation = verifyCandidateExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\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.candidateDigest !== measuredCandidateDigest(proposal) ||\n Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) ||\n Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)\n ) {\n throw new Error('candidate activation does not bind the measured and approved candidate')\n }\n if (\n activation.targets.some((target) => target.surface === 'agent-profile') &&\n (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison' ||\n activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(proposal.evaluation.experiment.executionRef))\n ) {\n throw new Error('profile activation does not bind the measured executor')\n }\n assertAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n activation.intent,\n activation.targets,\n )\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 = materializeAgentCandidateProfilePlan({\n profile: bundle.profile,\n harness: bundle.execution.harness,\n launch: bundle.execution.launch,\n workspace: bundle.execution.cwd.workspace,\n workspaces: plan.material.workspaces,\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\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;;AAkHjC,SAAgB,iBAAiB,MAAmD;CAClF,MAAM,UAAU,iBACd,mBAAmB,MAAM,KAAK,OAAO,GACrC,0BACF;CACA,6BAA6B,SAAS,kBAAkB;CACxD,MAAM,UAAU,QAAQ;CACxB,MAAM,WAAW,QAAQ,MAAO,SAAU,KAAK;CAC/C,MAAM,QAAQ,qBAAqB,OAAO;CAC1C,MAAM,gBAAgB,4BAA4B,OAAO;CACzD,MAAM,QAAQ,KAAK,WAAW;CAC9B,MAAM,SAAS,KAAK;CAEpB,OAAO;EACL,MAAM,WAAW;EAMjB,yBAAyB;EACzB,MAAM,SAAS,EACb,cACA,UACA,UACA,QACA,YACA,gBACA,YACA,aACC;GACD,OAAO,eAAe;GACtB,IAAI,KAAK,iBAAiB,CAAC,YACzB,MAAM,IAAI,MACR,yFACF;GAEF,MAAM,aAAa,KAAK,YAAY,EAAE,SAAS,CAAC;GAChD,IAAI,OAAO,eAAe,YAAY,WAAW,KAAK,CAAC,CAAC,WAAW,GACjE,MAAM,IAAI,MAAM,8DAA8D;GAEhF,MAAM,iBAAiB,KAAK,oBAAo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