@tangle-network/agent-runtime 0.104.0 → 0.105.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +176 -42
- package/dist/agent.js +4 -4
- package/dist/candidate-execution/index.d.ts +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{chunk-2QJSNOGK.js → chunk-C5RTIBNZ.js} +2 -2
- package/dist/{chunk-SNSMRT6H.js → chunk-CTRA64LY.js} +3 -3
- package/dist/{chunk-ZXICDSAK.js → chunk-H5QPIZNX.js} +2 -2
- package/dist/{chunk-2X65HYMI.js → chunk-HLKC4UYB.js} +1 -13
- package/dist/chunk-HLKC4UYB.js.map +1 -0
- package/dist/{chunk-3PPVCS75.js → chunk-HNP72PNU.js} +3 -10
- package/dist/chunk-HNP72PNU.js.map +1 -0
- package/dist/chunk-OPVWXJ2H.js +75 -0
- package/dist/chunk-OPVWXJ2H.js.map +1 -0
- package/dist/{chunk-B7K7V22Y.js → chunk-RDOAVVHY.js} +2 -2
- package/dist/{chunk-L5DST3QC.js → chunk-SMQXZGLZ.js} +1 -1
- package/dist/chunk-SMQXZGLZ.js.map +1 -0
- package/dist/{chunk-FJI3EXU3.js → chunk-UHEZW5BU.js} +1104 -588
- package/dist/chunk-UHEZW5BU.js.map +1 -0
- package/dist/{chunk-HAO4CXHP.js → chunk-VISA6CI3.js} +3 -3
- package/dist/{chunk-2UABGGUB.js → chunk-WMTCUOQL.js} +5 -5
- package/dist/{chunk-ATDFUJYI.js → chunk-WRTOVNN4.js} +4 -4
- package/dist/{chunk-ATDFUJYI.js.map → chunk-WRTOVNN4.js.map} +1 -1
- package/dist/{chunk-SBTWKPVR.js → chunk-WSTRQZYQ.js} +1 -1
- package/dist/chunk-WSTRQZYQ.js.map +1 -0
- package/dist/{chunk-5HNDYWUT.js → chunk-XBG2W2VW.js} +13 -3
- package/dist/chunk-XBG2W2VW.js.map +1 -0
- package/dist/{chunk-STJEHM5F.js → chunk-YJZA2BIK.js} +2 -2
- package/dist/{chunk-STJEHM5F.js.map → chunk-YJZA2BIK.js.map} +1 -1
- package/dist/{completion-gate-Bv47cOnn.d.ts → completion-gate-BMy5LGoP.d.ts} +1 -1
- package/dist/{coordination-CxtzMxSM.d.ts → coordination-BZZSVYpZ.d.ts} +2 -2
- package/dist/index.d.ts +101 -177
- package/dist/index.js +373 -235
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +49 -40
- package/dist/intelligence.js +14 -57
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +4 -4
- package/dist/knowledge.js +8 -8
- package/dist/{local-harness-CtK9dSny.d.ts → local-harness-BDNcl6jI.d.ts} +1 -1
- package/dist/{loop-runner-bin-DUOGtvOl.d.ts → loop-runner-bin-68aoM9-7.d.ts} +3 -11
- package/dist/loop-runner-bin.d.ts +4 -6
- package/dist/loop-runner-bin.js +5 -5
- package/dist/loops.d.ts +11 -11
- package/dist/loops.js +5 -5
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.d.ts +7 -8
- package/dist/mcp/index.js +6 -6
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/primeintellect/index.d.ts +2 -3
- package/dist/primeintellect/index.js +5 -6
- package/dist/primeintellect/index.js.map +1 -1
- package/dist/{protected-model-port-DzkUY3HQ.d.ts → protected-model-port-B4t-OQjL.d.ts} +1 -1
- package/dist/{improve--2A0gK1-.d.ts → redact-BuFjxBUJ.d.ts} +201 -160
- package/dist/{structural-rollout-C4mabf87.d.ts → structural-rollout-DEh6CEsa.d.ts} +2 -2
- package/dist/{supervise-7q9F5brx.d.ts → supervise-4_48wwvy.d.ts} +2 -2
- package/dist/testing.js +9 -9
- package/dist/testing.js.map +1 -1
- package/dist/{worktree-fanout-WsOzt8qu.d.ts → worktree-fanout-DxhAWr5Z.d.ts} +2 -2
- package/package.json +6 -5
- package/skills/build-with-agent-runtime/SKILL.md +15 -9
- package/skills/loop-writer/SKILL.md +1 -1
- package/dist/chunk-2X65HYMI.js.map +0 -1
- package/dist/chunk-3PPVCS75.js.map +0 -1
- package/dist/chunk-5HNDYWUT.js.map +0 -1
- package/dist/chunk-FJI3EXU3.js.map +0 -1
- package/dist/chunk-L5DST3QC.js.map +0 -1
- package/dist/chunk-SBTWKPVR.js.map +0 -1
- /package/dist/{chunk-2QJSNOGK.js.map → chunk-C5RTIBNZ.js.map} +0 -0
- /package/dist/{chunk-SNSMRT6H.js.map → chunk-CTRA64LY.js.map} +0 -0
- /package/dist/{chunk-ZXICDSAK.js.map → chunk-H5QPIZNX.js.map} +0 -0
- /package/dist/{chunk-B7K7V22Y.js.map → chunk-RDOAVVHY.js.map} +0 -0
- /package/dist/{chunk-HAO4CXHP.js.map → chunk-VISA6CI3.js.map} +0 -0
- /package/dist/{chunk-2UABGGUB.js.map → chunk-WMTCUOQL.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/improvement/agentic-generator.ts","../src/improvement/findings.ts","../src/improvement/improvement-driver.ts","../src/improvement/cleanup.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/rollout-policy.ts","../src/improvement/improve.ts","../src/intelligence/improvement-surfaces.ts","../src/intelligence/improvement-cycle.ts"],"sourcesContent":["/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`: the\n * `shots=N, sandbox=on` setting of the one `improvementDriver`. It runs a real\n * coding harness (claude / codex / opencode) inside the candidate worktree the\n * driver already created, letting the agent read the codebase + the research\n * report and make the change in place. The driver then commits the worktree\n * into a `CodeSurface`.\n *\n * Mechanism: identical to the proven Phase-2.8 in-process executor — spawn the\n * harness as a subprocess with `cwd` = the worktree, on the same filesystem,\n * so edits land in place (no sandbox-mount round-trip). `runLocalHarness` is\n * the verified primitive. The OUTER sandbox is the improvement loop's own\n * execution context; the generator does not nest a second sandbox per\n * candidate (which would reintroduce a host↔sandbox worktree-transport\n * problem that does not need solving here).\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 `--resume` session plumbing needed,\n * and harness-agnostic across claude/codex/opencode)\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 legacy behavior holds: first dirty shot\n * is the candidate.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join, resolve, sep } from 'node:path'\nimport type {\n AnalystFinding,\n CostLedgerHandle,\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n} from '@tangle-network/agent-eval'\nimport type { AgentProfile, ReasoningEffort } from '@tangle-network/agent-interface'\nimport {\n applyWorkspacePlan,\n materializeProfile,\n type WorkspacePlan,\n type WorkspacePlanReceipt,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n type CodexExecutionEvidence,\n type CodexTokenUsage,\n harnessInvocation,\n type LocalHarness,\n type LocalHarnessResult,\n runLocalHarness,\n} from '../mcp/local-harness'\nimport { runSettledCommand } from '../mcp/worktree-harness'\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/** Dedicated ephemeral root for generic author-profile files. Every declared\n * file must live below this root so cleanup cannot alter candidate-owned files. */\nexport const AGENTIC_PROFILE_RESOURCE_ROOT = '.agent-runtime-profile-resources'\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 readonly harness: LocalHarness\n readonly model: string | null\n readonly reasoningEffort: ReasoningEffort | null\n readonly promptSha256: `sha256:${string}`\n readonly startedAt: string\n readonly completedAt: string\n readonly durationMs: number\n readonly exitCode: number | null\n readonly timedOut: boolean\n /** True when caller cancellation reached the author process; absent in older receipts. */\n readonly aborted?: boolean\n readonly killedBySignal: NodeJS.Signals | null\n readonly stdoutBytes: number | null\n readonly stdoutSha256: `sha256:${string}` | null\n readonly stderrBytes: number | null\n readonly stderrSha256: `sha256:${string}` | null\n readonly usage: CodexTokenUsage | null\n /** Digest of the exact profile-file workspace plan applied for this shot. */\n readonly profileWorkspacePlanDigest: string | null\n readonly profileWorkspaceFileCount: number\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 evidence: CodexExecutionEvidence | null\n readonly error: { readonly name: string; readonly message: string } | null\n}\n\n/** Frozen exact harness result for an author shot: full streams, process state,\n * token usage, and execution-policy evidence.\n * The `onShotCompleted` callback receives `null` when execution failed before\n * the harness returned. */\nexport type AgenticGeneratorShotExecution = Readonly<\n Omit<LocalHarnessResult, 'usage' | 'evidence'> & {\n readonly usage?: Readonly<CodexTokenUsage>\n readonly evidence?: Readonly<Omit<CodexExecutionEvidence, 'readDeniedPaths' | 'policy'>> & {\n readonly readDeniedPaths: ReadonlyArray<string>\n readonly policy: Readonly<CodexExecutionEvidence['policy']>\n }\n }\n>\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 interface AgenticGeneratorOptions {\n /** Local coding harness to run in the worktree. Default `claude`. */\n harness?: LocalHarness\n /** Author profile rendered through the canonical harness mapper. Required\n * for reproducible Codex so model and reasoning settings are explicit. */\n profile?: AgentProfile\n /** Run Codex with isolated configuration, exact prompt evidence, and required\n * terminal token usage. Requires `harness: 'codex'` and `profile`. */\n codexReproducible?: boolean\n /** Absolute paths reproducible Codex must not read. A function can derive\n * candidate-specific paths after the driver creates its worktree. */\n codexReadDeniedPaths?: ReadonlyArray<string> | ((worktreePath: string) => ReadonlyArray<string>)\n /** Awaited once for every attempted author shot, including process failures.\n * The second argument preserves the exact harness result, including stdout\n * and stderr, before worktree inspection or verification can reject the\n * shot. 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\n * author shot. This MUST be enforced by the provider or executor; a planning\n * estimate is not an admissible bound. Omit for an uncapped ledger. A capped\n * ledger rejects before model dispatch when this is absent. */\n maximumCharge?: MaximumCharge\n /** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */\n timeoutMs?: number\n /** Build the harness task prompt from the report + findings. Override for\n * domain phrasing; the default turns findings into a concrete coder task. */\n buildPrompt?: (args: { report: unknown; findings: AnalystFinding[] }) => 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 ⇒ legacy behavior:\n * the first dirty shot is the candidate. See `commandVerifier`. */\n verify?: Verifier\n /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions = {}): CandidateGenerator {\n const harness = opts.harness ?? 'claude'\n if (opts.codexReproducible && harness !== 'codex') {\n throw new Error(\"agenticGenerator: codexReproducible requires harness 'codex'\")\n }\n if (opts.codexReproducible && !opts.profile) {\n throw new Error('agenticGenerator: codexReproducible requires an explicit author profile')\n }\n if (opts.codexReadDeniedPaths && !opts.codexReproducible) {\n throw new Error('agenticGenerator: codexReadDeniedPaths requires codexReproducible')\n }\n if (opts.maximumCharge && !opts.codexReproducible) {\n throw new Error('agenticGenerator: maximumCharge requires codexReproducible')\n }\n const profileResourcePlan = opts.codexReproducible\n ? authorProfileResourcePlan(opts.profile as AgentProfile)\n : null\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const run = opts.runHarness ?? runLocalHarness\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 improvementDriver'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 report,\n findings,\n maxShots,\n signal,\n generation,\n candidateIndex,\n costLedger,\n costPhase,\n }) {\n signal.throwIfAborted()\n let reproducibleCostLedger: CostLedgerHandle | undefined\n if (opts.codexReproducible) {\n if (!costLedger) {\n throw new Error(\n 'agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval',\n )\n }\n reproducibleCostLedger = costLedger\n }\n const basePrompt = appendProfileResourcePaths(\n buildPrompt({ report, findings }),\n profileResourcePlan,\n )\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 invocation = opts.profile\n ? harnessInvocation(harness, opts.profile, taskPrompt, {\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n })\n : undefined\n const exactPrompt = invocation?.prompt ?? taskPrompt\n const readDeniedPaths =\n typeof opts.codexReadDeniedPaths === 'function'\n ? opts.codexReadDeniedPaths(worktreePath)\n : opts.codexReadDeniedPaths\n const startedAt = new Date()\n let harnessResult: LocalHarnessResult | null = null\n let profileWorkspaceReceipt: WorkspacePlanReceipt | 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 (executionSignal: AbortSignal): Promise<LocalHarnessResult> => {\n harnessResult = await withAuthorProfileResources(\n profileResourcePlan,\n worktreePath,\n async (receipt) => {\n profileWorkspaceReceipt = receipt\n const result = await run({\n harness,\n cwd: worktreePath,\n taskPrompt,\n ...(invocation\n ? { invocation: { command: invocation.command, args: invocation.args } }\n : {}),\n // The candidate worktree is isolated and must be editable without an\n // interactive permission prompt. Other runLocalHarness callers remain\n // permission-safe by default.\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n ...(readDeniedPaths ? { codexReadDeniedPaths: readDeniedPaths } : {}),\n timeoutMs: opts.timeoutMs,\n signal: executionSignal,\n })\n // Assign before profile cleanup so a cleanup failure still\n // settles the model usage already returned by the harness.\n harnessResult = result\n return result\n },\n )\n const failure = shotFailure(harnessResult, exactPrompt, opts.codexReproducible === true)\n if (failure) throw failure\n return harnessResult\n }\n\n if (reproducibleCostLedger) {\n const model = opts.profile?.model?.default\n if (!model) {\n throw new Error('agenticGenerator: reproducible Codex requires profile.model.default')\n }\n const paid = await reproducibleCostLedger.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,\n receipt: (result) => costReceiptFromHarness(result, model),\n receiptFromError: () =>\n harnessResult?.usage ? costReceiptFromHarness(harnessResult, model) : undefined,\n })\n costCallId = paid.callId ?? null\n costReceipt = paid.receipt ?? null\n if (!paid.succeeded) throw paid.error\n harnessResult = paid.value\n } else {\n harnessResult = await execute(signal)\n }\n } catch (cause) {\n shotError = cause instanceof Error ? cause : new Error(String(cause))\n }\n const execution = shotExecutionSnapshot(harnessResult)\n const receipt = shotReceipt({\n generation,\n candidateIndex,\n shot,\n maxShots: shots,\n harness,\n profile: opts.profile,\n prompt: exactPrompt,\n startedAt,\n completedAt: new Date(),\n result: execution,\n profileWorkspaceReceipt,\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 harness result')\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 harness's stdout). 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\nfunction authorProfileResourcePlan(profile: AgentProfile): WorkspacePlan | null {\n const resources = profile.resources\n if (!resources) return null\n const unsupportedKinds = [\n resources.tools?.length ? 'tools' : null,\n resources.skills?.length ? 'skills' : null,\n resources.agents?.length ? 'agents' : null,\n ].filter((kind): kind is string => kind !== null)\n if (unsupportedKinds.length > 0) {\n throw new Error(\n `agenticGenerator: reproducible Codex author resources support files only; unsupported: ${unsupportedKinds.join(', ')}`,\n )\n }\n if (!resources.files || resources.files.length === 0) return null\n\n const plan = materializeProfile(\n {\n name: profile.name,\n resources: { files: resources.files },\n },\n 'codex',\n )\n if (plan.unsupported.length > 0) {\n throw new Error(\n `agenticGenerator: author profile files could not be materialized: ${plan.unsupported.map((item) => item.reason).join('; ')}`,\n )\n }\n if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) {\n throw new Error(\n 'agenticGenerator: generic author profile files unexpectedly changed spawn values',\n )\n }\n\n const virtualRoot = resolve('/', AGENTIC_PROFILE_RESOURCE_ROOT)\n const seen = new Set<string>()\n for (const file of plan.files) {\n const target = resolve('/', file.relPath)\n if (!target.startsWith(`${virtualRoot}${sep}`)) {\n throw new Error(\n `agenticGenerator: author profile file must be below ${AGENTIC_PROFILE_RESOURCE_ROOT}: ${file.relPath}`,\n )\n }\n if (seen.has(target)) {\n throw new Error(`agenticGenerator: duplicate author profile file path: ${file.relPath}`)\n }\n seen.add(target)\n }\n return plan\n}\n\nfunction appendProfileResourcePaths(prompt: string, plan: WorkspacePlan | null): string {\n if (!plan) return prompt\n return [\n prompt,\n '',\n 'Profile resource files available for this shot:',\n ...plan.files.map((file) => `- ${file.relPath}`),\n ].join('\\n')\n}\n\nasync function withAuthorProfileResources<T>(\n plan: WorkspacePlan | null,\n worktreePath: string,\n run: (receipt: WorkspacePlanReceipt | null) => Promise<T>,\n): Promise<T> {\n if (!plan) return run(null)\n\n const rootPath = resolve(worktreePath, AGENTIC_PROFILE_RESOURCE_ROOT)\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root already exists: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n\n let value: T | undefined\n let primaryError: unknown\n try {\n const receipt = applyWorkspacePlan(plan, worktreePath)\n value = await run(receipt)\n } catch (cause) {\n primaryError = cause\n }\n\n let cleanupError: unknown\n try {\n rmSync(rootPath, { recursive: true, force: true })\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root survived cleanup: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n } catch (cause) {\n cleanupError = cause\n }\n\n if (primaryError !== undefined && cleanupError !== undefined) {\n throw new AggregateError(\n [primaryError, cleanupError],\n 'agenticGenerator: author shot and profile resource cleanup both failed',\n )\n }\n if (primaryError !== undefined) throw primaryError\n if (cleanupError !== undefined) throw cleanupError\n return value as T\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 shotExecutionSnapshot(\n result: LocalHarnessResult | null,\n): AgenticGeneratorShotExecution | null {\n if (result === null) return null\n const usage = result.usage ? Object.freeze({ ...result.usage }) : undefined\n const evidence = result.evidence\n ? Object.freeze({\n ...result.evidence,\n readDeniedPaths: Object.freeze([...result.evidence.readDeniedPaths]),\n policy: Object.freeze({ ...result.evidence.policy }),\n })\n : undefined\n return Object.freeze({\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n killedBySignal: result.killedBySignal,\n durationMs: result.durationMs,\n timedOut: result.timedOut,\n ...(result.aborted !== undefined ? { aborted: result.aborted } : {}),\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\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: LocalHarness\n readonly profile: AgentProfile | undefined\n readonly prompt: string\n readonly startedAt: Date\n readonly completedAt: Date\n readonly result: AgenticGeneratorShotExecution | null\n readonly profileWorkspaceReceipt: WorkspacePlanReceipt | 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)\n return {\n generation: input.generation ?? null,\n candidateIndex: input.candidateIndex ?? null,\n shot: input.shot + 1,\n maxShots: input.maxShots,\n harness: input.harness,\n model: input.profile?.model?.default ?? null,\n reasoningEffort: input.profile?.model?.reasoningEffort ?? null,\n promptSha256: sha256(input.prompt),\n startedAt: input.startedAt.toISOString(),\n completedAt: input.completedAt.toISOString(),\n durationMs: result?.durationMs ?? input.completedAt.getTime() - input.startedAt.getTime(),\n exitCode: result?.exitCode ?? null,\n timedOut: result?.timedOut ?? false,\n aborted: result?.aborted ?? false,\n killedBySignal: result?.killedBySignal ?? null,\n stdoutBytes: result ? Buffer.byteLength(result.stdout) : null,\n stdoutSha256: result ? sha256(result.stdout) : null,\n stderrBytes: result ? Buffer.byteLength(result.stderr) : null,\n stderrSha256: result ? sha256(result.stderr) : null,\n usage: result?.usage ? { ...result.usage } : null,\n profileWorkspacePlanDigest: input.profileWorkspaceReceipt?.workspacePlanDigest ?? null,\n profileWorkspaceFileCount: input.profileWorkspaceReceipt?.written.length ?? 0,\n costCallId: input.costCallId,\n costBasis,\n costUsd: costBasis === 'unknown' ? null : (input.costReceipt?.costUsd ?? null),\n costUsdKnown: costBasis === 'provider-reported',\n evidence: result?.evidence\n ? {\n ...result.evidence,\n readDeniedPaths: [...result.evidence.readDeniedPaths],\n policy: { ...result.evidence.policy },\n }\n : null,\n error,\n }\n}\n\nfunction costBasisFor(receipt: CostReceipt | null): AgenticGeneratorShotReceipt['costBasis'] {\n if (receipt === null || receipt.costUnknown) return 'unknown'\n return receipt.actualCostUsd === undefined ? 'estimated-pricing' : 'provider-reported'\n}\n\nfunction shotFailure(\n result: LocalHarnessResult,\n exactPrompt: string,\n codexReproducible: boolean,\n): Error | null {\n if (result.timedOut) {\n return new Error('agenticGenerator: author shot timed out')\n }\n if (result.aborted) {\n return new Error('agenticGenerator: author shot was cancelled by the caller')\n }\n if (result.killedBySignal) {\n return new Error(`agenticGenerator: author shot was killed by ${result.killedBySignal}`)\n }\n if (result.exitCode !== 0) {\n return new Error(`agenticGenerator: author shot exited with code ${String(result.exitCode)}`)\n }\n if (!codexReproducible) return null\n if (!result.usage || !result.evidence) {\n return new Error(\n 'agenticGenerator: reproducible Codex shot completed without usage or execution evidence',\n )\n }\n const expectedPromptSha256 = sha256(exactPrompt).slice('sha256:'.length)\n if (result.evidence.requestedPromptSha256 !== expectedPromptSha256) {\n return new Error(\n 'agenticGenerator: reproducible Codex prompt evidence does not match the exact authored prompt',\n )\n }\n return null\n}\n\nfunction costReceiptFromHarness(result: LocalHarnessResult, model: string): CostReceiptInput {\n if (!result.usage) {\n throw new Error('agenticGenerator: author shot did not report terminal token usage')\n }\n return {\n model,\n inputTokens: result.usage.inputTokens - result.usage.cachedInputTokens,\n outputTokens: result.usage.outputTokens,\n ...(result.usage.cachedInputTokens > 0 ? { cachedTokens: result.usage.cachedInputTokens } : {}),\n }\n}\n\nfunction sha256(value: string): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\n/** Turn the analyst's findings (+ optional report) into a concrete coder task —\n * the senior scientific-method framing shared with the tool/MCP build prompts. */\nexport function defaultBuildPrompt(args: { report: unknown; findings: AnalystFinding[] }): 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\nexport function rawTraceEvidenceProblem(\n worktreePath: string,\n findings: AnalystFinding[],\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\nexport function requiresRawTraceEvidence(findings: AnalystFinding[]): 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: AnalystFinding[]): 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. */\nexport function summarizeFindings(findings: AnalystFinding[]): 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: AnalystFinding[]): {\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: AnalystFinding[]): 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\nexport function 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","/**\n * Typed-findings accessor — the one place `unknown[]` findings become\n * `AnalystFinding[]`.\n *\n * agent-eval's `ProposeContext.findings` is `TFindings[] = unknown[]` on the\n * wire: the loop threads whatever the previous `analyzeGeneration` producer (or\n * the caller's static seed) returned. Consumers that need the typed envelope\n * (`claim`/`severity`/`recommended_action`) were down-casting with a bare\n * `as AnalystFinding[]` — a lie at runtime whenever the seed was a raw string\n * or an ad-hoc digest, which then rendered `undefined` into build prompts.\n *\n * `toAnalystFindings` replaces that cast: real findings pass through\n * unchanged (structural guard, fail-closed), and non-conforming values are\n * LIFTED into a real `AnalystFinding` envelope via `makeFinding` — the most\n * actionable text becomes the claim, the original value rides in `metadata.raw`\n * — so everything downstream of the accessor handles exactly one shape.\n */\n\nimport { type AnalystFinding, makeFinding } from '@tangle-network/agent-eval'\n\nconst SEVERITIES: ReadonlySet<string> = new Set(['critical', 'high', 'medium', 'low', 'info'])\n\n/** Analyst id stamped on findings lifted from untyped seed values. */\nexport const LIFTED_FINDING_ANALYST_ID = 'lifted-seed'\n\n/** Structural guard for the schema-versioned `AnalystFinding` envelope.\n * Strict on the identity fields `makeFinding` always populates — a partial\n * look-alike is lifted (re-enveloped), not trusted. */\nexport function isAnalystFinding(value: unknown): value is AnalystFinding {\n if (!value || typeof value !== 'object') return false\n const o = value as Record<string, unknown>\n return (\n o.schema_version === '1.0.0' &&\n typeof o.finding_id === 'string' &&\n typeof o.analyst_id === 'string' &&\n typeof o.severity === 'string' &&\n SEVERITIES.has(o.severity) &&\n typeof o.area === 'string' &&\n typeof o.claim === 'string' &&\n typeof o.confidence === 'number' &&\n Array.isArray(o.evidence_refs)\n )\n}\n\n/** The most actionable text of an untyped finding-ish value — mirrors the\n * extraction order agent-eval's curator proposers use (`recommended_action` >\n * `claim` > `lesson` > `notes` > `text` > `message`), so the two ends of the\n * wire read the same field first. */\nfunction liftedClaim(value: unknown): string | null {\n if (typeof value === 'string') return value.trim() || null\n if (value && typeof value === 'object') {\n const o = value as Record<string, unknown>\n for (const key of ['recommended_action', 'claim', 'lesson', 'notes', 'text', 'message']) {\n const v = o[key]\n if (typeof v === 'string' && v.trim()) return v.trim()\n }\n try {\n const json = JSON.stringify(value)\n if (json && json !== '{}' && json !== '[]') {\n return json.length > 400 ? `${json.slice(0, 399)}…` : json\n }\n } catch {\n /* circular / non-serializable → drop below */\n }\n }\n return null\n}\n\nexport interface ToAnalystFindingsOptions {\n /** `analyst_id` stamped on lifted (non-conforming) values.\n * Default {@link LIFTED_FINDING_ANALYST_ID}. */\n analystId?: string\n /** `area` stamped on lifted values. Default `'seed'`. */\n area?: string\n}\n\n/**\n * Normalize a mixed `unknown[]` findings array to `AnalystFinding[]`:\n * conforming findings pass through by reference; strings and finding-ish\n * objects are lifted into envelopes (claim = most actionable text, original\n * value under `metadata.raw`); values with no extractable text are dropped.\n * Never throws — a malformed seed must not kill a proposal round.\n */\nexport function toAnalystFindings(\n findings: readonly unknown[],\n opts: ToAnalystFindingsOptions = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? LIFTED_FINDING_ANALYST_ID\n const area = opts.area ?? 'seed'\n const out: AnalystFinding[] = []\n for (const f of findings) {\n if (isAnalystFinding(f)) {\n out.push(f)\n continue\n }\n const claim = liftedClaim(f)\n if (!claim) continue\n out.push(\n makeFinding({\n analyst_id: analystId,\n severity: 'info',\n area,\n confidence: 0.5,\n claim,\n evidence_refs: [],\n ...(f && typeof f === 'object' ? { metadata: { raw: f } } : {}),\n }),\n )\n }\n return out\n}\n","/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { AnalystFinding, CostLedgerHandle } from '@tangle-network/agent-eval'\nimport {\n type CodeSurface,\n type LabeledScenarioStore,\n type ProposeContext,\n type ProposedCandidate,\n type SurfaceProposer,\n verifyCodeSurface,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport { rethrowAfterCleanup } from './cleanup'\nimport { toAnalystFindings } from './findings'\n\n/** The byte-producing seam — the ONE thing that differs between the cheap\n * reflective path and the full agentic path. A generator makes (uncommitted)\n * changes inside `worktreePath`; the driver commits them via the worktree\n * adapter's `finalize`. */\nexport interface CandidateGenerator {\n kind: string\n /** Whether this generator can produce a candidate from an EMPTY findings set\n * and no phase-2 report — i.e. it draws its change signal from the repo and\n * the raw-trace filesystem context on disk, not only from pre-summarized\n * findings. An agentic coder (`agenticGenerator`) sets this: the seed repo +\n * raw traces ARE the signal, so it must still run the full `populationSize`\n * when the distiller yielded nothing (this is the meta-harness contract — the\n * agent diagnoses from the raw traces itself). A patch-applier\n * (`reflectiveGenerator`) leaves it unset — with no findings there is no\n * patch to draft, so the driver short-circuits rather than spin up worktrees\n * for a guaranteed no-op. Default `false`. */\n proposesWithoutFindings?: boolean\n generate(args: {\n /** The candidate worktree — a clean checkout of the current incumbent. */\n worktreePath: string\n /** Phase-2 research report (analyst findings + diff), opaque. */\n report: unknown\n /** Findings resolved from the report or the loop context. */\n findings: AnalystFinding[]\n /** Handle to all captured data, to ground the change. */\n dataset?: LabeledScenarioStore\n /** DEPTH: max iterations the generator may take (agentic uses this; the\n * reflective generator ignores it). */\n maxShots: number\n signal: AbortSignal\n /** Improvement-loop coordinates. Present when called through improvementDriver. */\n generation?: number\n candidateIndex?: number\n /** Shared run-wide paid-call account supplied by agent-eval 0.117+. */\n costLedger?: CostLedgerHandle\n /** Receipt attribution phase supplied alongside `costLedger`. */\n costPhase?: string\n }): Promise<{\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<AnalystFinding> {\n /** Remove every owned candidate except explicitly retained finalized winners. */\n cleanup(retainWorktreeRefs?: readonly string[]): Promise<void>\n}\n\n/** The one reflective/agentic improvement proposer (`SurfaceProposer`): owns the candidate worktree lifecycle and delegates HOW a change is produced to a pluggable `CandidateGenerator`. */\nexport function improvementDriver(opts: ImprovementDriverOptions): ManagedImprovementDriver {\n const baseRef = opts.baseRef ?? 'main'\n const owned = new Map<string, Worktree>()\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the reflective patch-applier) — propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: 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 report: ctx.report,\n findings,\n dataset: ctx.dataset,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n generation: ctx.generation,\n candidateIndex: i,\n ...(ctx.costLedger ? { costLedger: ctx.costLedger } : {}),\n ...(ctx.costPhase ? { costPhase: ctx.costPhase } : {}),\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n owned.delete(wt.path)\n continue\n }\n const surface = await opts.worktree.finalize(wt, summary)\n // 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\n/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. Both paths run through `toAnalystFindings` — the wire is\n * `unknown[]` at runtime regardless of the generic (static seeds, legacy\n * digests), and a bare cast here fed `undefined` claims into build prompts. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) {\n const lifted = toAnalystFindings(f, { analystId: 'report-findings', area: 'report' })\n if (lifted.length > 0) return lifted\n }\n }\n return toAnalystFindings(ctx.findings ?? [], { analystId: 'loop-context', area: 'seed' })\n}\n","export async function rethrowAfterCleanup(\n cause: unknown,\n cleanup: () => Promise<void>,\n context: string,\n): Promise<never> {\n const cleanupErrors: unknown[] = []\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await cleanup()\n } catch (cleanupCause) {\n cleanupErrors.push(cleanupCause)\n continue\n }\n if (cleanupErrors.length === 0) throw cause\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup retry succeeded`)\n }\n throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup failed`)\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~1500-char structured findings before the next\n * proposal round. That is the ACE-style recipe: a small summary is the proposer's\n * whole view of what went wrong. This producer does the opposite — the\n * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It\n * points the coding-agent proposer at the generation's RAW run traces already on\n * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,\n * `cached-result.json` scores, and any artifacts the substrate persisted — and\n * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself\n * (up to the harness's full context, ~millions of tokens, vs a ~1500-char digest).\n *\n * It emits `AnalystFinding[]` so it drops into the SAME `opts.analyzeGeneration`\n * slot the default distiller uses, and renders through the same\n * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings\n * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate\n * worktree, so a relative `runDir` would be uncattable from there.\n *\n * Runtime layout it reads (written by agent-eval's optimization loop):\n *\n * <runDir>/gen-<N>/ ← the generation dir (input.runDir)\n * candidate-<i>/ ← one candidate campaign (campaign.runDir)\n * <sanitized cellId>/ ← one scenario×rep cell\n * spans.jsonl ← the raw trace (event/span log)\n * cached-result.json ← the cell's score + artifact ref\n * <artifacts…> ← whatever the dispatch wrote\n *\n * @experimental\n */\n\nimport { type Dirent, existsSync, readdirSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { type AnalystFinding, makeFinding } from '@tangle-network/agent-eval'\nimport type { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract'\n\nconst ANALYST_ID = 'raw-trace-distiller'\n/** A cell counts as \"failing\" below this mean composite (matches the default\n * distiller's near-perfect threshold) or when it recorded an `error`. */\nconst PASS_THRESHOLD = 0.999\n\nexport interface RawTraceDistillerOptions {\n /** Anchor the emitted paths at this run root instead of the generation `runDir`\n * the loop passes in. Normally unset — each call points at that generation's\n * own directory (`input.runDir`). Pass an absolute path when you construct the\n * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */\n runDir?: string\n /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */\n maxCandidates?: number\n /** Max failing cells to enumerate per candidate before collapsing the rest into\n * an \"ls the candidate dir\" pointer. Default 8. */\n maxCellsPerCandidate?: number\n /** Max concrete file paths to list per cell (the agent can always `ls` the dir\n * for the rest). Default 24. */\n maxFilesPerCell?: number\n /** Findings to fall back to when the generation had NO failing cells, so a\n * clean round never wipes the proposer's steering context. Mirrors the default\n * distiller's static-seed fallback. Default: a single instruction finding. */\n fallbackFindings?: unknown[]\n}\n\ninterface CellTrace {\n scenarioId: string\n composite: number\n error?: string\n cellDir: string\n files: string[]\n truncatedFiles: boolean\n}\n\n/**\n * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE\n * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a\n * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.\n *\n * Drop-in for `opts.analyzeGeneration` on `improve()` / `selfImprove()`:\n *\n * await improve(profile, seedFindings, {\n * surface: 'code',\n * code: { repoRoot },\n * runDir: '/abs/run', // MUST be a real path — the traces live here\n * analyzeGeneration: rawTraceDistiller(),\n * scenarios, judge, agent,\n * })\n */\nexport function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(\n options: RawTraceDistillerOptions = {},\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const maxCandidates = options.maxCandidates ?? 12\n const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8\n const maxFilesPerCell = options.maxFilesPerCell ?? 24\n\n return async (input) => {\n const genRoot = absoluteRunDir(options.runDir ?? input.runDir)\n const durable = isDurable(genRoot)\n\n // Rank candidates worst-first; the worst failures are the highest-signal\n // context for the next edit. Stable sort keeps equal-composite order.\n const ranked = [...input.candidates]\n .map((c) => ({\n surfaceHash: c.surfaceHash,\n composite: c.composite,\n campaignDir: absoluteRunDir(c.campaign.runDir),\n cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell),\n }))\n .sort((a, b) => a.composite - b.composite)\n .slice(0, maxCandidates)\n\n const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0)\n\n // A clean generation: keep the proposer's steering context rather than\n // wiping it (parity with the default distiller's static-seed fallback). An\n // EMPTY fallback array means there is no STATIC seed to preserve — it must NOT\n // wipe the context to nothing. Fall through to the default raw-trace\n // instruction so the meta-harness discipline stays live (the agent still\n // inspects the on-disk traces next round, and the finding's `raw-trace-context`\n // area keeps the agenticGenerator's diagnosis-evidence gate armed). A bare\n // `??` would return the empty array and silently disable both.\n if (totalFailingCells === 0) {\n if (options.fallbackFindings && options.fallbackFindings.length > 0) {\n return options.fallbackFindings\n }\n return [\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'info',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,\n recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 },\n }),\n ]\n }\n\n const findings: AnalystFinding[] = []\n\n // 1. The meta-harness instruction: diagnose from the RAW traces, not a digest.\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: 'high',\n area: 'raw-trace-context',\n confidence: 1,\n claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} — the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${\n durable\n ? ''\n : ' (WARNING: this run root does not exist on disk — it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)'\n }`,\n recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \\`grep\\`/\\`cat\\`/\\`ls\\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \\`grep -rIn \"error\" ${genRoot}\\` then \\`cat\\` the spans.jsonl of the worst cell.`,\n evidence_refs: [{ kind: 'artifact', uri: genRoot }],\n metadata: {\n generation: input.generation,\n runDir: genRoot,\n failingCells: totalFailingCells,\n candidates: ranked.length,\n },\n }),\n )\n\n // 2. One finding per failing candidate: its campaign dir + the concrete raw\n // trace files to grep/cat.\n for (const cand of ranked) {\n if (cand.cells.length === 0) continue\n const scenarioList = cand.cells.map((c) => c.scenarioId).join(', ')\n const fileLines = cand.cells\n .map((c) => {\n const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${\n c.error ? `, error: ${truncate(c.error, 160)}` : ''\n }) — dir ${c.cellDir}`\n const files = c.files.map((f) => ` - ${f}`).join('\\n')\n const more = c.truncatedFiles ? `\\n - …(ls ${c.cellDir} for the rest)` : ''\n return c.files.length > 0 ? `${header}\\n${files}${more}` : header\n })\n .join('\\n')\n\n findings.push(\n makeFinding({\n analyst_id: ANALYST_ID,\n severity: cand.composite < 0.5 ? 'critical' : 'high',\n area: 'raw-trace-context',\n confidence: 1,\n subject: cand.surfaceHash,\n claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,\n recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:\\n${fileLines}\\nOr scan the whole candidate at once: \\`grep -rIn . ${cand.campaignDir}\\` and \\`ls -R ${cand.campaignDir}\\`.`,\n evidence_refs: [\n { kind: 'artifact', uri: cand.campaignDir },\n ...cand.cells.flatMap((c) =>\n c.files.map((f) => ({ kind: 'artifact' as const, uri: f })),\n ),\n ],\n metadata: {\n surfaceHash: cand.surfaceHash,\n composite: cand.composite,\n campaignDir: cand.campaignDir,\n cells: cand.cells.map((c) => ({\n scenarioId: c.scenarioId,\n composite: c.composite,\n cellDir: c.cellDir,\n files: c.files,\n ...(c.error ? { error: c.error } : {}),\n })),\n },\n }),\n )\n }\n\n return findings\n }\n}\n\n/** The failing cells of a candidate campaign, each with its on-disk trace files.\n * Mirrors the default distiller's per-cell composite (mean of judge composites,\n * 0 when a cell produced no judge score) and its failing predicate. */\nfunction failingCells(\n campaign: {\n runDir: string\n cells: ReadonlyArray<{\n cellId: string\n scenarioId: string\n error?: string\n judgeScores: Record<string, { composite?: number }>\n }>\n artifactsByPath?: Record<string, string>\n },\n maxCells: number,\n maxFiles: number,\n): CellTrace[] {\n const campaignDir = absoluteRunDir(campaign.runDir)\n const durable = isDurable(campaignDir)\n const out: CellTrace[] = []\n for (const cell of campaign.cells) {\n const scores = Object.values(cell.judgeScores ?? {})\n const composite =\n scores.length === 0\n ? 0\n : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length\n if (!cell.error && composite >= PASS_THRESHOLD) continue\n\n const cellDir = join(campaignDir, sanitizeCellId(cell.cellId))\n const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId)\n const discovered = durable ? listTraceFiles(cellDir) : []\n // Canonical anchors the substrate always writes, kept even when a mem:// run\n // never flushed them to disk (so the agent still learns the expected path).\n const canonical = [join(cellDir, 'spans.jsonl'), join(cellDir, 'cached-result.json')]\n const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical])\n\n out.push({\n scenarioId: cell.scenarioId,\n composite: Number(composite.toFixed(3)),\n ...(cell.error ? { error: cell.error } : {}),\n cellDir,\n files: files.slice(0, maxFiles),\n truncatedFiles: files.length > maxFiles,\n })\n if (out.length >= maxCells) break\n }\n return out\n}\n\n/** Absolute paths of artifacts the campaign recorded for a cell. `artifactsByPath`\n * is keyed `${cellId}/${relPath}` → absolute path. */\nfunction artifactPathsForCell(\n artifactsByPath: Record<string, string> | undefined,\n cellId: string,\n): string[] {\n if (!artifactsByPath) return []\n const prefix = `${cellId}/`\n return Object.entries(artifactsByPath)\n .filter(([key]) => key.startsWith(prefix))\n .map(([, absPath]) => resolve(absPath))\n}\n\n/** Real files directly under `dir` and one level of sub-directories (artifacts\n * are sometimes nested). Absolute paths, sorted. `[]` when the dir is absent,\n * stale, unreadable, or contains symlinked dirs — trace context is advisory and\n * the canonical anchors below still tell the proposer where to inspect. */\nfunction listTraceFiles(dir: string): string[] {\n const out: string[] = []\n for (const entry of safeReadDir(dir)) {\n const full = join(dir, entry.name)\n if (entry.isFile()) {\n out.push(full)\n } else if (!entry.isSymbolicLink() && entry.isDirectory()) {\n for (const sub of safeReadDir(full)) {\n if (sub.isFile()) out.push(join(full, sub.name))\n }\n }\n }\n return out\n}\n\nfunction safeReadDir(dir: string): Dirent[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n}\n\n/** Substrate cell-dir sanitization — must match agent-eval's\n * `cellId.replace(/[^a-zA-Z0-9_-]/g, '_')` so the computed dir matches disk. */\nfunction sanitizeCellId(cellId: string): string {\n return cellId.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\n/** A run root is durable (has real files) when it is not an in-memory sentinel\n * and exists on disk. `mem://` runs keep everything in-process — no traces. */\nfunction isDurable(runDir: string): boolean {\n return !runDir.startsWith('mem://') && existsSync(runDir)\n}\n\n/** Resolve a run dir to absolute (the coding harness runs from a worktree cwd, so\n * relative paths are uncattable there). `mem://` sentinels pass through untouched. */\nfunction absoluteRunDir(runDir: string): string {\n return runDir.startsWith('mem://') ? runDir : resolve(runDir)\n}\n\nfunction dedupeSorted(paths: string[]): string[] {\n return [...new Set(paths)].sort((a, b) => {\n // Group by directory then filename for a stable, readable listing.\n const da = a.slice(0, a.length - basename(a).length)\n const db = b.slice(0, b.length - basename(b).length)\n return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db)\n })\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n","/**\n * `rolloutPolicyProposer` — the `'rollout-policy'` surface for `improve()`: the\n * inference-time `StructuralRolloutPolicy` dials { k, repairRounds, testgen } as a\n * held-out-gated optimizable surface.\n *\n * Why this seam: agent-eval's loop contract is already generic — `MutableSurface`\n * admits any string, documented as \"serialized tool config\" — so the policy rides\n * the SAME serialize→propose→gate→parse-back cycle the tools/mcp/hooks surfaces\n * use. No agent-eval changes; the only net-new piece is this proposer.\n *\n * Why deterministic: prompt-wording proposals are a measured zero on this stack,\n * and the policy space is tiny and fully enumerable. The proposer emits bounded\n * single-dial neighbors (k±2 in [1,10], repairRounds±1 in [0,3], testgen±3 in\n * [0,10], ≤4 per generation) and lets the held-out gate do ALL the deciding — an\n * LLM proposer would add cost and nondeterminism with nothing to reason about.\n *\n * Persistence: the policy lives in `profile.extensions['structural-rollout']`\n * (AgentProfile's designed slot for runtime-specific config). A gated winner is\n * written back there by `improve()`, the same profile-field write-back every other\n * config surface gets; `structuralRolloutPolicyFromProfile` is the read side a\n * runtime caller feeds to `structuralRollout({ policy })`.\n *\n * @experimental\n */\n\nimport type {\n MutableSurface,\n ProposeContext,\n ProposedCandidate,\n SurfaceProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\n/** Proposal bounds per dial. These are the SEARCH bounds (what the proposer may\n * explore), chosen so every reachable value is a measured-sane recipe: k=1 is the\n * low-compute preset, testgen=0 disables check authoring, repairRounds caps where\n * the measured increment flattens (+1–3pp beyond round 2). */\nexport const ROLLOUT_POLICY_BOUNDS = {\n k: { min: 1, max: 10, step: 2 },\n repairRounds: { min: 0, max: 3, step: 1 },\n testgen: { min: 0, max: 10, step: 3 },\n} as const\n\n/** Max candidates per generation — the search space is 3 dials, so a small\n * neighborhood per generation converges without burning gate budget. */\nconst MAX_CANDIDATES_PER_GENERATION = 4\n\nconst clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))\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. Defensive by design — the proposer reads\n * `ctx.currentSurface`, which the loop types as `string | CodeSurface`. Returns\n * `undefined` (never throws) for non-strings, malformed JSON, or a shape that\n * violates the policy's own invariants: the no-op signal. Unknown dials are\n * dropped; `diverse`/`temperature` ride through untouched (the proposer never\n * mutates them — `diverse` is a measured paired null). */\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 ...(typeof bag.temperature === 'number' ? { temperature: bag.temperature } : {}),\n }\n}\n\n/** Stable serialization — dial order is fixed so identical policies produce\n * identical surfaces (the loop dedupes/hashes candidates by surface content). */\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 ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout — the improve() surface no-ops then, because\n * tuning dials nothing consumes would ship dead config. */\nexport function structuralRolloutPolicyFromProfile(\n profile: AgentProfile,\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 policy into the profile's extensions namespace. Shallow copy; never\n * mutates the input profile (the applyWinnerToProfile contract). */\nexport function applyRolloutPolicyToProfile(\n profile: AgentProfile,\n policy: StructuralRolloutPolicy,\n): 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 ...(policy.temperature !== undefined ? { temperature: policy.temperature } : {}),\n }\n return {\n ...profile,\n extensions: { ...profile.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\n }\n}\n\n/** All bounded single-dial neighbors of `policy`, in a fixed priority order: k\n * first (selection breadth carries 85–92% of the measured effect), then\n * repairRounds, then testgen. Steps clamp to the dial's bounds; clamped-to-no-op\n * and duplicate policies are dropped. */\nexport function enumerateNeighborPolicies(\n policy: StructuralRolloutPolicy,\n): StructuralRolloutPolicy[] {\n const moves: Array<{ dial: 'k' | 'repairRounds' | 'testgen'; delta: 1 | -1 }> = [\n { dial: 'k', delta: 1 },\n { dial: 'k', delta: -1 },\n { dial: 'repairRounds', delta: 1 },\n { dial: 'repairRounds', delta: -1 },\n { dial: 'testgen', delta: 1 },\n { dial: 'testgen', delta: -1 },\n ]\n const seen = new Set<string>([serializeRolloutPolicy(policy)])\n const neighbors: StructuralRolloutPolicy[] = []\n for (const move of moves) {\n const bounds = ROLLOUT_POLICY_BOUNDS[move.dial]\n const next = clamp(policy[move.dial] + move.delta * bounds.step, bounds.min, bounds.max)\n const candidate: StructuralRolloutPolicy = { ...policy, [move.dial]: next }\n const key = serializeRolloutPolicy(candidate)\n if (seen.has(key)) continue\n seen.add(key)\n neighbors.push(candidate)\n }\n return neighbors\n}\n\nfunction candidateLabel(base: StructuralRolloutPolicy, next: StructuralRolloutPolicy): string {\n for (const dial of ['k', 'repairRounds', 'testgen'] as const) {\n if (next[dial] !== base[dial]) return `${dial} ${base[dial]}→${next[dial]}`\n }\n return 'unchanged'\n}\n\n/**\n * The deterministic `SurfaceProposer` for the `'rollout-policy'` surface.\n *\n * Each generation: parse the current policy surface, enumerate its bounded\n * single-dial neighbors, and return at most `min(populationSize, 4)` of them,\n * rotating the enumeration window by generation so successive generations explore\n * different neighbors when nothing promoted. Proposes NOTHING when the surface\n * carries no policy (the profile never opted in) — an empty proposal is the\n * loop-native no-op, mirroring `improvementDriver`'s no-findings behavior.\n */\nexport function rolloutPolicyProposer(): SurfaceProposer {\n return {\n kind: 'rollout-policy',\n async propose(ctx: ProposeContext): Promise<ProposedCandidate[]> {\n const policy = parseRolloutPolicy(ctx.currentSurface)\n if (!policy) return []\n const neighbors = enumerateNeighborPolicies(policy)\n if (neighbors.length === 0) return []\n const cap = Math.max(1, Math.min(ctx.populationSize, MAX_CANDIDATES_PER_GENERATION))\n const start = (ctx.generation * cap) % neighbors.length\n const window: StructuralRolloutPolicy[] = []\n for (let i = 0; i < Math.min(cap, neighbors.length); i += 1) {\n window.push(neighbors[(start + i) % neighbors.length] as StructuralRolloutPolicy)\n }\n return window.map((candidate) => ({\n surface: serializeRolloutPolicy(candidate),\n label: candidateLabel(policy, candidate),\n rationale:\n 'bounded single-dial neighbor of the current structuralRollout policy; ' +\n 'the held-out gate decides (deterministic enumeration — the dial space is tiny ' +\n 'and prompt-style reflective proposals are a measured zero here)',\n }))\n },\n }\n}\n","/**\n *\n * `improve` — the ONE public, surface-pluggable RSI verb.\n *\n * A thin facade over agent-eval's `selfImprove` (the held-out-gated closed\n * loop). It removes the two things a caller otherwise has to know to drive the\n * loop by hand: WHICH `MutableSurface` of the profile is being optimized, and\n * WHICH `SurfaceProposer` mutates that surface. You name a `surface`; the\n * facade picks the matching default proposer, extracts the baseline surface from\n * the profile, and runs `selfImprove`. It returns a frozen candidate and never\n * changes the input profile or caller-owned state.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates one named inline skill.\n * - `surface: 'memory'` → `memoryCurationProposer` curates the profile's\n * additional instructions as bounded durable lessons.\n * - `surface: 'rollout-policy'` → `rolloutPolicyProposer` mutates the\n * inference-time `StructuralRolloutPolicy` dials ({ k, repairRounds, testgen })\n * persisted in `profile.extensions['structural-rollout']` — deterministic\n * bounded neighbor enumeration; the held-out gate does the deciding. No-op\n * (nothing proposed, nothing shipped) when the profile has no such extension.\n * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete\n * canonical AgentProfile JSON in one candidate.\n * - `surface` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `agent-profile`} → no zero-config default\n * proposer exists (a code/config proposer needs caller-supplied wiring — a\n * worktree repo root, a candidate generator, a serializer). The facade\n * requires an explicit `opts.generator` for these and throws a `ConfigError`\n * otherwise. This is a designed boundary, not a missing default: there is\n * no safe value the facade could invent for those surfaces. Code instead\n * requires `opts.code.repoRoot` and accepts only the runtime-owned\n * `opts.code.generator` path so every isolated checkout can be released.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport { canonicalJson, makeFinding } from '@tangle-network/agent-eval'\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n memoryCurationProposer,\n type ProfileDispatchFn,\n skillOptProposer,\n type Worktree,\n type WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type CodeSurface,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport {\n type AgentProfile,\n type AgentProfileResourceRef,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport { rethrowAfterCleanup } from './cleanup'\nimport {\n type CandidateGenerator,\n improvementDriver,\n type ManagedImprovementDriver,\n} from './improvement-driver'\nimport { rawTraceDistiller } from './raw-trace-distiller'\nimport {\n applyRolloutPolicyToProfile,\n normalizeRolloutPolicy,\n rolloutPolicyProposer,\n serializeRolloutPolicy,\n structuralRolloutPolicyFromProfile,\n} from './rollout-policy'\n\n/** The executable agent lever `improve` optimizes. Profile fields remain\n * portable AgentProfile coordinates; implementation and orchestration files\n * use the code surface so a winner can be sealed into an exact candidate.\n * `rollout-policy` is the inference-time structuralRollout dials\n * (`profile.extensions['structural-rollout']`). */\nexport type ImproveSurface =\n | 'prompt'\n | 'skills'\n | 'tools'\n | 'mcp'\n | 'hooks'\n | 'subagents'\n | 'agent-profile'\n | 'memory'\n | 'code'\n | 'rollout-policy'\n\nexport interface ImproveOptions<TScenario extends Scenario, TArtifact>\n extends Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'agent' | 'analyzeGeneration' | 'baselineSurface' | 'findings' | 'gate' | 'proposer'\n > {\n /** Dispatch the mutable surface directly when the host already owns that seam.\n * Exactly one of `agent` or `profileDispatch` is required. */\n agent?: SelfImproveOptions<TScenario, TArtifact>['agent']\n /** Dispatch each baseline or candidate as its complete AgentProfile.\n * Exactly one of `agent` or `profileDispatch` is required. */\n profileDispatch?: ProfileDispatchFn<TScenario, TArtifact>\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates a profile surface. When unset, the facade\n * picks the default for prompt, skills, and memory; surfaces\n * with no default REQUIRE this (fail-loud otherwise). Forbidden for code;\n * use `code.generator` so the runtime owns candidate cleanup. */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: with a real (non-`mem://`) `runDir`, the raw-trace distiller\n * (`rawTraceDistiller`) — typed `AnalystFinding`s pointing the proposer at the\n * prior generation's actual on-disk traces; for in-memory runs (no traces on\n * disk to point at), the built-in failure distiller — the worst-scoring/errored\n * cells distilled into typed `AnalystFinding`s for the NEXT proposal round.\n * Pass your own producer to replace either; pass `null` to disable and keep the\n * static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the distilled findings, feed the proposer\n * RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Unset (default): raw-trace findings whenever the run is durable\n * (a real `runDir` — that is where the traces live), the distilled failure digest\n * otherwise; the `memory` surface always defaults to its curation distiller.\n * `true` forces `rawTraceDistiller()` even for an in-memory run (it emits a loud\n * warning finding instead of paths); `false` forces the digest distiller even\n * with a real `runDir`. Ignored when `analyzeGeneration` is set explicitly\n * (that wins) or is `null` (disabled). */\n rawTraceContext?: boolean\n /** CODE-surface wiring: name `surface: 'code'`, point at a repo, and the\n * facade assembles the whole candidate pipeline — an isolated incumbent plus git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Required for every code run because a real\n * repository and base ref are necessary to measure the incumbent. */\n code?: ImproveCodeOptions\n /** Select the exact inline skill document to optimize. */\n skills?: ImproveSkillsOptions\n /** Custom held-back-exam decision. The string `gate` above controls whether\n * the exam runs; this callback controls how its evidence decides promotion. */\n promotionGate?: SelfImproveOptions<TScenario, TArtifact>['gate']\n}\n\nexport interface ImproveSkillsOptions {\n /** `name` of one inline entry in `profile.resources.skills`. */\n resourceName: string\n}\n\nexport interface ImproveCodeOptions {\n /** Repo root candidate worktrees fork from. */\n repoRoot: string\n /** Base ref candidates fork from. Default `main`. */\n baseRef?: string\n /** Directory worktrees are created under. Default `<repoRoot>/.worktrees`. */\n worktreeDir?: string\n /** Git-compatible adapter override, primarily for tests. Candidate advancement\n * still requires normal Git worktree and commit semantics. */\n worktree?: WorktreeAdapter\n /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImprovementCandidate {\n /** Surface searched by this run. */\n surface: ImproveSurface\n /** Exact winning value returned by agent-eval. */\n value: MutableSurface\n /** Detached profile candidate when the surface maps directly to AgentProfile. */\n profile?: AgentProfile\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** Frozen candidate only. Live state is changed through an approved activation. */\n candidate: ImprovementCandidate\n /** Held-out decision for this search result. */\n decision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Held-out lift (`winner − baseline` composite). Absent iff\n * `budget.holdout === 'deferred'` — no held-out measurement ran, so there\n * is no lift to report (never a fabricated 0). */\n lift?: number\n /** Full `selfImprove` result for advanced inspection. For code runs,\n * `raw.winner.surface.worktreeRef` remains live after return whether the\n * candidate passed or held; call `dispose()` after consuming it. */\n raw: SelfImproveResult<TScenario, TArtifact>\n /** Release resources owned by this result. Idempotent; currently disposes\n * the returned code worktree and is a no-op for profile-only surfaces. */\n dispose(): Promise<void>\n}\n\n/** Default model id for the reflective drivers when `llm.model` is unset — a model the Tangle\n * router actually serves (callers should pass their own `llm.model`). */\nconst defaultReflectionModel = 'deepseek-v4-flash'\n\n/** The reflective proposers (`gepaProposer`/`skillOptProposer`) take a full\n * `LlmClientOptions`; `SelfImproveLlm` is the thin user-facing subset. */\nfunction llmClientOptions(llm: SelfImproveLlm | undefined): { baseUrl?: string; apiKey?: string } {\n return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey }\n}\n\n/** The default proposer for a surface, or `undefined` when the surface has no\n * zero-config default (the caller must supply `opts.generator`). */\nfunction defaultGeneratorFor(\n surface: ImproveSurface,\n llm: SelfImproveLlm | undefined,\n): SurfaceProposer | undefined {\n const model = llm?.model ?? defaultReflectionModel\n switch (surface) {\n case 'prompt':\n return gepaProposer({ llm: llmClientOptions(llm), model, target: 'agent system prompt' })\n case 'skills':\n return skillOptProposer({ llm: llmClientOptions(llm), model, target: 'agent skill document' })\n case 'memory':\n return memoryCurationProposer()\n case 'rollout-policy':\n // Deterministic bounded enumeration — no LLM, so `llm` is unused here.\n return rolloutPolicyProposer()\n default:\n return undefined\n }\n}\n\n/** Extract the baseline surface a driver mutates from the profile field that\n * backs `surface`. Prompt, skills, and memory are text surfaces; config\n * surfaces serialize the matching profile record. */\nfunction baselineSurfaceFor(\n profile: AgentProfile,\n surface: ImproveSurface,\n skills?: ImproveSkillsOptions,\n): MutableSurface {\n switch (surface) {\n case 'prompt':\n return profile.prompt?.systemPrompt ?? ''\n case 'skills':\n return inlineSkill(profile, skills).content\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'subagents':\n return JSON.stringify(profile.subagents ?? {})\n case 'agent-profile':\n return canonicalJson(profile)\n case 'memory':\n return profileInstructions(profile)\n case 'rollout-policy': {\n // Empty surface when the profile never opted into structural rollout: the\n // proposer reads it as \"propose nothing\", so the loop runs baseline-only and\n // holds — tuning dials nothing consumes would ship dead config.\n const policy = structuralRolloutPolicyFromProfile(profile)\n return policy ? serializeRolloutPolicy(policy) : ''\n }\n case 'code':\n throw new ConfigError(\n 'improve(): code requires the isolated baseline created from opts.code.repoRoot',\n )\n }\n}\n\n/** Slice bound for distilled judge notes: wide enough that a real traceback /\n * failing-assertion note survives intact — clipping mid-traceback would leave\n * the proposer trace-blind. Referenced by the `rawTraceContext` docs. */\nconst DISTILLED_NOTES_MAX_CHARS = 1500\n\n/** Slice bound for a cell's error string — tighter than notes (errors are\n * usually one line; the full text stays on the raw cell). Also bounds the\n * error-derived `claim` fallback. */\nconst DISTILLED_ERROR_MAX_CHARS = 500\n\n/** The in-memory-run `analyzeGeneration`: distill each generation's failing cells\n * into TYPED `AnalystFinding`s for the next proposal round — the same envelope\n * `rawTraceDistiller` and the analyst registry emit, so consumers never branch on\n * a second ad-hoc digest shape. Judge notes and errors are already the domain's\n * own diagnosis (executable gates put their reasons there); a trace-analyst can\n * replace this wholesale via `opts.analyzeGeneration`. Falls back to the static\n * seed findings when the generation had no failures, so a clean round never wipes\n * the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{\n scenario: string\n composite: number\n notes: string\n claim?: string\n error?: string\n }> = []\n for (const candidate of input.candidates) {\n for (const rawCell of candidate.campaign.cells) {\n const cell = rawCell as unknown as Record<string, unknown>\n const scenario = String(cell.scenarioId ?? 'unknown')\n const error = typeof cell.error === 'string' ? cell.error : undefined\n const judgeScores =\n cell.judgeScores && typeof cell.judgeScores === 'object'\n ? Object.values(\n cell.judgeScores as Record<string, { composite?: number; notes?: string }>,\n )\n : []\n const composite =\n judgeScores.length === 0\n ? 0\n : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length\n if (!error && composite >= 0.999) continue\n const notes = judgeScores\n .map((j) => j.notes)\n .filter((n): n is string => typeof n === 'string' && n.length > 0)\n .join('; ')\n .slice(0, DISTILLED_NOTES_MAX_CHARS)\n const claim =\n notes ||\n (error ? `Scenario ${scenario} failed: ${error.slice(0, DISTILLED_ERROR_MAX_CHARS)}` : '')\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(claim ? { claim } : {}),\n ...(error ? { error: error.slice(0, DISTILLED_ERROR_MAX_CHARS) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP).map((f) =>\n makeFinding({\n analyst_id: 'generation-failure-distiller',\n severity: f.error !== undefined || f.composite < 0.5 ? 'high' : 'medium',\n area: 'generation-failure',\n confidence: 1,\n subject: f.scenario,\n claim: `Scenario ${f.scenario} scored composite ${f.composite}${\n f.notes ? `: ${f.notes}` : ''\n }${f.error ? ` (error: ${f.error})` : ''}`,\n evidence_refs: [],\n metadata: {\n scenario: f.scenario,\n composite: f.composite,\n ...(f.notes ? { notes: f.notes } : {}),\n ...(f.error !== undefined ? { error: f.error } : {}),\n },\n }),\n )\n }\n}\n\n/** Memory accumulates durable lessons, so keep the caller's seed findings while\n * adding fresh judge failures. Curator proposers consume `claim`; the generic\n * distiller retains the richer diagnostic fields for reflective proposers. */\nfunction memoryGenerationDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const distillFailures = generationFailureDistiller<TScenario, TArtifact>(staticFindings)\n return async (input) => {\n const fresh = await distillFailures(input)\n return fresh === staticFindings ? staticFindings : [...staticFindings, ...fresh]\n }\n}\n\n/** The default `analyzeGeneration` when the caller passed none: raw-trace context\n * whenever the run is durable (a real `runDir` is where the traces live — see\n * `rawTraceDistiller`), the failure digest for in-memory runs, with\n * `rawTraceContext` as the explicit override in either direction. The `memory`\n * surface keeps its curation distiller (its proposer consumes `claim` findings,\n * not trace paths) unless `rawTraceContext: true` is explicit. */\nfunction defaultDistillerFor<TScenario extends Scenario, TArtifact>(\n opts: ImproveOptions<TScenario, TArtifact>,\n findings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const surface = opts.surface ?? 'prompt'\n const durableRun = opts.runDir !== undefined && !opts.runDir.startsWith('mem://')\n const useRawTraces = opts.rawTraceContext ?? (surface === 'memory' ? false : durableRun)\n if (useRawTraces) return rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n if (surface === 'memory') return memoryGenerationDistiller<TScenario, TArtifact>(findings)\n return generationFailureDistiller<TScenario, TArtifact>(findings)\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer\n cleanup(retainedWinner?: MutableSurface): Promise<void>\n}\n\nasync function discardPreparedBaseline(\n worktree: WorktreeAdapter,\n baselineWorktree: Worktree,\n cause: unknown,\n): Promise<never> {\n return rethrowAfterCleanup(\n cause,\n () => worktree.discard(baselineWorktree),\n 'improve(): code preparation failed',\n )\n}\n\nfunction isCodeSurface(surface: MutableSurface | undefined): surface is CodeSurface {\n return typeof surface === 'object' && surface !== null && surface.kind === 'code'\n}\n\n/** Create a clean incumbent checkout and the candidate producer for a code run. */\nasync function prepareCodeRun(code: ImproveCodeOptions): Promise<PreparedCodeRun> {\n const baseRef = code.baseRef ?? 'main'\n const worktree =\n code.worktree ??\n gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}),\n })\n const baselineWorktree = await worktree.create({ baseRef, label: 'incumbent-baseline' })\n try {\n const baseline = await worktree.finalize(baselineWorktree, 'Incumbent code checkout')\n let baselineDiscarded = false\n const generator =\n code.generator ??\n agenticGenerator({\n ...(code.harness ? { harness: code.harness } : {}),\n ...(code.verify ? { verify: code.verify } : {}),\n ...(code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}),\n })\n const managed: ManagedImprovementDriver = improvementDriver({ worktree, generator, baseRef })\n\n return {\n baseline,\n proposer: managed,\n async cleanup(retainedWinner) {\n const errors: unknown[] = []\n const retainedWorktreeRef = isCodeSurface(retainedWinner)\n ? retainedWinner.worktreeRef\n : undefined\n try {\n await managed?.cleanup(retainedWorktreeRef ? [retainedWorktreeRef] : [])\n } catch (cause) {\n errors.push(cause)\n }\n if (!baselineDiscarded && retainedWorktreeRef !== baseline.worktreeRef) {\n try {\n await worktree.discard(baselineWorktree)\n baselineDiscarded = true\n } catch (cause) {\n errors.push(cause)\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improve(): failed to clean code improvement worktrees')\n }\n },\n }\n } catch (cause) {\n return discardPreparedBaseline(worktree, baselineWorktree, cause)\n }\n}\n\nfunction idempotentDispose(dispose: () => Promise<void>): () => Promise<void> {\n let disposed = false\n let inFlight: Promise<void> | undefined\n return async () => {\n if (disposed) return\n if (inFlight) return inFlight\n inFlight = (async () => {\n await dispose()\n disposed = true\n })()\n try {\n await inFlight\n } finally {\n inFlight = undefined\n }\n }\n}\n\n/** Parse a JSON winner surface 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\nfunction assertCandidateSurfaceKind(\n surface: ImproveSurface,\n winner: MutableSurface,\n): asserts winner is MutableSurface {\n if (surface === 'code' ? typeof winner === 'string' : typeof winner !== 'string') {\n throw new ConfigError(\n `improve(): the '${surface}' candidate returned an incompatible surface value`,\n )\n }\n}\n\n/** Materialize a detached profile candidate without changing the baseline. */\nfunction materializeImprovementProfileCandidate(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n skills?: ImproveSkillsOptions,\n): AgentProfile | undefined {\n if (typeof winner !== 'string') return undefined\n let candidate: AgentProfile\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 // An empty winner is the never-opted-in baseline (see baselineSurfaceFor):\n // nothing to apply, so no profile candidate — never a parse error.\n if (winner === '') return undefined\n // Parse + re-validate the winner against the policy's own invariants — a\n // custom generator's malformed dial must fail loud, not persist silently.\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 case 'code':\n return undefined\n }\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\n/** Build the mutable-surface callback expected by agent-eval from a host that\n * runs complete profiles. The host sees the same immutable baseline/candidate\n * profile Runtime reports as the result; it never needs to duplicate surface\n * replacement rules. */\nfunction profileImprovementAgent<TScenario extends Scenario, TArtifact>(input: {\n baselineProfile: AgentProfile\n surface: ImproveSurface\n skills?: ImproveSkillsOptions\n dispatch: ProfileDispatchFn<TScenario, TArtifact>\n}): SelfImproveOptions<TScenario, TArtifact>['agent'] {\n return (surfaceValue, scenario, ctx) => {\n const profile = materializeImprovementProfileCandidate(\n input.baselineProfile,\n input.surface,\n surfaceValue,\n input.skills,\n )\n // An unset rollout policy deliberately uses the unchanged profile as its\n // baseline. Every other unsupported surface must stop before a host run.\n const dispatchedProfile =\n profile ??\n (input.surface === 'rollout-policy' && surfaceValue === ''\n ? input.baselineProfile\n : undefined)\n if (!dispatchedProfile) {\n throw new ConfigError(\n `improve(): surface '${input.surface}' cannot run through profileDispatch; use opts.agent for a non-profile surface`,\n )\n }\n return input.dispatch(dispatchedProfile, scenario, ctx)\n }\n}\n\nfunction inlineSkill(\n profile: AgentProfile,\n options: ImproveSkillsOptions | undefined,\n): 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: AgentProfile): 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(profile: AgentProfile, surface: 'skills' | 'memory'): 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 * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.decision === 'ship') console.log(out.candidate)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const {\n surface = 'prompt',\n gate = 'holdout',\n agent,\n profileDispatch,\n generator,\n allowedModels,\n rawTraceContext,\n code,\n skills,\n promotionGate,\n analyzeGeneration,\n ...sharedOptions\n } = opts\n\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n if (agent !== undefined && profileDispatch !== undefined) {\n throw new ConfigError('improve(): provide exactly one of opts.agent or opts.profileDispatch')\n }\n if (agent === undefined && profileDispatch === undefined) {\n throw new ConfigError('improve(): provide exactly one of opts.agent or opts.profileDispatch')\n }\n const baselineProfile = immutableCandidateValue(parsedProfile.data)\n if (profileDispatch && surface === 'code') {\n throw new ConfigError(\n \"improve(): surface 'code' cannot use profileDispatch because code candidates require isolated worktree execution; use opts.agent\",\n )\n }\n if (surface === 'code' && generator) {\n throw new ConfigError(\n \"improve(): surface 'code' forbids opts.generator because an external SurfaceProposer cannot transfer checkout ownership; pass opts.code.generator instead\",\n )\n }\n const usesReflectionModel = !generator && (surface === 'prompt' || surface === 'skills')\n if (usesReflectionModel) {\n assertModelAllowed(sharedOptions.llm?.model ?? defaultReflectionModel, allowedModels)\n }\n\n let preparedCode: PreparedCodeRun | undefined\n if (surface === 'code') {\n if (!code) {\n throw new ConfigError(\n \"improve(): surface 'code' requires opts.code.repoRoot so the incumbent can run from an isolated checkout\",\n )\n }\n preparedCode = await prepareCodeRun(code)\n }\n const proposer =\n preparedCode?.proposer ?? generator ?? defaultGeneratorFor(surface, sharedOptions.llm)\n if (!proposer) {\n throw new ConfigError(\n `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n const effectiveAgent =\n profileDispatch === undefined\n ? agent\n : profileImprovementAgent({\n baselineProfile,\n surface,\n ...(skills === undefined ? {} : { skills }),\n dispatch: profileDispatch,\n })\n if (!effectiveAgent) {\n throw new ConfigError('improve(): provide exactly one of opts.agent or opts.profileDispatch')\n }\n\n let raw: SelfImproveResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n agent: effectiveAgent,\n baselineSurface:\n preparedCode?.baseline ?? baselineSurfaceFor(baselineProfile, surface, skills),\n 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 if (!preparedCode) throw 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(surface, winnerSurface)\n if (preparedCode) {\n try {\n await preparedCode.cleanup(winnerSurface)\n } catch (cleanupCause) {\n try {\n await preparedCode.cleanup()\n } catch (finalCleanupCause) {\n throw new AggregateError(\n [cleanupCause, finalCleanupCause],\n 'improve(): code result cleanup failed, including the final all-worktree retry',\n )\n }\n throw new AggregateError(\n [cleanupCause],\n 'improve(): code result cleanup failed; the final all-worktree retry succeeded',\n )\n }\n }\n const dispose = idempotentDispose(async () => preparedCode?.cleanup())\n const candidateProfile = materializeImprovementProfileCandidate(\n baselineProfile,\n surface,\n winnerSurface,\n skills,\n )\n const candidate = immutableCandidateValue<ImprovementCandidate>({\n surface,\n value: winnerSurface,\n ...(candidateProfile ? { profile: candidateProfile } : {}),\n })\n\n return {\n candidate,\n decision: raw.gateDecision,\n ...(raw.lift !== undefined ? { lift: raw.lift } : {}),\n raw,\n dispose,\n }\n}\n","import {\n type AgentCandidateBundle,\n type AgentCandidateExperiment,\n type AgentImprovementActivationIntent,\n type AgentImprovementActivationTarget,\n type AgentImprovementSurface,\n type AgentProfile,\n type AgentProfileDiff,\n type AgentProfileDiffRemoval,\n agentProfileDiffSchema,\n agentProfileSchema,\n defineAgentProfileDiff,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n agentCandidateProfileAsAgentProfile,\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\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: AgentCandidateExperiment,\n intent: AgentImprovementActivationIntent,\n targets: readonly AgentImprovementActivationTarget[],\n): void {\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 targets.some((target) => !target.identity.trim()) ||\n targets.some(\n (target) =>\n target.expectedBaseDigest !==\n agentImprovementTargetDigest(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('candidate activation targets must cover exactly the changed surfaces')\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: AgentCandidateExperiment,\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: agentImprovementTargetDigest(experiment, sourceArm, target.surface),\n }))\n assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets)\n return targets as [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]]\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\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/**\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\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 AnalystFinding, assertNoJudgeVerdict } from '@tangle-network/agent-eval/analyst'\nimport {\n type CandidateExperimentExecutionInput,\n type CompareCandidateExperimentOptions,\n measuredComparisonFromCandidateExperiment,\n runCandidateExperiment,\n type Scenario,\n sealCandidateExperiment,\n verifyCandidateExperiment,\n verifyCandidateExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateBenchmarkCellRef,\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentCandidateExperimentMaterial,\n AgentCandidateExperimentMeasurement,\n AgentCandidateLineage,\n AgentCandidateRunCell,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n AgentProfile,\n CandidateExecutionEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateMaterializationReceiptSchema,\n agentCandidateRunReceiptSchema,\n agentImprovementActivationSchema,\n agentImprovementProposalSchema,\n agentImprovementReviewSchema,\n candidateExecutionEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { materializeCandidateProfile } from '@tangle-network/agent-profile-materialize'\n\nimport { runAnalystLoop } from '../analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from '../analyst-loop/types'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n type ExecutePreparedAgentCandidateOptions,\n executePreparedAgentCandidate,\n} from '../candidate-execution/execute'\nimport {\n type PrepareAgentCandidateExecutionOptions,\n prepareAgentCandidateExecution,\n} from '../candidate-execution/prepare'\nimport {\n assertCandidateProfileBinding,\n candidateMaterializerHarness,\n createAgentCandidateProfileActivation,\n parseAgentCandidateProfileActivation,\n} from '../candidate-execution/profile'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateRunFinalization,\n AgentCandidateTaskExecution,\n} from '../candidate-execution/types'\nimport {\n verifiedResourceTextByDigest,\n verifyAgentCandidateBundle,\n} from '../candidate-execution/verify'\nimport { rethrowAfterCleanup } from '../improvement/cleanup'\nimport { type ImproveOptions, type ImproveResult, improve } from '../improvement/improve'\nimport {\n type AgentImprovementActivationTargetIdentity,\n assertAgentImprovementActivationTargets,\n buildAgentImprovementActivationTargets,\n deriveChangedSurfaces,\n} from './improvement-surfaces'\n\nexport type {\n AgentImprovementActivation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n CandidateExecutionEvidence,\n} from '@tangle-network/agent-interface'\n\nexport interface AgentCandidateExperimentCellPlacement {\n executionId: string\n attempt?: number\n executionRoots: AgentCandidateTaskExecution['executionRoots']\n stagingRoots: AgentCandidateTaskExecution['stagingRoots']\n ports: AgentCandidateExecutionPorts\n preparation?: PrepareAgentCandidateExecutionOptions\n execution: ExecutePreparedAgentCandidateOptions\n}\n\nexport interface RunAgentCandidateExperimentOptions\n extends Omit<CompareCandidateExperimentOptions, 'experiment' | 'measurements'> {\n experiment: AgentCandidateExperiment\n placeCell: (\n input: CandidateExperimentExecutionInput,\n ) => AgentCandidateExperimentCellPlacement | Promise<AgentCandidateExperimentCellPlacement>\n maxConcurrency?: number\n signal?: AbortSignal\n}\n\nexport interface RunAgentCandidateExperimentResult {\n experiment: AgentCandidateExperiment\n measurements: AgentCandidateExperimentMeasurement[]\n evaluation: AgentImprovementMeasuredComparison\n}\n\nexport interface ExecuteAgentCandidateExperimentCellOptions\n extends CandidateExperimentExecutionInput,\n AgentCandidateExperimentCellPlacement {}\n\nexport interface VerifyCandidateExecutionEvidenceOptions {\n experiment: AgentCandidateExperiment\n arm: 'baseline' | 'candidate'\n benchmarkCell: AgentCandidateBenchmarkCellRef\n seed: number\n attempt?: number\n resolvedResources?: ReadonlyMap<Sha256Digest, string>\n}\n\n/** A failed baseline or candidate cell with its complete Runtime failure result. */\nexport class AgentCandidateExperimentCellExecutionError extends Error {\n readonly finalization: Extract<AgentCandidateRunFinalization, { succeeded: false }>\n\n constructor(finalization: Extract<AgentCandidateRunFinalization, { succeeded: false }>) {\n super(`candidate experiment cell failed: ${finalization.reason}`)\n this.name = 'AgentCandidateExperimentCellExecutionError'\n this.finalization = finalization\n }\n}\n\nexport interface CreateAgentImprovementProposalOptions {\n runId: string\n findings: readonly AnalystFinding[]\n evaluation: AgentImprovementMeasuredComparison\n now?: () => Date\n}\n\nexport type CreateAgentImprovementMeasuredComparisonOptions = CompareCandidateExperimentOptions\n\nexport interface ReviewAgentImprovementInput {\n decision: AgentImprovementReviewDecision\n reviewedBy: string\n reason: string\n feedback?: string\n now?: () => Date\n}\n\nexport interface CreateAgentImprovementActivationOptions {\n 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 now?: () => Date\n}\n\nexport interface ProposeAgentImprovementOptions<TScenario extends Scenario, TArtifact> {\n runId: string\n profile: AgentProfile\n analysis: Omit<RunAnalystLoopOpts, 'runId' | 'improvementProposalSource'>\n improvement: 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\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.raw.provenance.runId],\n developmentSplitDigest: improvement.raw.provenance.evidence.search.splitDigest,\n }\n return sealCandidateExperiment({ ...material, candidateLineage })\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 AnalystImprovementProposal = Omit<AgentImprovementProposal, 'findings'> & {\n findings: AnalystFinding[]\n}\n\n/** Execute both arms of one immutable experiment and derive its paired result. */\nexport async function runAgentCandidateExperiment(\n options: RunAgentCandidateExperimentOptions,\n): Promise<RunAgentCandidateExperimentResult> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const measurements = await runCandidateExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const placement = await options.placeCell(input)\n return await executeAgentCandidateExperimentCell({ ...input, ...placement })\n },\n })\n const evaluation = createAgentImprovementMeasuredComparison({\n experiment,\n measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n ...(options.generationsExplored === undefined\n ? {}\n : { generationsExplored: options.generationsExplored }),\n ...(options.searchDurationMs === undefined\n ? {}\n : { searchDurationMs: options.searchDurationMs }),\n ...(options.searchCostUsd === undefined ? {} : { searchCostUsd: options.searchCostUsd }),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n return { experiment, measurements, evaluation }\n}\n\n/** Execute one exact arm, task, repetition, seed, and attempt through Runtime. */\nexport async function executeAgentCandidateExperimentCell(\n options: ExecuteAgentCandidateExperimentCellOptions,\n): Promise<CandidateExecutionEvidence> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const bundle = experiment[options.arm]\n assertExactExperimentInput(options, experiment, bundle)\n const attempt = options.attempt ?? 1\n if (attempt > options.task.attempt.maxAttempts) {\n throw new Error('candidate experiment attempt exceeds the signed task policy')\n }\n const runCell = canonicalCandidateDocument<AgentCandidateRunCell>({\n kind: 'agent-candidate-run-cell',\n experimentDigest: experiment.digest,\n arm: options.arm,\n bundleDigest: bundle.digest,\n suiteDigest: options.benchmarkCell.suiteDigest,\n taskDigest: options.task.digest,\n taskIndex: options.benchmarkCell.taskIndex,\n repetition: options.benchmarkCell.repetition,\n seed: options.seed,\n attempt,\n }).value\n const verified = await verifyAgentCandidateBundle(bundle, options.ports)\n const prepared = await prepareAgentCandidateExecution(\n verified,\n {\n executionId: options.executionId,\n runCell,\n benchmarkSuite: experiment.benchmark.suite,\n task: options.task,\n executionRoots: options.executionRoots,\n stagingRoots: options.stagingRoots,\n },\n options.ports,\n options.preparation,\n )\n const finalization = await executePreparedAgentCandidate(prepared, options.execution)\n if (!finalization.succeeded) {\n throw new AgentCandidateExperimentCellExecutionError(finalization)\n }\n const evidence = canonicalCandidateDocument<CandidateExecutionEvidence>({\n kind: 'agent-candidate-execution-evidence',\n materializationReceipt: prepared.materializationReceipt.value,\n receipt: finalization.receipt.value,\n }).value\n return verifyCandidateExecutionEvidence(evidence, {\n experiment,\n arm: options.arm,\n benchmarkCell: options.benchmarkCell,\n seed: options.seed,\n attempt,\n resolvedResources: verifiedResourceTextByDigest(verified),\n })\n}\n\n/** Delegate all statistics and promotion checks to agent-eval's receipt-based comparison. */\nexport function createAgentImprovementMeasuredComparison(\n options: CreateAgentImprovementMeasuredComparisonOptions,\n): AgentImprovementMeasuredComparison {\n return verifyCandidateExperimentComparison(measuredComparisonFromCandidateExperiment(options))\n}\n\n/** Analyze, search, then remeasure the resulting exact candidate before proposing it. */\nexport async function proposeAgentImprovement<TScenario extends Scenario, TArtifact>(\n options: ProposeAgentImprovementOptions<TScenario, TArtifact>,\n): Promise<ProposeAgentImprovementResult<TScenario, TArtifact>> {\n const analysis = await runAnalystLoop({ ...options.analysis, runId: options.runId })\n const findings = assertNoJudgeVerdict(\n analysis.analystResult.findings,\n 'proposeAgentImprovement findings',\n )\n const improvement = await improve(options.profile, [...findings], options.improvement)\n try {\n if (improvement.decision !== 'ship') {\n throw new Error('agent improvement search did not produce a promotable candidate')\n }\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 ...(options.metadata ? { metadata: options.metadata } : {}),\n generationsExplored: improvement.raw.generationsExplored,\n searchDurationMs: improvement.raw.durationMs,\n searchCostUsd: improvement.raw.totalCostUsd,\n })\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings,\n evaluation: measured.evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return {\n analysis,\n improvement,\n experiment,\n measurements: measured.measurements,\n proposal,\n }\n } catch (cause) {\n return rethrowAfterCleanup(cause, () => improvement.dispose(), 'proposeAgentImprovement failed')\n }\n}\n\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 if (!candidate.profile) {\n throw new Error(`improvement surface '${candidate.surface}' did not produce an exact profile`)\n }\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 = assertNoJudgeVerdict(\n [...options.findings],\n 'createAgentImprovementProposal findings',\n )\n const evaluation = verifyCandidateExperimentComparison(options.evaluation)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error('agent improvement proposal requires a passing experiment')\n }\n if (options.runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces = deriveChangedSurfaces(\n evaluation.experiment.baseline,\n evaluation.experiment.candidate,\n )\n return agentImprovementProposalSchema.parse(\n canonicalCandidateDocument<AnalystImprovementProposal>({\n kind: 'agent-improvement-proposal',\n runId: options.runId,\n changedSurfaces,\n proposedAt: (options.now ?? (() => new Date()))().toISOString(),\n findings: [...findings],\n evaluation,\n }).value,\n )\n}\n\n/** Persist a human or tenant-policy decision bound to one exact proposal. */\nexport function reviewAgentImprovementProposal(\n inputProposal: AgentImprovementProposal,\n input: ReviewAgentImprovementInput,\n): AgentImprovementReview {\n const proposal = verifyAgentImprovementProposal(inputProposal)\n if (!input.reviewedBy.trim()) throw new Error('candidate review requires reviewedBy')\n if (!input.reason.trim()) throw new Error('candidate review requires a reason')\n if (input.decision === 'approve' && proposal.evaluation.decision.outcome !== 'ship') {\n throw new Error('candidate cannot be approved without a passing experiment')\n }\n 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 return agentImprovementActivationSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivation>({\n kind: 'agent-improvement-activation',\n proposalDigest: proposal.digest,\n reviewDigest: review.digest,\n experimentDigest: experiment.digest,\n candidateBundleDigest: experiment.candidate.digest,\n 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 evaluation = verifyCandidateExperimentComparison(proposal.evaluation)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error('agent improvement proposal does not contain a passing experiment')\n }\n if (proposal.runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces = deriveChangedSurfaces(\n evaluation.experiment.baseline,\n evaluation.experiment.candidate,\n )\n if (!sameOrderedValues(proposal.changedSurfaces, changedSurfaces)) {\n throw new Error('proposal changed surfaces do not match its exact experiment')\n }\n assertNoJudgeDerivedProposalFindings(proposal.findings)\n return proposal\n}\n\n/** Validate the canonical identity and wire shape of an improvement review. */\nexport function verifyAgentImprovementReview(input: unknown): AgentImprovementReview {\n return verifyCanonicalCandidateDocument(\n agentImprovementReviewSchema.parse(input),\n 'agent improvement review',\n )\n}\n\n/** Validate activation authority against the exact proposal, review, experiment, and base state. */\nexport function verifyAgentImprovementActivation(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n}): AgentImprovementActivation {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const review = verifyAgentImprovementReview(input.review)\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(input.activation),\n 'agent improvement activation',\n )\n const experiment = proposal.evaluation.experiment\n if (\n review.decision !== 'approve' ||\n review.proposalDigest !== proposal.digest ||\n activation.proposalDigest !== proposal.digest ||\n activation.reviewDigest !== review.digest ||\n activation.experimentDigest !== experiment.digest ||\n activation.candidateBundleDigest !== experiment.candidate.digest ||\n 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 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 = materializeCandidateProfile(\n bundle.profile,\n candidateMaterializerHarness(materialization.harness),\n { resolvedResources: options.resolvedResources },\n )\n const activation = parseAgentCandidateProfileActivation(\n materialization.profileActivation,\n materialization.profileActivation.profilePlan.digest,\n )\n const regeneratedActivation = createAgentCandidateProfileActivation(\n expectedProfilePlan,\n materialization.profileActivation.profilePlan,\n )\n if (activation.digest !== regeneratedActivation.digest) {\n throw new Error('candidate profile activation does not match the experiment bundle')\n }\n if (\n materialization.bundleDigest !== bundle.digest ||\n receipt.bundleDigest !== bundle.digest ||\n receipt.runCellDigest !== cell.digest ||\n receipt.materializationReceiptDigest !== materialization.digest ||\n receipt.executionPlanDigest !== plan.digest\n ) {\n throw new Error('candidate execution evidence does not bind one exact Runtime run')\n }\n assertEvidenceMaterialDigest(receipt.modelSettlement, 'candidate model settlement')\n assertEvidenceMaterialDigest(receipt.taskOutcome, 'candidate task outcome')\n assertEvidenceMaterialDigest(receipt.benchmarkResult, 'candidate benchmark result')\n return immutableCandidateValue(evidence)\n}\n\nfunction assertExactExperimentInput(\n input: CandidateExperimentExecutionInput,\n experiment: AgentCandidateExperiment,\n bundle: AgentCandidateBundle,\n): void {\n const task = experiment.benchmark.tasks[input.benchmarkCell.taskIndex]\n const index =\n input.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + input.benchmarkCell.repetition\n if (\n input.experiment.digest !== experiment.digest ||\n input.bundle.digest !== bundle.digest ||\n !task ||\n input.task.digest !== task.digest ||\n input.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest ||\n input.seed !== experiment.benchmark.suite.seeds[index]\n ) {\n throw new Error('Runtime received a substituted candidate experiment cell')\n }\n}\n\nfunction assertCapturedInput(\n captured: { digest: Sha256Digest; material: { sha256: Sha256Digest; byteLength: number } },\n expected: { digest: Sha256Digest },\n label: string,\n): void {\n const bytes = canonicalCandidateBytes(omitTopLevelDigest(expected))\n if (\n captured.digest !== expected.digest ||\n captured.material.sha256 !== expected.digest ||\n captured.material.byteLength !== bytes.byteLength\n ) {\n throw new Error(`candidate materialization substituted its ${label}`)\n }\n}\n\nfunction assertEvidenceMaterialDigest(\n evidence: {\n digest: Sha256Digest\n material: unknown\n artifact: { sha256: Sha256Digest; byteLength: number }\n },\n label: string,\n): void {\n const bytes = canonicalCandidateBytes(evidence.material)\n if (\n canonicalCandidateDigest(evidence.material) !== evidence.digest ||\n evidence.artifact.sha256 !== evidence.digest ||\n evidence.artifact.byteLength !== bytes.byteLength\n ) {\n throw new Error(`${label} digest does not match its canonical material`)\n }\n}\n\nfunction sameOrderedValues<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction assertNoJudgeDerivedProposalFindings(\n findings: AgentImprovementProposal['findings'],\n): void {\n const leaked = findings.filter((finding) => finding.derived_from_judge === true)\n if (leaked.length === 0) return\n const identifiers = leaked.map((finding) =>\n typeof finding.finding_id === 'string' ? finding.finding_id : '<unknown>',\n )\n throw new Error(\n 'agent improvement proposal findings: judge-derived findings cannot steer an improvement: ' +\n `[${identifiers.join(', ')}]`,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,cAAc,cAAc;AACjD,SAAS,MAAM,SAAS,WAAW;AASnC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAaP,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AAI1B,IAAM,gCAAgC;AA+ItC,SAAS,iBAAiB,OAAgC,CAAC,GAAuB;AACvF,QAAM,UAAU,KAAK,WAAW;AAChC,MAAI,KAAK,qBAAqB,YAAY,SAAS;AACjD,UAAM,IAAI,MAAM,8DAA8D;AAAA,EAChF;AACA,MAAI,KAAK,qBAAqB,CAAC,KAAK,SAAS;AAC3C,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC3F;AACA,MAAI,KAAK,wBAAwB,CAAC,KAAK,mBAAmB;AACxD,UAAM,IAAI,MAAM,mEAAmE;AAAA,EACrF;AACA,MAAI,KAAK,iBAAiB,CAAC,KAAK,mBAAmB;AACjD,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,QAAM,sBAAsB,KAAK,oBAC7B,0BAA0B,KAAK,OAAuB,IACtD;AACJ,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,MAAM,KAAK,cAAc;AAC/B,QAAM,QAAQ,KAAK,WAAW;AAC9B,QAAM,SAAS,KAAK;AAEpB,SAAO;AAAA,IACL,MAAM,WAAW,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMxB,yBAAyB;AAAA,IACzB,MAAM,SAAS;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAA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AAO;AAAA,IAAI,CAAC,YAC9B,OAAO,QAAQ,eAAe,WAAW,QAAQ,aAAa;AAAA,EAChE;AACA,QAAM,IAAI;AAAA,IACR,6FACM,YAAY,KAAK,IAAI,CAAC;AAAA,EAC9B;AACF;","names":["receipt","result","spawnSync","spawnSync","existsSync","join","resolve","makeFinding","truncate","makeFinding","makeFinding","agentProfileSchema","agentProfileSchema"]}
|