@tangle-network/agent-runtime 0.92.1 → 0.93.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 +14 -4
- package/dist/candidate-execution/index.d.ts +48 -4
- package/dist/candidate-execution/index.js +6 -2
- package/dist/{chunk-A62TP7SK.js → chunk-26WCEARH.js} +295 -40
- package/dist/chunk-26WCEARH.js.map +1 -0
- package/dist/{chunk-PH65PR4F.js → chunk-3VU2OWOY.js} +106 -2
- package/dist/chunk-3VU2OWOY.js.map +1 -0
- package/dist/{chunk-4FPXIMSI.js → chunk-VMHKMNEU.js} +38 -9
- package/dist/chunk-VMHKMNEU.js.map +1 -0
- package/dist/{improve-CUVCq7xg.d.ts → improve-DDhQaaJT.d.ts} +17 -5
- package/dist/index.d.ts +3 -3
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +6 -8
- package/dist/intelligence.js +23 -131
- package/dist/intelligence.js.map +1 -1
- package/dist/{prepare-Z08a4heC.d.ts → prepare-DiVGKcwS.d.ts} +7 -2
- package/package.json +4 -4
- package/skills/build-with-agent-runtime/SKILL.md +2 -1
- package/dist/chunk-4FPXIMSI.js.map +0 -1
- package/dist/chunk-A62TP7SK.js.map +0 -1
- package/dist/chunk-PH65PR4F.js.map +0 -1
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
import { AgentCandidateBundle, AgentCandidateArtifactRef, AgentCandidateTermination, AgentCandidateTaskOutcomeEvidence, Sha256Digest, AgentCandidateContainer, AgentCandidateOciPlatform, AgentCandidateGitHubRepository, AgentCandidateWorkspaceSnapshotEvidence, AgentCandidateResolvedModel, AgentCandidateAttemptPolicy, AgentCandidateExecutionLimits, AgentCandidateModelAccessNetwork, AgentCandidateCapturedArtifact, AgentCandidateWorkspaceManifestMaterialV1, AgentCandidateProfilePlanEvidence, AgentCandidateExecutionPlanEvidence, AgentCandidateMaterializationReceipt, AgentCandidateInstructionDelivery, AgentCandidateEffectiveMemory, AgentCandidateRunReceiptV2, AgentCandidateSpend, ReasoningEffort } from '@tangle-network/agent-interface';
|
|
1
2
|
import { BenchmarkEvaluation, TraceStore } from '@tangle-network/agent-eval';
|
|
2
|
-
|
|
3
|
+
|
|
4
|
+
/** Exact candidate wire shape before the runtime computes its canonical digest. */
|
|
5
|
+
type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>;
|
|
6
|
+
/** Validate and content-address a candidate bundle before it crosses an approval boundary. */
|
|
7
|
+
declare function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle;
|
|
3
8
|
|
|
4
9
|
declare const verifiedCandidateBrand: unique symbol;
|
|
5
10
|
declare const preparedCandidateBrand: unique symbol;
|
|
@@ -710,4 +715,4 @@ interface PrepareAgentCandidateExecutionOptions {
|
|
|
710
715
|
/** Materializes a verified candidate into one immutable evaluator-owned execution plan. */
|
|
711
716
|
declare function prepareAgentCandidateExecution(candidate: VerifiedAgentCandidate, task: AgentCandidateTaskExecution, ports: AgentCandidateExecutionPorts, options?: PrepareAgentCandidateExecutionOptions): Promise<PreparedAgentCandidateExecution>;
|
|
712
717
|
|
|
713
|
-
export {
|
|
718
|
+
export { InMemoryAgentCandidateExecutionClaimStore as $, type AgentCandidateTaskExecution as A, type AgentCandidateExecutorProfileFile as B, type AgentCandidateExecutorRequest as C, type AgentCandidateExecutorStopRequest as D, type ExecutePreparedAgentCandidateOptions as E, type AgentCandidateExecutorTaskOutcomeCapture as F, type AgentCandidateExecutorWorkspaceFile as G, type AgentCandidateExecutorWorkspaceInput as H, type AgentCandidateMemoryPort as I, type AgentCandidateMemoryResetResult as J, type AgentCandidateModelLimits as K, type AgentCandidateModelPort as L, type AgentCandidateOutputArtifactPort as M, type AgentCandidateOutputPurpose as N, type AgentCandidateProtectedModelActivation as O, type PrepareAgentCandidateExecutionOptions as P, type AgentCandidateProtectedModelCall as Q, type AgentCandidateProtectedModelReservation as R, type AgentCandidateProtectedModelSettlement as S, type AgentCandidateProtectedRunCapture as T, type AgentCandidateRepositoryPort as U, type AgentCandidateRetryRejection as V, type AgentCandidateVerificationPorts as W, type AgentCandidateWorkspacePort as X, CANDIDATE_TRACE_ENV as Y, CANDIDATE_TRACE_TAGS as Z, type CanonicalCandidateDocument as _, type AgentCandidateExecutionPorts as a, type PreparedAgentCandidateExecution as a0, type PreparedAgentCandidateInstruction as a1, type PreparedAgentCandidateLaunch as a2, type PreparedAgentCandidateTrace as a3, type ResolvedAgentCandidateContainer as a4, type VerifiedAgentCandidate as a5, type VerifiedAgentCandidateTaskOutcome as a6, executePreparedAgentCandidate as a7, prepareAgentCandidateExecution as a8, sealAgentCandidateBundle as a9, type AgentCandidateRunFinalization as b, type AgentCandidateBundleInput as c, type AgentCandidateArtifactPort as d, type AgentCandidateBenchmarkGraderIdentity as e, type AgentCandidateBenchmarkGraderPort as f, type AgentCandidateContainerPort as g, type AgentCandidateExecutionAttemptRecord as h, type AgentCandidateExecutionAttemptRef as i, type AgentCandidateExecutionClaim as j, type AgentCandidateExecutionClaimResult as k, type AgentCandidateExecutionClaimStore as l, type AgentCandidateExecutionCleanupHandles as m, type AgentCandidateExecutionFailureClass as n, type AgentCandidateExecutionFinishResult as o, type AgentCandidateExecutionLease as p, type AgentCandidateExecutionPhase as q, type AgentCandidateExecutionPhaseResult as r, type AgentCandidateExecutionRecoveryEvidence as s, type AgentCandidateExecutionStageResult as t, type AgentCandidateExecutionTerminalRecord as u, type AgentCandidateExecutionTerminalResult as v, type AgentCandidateExecutionUsage as w, type AgentCandidateExecutorFinalCapture as x, type AgentCandidateExecutorMemoryCapture as y, type AgentCandidateExecutorPort as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.93.0",
|
|
4
4
|
"description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-runtime#readme",
|
|
6
6
|
"repository": {
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
},
|
|
105
105
|
"devDependencies": {
|
|
106
106
|
"@biomejs/biome": "^2.4.15",
|
|
107
|
-
"@tangle-network/agent-eval": "^0.
|
|
107
|
+
"@tangle-network/agent-eval": "^0.114.0",
|
|
108
108
|
"@tangle-network/agent-interface": "^0.25.0",
|
|
109
109
|
"@tangle-network/sandbox": "^0.9.7",
|
|
110
110
|
"@types/node": "^25.9.3",
|
|
@@ -134,7 +134,7 @@
|
|
|
134
134
|
"license": "MIT",
|
|
135
135
|
"packageManager": "pnpm@10.28.0",
|
|
136
136
|
"peerDependencies": {
|
|
137
|
-
"@tangle-network/agent-eval": ">=0.
|
|
137
|
+
"@tangle-network/agent-eval": ">=0.114.0 <1.0.0",
|
|
138
138
|
"@tangle-network/agent-interface": ">=0.25.0 <1.0.0",
|
|
139
139
|
"@tangle-network/sandbox": ">=0.8.0 <1.0.0",
|
|
140
140
|
"playwright": "^1.40.0"
|
|
@@ -149,6 +149,6 @@
|
|
|
149
149
|
},
|
|
150
150
|
"dependencies": {
|
|
151
151
|
"@tangle-network/agent-knowledge": "^1.11.2",
|
|
152
|
-
"@tangle-network/agent-profile-materialize": "0.3.
|
|
152
|
+
"@tangle-network/agent-profile-materialize": "0.3.2"
|
|
153
153
|
}
|
|
154
154
|
}
|
|
@@ -92,7 +92,8 @@ to its native default (`HARNESS_NATIVE_MODEL`) — never silently dropped.
|
|
|
92
92
|
| **Spawn N coding agents on isolated git worktrees, keep the one whose patch passes checks** | `worktreeFanout` + `createWorktreeCliExecutor` + `gateOnDeliverable(DeliverableSpec)` over a raw `WorktreePatchArtifact`, winner via `selectValidWinner` — `/loops` — NOT a hand-rolled spawn-loop / "coder" role | canonical-api §3.1 / §5 |
|
|
93
93
|
| **Sandbox coding rollout** (fresh box/round, or persistent+resume) | `runLoop(options)` / `openSandboxRun(client, opts, deliverable)` — `/loops` | canonical-api §3.1 |
|
|
94
94
|
| **Optimize a CODE surface** in a gated loop | `improvementDriver({ worktree, generator })` — root `.` | canonical-api §3.4 |
|
|
95
|
-
| **
|
|
95
|
+
| **Freeze a measured profile/diff + code surface for execution** | `buildAgentCandidateBundle(...)` then `verifyAgentCandidateBundle(...)` — `/candidate-execution` | canonical-api §2 |
|
|
96
|
+
| **Optimize any agent/code surface** (one call) — START HERE | `improve(profile, findings, { surface, gate })` — root `.`; prompt, skill-document, and curated-memory surfaces have built-in proposers, config/whole-profile surfaces accept a proposer, rollout policy enumerates bounded variants, and code gets isolated incumbent/candidate worktrees; drop to `selfImprove({ agent, scenarios, judge, baselineSurface })` only for lower-level control | canonical-api §3.4 |
|
|
96
97
|
| **Gate: ship/hold a candidate** (campaign ctx) | `defaultProductionGate` / `heldOutGate` / `composeGate` — `agent-eval/contract`; `neutralizationGate` (footprint-matched PLACEBO gate — proves a held-out lift is CONTENT, not added prompt/mount footprint) — `agent-eval/campaign` | canonical-api §3.4 |
|
|
97
98
|
| **Gate: ship/hold from a `BenchmarkReport`** (per-task cells) | `promotionGate({ report, incumbent, candidate })` — `/loops` | canonical-api §3.4 |
|
|
98
99
|
| **Run the full multi-generation flywheel + certify** | `runStrategyEvolution(config)` — `/loops` | canonical-api §3.4 |
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/improvement/improvement-driver.ts","../src/improvement/raw-trace-distiller.ts","../src/improvement/rollout-policy.ts","../src/improvement/improve.ts"],"sourcesContent":["/**\n *\n * `improvementDriver` — the ONE reflective/agentic improvement proposer for\n * agent-eval's improvement loop. It implements `SurfaceProposer` and owns\n * the candidate lifecycle (worktree create → generate → finalize/discard,\n * × populationSize); it delegates the only thing that genuinely varies — HOW\n * a candidate change is produced — to a pluggable `CandidateGenerator`.\n *\n * There is no separate \"analyst driver\" vs \"autoresearch driver\": those are\n * the SAME driver at two settings of a dial.\n * - cheap reflective path → `reflectiveGenerator` (shots=1, no sandbox;\n * applies pre-drafted patches)\n * - full agentic path → `agenticGenerator` (shots=N, multi-shot\n * verify-in-session loop; an agent reads code +\n * report, edits, and re-tries on verifier failure)\n * Both emit changes into a worktree the driver finalizes into a\n * `CodeSurface{ worktreeRef }` the loop measures on the holdout. See\n * agent-eval's `docs/design/self-improvement-engine.md`.\n *\n * @experimental\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type {\n CodeSurface,\n LabeledScenarioStore,\n ProposeContext,\n SurfaceProposer,\n Worktree,\n WorktreeAdapter,\n} from '@tangle-network/agent-eval/campaign'\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 fresh checkout of baseRef. Write changes here. */\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 }): Promise<{ applied: boolean; summary: string }>\n}\n\nexport interface ImprovementDriverOptions {\n worktree: WorktreeAdapter\n generator: CandidateGenerator\n /** Base ref candidate worktrees fork from. Default `main`. */\n baseRef?: string\n}\n\nexport interface ManagedImprovementDriver extends SurfaceProposer<AnalystFinding> {\n /** Remove every finalized candidate except explicitly retained 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 finalized = new Map<string, Worktree>()\n\n return {\n kind: `improvement:${opts.generator.kind}`,\n async propose(ctx: ProposeContext<AnalystFinding>) {\n const findings = resolveFindings(ctx)\n // No findings AND no report AND a generator that can only act on findings\n // (the reflective patch-applier) — propose nothing rather than spin up\n // worktrees for a guaranteed no-op. An agentic coder draws its signal from\n // the repo + raw traces on disk, so it opts in via `proposesWithoutFindings`\n // and still runs the full populationSize even on an empty findings set —\n // otherwise the FIRST generation (whose seed findings are empty and whose\n // rawTraceDistiller has not run yet) would always generate ZERO candidates.\n if (\n findings.length === 0 &&\n ctx.report === undefined &&\n !opts.generator.proposesWithoutFindings\n ) {\n return []\n }\n\n const surfaces: CodeSurface[] = []\n for (let i = 0; i < ctx.populationSize; i++) {\n if (ctx.signal.aborted) break\n const wt = await opts.worktree.create({\n baseRef,\n label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`,\n })\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 const { applied, summary } = await opts.generator.generate({\n worktreePath: wt.path,\n report: ctx.report,\n findings,\n dataset: ctx.dataset,\n maxShots: ctx.maxImprovementShots ?? 1,\n signal: ctx.signal,\n })\n if (!applied) {\n await opts.worktree.discard(wt)\n continue\n }\n const surface = await opts.worktree.finalize(wt, summary)\n surfaces.push(surface)\n finalized.set(surface.worktreeRef, wt)\n } catch (err) {\n // Best-effort cleanup; never mask the original failure.\n await opts.worktree.discard(wt).catch(() => {})\n throw err\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 finalized) {\n if (retained.has(worktreeRef)) continue\n try {\n await opts.worktree.discard(worktree)\n finalized.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/** Phase-2 report carries `findings` when present; else fall back to the\n * loop's `ctx.findings`. The report is opaque to the substrate, so probe it\n * structurally. */\nfunction resolveFindings(ctx: ProposeContext<AnalystFinding>): AnalystFinding[] {\n const report = ctx.report\n if (report && typeof report === 'object' && 'findings' in report) {\n const f = (report as { findings: unknown }).findings\n if (Array.isArray(f) && f.length > 0) return f as AnalystFinding[]\n }\n return ctx.findings\n}\n","/**\n *\n * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.\n *\n * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each\n * generation's failing cells into ~400-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 ~400-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, runs `selfImprove`, and (on a ship verdict) writes the promoted\n * winner back into the corresponding profile field.\n *\n * - `surface: 'prompt'` → `gepaProposer` mutates `profile.prompt.systemPrompt`.\n * - `surface: 'skills'` → `skillOptProposer` mutates a skills document string.\n * - `surface: 'agent-profile'` → caller-supplied proposer mutates the complete\n * canonical AgentProfile JSON in one candidate.\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` ∈ {`tools`, `mcp`, `hooks`, `subagents`, `workflow`, `agent-profile`, `code`} → 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 also\n * requires `opts.code.repoRoot` so its incumbent is a real isolated checkout.\n *\n * Everything else (`scenarios`, `judge`, `agent`, `budget`, `llm`) passes\n * straight through to `selfImprove`.\n *\n * @experimental\n */\n\nimport {\n gepaProposer,\n gitWorktreeAdapter,\n skillOptProposer,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type CodeSurface,\n type MutableSurface,\n type Scenario,\n type SelfImproveBudget,\n type SelfImproveLlm,\n type SelfImproveOptions,\n type SelfImproveResult,\n type SurfaceProposer,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { LocalHarness } from '../mcp/local-harness'\nimport { assertModelAllowed } from '../runtime/supervise/model-policy'\nimport { agenticGenerator, type Verifier } from './agentic-generator'\nimport {\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 agent-profile lever `improve` optimizes. Mirrors the AgentProfile-law\n * profile levers; `code` is the implementation-tier surface, `rollout-policy`\n * 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 | 'workflow'\n | 'agent-profile'\n | 'code'\n | 'rollout-policy'\n\nexport type ImproveOptions<TScenario extends Scenario, TArtifact> = Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'analyzeGeneration' | 'baselineSurface' | 'findings' | 'gate' | 'proposer'\n> & {\n /** Which profile lever to optimize. Default `'prompt'`. Selects the default\n * generator + the baseline-surface extraction shape. */\n surface?: ImproveSurface\n /** The `SurfaceProposer` that mutates the surface. When unset, the facade\n * picks the default for `surface` (`gepaProposer` for prompt, `skillOptProposer`\n * for skills); surfaces with no default REQUIRE this (fail-loud otherwise). */\n generator?: SurfaceProposer\n /** Gate mode. `'holdout'` (default) runs the held-out promotion gate;\n * `'none'` is a baseline-only run (`budget.generations = 0`). */\n gate?: 'holdout' | 'none'\n /** Restrict the run to this subset of models. When set, the reflection model\n * (`llm.model`, or the default when unset) must be a member, or `improve()` throws\n * a `ConfigError` before the generator is built. Unset = unrestricted. */\n allowedModels?: readonly string[]\n /** Per-generation findings producer passthrough (see selfImprove.analyzeGeneration).\n * DEFAULT: the built-in failure distiller — after each generation it turns the\n * worst-scoring/errored cells into structured findings ({ scenario, composite,\n * notes, error }) for the NEXT proposal round, so the proposer reasons over what\n * actually failed instead of a static seed. Pass your own producer (e.g. a\n * trace-analyst over the runDir's traces) to replace it; pass `null` to disable\n * and keep the static `findings` all the way through. */\n analyzeGeneration?: SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration'] | null\n /** META-HARNESS mode: instead of the ~400-char distilled findings, feed the\n * proposer RAW-TRACE FILESYSTEM CONTEXT — the PATHS into the prior generation's\n * real run traces under `runDir` (per-cell `spans.jsonl` event logs +\n * `cached-result.json` scores + artifacts) plus a `grep`/`cat`-to-diagnose\n * instruction — so the coding agent reads the actual failures itself rather than\n * a pre-summary. Requires a REAL `runDir` (that is where the traces live).\n * Ignored when `analyzeGeneration` is set explicitly (that wins) or is `null`\n * (disabled). Equivalent to `analyzeGeneration: rawTraceDistiller()`; this flag\n * is the one-line enable. Default `false` (the distiller stays the default). */\n rawTraceContext?: boolean\n /** CODE-surface wiring: name `surface: 'code'`, point at a repo, and the\n * facade assembles the whole candidate pipeline — an isolated incumbent plus git worktrees\n * (`gitWorktreeAdapter`) driven by `improvementDriver` with the full agentic\n * generator (a real coding harness edits each candidate worktree; a `verify`\n * hook gates candidates before they are ever measured). Ignored when\n * `opts.generator` is supplied. Required for every code run because a real\n * repository and base ref are necessary to measure the incumbent. */\n code?: ImproveCodeOptions\n /** SKILLS-surface wiring for real skill-DOCUMENT optimization. Without this,\n * `surface: 'skills'` optimizes the profile's skills REFS array (file pointers)\n * — which `skillOptProposer` (a document patcher) cannot meaningfully edit.\n * Provide the document CONTENT to optimize + a `writeBack` to persist the\n * shipped winner (the profile ref points at a file the caller owns). This is\n * what makes skillOpt reachable through improve(). */\n skills?: ImproveSkillsOptions\n /** Custom held-back-exam decision. The string `gate` above controls whether\n * the exam runs; this callback controls how its evidence decides promotion. */\n promotionGate?: SelfImproveOptions<TScenario, TArtifact>['gate']\n}\n\nexport interface ImproveSkillsOptions {\n /** The skill document's current text — the baseline `skillOptProposer` patches. */\n document: string\n /** Persist the shipped winner document (write the file the profile ref points at).\n * Called only on a ship verdict. When omitted, the winner is still returned in\n * `result.raw.winner.surface` for the caller to materialize. */\n writeBack?: (winnerDocument: string) => void\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 /** Coding harness the agentic generator runs in each worktree. Default `claude`. */\n harness?: LocalHarness\n /** Verify a candidate worktree before it becomes a measurable surface; failures\n * feed the next shot (see `agenticGenerator.verify` / `commandVerifier`). */\n verify?: Verifier\n /** Per-shot wall-clock timeout for the harness (ms). */\n timeoutMs?: number\n /** Byte-producer override — the test seam and the escape hatch for custom\n * candidate production. When set, `harness`/`verify`/`timeoutMs` are unused. */\n generator?: CandidateGenerator\n}\n\nexport interface ImproveResult<TScenario extends Scenario, TArtifact> {\n /** The profile after improvement: the winner surface applied back into the\n * matching field when the gate shipped, else the input profile unchanged. */\n profile: AgentProfile\n /** True when `gateDecision === 'ship'`. */\n shipped: boolean\n /** Held-out lift (`winner − baseline` composite). */\n lift: number\n /** The five-valued gate verdict from `selfImprove`. */\n gateDecision: SelfImproveResult<TScenario, TArtifact>['gateDecision']\n /** Full `selfImprove` result for advanced inspection. */\n raw: SelfImproveResult<TScenario, TArtifact>\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'\nconst workflowExtension = 'tangle.workflow'\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 '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` are string surfaces; the config surfaces\n * 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 // With a document supplied, optimize its CONTENT (the real skillOpt path);\n // otherwise fall back to the refs-array surface for back-compat.\n return skills?.document ?? JSON.stringify(profile.resources?.skills ?? [])\n case 'tools':\n return JSON.stringify(profile.tools ?? {})\n case 'mcp':\n return JSON.stringify(profile.mcp ?? {})\n case 'hooks':\n return JSON.stringify(profile.hooks ?? {})\n case 'subagents':\n return JSON.stringify(profile.subagents ?? {})\n case 'workflow':\n return JSON.stringify(profile.extensions?.[workflowExtension] ?? {})\n case 'agent-profile':\n return JSON.stringify(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/** The default `analyzeGeneration`: distill each generation's failing cells into\n * findings for the next proposal round. Deliberately dependency-free — judge notes\n * and errors are already the domain's own diagnosis (executable gates put their\n * reasons there); a trace-analyst can replace this wholesale via\n * `opts.analyzeGeneration`. Falls back to the static seed findings when the\n * generation had no failures, so a clean round never wipes the seed context. */\nfunction generationFailureDistiller<TScenario extends Scenario, TArtifact>(\n staticFindings: unknown[],\n): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']> {\n const CAP = 12\n return async (input) => {\n const failures: Array<{ scenario: string; composite: number; notes: string; 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, 400)\n failures.push({\n scenario,\n composite: Number(composite.toFixed(3)),\n notes,\n ...(error ? { error: error.slice(0, 200) } : {}),\n })\n }\n }\n if (failures.length === 0) return staticFindings\n failures.sort((a, b) => a.composite - b.composite)\n return failures.slice(0, CAP)\n }\n}\n\ninterface PreparedCodeRun {\n baseline: CodeSurface\n proposer: SurfaceProposer\n cleanup(retainedWinner?: MutableSurface): Promise<void>\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(\n code: ImproveCodeOptions,\n proposerOverride?: SurfaceProposer,\n): Promise<PreparedCodeRun> {\n const baseRef = code.baseRef ?? 'main'\n const worktree = gitWorktreeAdapter({\n repoRoot: code.repoRoot,\n ...(code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}),\n })\n const baselineWorktree = await worktree.create({ baseRef, label: 'incumbent-baseline' })\n const baseline = await worktree.finalize(baselineWorktree, 'Incumbent code checkout')\n let managed: ManagedImprovementDriver | undefined\n if (!proposerOverride) {\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 managed = improvementDriver({ worktree, generator, baseRef })\n }\n const proposer = proposerOverride ?? managed\n if (!proposer) {\n throw new ConfigError('improve(): code candidate generator could not be constructed')\n }\n\n return {\n baseline,\n proposer,\n async cleanup(retainedWinner) {\n const errors: unknown[] = []\n try {\n await managed?.cleanup(isCodeSurface(retainedWinner) ? [retainedWinner.worktreeRef] : [])\n } catch (cause) {\n errors.push(cause)\n }\n try {\n await worktree.discard(baselineWorktree)\n } catch (cause) {\n errors.push(cause)\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, 'improve(): failed to clean code improvement worktrees')\n }\n },\n }\n}\n\n/** Parse a JSON winner surface (`skills`/`tools`/`mcp`/`hooks`/`subagents`/`workflow`/`agent-profile`) with a typed,\n * contextual error. A malformed generator output must fail loud here, not throw\n * a raw `SyntaxError` to the caller after a ship verdict. */\nfunction parseWinnerJson<T>(winner: string, surface: ImproveSurface): T {\n try {\n return JSON.parse(winner) as T\n } catch (cause) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${\n (cause as Error).message\n }`,\n )\n }\n}\n\n/** Apply a promoted winner surface back into the profile field for `surface`.\n * Returns a shallow copy; never mutates the input profile. */\nfunction applyWinnerToProfile(\n profile: AgentProfile,\n surface: ImproveSurface,\n winner: MutableSurface,\n): AgentProfile {\n // Only string surfaces map cleanly back onto a profile field. A `CodeSurface`\n // winner (the `code` lever) is a worktree ref, not a profile value — the\n // caller materializes it from `raw.winner.surface`; the returned profile is\n // unchanged for that lever.\n if (typeof winner !== 'string') return profile\n let candidate: AgentProfile\n switch (surface) {\n case 'prompt':\n candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } }\n break\n case 'skills':\n candidate = {\n ...profile,\n resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) },\n }\n break\n case 'tools':\n candidate = { ...profile, tools: parseWinnerJson(winner, surface) }\n break\n case 'mcp':\n candidate = { ...profile, mcp: parseWinnerJson(winner, surface) }\n break\n case 'hooks':\n candidate = { ...profile, hooks: parseWinnerJson(winner, surface) }\n break\n case 'subagents':\n candidate = { ...profile, subagents: parseWinnerJson(winner, surface) }\n break\n case 'workflow':\n candidate = {\n ...profile,\n extensions: {\n ...profile.extensions,\n [workflowExtension]: parseWinnerJson(winner, surface),\n },\n }\n break\n case 'agent-profile':\n candidate = parseWinnerJson(winner, surface)\n break\n case 'rollout-policy': {\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 profile\n }\n const parsed = agentProfileSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new ConfigError(\n `improve(): the shipped '${surface}' winner does not produce a valid AgentProfile: ${parsed.error.message}`,\n )\n }\n return parsed.data\n}\n\n/**\n * Run the held-out-gated self-improvement loop on ONE profile surface.\n *\n * @example Optimize the system prompt, default holdout gate:\n *\n * const out = await improve(profile, findings, {\n * surface: 'prompt',\n * scenarios,\n * judge,\n * agent: (surface, scenario, ctx) => runAgent(surface, scenario, ctx.signal),\n * })\n * if (out.shipped) deploy(out.profile)\n */\nexport async function improve<TScenario extends Scenario, TArtifact>(\n profile: AgentProfile,\n findings: unknown[],\n opts: ImproveOptions<TScenario, TArtifact>,\n): Promise<ImproveResult<TScenario, TArtifact>> {\n const {\n surface = 'prompt',\n gate = 'holdout',\n generator,\n allowedModels,\n rawTraceContext,\n code,\n skills,\n promotionGate,\n analyzeGeneration,\n ...sharedOptions\n } = opts\n\n const parsedProfile = agentProfileSchema.safeParse(profile)\n if (!parsedProfile.success) {\n throw new ConfigError(\n `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`,\n )\n }\n if (surface === 'skills' && !generator && !skills) {\n throw new ConfigError(\n 'improve(): the default skills optimizer requires opts.skills.document; pass the skill text or an explicit generator that understands resource refs',\n )\n }\n 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, generator)\n }\n const proposer =\n preparedCode?.proposer ?? generator ?? defaultGeneratorFor(surface, sharedOptions.llm)\n if (!proposer) {\n throw new ConfigError(\n `improve(): surface '${surface}' has no default generator — pass opts.generator (a SurfaceProposer) explicitly`,\n )\n }\n\n const budget: SelfImproveBudget =\n gate === 'none' ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget }\n\n let raw: SelfImproveResult<TScenario, TArtifact>\n try {\n raw = await selfImprove<TScenario, TArtifact>({\n ...sharedOptions,\n baselineSurface: preparedCode?.baseline ?? baselineSurfaceFor(profile, surface, skills),\n proposer,\n budget,\n findings,\n ...(promotionGate !== undefined ? { gate: promotionGate } : {}),\n ...(analyzeGeneration === null\n ? {}\n : {\n analyzeGeneration:\n analyzeGeneration ??\n (rawTraceContext\n ? rawTraceDistiller<TScenario, TArtifact>({ fallbackFindings: findings })\n : generationFailureDistiller<TScenario, TArtifact>(findings)),\n }),\n })\n } catch (cause) {\n if (!preparedCode) throw cause\n try {\n await preparedCode.cleanup()\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n 'improve(): code improvement failed and its worktrees could not be cleaned',\n )\n }\n throw cause\n }\n\n const shipped = raw.gateDecision === 'ship'\n await preparedCode?.cleanup(shipped ? raw.winner.surface : undefined)\n // When a skill DOCUMENT was optimized, the winner is document text — persist it\n // via writeBack (the profile ref points at the caller's file, unchanged) rather\n // than parsing it as a refs array. Otherwise use the standard field write-back.\n const usedSkillDocument = surface === 'skills' && skills !== undefined\n if (shipped && usedSkillDocument && typeof raw.winner.surface === 'string') {\n skills?.writeBack?.(raw.winner.surface)\n }\n const nextProfile =\n shipped && !usedSkillDocument\n ? applyWinnerToProfile(profile, surface, raw.winner.surface)\n : profile\n\n return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw }\n}\n"],"mappings":";;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