@tangle-network/agent-runtime 0.81.0 → 0.82.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/dist/agent.js +3 -3
- package/dist/{chunk-Y47PMSZ7.js → chunk-A7LZR5DT.js} +2 -2
- package/dist/{chunk-QWLUOITV.js → chunk-CO2KBPRE.js} +3 -4
- package/dist/{chunk-QWLUOITV.js.map → chunk-CO2KBPRE.js.map} +1 -1
- package/dist/{chunk-CA43KLZW.js → chunk-DJQFJEOD.js} +2 -2
- package/dist/{chunk-SN3XBTTH.js → chunk-JYURIKPF.js} +49 -2
- package/dist/chunk-JYURIKPF.js.map +1 -0
- package/dist/{chunk-5GCTCLKP.js → chunk-KSGHI53L.js} +3 -3
- package/dist/{chunk-HUT4RXDJ.js → chunk-SRGV56W4.js} +2 -2
- package/dist/{chunk-HUT4RXDJ.js.map → chunk-SRGV56W4.js.map} +1 -1
- package/dist/index.js +5 -5
- package/dist/intelligence.js +1 -1
- package/dist/loop-runner-bin.js +4 -4
- package/dist/loops.d.ts +51 -1
- package/dist/loops.js +5 -3
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-SN3XBTTH.js.map +0 -1
- /package/dist/{chunk-Y47PMSZ7.js.map → chunk-A7LZR5DT.js.map} +0 -0
- /package/dist/{chunk-CA43KLZW.js.map → chunk-DJQFJEOD.js.map} +0 -0
- /package/dist/{chunk-5GCTCLKP.js.map → chunk-KSGHI53L.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/index.ts","../src/runtime/anytime.ts","../src/runtime/audit-intent.ts","../src/runtime/benchmark-report.ts","../src/runtime/completion.ts","../src/runtime/observe.ts","../src/runtime/harvest-corpus.ts","../src/runtime/in-process-sandbox-client.ts","../src/runtime/inline-sandbox-client.ts","../src/runtime/report-usage.ts","../src/runtime/loop-dispatch.ts","../src/runtime/mcp-environment.ts","../src/runtime/personify/analyst.ts","../src/runtime/personify/combinators.ts","../src/runtime/personify/corpus.ts","../src/runtime/personify/registry.ts","../src/runtime/personify/persona.ts","../src/runtime/personify/trajectory.ts","../src/runtime/promotion-gate.ts","../src/runtime/run-benchmark.ts","../src/runtime/strategy.ts","../src/runtime/sandbox-run.ts","../src/runtime/steering-drivers.ts","../src/runtime/strategy-author.ts","../src/runtime/strategy-evolution.ts","../src/runtime/supervise/detector-monitor.ts","../src/runtime/supervise/patch-checks.ts","../src/runtime/supervise/patch-deliverable.ts","../src/runtime/supervise/trace-source.ts","../src/runtime/supervise/trajectory-recorder.ts","../src/runtime/supervise/worktree-fanout.ts","../src/runtime/supervise-surface.ts","../src/runtime/verifier-environment.ts","../src/runtime/waterfall.ts","../src/runtime/workspace.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Driven-loop substrate. `runLoop` orchestrates around the sandbox SDK; it\n * does not invent its own notion of \"what an agent is\". Each iteration is\n * a `sandboxClient.create({ backend: { profile } })` + `box.streamPrompt`\n * call. The driver owns topology; the validator owns scoring; the output\n * adapter owns event-stream decode; the kernel owns iteration accounting,\n * concurrency, abort, cost aggregation, and trace emission.\n */\n\n// The analyst-finding factory + id helper from the substrate, re-surfaced here so a host that builds\n// findings on the coordination bus (the profile-richness gate, an online detector) does not need a\n// separate agent-eval import. The taxonomy + firewall provenance live in agent-eval.\nexport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\n// One-stop import: sandbox-SDK types consumers need to spell out an\n// `AgentRunSpec` without importing `@tangle-network/sandbox` separately.\nexport type {\n AgentProfile,\n CreateSandboxOptions,\n SandboxEvent,\n SandboxInstance,\n} from '@tangle-network/sandbox'\n// Two substrates for the same \"recursive agent decision\" atom, both exported here (per\n// docs/architecture.md): canonical = the reactive `Scope`/`Supervisor` + the personify\n// combinators (budget-conserving, equal-k by construction — prefer for new recursive work);\n// the round-synchronous `runLoop` kernel = the path most benches still drive, with a\n// caller-supplied `Driver` (fixed-shape or scripted) authoring the per-round topology.\n// Recursive execution atom (the keystone): the open `Executor` runtime, the\n// budget-conserving reactive `Scope`, the event-sourced `Supervisor`, and the spawn\n// journal. Substrate types come from `./supervise/types`; the in-memory journal +\n// blob store live in `../durable/spawn-journal`.\nexport {\n contentAddress,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n} from '../durable/spawn-journal'\n// The typed coordination-bus event (up: settled/question/finding; down: steer/answer) — surfaced\n// here so a host folding the bus onto its own timeline (the supervise-topology observability) can\n// type its `onEvent` subscriber without reaching into the `/mcp` subpath. `MakeWorkerAgent` rides\n// alongside it: the worker-seam type `supervise`/`workerFromBackend` traffic in, so a host authoring\n// its own seam types it from the loop layer rather than the `/mcp` subpath.\nexport type {\n AnalystRegistry,\n CoordinationEvent,\n MakeWorkerAgent,\n} from './../mcp/tools/coordination'\nexport {\n type AnytimeReport,\n type AnytimeStrategySummary,\n type AnytimeTaskCurve,\n anytimeReport,\n renderAnytimeTable,\n} from './anytime'\nexport {\n type AuditIntentInput,\n type AuditIntentOptions,\n auditIntent,\n defaultAuditorInstruction,\n type IntentAudit,\n} from './audit-intent'\n// The domain-agnostic benchmark report engine: a fleet of `RunRecord`s → a ranked leaderboard, the full\n// profile×axis score matrix, and embeddable SVG/HTML charts (the hosted-leaderboard surface). Reads only\n// the universal `RunRecord` currency, so it reports ANY benchmark in ANY domain.\nexport {\n type Interval,\n type Leaderboard,\n type LeaderboardOptions,\n type LeaderboardRow,\n leaderboard,\n type PairwiseOptions,\n type PairwiseVerdict,\n pairwiseSignificance,\n renderLeaderboardHtml,\n renderLeaderboardMarkdown,\n renderLeaderboardSvg,\n renderPairwiseMarkdown,\n} from './benchmark-report'\nexport {\n type CompletionAnalyst,\n type CompletionEvidence,\n type CompletionPolicy,\n type CompletionVerdict,\n completionAuthorizes,\n deterministicCompletion,\n sentinelCompletion,\n stopSentinel,\n} from './completion'\nexport {\n type AgentEnvironment,\n type AgentEnvironmentCapabilities,\n type AgentEnvironmentEvent,\n type AgentEnvironmentProvider,\n type AgentEnvironmentProviderRef,\n type AgentEnvironmentProviderRegistry,\n type AgentEnvironmentQuery,\n type AgentEnvironmentStatus,\n type AgentEnvironmentSummary,\n type AgentProfileRef,\n type AgentSession,\n type AgentSessionRef,\n type AgentSessionStatus,\n type AgentTurnInput,\n type AgentTurnResult,\n type CheckpointRef,\n type CheckpointRequest,\n type CreateAgentEnvironmentInput,\n createAgentEnvironmentProviderRegistry,\n type ExecRequest,\n type ExecResult,\n type ForkRequest,\n type PlacementInfo,\n type ProviderAsSandboxClientOptions,\n type ProviderExecutorOptions,\n providerAsExecutor,\n providerAsSandboxClient,\n type ResourceRequest,\n resolveAgentEnvironmentProvider,\n type SandboxClientProviderOptions,\n sandboxClientAsProvider,\n type WorkspaceRequest,\n} from './environment-provider'\nexport {\n type HarvestCorpusOptions,\n type HarvestFailure,\n type HarvestReport,\n harvestCorpus,\n} from './harvest-corpus'\n// The in-process pseudo-box: a user `onPrompt` callback → a SandboxClient for\n// runLoop / openSandboxRun (the typed offline seam, no SandboxInstance cast).\nexport {\n type InProcessOnPrompt,\n type InProcessPromptCtx,\n type InProcessSandboxClientOptions,\n inProcessSandboxClient,\n} from './in-process-sandbox-client'\n// The one pseudo-box adapter: any non-box Executor → a SandboxClient for runLoop.\nexport { inlineSandboxClient } from './inline-sandbox-client'\nexport {\n type LoopCampaignDispatchOptions,\n type LoopDispatchOptions,\n type LoopOptionsForDispatch,\n loopCampaignDispatch,\n loopDispatch,\n} from './loop-dispatch'\nexport {\n createMcpEnvironment,\n type McpEndpoint,\n type McpEnvironmentOptions,\n} from './mcp-environment'\n// The third-person observer: a worker's trace → trace-grounded findings, an\n// operator report, and durable corpus facts for the next run (the closed loop).\nexport {\n defaultAnalystInstruction,\n type Observation,\n type ObserveInput,\n type ObserveOptions,\n observe,\n renderReport,\n} from './observe'\n// The personify layer + the RSI wave built on the recursive keystone: the persona content seam\n// (`definePersona`/`runPersonified`), the open shape registry, the content-free generic\n// combinators, the cross-run corpus, the analyst-on-scope steer firewall, and the trajectory +\n// equal-k-on-cost ledger. The wave's type contracts live in `./personify/wave-types`.\nexport {\n assertTraceDerivedFindings,\n buildSteerContext,\n type CreateScopeAnalystOptions,\n createScopeAnalyst,\n type RegistryAnalyzeProjection,\n registryScopeAnalyst,\n} from './personify/analyst'\nexport {\n fanout,\n flatWidenGate,\n loopUntil,\n panel,\n pipeline,\n selectValidWinner,\n verify,\n widen,\n} from './personify/combinators'\nexport {\n FileCorpus,\n InMemoryCorpus,\n renderCorpusToInstructions,\n} from './personify/corpus'\nexport { definePersona, runPersonified } from './personify/persona'\nexport { builtinShapes, createShapeRegistry, registerShape } from './personify/registry'\nexport { equalKOnCost, trajectoryReport } from './personify/trajectory'\nexport type {\n DefinePersona,\n DefinePersonaInput,\n LoopShape,\n Outcome,\n Persona,\n PersonaContext,\n PersonaExecutors,\n RunPersonified,\n RunPersonifiedOptions,\n ShapeBudget,\n ShapeContext,\n ShapeRegistry,\n} from './personify/types'\nexport type {\n AssertTraceDerivedFindings,\n CombinatorShape,\n Corpus,\n CorpusFilter,\n CorpusRecord,\n EqualKArm,\n EqualKOnCost,\n EqualKOnCostOptions,\n EqualKVerdict,\n Fanout,\n FanoutOptions,\n FanoutSynthesis,\n FanoutWinnerSelector,\n FlatWidenGate,\n LoopUntil,\n LoopUntilSpec,\n LoopUntilState,\n Panel,\n PanelJudge,\n PanelSpec,\n PanelVerdict,\n Pipeline,\n PipelineStage,\n RenderCorpusToInstructions,\n RenderCorpusToInstructionsOptions,\n ScopeAnalyst,\n ScopeAnalyzeInput,\n ScopeWidenGate,\n SteerContext,\n TrajectoryNode,\n TrajectoryReport,\n TrajectoryReportFn,\n TrajectoryReportOptions,\n Verify,\n VerifySpec,\n Widen,\n WidenDecision,\n WidenLineage,\n WidenSpec,\n WinnerStrategy,\n} from './personify/wave-types'\nexport {\n type PromotionGateOptions,\n type PromotionVerdict,\n promotionGate,\n} from './promotion-gate'\nexport { reportLoopUsage, type UsageSink } from './report-usage'\n// The one router chat client (chat / chat-with-tools / off-box tool loop). `ToolSpec` is exported\n// with the executor seam block below. `routerBrain` is the production supervisor BRAIN — the\n// router's tool-calling as the canonical `ToolLoopChat` seam a `driverAgent` drives\n// (tests script a mock `ToolLoopChat`, production passes `routerBrain(cfg)`).\nexport {\n type RouterChatResult,\n type RouterChatToolsResult,\n type RouterConfig,\n type RouterToolCall,\n type RouterToolLoopResult,\n routerBrain,\n routerChatWithTools,\n routerChatWithUsage,\n routerToolLoop,\n} from './router-client'\nexport {\n type BenchmarkCell,\n type BenchmarkConfig,\n type BenchmarkLift,\n type BenchmarkReport,\n type BenchmarkStrategySummary,\n type BenchmarkTaskRow,\n type Environment,\n printBenchmarkReport,\n runBenchmark,\n} from './run-benchmark'\nexport { defaultSelectWinner, runLoop } from './run-loop'\nexport { acquireSandbox } from './sandbox-acquire'\nexport {\n type CriuCapableClient,\n probeSandboxCapabilities,\n type SandboxCapabilities,\n} from './sandbox-capabilities'\nexport { extractLlmCallEvent, mapSandboxEvent, sumSandboxUsage } from './sandbox-events'\nexport {\n type CheckpointCapableBox,\n createSandboxLineage,\n type ForkCapableBox,\n type SandboxLineage,\n type SandboxLineageHandle,\n type SessionCapableBox,\n} from './sandbox-lineage'\nexport {\n type Deliverable,\n type OpenSandboxRunOptions,\n openSandboxRun,\n type SandboxRun,\n SandboxRunAbortError,\n type TurnResult,\n} from './sandbox-run'\nexport {\n type ApplyContinuation,\n type DumbDriverOptions,\n dumbDriver,\n type NaiveDriverOptions,\n naiveDriver,\n type SteeringDecision,\n} from './steering-drivers'\n// The optimization suite: a domain = an Environment (5 hooks); a Strategy = how the\n// budget is spent to beat its check. Built-ins `sample`/`refine`; author your own with\n// `defineStrategy` (compose shot() + critique(), zero Supervisor ceremony); compare\n// with runBenchmark. The depth/breadth drivers are the reference implementations.\nexport {\n type AgenticOptions,\n type AgenticRunResult,\n type AgenticSurface,\n type AgenticTask,\n type AgenticTool,\n type ArtifactHandle,\n adaptiveRefine,\n breadthStrategy,\n defineStrategy,\n depthStrategy,\n type RunAgenticOptions,\n refine,\n runAgentic,\n type ShotPersona,\n type ShotSpec,\n type Strategy,\n type StrategyCtx,\n type StrategyResult,\n type SurfaceScore,\n sample,\n sampleThenRefine,\n} from './strategy'\nexport {\n type AuthoredStrategy,\n type AuthorStrategyOptions,\n assertStrategyContract,\n authorStrategy,\n strategyAuthorContract,\n} from './strategy-author'\nexport {\n type ChampionPick,\n type ChampionPolicy,\n discriminatingMeans,\n type EvolutionArchiveNode,\n type EvolutionAuthor,\n type EvolutionBandInfo,\n type EvolutionCandidate,\n type EvolutionGeneration,\n type EvolutionReport,\n pickChampion,\n runStrategyEvolution,\n type StrategyEvolutionConfig,\n selectChampion,\n} from './strategy-evolution'\n// The supervisor's intelligence: it AUTHORS each worker's profile (instructions + model) from a\n// SKILL (its own system prompt) — the optimizable self-improvement surface, not the plumbing.\nexport {\n type AuthoredProfile,\n asAuthoredProfile,\n assessAuthoredProfile,\n authoredWorker,\n defaultProfileRichnessThresholds,\n type ProfileRichness,\n type ProfileRichnessThresholds,\n profileRichnessFinding,\n supervisorInstructions,\n} from './supervise/authoring'\nexport {\n type BudgetPool,\n type BudgetReadout,\n createBudgetPool,\n type ReservationTicket,\n spendFromUsageEvents,\n} from './supervise/budget'\n// The completion-oracle: settled ⟺ DELIVERED. `gateOnDeliverable` wraps an executor so its\n// settlement `valid` reflects a deployable deliverable check (a test/judge), never self-report.\nexport { type DeliverableSpec, gateOnDeliverable } from './supervise/completion-gate'\n// The CHEAP / offline driver: an in-process router-tools loop that drives the coordination\n// verbs over the Scope (no box, no creds). The CAPABLE driver is a sandbox agent with the\n// coordination verbs mounted as an MCP — this is the low-cost + offline-testable variant.\nexport {\n type DriverAgentOptions,\n driverAgent,\n finalizeBestDelivered,\n} from './supervise/coordination-driver'\n// Supervisor-as-MCP: serve the coordination verbs as a real HTTP MCP over a live Scope, so any\n// harness (claude-code / codex / opencode) BECOMES the supervisor by mounting one MCP server.\nexport { type CoordinationMcpHandle, serveCoordinationMcp } from './supervise/coordination-mcp'\n// The one generic delegation verb: hand it an INTENT, it routes to `supervise()` with a default\n// authoring supervisor (no hardcoded worker profile) and returns the `SupervisedResult` unchanged —\n// so `spentTotal` (what the delegation cost) rides straight back.\nexport {\n type DelegateOptions,\n defaultDelegateBudget,\n delegate,\n} from './supervise/delegate'\n// The ONLINE analyst: watch a TraceSource and raise a `finding` the moment a worker loops/error-storms.\nexport {\n defaultToolDetectors,\n type WatchTraceOptions,\n watchTrace,\n} from './supervise/detector-monitor'\n// The child→parent message bus: the one typed pipe carrying settled outputs, questions, and\n// analyst findings up to the driver (pass-through + queued lanes, transport-agnostic).\nexport {\n type BusEvent,\n type BusRecord,\n type BusStats,\n createEventBus,\n type EventBus,\n type PublishOptions,\n} from './supervise/event-bus'\n// The down-leg receive end: a per-worker inbox an executor exposes as `Executor.deliver`; the loop\n// drains it at the step boundary + before settle (queued) or aborts the turn (forceful interrupt).\nexport { createInbox, type Inbox, type InboxMessage } from './supervise/inbox'\n// The fail-loud model-subset guard the front doors call: restrict a run to a chosen set of models.\nexport { assertModelAllowed } from './supervise/model-policy'\n// The mechanical patch gate as a generic DeliverableSpec over the worktree-CLI patch artifact:\n// no-op / always-on secret-path floor / forbidden-path / diff-size + required test/typecheck pass.\nexport { type PatchDeliverableOptions, patchDelivered } from './supervise/patch-deliverable'\n// The one-call in-memory store bundle for a supervised run: a fresh journal + blob store +\n// executor registry, shaped to spread straight into `SupervisorOpts`. `{ withDriver: true }`\n// wraps the registry for the recursive agents-drive-agents path.\nexport {\n createInMemoryRunContext,\n type InMemoryRunContext,\n type InMemoryRunContextOptions,\n} from './supervise/run-context'\n// The ONE built-in executor entrypoint: backend-as-data (`createExecutor({backend})`).\n// The per-backend factories are internal case-arms; BYO agents implement `Executor`.\nexport {\n cliWorktreeExecutor,\n createExecutor,\n createExecutorRegistry,\n type ExecutorConfig,\n type ProviderSeam,\n type ToolSpec,\n} from './supervise/runtime'\nexport { createScope, settledToIteration } from './supervise/scope'\n// The one-call \"just invoke the supervisor\": `supervise(profile, task, { backend, budget })` with\n// sensible defaults (blobs/perWorker/journal/executors). `workerFromBackend` derives the worker seam\n// from a backend config + an optional completion oracle (settled⟺delivered).\nexport {\n type SuperviseOptions,\n supervise,\n workerFromBackend,\n} from './supervise/supervise'\nexport { createSupervisor } from './supervise/supervisor'\n// Build a supervisor FROM its profile: the brain is resolved from `profile.harness` like\n// `createExecutor({backend})` resolves a worker — `null` → the in-process router tool-loop,\n// a coding-CLI harness → a sandboxed harness driving the coordination verbs. No hand-built brain.\nexport {\n type DriveHarness,\n type SupervisorAgentDeps,\n type SupervisorProfile,\n supervisorAgent,\n} from './supervise/supervisor-agent'\n// The substrate-agnostic trace source: a worker's tool calls as agent-eval `ToolSpan`s, from an\n// OWNED loop (push) OR a sandbox box session (message parts). The common currency for both analysts.\nexport {\n createPushTraceSource,\n decodeToolPart,\n type SessionTraceBox,\n sandboxSessionTraceSource,\n type TraceSource,\n} from './supervise/trace-source'\n// The SETTLE-time analyzer: collect a TraceSource's spans and run agent-eval's published batch\n// analyzers (buildTrajectory / stuckLoopView / toolWasteView) — the post-hoc half.\nexport { analyzeTrace, type TrajectoryAnalysis } from './supervise/trajectory-recorder'\nexport type {\n Agent,\n AgentSpec,\n Budget,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n ResultBlobStore,\n Runtime,\n Scope,\n Settled,\n Spend,\n SupervisedResult,\n Supervisor,\n SupervisorOpts,\n TreeView,\n UsageEvent,\n WidenGate,\n} from './supervise/types'\n// The worktree-CLI leaf executor: a supervisor-authored AgentProfile (systemPrompt + model)\n// driving a local harness CLI on its own git worktree, surfaced as the open `Executor` port.\nexport {\n createWorktreeCliExecutor,\n type WorktreeCliExecutorOptions,\n type WorktreeCommandResult,\n type WorktreePatchArtifact,\n} from './supervise/worktree-cli-executor'\n// The generic coding combinator: a fanout of authored harness profiles, each on its own\n// worktree-CLI leaf, each gated by the injected deliverable, winner via the shared valid-only\n// `selectValidWinner`.\nexport {\n type AuthoredHarness,\n type WorktreeFanoutOptions,\n worktreeFanout,\n} from './supervise/worktree-fanout'\n// `supervise()` specialized for a graded `AgenticSurface` task: workers each `runAgentic` over the surface\n// (refine by default), settle on the surface's own check, and feed the driver a self-improvement lens (the\n// failing tests, by default) so the next spawn targets them. One capability over `supervise` + `runAgentic`.\nexport {\n failuresAnalyst,\n type SuperviseSurfaceOptions,\n type SuperviseSurfaceResult,\n type SurfaceWorkerConfig,\n type SurfaceWorkerOut,\n superviseSurface,\n} from './supervise-surface'\n// The driver-brain seam type a consumer scripts (a mock) or passes (`routerBrain`) into\n// `DriverAgentOptions.brain` — the canonical one-inference-turn tool-loop chat. `ToolLoopCompaction`\n// is the self-compaction config that bounds the brain's own context window (the supervisor chapter-close).\nexport type { ToolLoopChat, ToolLoopCompaction, ToolLoopCompactionOptions } from './tool-loop'\nexport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n ExecCtx,\n Iteration,\n LoopDecisionPayload,\n LoopEndedPayload,\n LoopIterationDispatchPayload,\n LoopIterationEndedPayload,\n LoopIterationStartedPayload,\n LoopLineageOptions,\n LoopPlanDescription,\n LoopPlanPayload,\n LoopResult,\n LoopSandboxPlacement,\n LoopStartedPayload,\n LoopTeardownFailedPayload,\n LoopTokenUsage,\n LoopTraceEmitter,\n LoopTraceEvent,\n LoopWinner,\n MountManifestEntry,\n MountRecorder,\n OutputAdapter,\n RunProvenance,\n SandboxClient,\n SelectionReceipt,\n ValidationCtx,\n Validator,\n} from './types'\nexport {\n createVerifierEnvironment,\n type VerifierEnvironmentOptions,\n} from './verifier-environment'\nexport {\n createWaterfallCollector,\n type WaterfallCollector,\n type WaterfallReport,\n type WaterfallSpan,\n} from './waterfall'\nexport {\n type GitWorkspaceOptions,\n gitWorkspace,\n jjWorkspace,\n localShell,\n runInWorkspace,\n type Shell,\n type Workspace,\n type WorkspaceCommit,\n type WorkspaceRun,\n} from './workspace'\n","/**\n * anytimeReport — time-to-satisfactory-output metrics, derived entirely from the\n * waterfall's spans (no new instrumentation): per task, the best-so-far score after each\n * shot with its elapsed wall-clock and cumulative spend; per strategy, the standard\n * anytime-optimization metrics:\n *\n * TTT time-to-target — elapsed ms until best-so-far ≥ the target (per task; median\n * over tasks that reached it)\n * STT shots-to-target — attempts until best-so-far ≥ target\n * ERT expected running time (the COCO benchmarking convention): TOTAL time spent\n * across all tasks — including failures' full budgets — divided by the number of\n * tasks that reached the target. The honest \"how long per success, all-in\".\n * AUC the anytime curve's area (mean best-so-far score across the budget, per shot\n * index) — higher = climbs earlier.\n *\n * The \"satisfactory\" bar follows the COCO/BBOB convention: a SET of satisficing targets\n * (e.g. [0.5, 0.8, 1.0] on the normalized check score), each measured independently —\n * runtime-to-target per (task, target) pair — optionally overridden per task\n * (`targetFor`) when satisfaction is task-specific. Spans come from\n * `createWaterfallCollector().report()`; tasks are grouped by the supervisor runId\n * (`agentic:<strategy>:<taskId>`); shot spans are `shot:N` labels.\n */\nimport type { WaterfallSpan } from './waterfall'\n\nexport interface AnytimeTaskCurve {\n taskId: string\n strategy: string\n /** Best-so-far after each settled shot: elapsed ms from the task's first spawn,\n * cumulative usd, and the running max score. */\n points: Array<{ elapsedMs: number; cumUsd: number; best: number }>\n /** Per satisficing target (keyed by the target value as a string): the first point\n * where best ≥ target, or null when never reached within budget. */\n hits: Record<string, { ms: number; shots: number; usd: number } | null>\n}\n\nexport interface AnytimeStrategySummary {\n strategy: string\n /** The satisficing target this row summarizes. */\n target: number\n tasks: number\n reachedTarget: number\n /** Median time-to-target over the tasks that reached it (null when none did). */\n medianTttMs: number | null\n medianShotsToTarget: number | null\n /** COCO ERT: Σ all task wall-time (incl. failures) / #successes. Null when 0 succeed. */\n ertMs: number | null\n /** Same construction over dollars: Σ all spend / #successes. */\n erUsd: number | null\n /** Mean best-so-far score by shot index (the anytime curve, averaged over tasks). */\n curveByShot: number[]\n /** Area under the per-shot anytime curve, normalized to [0,1]. */\n auc: number\n}\n\nexport interface AnytimeReport {\n targets: number[]\n perTask: AnytimeTaskCurve[]\n /** One summary per (strategy, target) pair — the COCO-style multi-target view. */\n perStrategy: AnytimeStrategySummary[]\n}\n\nconst median = (xs: number[]): number | null => {\n if (xs.length === 0) return null\n const s = [...xs].sort((a, b) => a - b)\n const mid = Math.floor(s.length / 2)\n return s.length % 2 === 1 ? (s[mid] as number) : ((s[mid - 1] as number) + (s[mid] as number)) / 2\n}\n\n/** Derive anytime metrics from waterfall spans. `targets` are the satisficing score\n * bars (default [1] = fully resolved; COCO-style multi-target: [0.5, 0.8, 1]);\n * `targetFor` overrides the bar per task (task-specific satisfaction) — when set, the\n * per-task bar replaces every entry of `targets` for that task. */\nexport function anytimeReport(\n spans: WaterfallSpan[],\n opts?: { targets?: number[]; targetFor?: (taskId: string) => number },\n): AnytimeReport {\n const targets = opts?.targets ?? [1]\n const byRun = new Map<string, WaterfallSpan[]>()\n for (const s of spans) {\n if (!s.label.startsWith('shot:')) continue\n const list = byRun.get(s.runId) ?? []\n list.push(s)\n byRun.set(s.runId, list)\n }\n\n const perTask: AnytimeTaskCurve[] = []\n for (const [runId, shots] of byRun) {\n const m = runId.match(/^agentic:(.+):(.+)$/)\n const strategy = m?.[1] ?? runId\n const taskId = m?.[2] ?? runId\n const ordered = [...shots].sort((a, b) => (a.endMs ?? a.startMs) - (b.endMs ?? b.startMs))\n const t0 = Math.min(...ordered.map((s) => s.startMs))\n const taskTargets = opts?.targetFor ? [opts.targetFor(taskId)] : targets\n let best = 0\n let cumUsd = 0\n const points: AnytimeTaskCurve['points'] = []\n const hits: AnytimeTaskCurve['hits'] = {}\n for (const t of taskTargets) hits[String(t)] = null\n for (const s of ordered) {\n cumUsd += s.usd\n if (typeof s.score === 'number' && s.score > best) best = s.score\n const elapsedMs = (s.endMs ?? s.startMs) - t0\n points.push({ elapsedMs, cumUsd, best })\n for (const t of taskTargets) {\n if (hits[String(t)] === null && best >= t) {\n hits[String(t)] = { ms: elapsedMs, shots: points.length, usd: cumUsd }\n }\n }\n }\n perTask.push({ taskId, strategy, points, hits })\n }\n\n const byStrategy = new Map<string, AnytimeTaskCurve[]>()\n for (const t of perTask) {\n const list = byStrategy.get(t.strategy) ?? []\n list.push(t)\n byStrategy.set(t.strategy, list)\n }\n\n const perStrategy: AnytimeStrategySummary[] = []\n for (const [strategy, tasks] of byStrategy) {\n const totalMs = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.elapsedMs ?? 0), 0)\n const totalUsd = tasks.reduce((s, t) => s + (t.points[t.points.length - 1]?.cumUsd ?? 0), 0)\n const maxShots = Math.max(0, ...tasks.map((t) => t.points.length))\n const curveByShot: number[] = []\n for (let i = 0; i < maxShots; i += 1) {\n // A task with fewer shots carries its final best forward (it stopped — its\n // best-so-far is what an operator would have at that point).\n const vals = tasks.map(\n (t) => (t.points[Math.min(i, t.points.length - 1)] as { best: number }).best,\n )\n curveByShot.push(vals.reduce((s, v) => s + v, 0) / vals.length)\n }\n const auc =\n curveByShot.length > 0 ? curveByShot.reduce((s, v) => s + v, 0) / curveByShot.length : 0\n const summaryTargets = opts?.targetFor ? [Number.NaN] : targets\n for (const t of summaryTargets) {\n const key = (\n taskCurve: AnytimeTaskCurve,\n ): { ms: number; shots: number; usd: number } | null =>\n opts?.targetFor\n ? (Object.values(taskCurve.hits)[0] ?? null)\n : (taskCurve.hits[String(t)] ?? null)\n const reached = tasks.filter((x) => key(x) !== null)\n perStrategy.push({\n strategy,\n target: t,\n tasks: tasks.length,\n reachedTarget: reached.length,\n medianTttMs: median(reached.map((x) => (key(x) as { ms: number }).ms)),\n medianShotsToTarget: median(reached.map((x) => (key(x) as { shots: number }).shots)),\n ertMs: reached.length > 0 ? totalMs / reached.length : null,\n erUsd: reached.length > 0 ? totalUsd / reached.length : null,\n curveByShot,\n auc,\n })\n }\n }\n perStrategy.sort((a, b) => a.strategy.localeCompare(b.strategy) || a.target - b.target)\n return { targets, perTask, perStrategy }\n}\n\n/** One row per (strategy, satisficing target): the shareable time-to-satisfactory table. */\nexport function renderAnytimeTable(report: AnytimeReport): string {\n const lines = [\n `anytime metrics · satisficing targets [${report.targets.join(', ')}] · ERT = Σ all wall-time / #successes (COCO)`,\n 'strategy ≥tgt reach med-TTT med-shots ERT(all-in) $/success AUC curve',\n ]\n for (const s of report.perStrategy) {\n const curve = s.curveByShot.map((v) => '▁▂▃▄▅▆▇█'[Math.min(7, Math.floor(v * 8))]).join('')\n const tgt = Number.isNaN(s.target) ? 'task' : s.target.toFixed(2)\n lines.push(\n `${s.strategy.padEnd(19)} ${tgt.padStart(4)} ${String(s.reachedTarget).padStart(4)}/${String(s.tasks).padEnd(3)} ` +\n `${s.medianTttMs === null ? ' —' : `${(s.medianTttMs / 1000).toFixed(1).padStart(6)}s`} ` +\n `${s.medianShotsToTarget === null ? ' —' : String(s.medianShotsToTarget).padStart(5)} ` +\n `${s.ertMs === null ? ' —' : `${(s.ertMs / 1000).toFixed(1).padStart(9)}s`} ` +\n `${s.erUsd === null ? ' —' : `$${s.erUsd.toFixed(4)}`} ${s.auc.toFixed(2)} ${curve}`,\n )\n }\n return lines.join('\\n')\n}\n","/**\n * auditIntent — the route-rigor analyst: is this trajectory even going the RIGHT WAY?\n *\n * `observe()` critiques execution quality (\"what's unfinished\"). This audits ALIGNMENT —\n * a different failure class the score can't see until it's too late: an agent can be\n * executing flawlessly down the wrong route. The auditor reads the trajectory and\n * compares three intents:\n *\n * declared — what the task says to do (the prompt / acceptance criteria)\n * revealed — what the agent is ACTUALLY optimizing, inferred from its action pattern\n * (the inverse-inference move: actions reveal objectives)\n * user — what the principal actually wants (the contract, when it differs from\n * the literal task text), plus where the user's own trajectory is heading\n *\n * and returns a verdict (aligned / drifting / diverged) with evidence and ONE\n * recommended intervention. FIREWALLED like every analyst: input is the trajectory and\n * the intents — never the verifier or its data (zero check-leakage, so route auditing\n * is always Goodhart-safe to run online).\n *\n * Where it runs: between shots (steer the next one), as a watchdog over the lifecycle\n * stream (abort-and-refund a diverged rollout — the budget pool makes early abort\n * strictly valuable), or post-hoc over a whole BenchmarkReport (the meta-intent pass:\n * is the LOOP optimizing the right thing — degenerate submissions, check-gaming shapes,\n * objective drift across tasks).\n */\n\nimport type { ChatClient } from '@tangle-network/agent-eval'\n\nexport interface AuditIntentInput {\n /** The declared intent: the task text / acceptance criteria the agent was given. */\n declaredIntent: string\n /** The trajectory so far — tool calls + results + assistant turns (any event shapes). */\n trace: ReadonlyArray<unknown>\n /** The principal's actual intent when it differs from the literal task (the contract). */\n userIntent?: string\n /** The loop-level purpose (meta-intent): what the WHOLE run is for — lets the auditor\n * flag locally-sensible work that serves the wrong larger objective. */\n metaIntent?: string\n runId?: string\n}\n\nexport interface AuditIntentOptions {\n chat: ChatClient\n model?: string\n /** Override the auditor instruction (optimizable like any analyst prompt). */\n auditorInstruction?: string\n /** Cap trace lines fed to the auditor. Default 80. */\n maxTraceLines?: number\n signal?: AbortSignal\n}\n\nexport interface IntentAudit {\n /** What the agent's actions reveal it is actually optimizing — one sentence. */\n revealedIntent: string\n verdict: 'aligned' | 'drifting' | 'diverged'\n /** Trajectory-grounded evidence for the verdict (specific calls/patterns). */\n evidence: string\n /** The single recommended intervention. */\n recommendation: 'continue' | 'steer' | 'abort'\n /** When recommendation is 'steer': the corrective instruction to inject. */\n steer?: string\n confidence: number\n}\n\nexport const defaultAuditorInstruction =\n 'You audit whether an AI agent is on the RIGHT ROUTE — not whether it works hard, but whether its ' +\n 'actions serve the stated intents. Infer the REVEALED intent from the action pattern (what the ' +\n 'trajectory is actually optimizing). Compare against the declared task intent, the user intent when ' +\n 'given, and the meta-intent when given. Flawless execution down the wrong route is DIVERGED. ' +\n 'Busy-work that neither advances nor harms is DRIFTING. Judge only from the trajectory — be specific ' +\n 'about which actions ground your verdict. Recommend abort only when continuing cannot serve the intent.'\n\nfunction summarize(trace: ReadonlyArray<unknown>, maxLines: number): string {\n const lines: string[] = []\n for (const ev of trace) {\n const e = ev as Record<string, unknown>\n const role = e.role as string | undefined\n if (role === 'tool') lines.push(`RESULT ${String(e.content).slice(0, 200)}`)\n else if (role === 'assistant') {\n const calls = (\n e.tool_calls as Array<{ function?: { name?: string; arguments?: string } }> | undefined\n )\n ?.map((c) => `${c.function?.name}(${(c.function?.arguments ?? '').slice(0, 120)})`)\n .join(', ')\n lines.push(calls ? `CALL ${calls}` : `SAY ${String(e.content).slice(0, 160)}`)\n } else if (role === 'user') lines.push(`USER ${String(e.content).slice(0, 160)}`)\n }\n return lines.slice(-maxLines).join('\\n')\n}\n\nconst auditSchema = {\n name: 'intent_audit',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['revealedIntent', 'verdict', 'evidence', 'recommendation', 'confidence'],\n properties: {\n revealedIntent: { type: 'string' },\n verdict: { type: 'string', enum: ['aligned', 'drifting', 'diverged'] },\n evidence: { type: 'string' },\n recommendation: { type: 'string', enum: ['continue', 'steer', 'abort'] },\n steer: { type: 'string' },\n confidence: { type: 'number' },\n },\n },\n}\n\nexport async function auditIntent(\n input: AuditIntentInput,\n opts: AuditIntentOptions,\n): Promise<IntentAudit> {\n const res = await opts.chat.chat(\n {\n ...(opts.model ? { model: opts.model } : {}),\n jsonSchema: auditSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\n { role: 'system', content: opts.auditorInstruction ?? defaultAuditorInstruction },\n {\n role: 'user',\n content:\n `DECLARED INTENT (the task):\\n${input.declaredIntent}\\n\\n` +\n (input.userIntent\n ? `USER INTENT (the principal's actual goal):\\n${input.userIntent}\\n\\n`\n : '') +\n (input.metaIntent\n ? `META-INTENT (what the whole run is for):\\n${input.metaIntent}\\n\\n`\n : '') +\n `TRAJECTORY (in order):\\n${summarize(input.trace, opts.maxTraceLines ?? 80)}\\n\\n` +\n 'Audit the route: revealed intent, verdict, evidence, one recommendation.',\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n let parsed: Partial<IntentAudit>\n try {\n parsed = JSON.parse(res.content) as Partial<IntentAudit>\n } catch {\n throw new Error(`auditIntent: auditor returned non-JSON: ${res.content.slice(0, 200)}`)\n }\n if (!parsed.verdict || !parsed.recommendation) {\n throw new Error(`auditIntent: missing verdict/recommendation: ${res.content.slice(0, 200)}`)\n }\n return {\n revealedIntent: parsed.revealedIntent ?? '',\n verdict: parsed.verdict,\n evidence: parsed.evidence ?? '',\n recommendation: parsed.recommendation,\n ...(parsed.steer ? { steer: parsed.steer } : {}),\n confidence: typeof parsed.confidence === 'number' ? parsed.confidence : 0.5,\n }\n}\n","/**\n * benchmark-report — turn a fleet of `RunRecord`s into a publishable, multi-axis benchmark report:\n * a ranked leaderboard, the full profile×axis score matrix, the cost/latency/token columns, and\n * embeddable charts (SVG) + a self-contained HTML page. Domain-agnostic by construction — it reads ONLY\n * the universal `RunRecord` currency (model, scenario, score, cost, tokens, latency, the `outcome.raw`\n * metric bag), so the SAME engine reports any benchmark in any domain: coding, search, agents, multimodal.\n *\n * This is the surface a hosted leaderboard (à la vals.ai) renders: for every harness×model profile, its\n * score on every axis, not a curated subset. It pairs with `runProfileMatrix` (whose `result.records`\n * feed straight in) but takes the records directly, so it is independent of how they were produced.\n *\n * An AXIS is any way to slice the score into columns — by default one column per scenario group\n * (`groupOf`, default = the scenario id), so the matrix is profile × scenario. Pass `axisScoresOf` to\n * score along judge dimensions or any custom decomposition instead. The reporter never invents a number:\n * a missing cell renders blank, never zero.\n */\nimport {\n benjaminiHochberg,\n confidenceInterval,\n pairedBootstrap,\n pairedTTest,\n type RunRecord,\n wilson,\n} from '@tangle-network/agent-eval'\n\n/** Pull the headline score in [0,1] from a record. Default: the held-out split, else the search split,\n * else a `composite`/`passed`/`score` entry in the raw bag. Override to score a domain differently. */\nexport type ScoreOf = (record: RunRecord) => number | undefined\n/** The profile (matrix row) a record belongs to — default `harness·model` from the record's profile cell,\n * falling back to the model. This is the leaderboard's unit of comparison. */\nexport type ProfileKeyOf = (record: RunRecord) => string\n/** The axis (matrix column) a record contributes to — default the scenario group. */\nexport type GroupOf = (record: RunRecord) => string\n/** Decompose ONE record into per-axis scores (e.g. judge dimensions). When set, it REPLACES the\n * scenario-group axes: the column set is the union of returned keys. */\nexport type AxisScoresOf = (record: RunRecord) => Record<string, number>\n\nexport interface LeaderboardOptions {\n readonly title?: string\n readonly scoreOf?: ScoreOf\n readonly profileKeyOf?: ProfileKeyOf\n readonly groupOf?: GroupOf\n readonly axisScoresOf?: AxisScoresOf\n /** Display label for a profile key (default: the key itself). */\n readonly labelOf?: (profileKey: string) => string\n /** Commit SHA / dataset / dates surfaced in the provenance block. */\n readonly meta?: Record<string, string>\n /** Compute per-row confidence intervals (bootstrap on score, Wilson on pass rate). Needs a\n * `scenarioId` on every record (reps are collapsed per scenario for the honest n). Default off. */\n readonly stats?: boolean\n /** A score ≥ this counts as a \"pass\" for the pass-rate proportion + its Wilson CI. Default 0.999\n * (fully solved). Lower it (e.g. 0.6) for a partial-credit domain. */\n readonly passThreshold?: number\n}\n\n/** A 95%-by-default confidence interval. */\nexport interface Interval {\n readonly lower: number\n readonly upper: number\n}\n\n/** One leaderboard row — a harness×model profile, every measured column. */\nexport interface LeaderboardRow {\n readonly profileKey: string\n readonly label: string\n readonly model: string\n readonly n: number\n readonly meanScore: number\n /** Fraction of records scoring ≥ `passThreshold` (default 0.999) — the binary pass rate. */\n readonly solveRate: number\n /** axis → mean score for this profile (blank in render when the profile never ran that axis). */\n readonly perAxis: Record<string, number>\n readonly costUsd: number\n readonly tokensIn: number\n readonly tokensOut: number\n readonly latencyP50Ms: number\n readonly latencyP90Ms: number\n /** Bootstrap CI on the mean score — present only when `opts.stats` is set. Computed over\n * per-scenario means (reps collapsed first), so identical reps can't fake a narrow interval. */\n readonly scoreCi?: Interval\n /** Wilson CI on the pass rate — present only when `opts.stats` is set. */\n readonly passCi?: Interval\n}\n\nexport interface Leaderboard {\n readonly title: string\n /** Column order — scenario groups (default) or dimension keys (`axisScoresOf`). */\n readonly axes: readonly string[]\n /** Rows ranked by `meanScore` desc (ties → lower cost, then label). */\n readonly profiles: readonly LeaderboardRow[]\n readonly meta: Record<string, string>\n /** Provenance counts — the denominators every honest report leads with. */\n readonly provenance: {\n readonly records: number\n readonly profiles: number\n readonly axes: number\n readonly models: readonly string[]\n readonly totalCostUsd: number\n }\n}\n\nconst defaultScoreOf: ScoreOf = (r) => {\n const o = r.outcome\n if (typeof o.holdoutScore === 'number') return o.holdoutScore\n if (typeof o.searchScore === 'number') return o.searchScore\n const raw = o.raw ?? {}\n for (const k of ['composite', 'score', 'passed', 'resolved']) {\n if (typeof raw[k] === 'number') return raw[k]\n }\n return undefined\n}\n\nconst defaultProfileKeyOf: ProfileKeyOf = (r) => {\n const cell = (r as { agentProfile?: { harness?: string; model?: string } }).agentProfile\n const harness = cell?.harness\n return harness ? `${harness}·${r.model}` : r.model\n}\n\nconst defaultGroupOf: GroupOf = (r) => r.scenarioId ?? r.experimentId\n\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.min(sorted.length - 1, Math.floor(q * (sorted.length - 1)))\n return sorted[idx] ?? 0\n}\n\nfunction mean(xs: readonly number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\n/** Collapse reps to ONE mean score per scenario — the honest unit for a CI or a paired test. Reps\n * tighten the per-(profile, scenario) estimate but are NOT independent samples, so feeding raw reps into\n * a CI lets identical reps fake a narrower interval. Fails LOUD on a record missing `scenarioId`: an\n * empty-string fallback would silently merge distinct scenarios into one bucket. */\nfunction meanByScenario(records: readonly RunRecord[], scoreOf: ScoreOf): Map<string, number> {\n const sums = new Map<string, { total: number; n: number }>()\n for (const r of records) {\n const s = scoreOf(r)\n if (typeof s !== 'number') continue\n const id = r.scenarioId\n if (!id) {\n throw new Error(\n `benchmark-report: RunRecord (candidate ${r.candidateId ?? 'unknown'}) is missing scenarioId — ` +\n 'cannot pair or interval it honestly. Pass opts.stats only on a scenario-tagged corpus.',\n )\n }\n const acc = sums.get(id) ?? { total: 0, n: 0 }\n acc.total += s\n acc.n += 1\n sums.set(id, acc)\n }\n const out = new Map<string, number>()\n for (const [id, acc] of sums) out.set(id, acc.n ? acc.total / acc.n : 0)\n return out\n}\n\n/** Aggregate a fleet of records into the ranked, multi-axis report. Pure — no IO, deterministic. */\nexport function leaderboard(\n records: readonly RunRecord[],\n opts: LeaderboardOptions = {},\n): Leaderboard {\n const scoreOf = opts.scoreOf ?? defaultScoreOf\n const profileKeyOf = opts.profileKeyOf ?? defaultProfileKeyOf\n const groupOf = opts.groupOf ?? defaultGroupOf\n const labelOf = opts.labelOf ?? ((k: string) => k)\n\n // Column set: explicit axis decomposition, else the scenario groups present in the data.\n const axisSet = new Set<string>()\n if (opts.axisScoresOf) {\n for (const r of records) for (const k of Object.keys(opts.axisScoresOf(r))) axisSet.add(k)\n } else {\n for (const r of records) axisSet.add(groupOf(r))\n }\n const axes = [...axisSet].sort()\n\n // Bucket records by profile.\n const byProfile = new Map<string, RunRecord[]>()\n for (const r of records) {\n const key = profileKeyOf(r)\n const bucket = byProfile.get(key)\n if (bucket) bucket.push(r)\n else byProfile.set(key, [r])\n }\n\n const rows: LeaderboardRow[] = []\n for (const [profileKey, recs] of byProfile) {\n const scores = recs.map(scoreOf).filter((s): s is number => typeof s === 'number')\n // Per-axis means.\n const axisBuckets = new Map<string, number[]>()\n for (const r of recs) {\n if (opts.axisScoresOf) {\n for (const [axis, s] of Object.entries(opts.axisScoresOf(r))) {\n const b = axisBuckets.get(axis) ?? []\n b.push(s)\n axisBuckets.set(axis, b)\n }\n } else {\n const s = scoreOf(r)\n if (typeof s === 'number') {\n const axis = groupOf(r)\n const b = axisBuckets.get(axis) ?? []\n b.push(s)\n axisBuckets.set(axis, b)\n }\n }\n }\n const perAxis: Record<string, number> = {}\n for (const [axis, b] of axisBuckets) perAxis[axis] = mean(b)\n\n const latencies = recs.map((r) => r.wallMs).sort((a, b) => a - b)\n const pass = opts.passThreshold ?? 0.999\n // Confidence intervals (opt-in) over per-scenario means — the honest n is #scenarios, not #reps.\n let scoreCi: Interval | undefined\n let passCi: Interval | undefined\n if (opts.stats) {\n const collapsed = [...meanByScenario(recs, scoreOf).values()]\n if (collapsed.length > 0) {\n const ci = confidenceInterval(collapsed, 0.95, { seed: 7 })\n scoreCi = { lower: ci.lower, upper: ci.upper }\n const w = wilson(collapsed.filter((s) => s >= pass).length, collapsed.length, 0.95)\n passCi = { lower: w.lower, upper: w.upper }\n }\n }\n rows.push({\n profileKey,\n label: labelOf(profileKey),\n model: recs[0]?.model ?? profileKey,\n n: recs.length,\n meanScore: mean(scores),\n solveRate: scores.length === 0 ? 0 : scores.filter((s) => s >= pass).length / scores.length,\n perAxis,\n costUsd: recs.reduce((a, r) => a + r.costUsd, 0),\n tokensIn: recs.reduce((a, r) => a + (r.tokenUsage?.input ?? 0), 0),\n tokensOut: recs.reduce((a, r) => a + (r.tokenUsage?.output ?? 0), 0),\n latencyP50Ms: quantile(latencies, 0.5),\n latencyP90Ms: quantile(latencies, 0.9),\n ...(scoreCi ? { scoreCi } : {}),\n ...(passCi ? { passCi } : {}),\n })\n }\n\n // Rank: score desc, then cheaper, then label for a stable order.\n rows.sort(\n (a, b) => b.meanScore - a.meanScore || a.costUsd - b.costUsd || a.label.localeCompare(b.label),\n )\n\n const models = [...new Set(records.map((r) => r.model))].sort()\n return {\n title: opts.title ?? 'Benchmark report',\n axes,\n profiles: rows,\n meta: opts.meta ?? {},\n provenance: {\n records: records.length,\n profiles: rows.length,\n axes: axes.length,\n models,\n totalCostUsd: records.reduce((a, r) => a + r.costUsd, 0),\n },\n }\n}\n\n/** One profile pair compared on the scenarios they BOTH ran — the \"who actually beat whom\" verdict. */\nexport interface PairwiseVerdict {\n readonly a: string\n readonly b: string\n /** Paired unit count (shared scenarios). The significance is suppressed below `minPairs`. */\n readonly pairs: number\n /** Median paired delta (b − a) and its bootstrap CI. */\n readonly delta: number\n readonly ciLow: number\n readonly ciHigh: number\n /** Paired-test p-value (before correction). */\n readonly p: number\n /** BH-significant across ALL pairs AND above the `minPairs` power floor. */\n readonly significant: boolean\n}\n\nexport interface PairwiseOptions {\n readonly scoreOf?: ScoreOf\n readonly profileKeyOf?: ProfileKeyOf\n readonly labelOf?: (profileKey: string) => string\n /** False-discovery rate for the Benjamini–Hochberg correction. Default 0.05. */\n readonly fdr?: number\n /** Below this many shared scenarios a paired test can't defensibly separate two profiles, so the\n * `significant` tag is suppressed regardless of p (small-n mirage protection). Default 12. */\n readonly minPairs?: number\n}\n\n/** Compare EVERY profile pair on the scenarios they both ran — paired-bootstrap effect + CI, a real\n * paired-test p-value, BH-corrected across all pairs. This is the honest \"did A beat B\" table the\n * leaderboard's point ranking cannot answer. Reuses the agent-eval statistics substrate. */\nexport function pairwiseSignificance(\n records: readonly RunRecord[],\n opts: PairwiseOptions = {},\n): PairwiseVerdict[] {\n const scoreOf = opts.scoreOf ?? defaultScoreOf\n const profileKeyOf = opts.profileKeyOf ?? defaultProfileKeyOf\n const labelOf = opts.labelOf ?? ((k: string) => k)\n const minPairs = opts.minPairs ?? 12\n\n const byProfile = new Map<string, RunRecord[]>()\n for (const r of records) {\n const k = profileKeyOf(r)\n const b = byProfile.get(k)\n if (b) b.push(r)\n else byProfile.set(k, [r])\n }\n const keys = [...byProfile.keys()].sort()\n const collapsed = new Map(keys.map((k) => [k, meanByScenario(byProfile.get(k) ?? [], scoreOf)]))\n\n const raw: Array<Omit<PairwiseVerdict, 'significant'>> = []\n for (let i = 0; i < keys.length; i += 1) {\n for (let j = i + 1; j < keys.length; j += 1) {\n const ka = keys[i] as string\n const kb = keys[j] as string\n const am = collapsed.get(ka) as Map<string, number>\n const bm = collapsed.get(kb) as Map<string, number>\n const aScores: number[] = []\n const bScores: number[] = []\n for (const sid of [...am.keys()].sort()) {\n const bv = bm.get(sid)\n if (bv !== undefined) {\n aScores.push(am.get(sid) as number)\n bScores.push(bv)\n }\n }\n if (aScores.length === 0) continue\n const boot = pairedBootstrap(aScores, bScores, { seed: 7, statistic: 'median' })\n const p = pairedTTest(aScores, bScores).p\n raw.push({\n a: labelOf(ka),\n b: labelOf(kb),\n pairs: aScores.length,\n delta: boot.median,\n ciLow: boot.low,\n ciHigh: boot.high,\n p,\n })\n }\n }\n const { significant } = benjaminiHochberg(\n raw.map((r) => r.p),\n opts.fdr ?? 0.05,\n )\n return raw.map((r, i) => ({\n ...r,\n significant: (significant[i] ?? false) && r.pairs >= minPairs,\n }))\n}\n\nconst pct = (x: number): string => `${(100 * x).toFixed(1)}%`\nconst ci = (iv: Interval | undefined): string => (iv ? ` [${pct(iv.lower)}, ${pct(iv.upper)}]` : '')\n\n/** Render the report as a publishable Markdown document: provenance → leaderboard → the full profile×axis\n * matrix → cost/latency/token columns. Every axis is shown — a curated subset is a reporting failure. */\nexport function renderLeaderboardMarkdown(report: Leaderboard): string {\n const lines: string[] = []\n lines.push(`# ${report.title}`, '')\n const p = report.provenance\n lines.push(\n `**${p.profiles} profiles × ${p.axes} axes**, ${p.records} runs, ${p.models.length} models · total $${p.totalCostUsd.toFixed(2)}`,\n '',\n )\n for (const [k, v] of Object.entries(report.meta)) lines.push(`- **${k}:** ${v}`)\n if (Object.keys(report.meta).length) lines.push('')\n\n // Leaderboard — the headline ranking with every measured column (+ CIs when computed).\n lines.push('## Leaderboard', '')\n lines.push(\n '| # | Profile | Score (95% CI) | Solved (95% CI) | Runs | Cost | Tok in/out | p50 | p90 |',\n )\n lines.push('|---|---|--:|--:|--:|--:|--:|--:|--:|')\n report.profiles.forEach((r, i) => {\n lines.push(\n `| ${i + 1} | ${r.label} | ${pct(r.meanScore)}${ci(r.scoreCi)} | ${pct(r.solveRate)}${ci(r.passCi)} | ${r.n} | $${r.costUsd.toFixed(3)} | ${r.tokensIn}/${r.tokensOut} | ${(r.latencyP50Ms / 1000).toFixed(1)}s | ${(r.latencyP90Ms / 1000).toFixed(1)}s |`,\n )\n })\n lines.push('')\n\n // The full matrix — profile × every axis.\n lines.push('## Score matrix — profile × axis', '')\n lines.push(`| Profile | ${report.axes.join(' | ')} |`)\n lines.push(`|---|${report.axes.map(() => '--:').join('|')}|`)\n for (const r of report.profiles) {\n const cells = report.axes.map((a) => {\n const v = r.perAxis[a]\n return v === undefined ? '·' : pct(v)\n })\n lines.push(`| ${r.label} | ${cells.join(' | ')} |`)\n }\n lines.push('')\n lines.push('> `·` = the profile never ran that axis (blank, never zero).')\n return lines.join('\\n')\n}\n\n/** Render the pairwise-significance table — every profile pair's paired delta, CI, and BH-corrected\n * verdict. Feed it `pairwiseSignificance(records)`. This is the \"did A really beat B\" evidence the point\n * ranking cannot give. */\nexport function renderPairwiseMarkdown(\n verdicts: readonly PairwiseVerdict[],\n title = 'Pairwise significance (paired, BH-corrected)',\n): string {\n const lines: string[] = [`## ${title}`, '']\n if (verdicts.length === 0) return lines.concat('_no comparable pairs_').join('\\n')\n lines.push('| A vs B | Δ(b−a) median | 95% CI | pairs | p | verdict |')\n lines.push('|---|--:|--:|--:|--:|---|')\n for (const v of verdicts) {\n const verdict = v.significant ? `**${v.delta >= 0 ? v.b : v.a} wins**` : 'ns'\n lines.push(\n `| ${v.a} vs ${v.b} | ${v.delta >= 0 ? '+' : ''}${pct(v.delta)} | [${pct(v.ciLow)}, ${pct(v.ciHigh)}] | ${v.pairs} | ${v.p.toFixed(3)} | ${verdict} |`,\n )\n }\n lines.push(\n '',\n '> `ns` = not significant after Benjamini–Hochberg (or below the paired-count floor).',\n )\n return lines.join('\\n')\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n}\n\n// A score → color ramp (red→amber→green) for the heatmap, deterministic and dependency-free.\nfunction ramp(score: number): string {\n const x = Math.max(0, Math.min(1, score))\n const r = Math.round(x < 0.5 ? 220 : 220 - (x - 0.5) * 2 * 160)\n const g = Math.round(x < 0.5 ? x * 2 * 170 : 170)\n return `rgb(${r},${g},60)`\n}\n\n/** Render a self-contained SVG: a ranked score bar chart on top, the profile×axis heatmap below. No deps,\n * embeddable anywhere (README, HTML page, hosted leaderboard). */\nexport function renderLeaderboardSvg(report: Leaderboard): string {\n const rowH = 26\n const labelW = 220\n const cellW = 54\n const pad = 16\n const barAreaW = 360\n const profiles = report.profiles\n const barsH = profiles.length * rowH + pad\n const heatTop = barsH + 48\n const heatW = labelW + report.axes.length * cellW + pad\n const heatH = profiles.length * rowH + pad\n const width = Math.max(labelW + barAreaW + pad * 2, heatW)\n const height = heatTop + heatH + pad\n\n const out: string[] = []\n out.push(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" font-family=\"ui-sans-serif,system-ui,sans-serif\" font-size=\"12\">`,\n )\n out.push(`<rect width=\"${width}\" height=\"${height}\" fill=\"white\"/>`)\n out.push(\n `<text x=\"${pad}\" y=\"${pad + 4}\" font-weight=\"700\" font-size=\"14\">${esc(report.title)} — score</text>`,\n )\n\n // Bar chart (ranked).\n profiles.forEach((r, i) => {\n const y = pad + 12 + i * rowH\n out.push(`<text x=\"${pad}\" y=\"${y + 14}\">${esc(r.label)}</text>`)\n const w = Math.round(r.meanScore * barAreaW)\n out.push(`<rect x=\"${labelW}\" y=\"${y + 4}\" width=\"${barAreaW}\" height=\"16\" fill=\"#eef0f2\"/>`)\n out.push(\n `<rect x=\"${labelW}\" y=\"${y + 4}\" width=\"${w}\" height=\"16\" fill=\"${ramp(r.meanScore)}\"/>`,\n )\n out.push(`<text x=\"${labelW + barAreaW + 6}\" y=\"${y + 16}\">${pct(r.meanScore)}</text>`)\n })\n\n // Heatmap.\n out.push(\n `<text x=\"${pad}\" y=\"${heatTop - 12}\" font-weight=\"700\" font-size=\"14\">profile × axis</text>`,\n )\n report.axes.forEach((a, c) => {\n const x = labelW + c * cellW\n out.push(\n `<text x=\"${x + cellW / 2}\" y=\"${heatTop}\" text-anchor=\"middle\" fill=\"#555\">${esc(a.length > 8 ? `${a.slice(0, 7)}…` : a)}</text>`,\n )\n })\n profiles.forEach((r, i) => {\n const y = heatTop + 8 + i * rowH\n out.push(`<text x=\"${pad}\" y=\"${y + 16}\">${esc(r.label)}</text>`)\n report.axes.forEach((a, c) => {\n const x = labelW + c * cellW\n const s = r.perAxis[a]\n if (s !== undefined) {\n out.push(\n `<rect x=\"${x}\" y=\"${y}\" width=\"${cellW - 3}\" height=\"${rowH - 4}\" fill=\"${ramp(s)}\"/>`,\n )\n out.push(\n `<text x=\"${x + (cellW - 3) / 2}\" y=\"${y + 15}\" text-anchor=\"middle\" fill=\"white\" font-size=\"10\">${Math.round(100 * s)}</text>`,\n )\n } else {\n out.push(\n `<rect x=\"${x}\" y=\"${y}\" width=\"${cellW - 3}\" height=\"${rowH - 4}\" fill=\"#f3f4f6\"/>`,\n )\n }\n })\n })\n out.push('</svg>')\n return out.join('\\n')\n}\n\n/** Render a self-contained HTML leaderboard page (the hosted surface): the SVG charts + the full Markdown\n * matrix as a table. Single file, no assets, opens in any browser. */\nexport function renderLeaderboardHtml(report: Leaderboard): string {\n const svg = renderLeaderboardSvg(report)\n const p = report.provenance\n const rows = report.profiles\n .map(\n (r, i) =>\n `<tr><td>${i + 1}</td><td>${esc(r.label)}</td><td class=\"n\">${pct(r.meanScore)}</td><td class=\"n\">${pct(r.solveRate)}</td><td class=\"n\">${r.n}</td><td class=\"n\">$${r.costUsd.toFixed(3)}</td>${report.axes\n .map((a) => {\n const v = r.perAxis[a]\n return `<td class=\"n\">${v === undefined ? '·' : pct(v)}</td>`\n })\n .join('')}</tr>`,\n )\n .join('\\n')\n const axisHead = report.axes.map((a) => `<th>${esc(a)}</th>`).join('')\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(report.title)}</title>\n<style>\nbody{font:14px ui-sans-serif,system-ui,sans-serif;margin:2rem;color:#111}\nh1{font-size:1.4rem}.sub{color:#555;margin:.2rem 0 1.2rem}\ntable{border-collapse:collapse;margin-top:1rem}td,th{border:1px solid #e5e7eb;padding:.35rem .6rem}\nth{background:#f9fafb;text-align:left}.n{text-align:right;font-variant-numeric:tabular-nums}\ntr:first-child td{font-weight:600}\n</style></head><body>\n<h1>${esc(report.title)}</h1>\n<div class=\"sub\">${p.profiles} profiles × ${p.axes} axes · ${p.records} runs · ${p.models.length} models · total $${p.totalCostUsd.toFixed(2)}</div>\n${svg}\n<table><thead><tr><th>#</th><th>Profile</th><th>Score</th><th>Solved</th><th>Runs</th><th>Cost</th>${axisHead}</tr></thead>\n<tbody>\n${rows}\n</tbody></table>\n</body></html>`\n}\n","/**\n * @experimental\n *\n * Completion / satisfiability — the OTHER output of the pluggable analyst (the steer output\n * is `AnalystFinding[]` via the `analyze` hook; this is the \"is it done?\" output via the\n * `complete` hook). A `CompletionAnalyst` reads a node's trace and returns a `CompletionVerdict`\n * the PARENT (driver) acts on: end the node, or keep going. It fits ANY node and composes to\n * any depth — a 1-deep loop has one; an N-deep tree has one per node.\n *\n * The verdict's authority scales with its DETERMINISM (the thing that varies by task):\n * - `deterministic` — build/test/lint pass, a proof checks, every claim's citation resolves:\n * ground truth, the driver TRUSTS it and ends. Not an opinion.\n * - `probabilistic` — a quality/soundness judgment (marketing, \"the experiment is sound\"):\n * ADVISORY. It passes to the driver with its reasons; the driver validates (here: a\n * confidence threshold; a richer driver may re-examine the reasons) before ending.\n *\n * Two stop-signal mechanisms, by node mode, both → one `CompletionVerdict`:\n * - sandbox-agent (text stream): a unique per-node STOP SENTINEL the agent emits when done\n * (`stopSentinel` / `sentinelCompletion`) — ralph-loop style; the seed makes it\n * unguessable + attributable, so it can't be spuriously emitted or confused with content.\n * - deterministic check (compile/test/citation/proof): `deterministicCompletion(check)` —\n * a verifier over the output, never the judge verdict (selector ≠ judge holds).\n */\n\nimport type { Iteration } from './types'\n\n/** Trace-derived evidence for a completion claim — an artifact (output) or a verifier metric,\n * never the judge's own verdict. Mirrors the steer-firewall's provenance discipline. */\nexport interface CompletionEvidence {\n kind: 'artifact' | 'metric'\n uri: string\n}\n\n/** The \"is it done?\" verdict an analyst returns to the parent. */\nexport interface CompletionVerdict {\n done: boolean\n /** How verifiable the claim is — sets whether the driver trusts it or validates it. */\n determinism: 'deterministic' | 'probabilistic'\n /** Why the analyst believes it is (or isn't) done — what the driver validates. */\n reasons?: string\n /** 0..1, for probabilistic verdicts; the driver's validation threshold reads this. */\n confidence?: number\n evidence?: ReadonlyArray<CompletionEvidence>\n}\n\n/** Reads a node's trace → a completion verdict. Same input shape as the `analyze` hook, so\n * ONE analyst node can back both channels (findings for steer, a verdict for stop). */\nexport interface CompletionAnalyst<Task, Output> {\n assess(input: {\n task: Task\n history: ReadonlyArray<Iteration<Task, Output>>\n }): CompletionVerdict | Promise<CompletionVerdict>\n}\n\n/** When a verdict authorizes the driver to END. Deterministic → trust (ground truth);\n * probabilistic → validate by confidence threshold (the driver's check). */\nexport interface CompletionPolicy {\n /** Minimum confidence a PROBABILISTIC verdict must clear to end. Default 0.8. */\n minConfidence?: number\n}\n\nexport function completionAuthorizes(v: CompletionVerdict, policy?: CompletionPolicy): boolean {\n if (!v?.done) return false\n if (v.determinism === 'deterministic') return true\n return (v.confidence ?? 0) >= (policy?.minConfidence ?? 0.8)\n}\n\n/**\n * A unique, attributable stop sentinel for a node (ralph-loop style). Deterministic from the\n * seed (no Math.random — reproducible + attributable to the node); the agent is instructed to\n * emit it VERBATIM when it judges itself done. Unguessable enough that content never trips it.\n */\nexport function stopSentinel(seed: string): string {\n let h = 0x811c9dc5\n for (let i = 0; i < seed.length; i += 1) {\n h ^= seed.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return `<<<{{STOP:${(h >>> 0).toString(16).padStart(8, '0')}}}>>>`\n}\n\n/**\n * Completion for a sandbox-agent node: done iff the latest output carries the node's stop\n * sentinel. PROBABILISTIC (the agent's own self-judgment) — the driver validates it.\n */\nexport function sentinelCompletion<Task>(\n sentinel: string,\n opts?: { confidence?: number },\n): CompletionAnalyst<Task, string> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n const out = typeof last?.output === 'string' ? last.output : ''\n const done = out.includes(sentinel)\n return {\n done,\n determinism: 'probabilistic',\n confidence: done ? (opts?.confidence ?? 0.9) : 0,\n reasons: done ? 'agent emitted its assigned stop sentinel' : undefined,\n evidence: done && last ? [{ kind: 'artifact', uri: `attempt:${last.index}` }] : [],\n }\n },\n }\n}\n\n/**\n * Completion for a DETERMINISTIC check (build/test/lint/citation/proof): done iff the check\n * passes. Ground truth — the driver ends directly, no validation. The check reads the output\n * (a verifier), never the judge verdict — selector ≠ judge stays intact.\n */\nexport function deterministicCompletion<Task, Output>(\n check: (\n output: Output,\n history: ReadonlyArray<Iteration<Task, Output>>,\n ) => { passed: boolean; reasons?: string },\n): CompletionAnalyst<Task, Output> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n if (last?.output === undefined) {\n return { done: false, determinism: 'deterministic', reasons: 'no output yet' }\n }\n const r = check(last.output, history)\n return {\n done: r.passed,\n determinism: 'deterministic',\n reasons: r.reasons,\n evidence: [{ kind: 'artifact', uri: `attempt:${last.index}` }],\n }\n },\n }\n}\n","/**\n * The third-person observer — the connective tissue that closes the loop.\n *\n * A driver spawns a worker; the worker can't see itself. `observe` reads the\n * worker's TRACE (what it actually did — every tool call, cost, failure) and\n * produces two streams:\n * - `findings` / `report` — fed back DOWN (a steer for the next attempt) and\n * OUT (the operator-facing \"what I noticed + what to change\").\n * - `learned` — durable facts written to the cross-run `Corpus` so the NEXT\n * run starts smarter (the continuous half of \"continuous self-improvement\").\n *\n * Findings are TRACE-derived, never JUDGE-derived (`derived_from_judge:false`):\n * the observer reads behavior, never the acceptance verdict — the selector≠judge\n * firewall (docs/learning-flywheel.md). The observer is harness-agnostic: it\n * reads a trace + an output, so it watches opencode, codex, hermes, or a BYO\n * agent identically.\n */\nimport { type AnalystFinding, type ChatClient, makeFinding } from '@tangle-network/agent-eval'\nimport type { Corpus, CorpusRecord } from './personify/wave-types'\n\nconst observerId = 'observe/trace'\n\nexport interface ObserveInput {\n /** What the worker was asked to do. */\n task: string\n /** What it produced (its final answer / artifact summary). */\n output: string\n /** The worker's trace — any event array (sandbox events, tool-call records). */\n trace: ReadonlyArray<unknown>\n /** Terminal status only (passed/failed/unknown) — NOT a judge score; the\n * observer never reads the verdict, it reads behavior. */\n outcome?: 'passed' | 'failed' | 'unknown'\n /** Provenance back to the run. */\n runId?: string\n}\n\nexport interface ObserveOptions {\n /** The model-call seam (agent-eval `createChatClient`: router / cli-bridge / …). */\n chat: ChatClient\n model?: string\n /** When set, learned facts are appended (idempotent) for the next run to read. */\n corpus?: Corpus\n /** Tags written onto learned facts + used by the next run's corpus query. */\n tags?: ReadonlyArray<string>\n signal?: AbortSignal\n /** Cap the trace lines fed to the observer (keeps the call cheap). Default 80. */\n maxTraceLines?: number\n /** Override the analyst's system instruction — the prompt that turns a trace into\n * findings + recommended_actions. The analyst IS the steerer, so this is the knob a\n * prompt optimizer (GEPA) tunes. Omitted ⇒ the default observer instruction. The\n * firewall (trace-only, never the verdict) is structural (input has no score), so a\n * custom instruction cannot break it. */\n analystInstruction?: string\n}\n\n/** The default observer instruction — exported so an optimizer can seed its population. */\nexport const defaultAnalystInstruction =\n 'You are a third-person OBSERVER watching an AI agent work. You see its TRACE (what it did), not its grader. ' +\n 'From the trace, name SPECIFIC, behavior-grounded findings: wasted/duplicated tool calls, thrash/retries, ' +\n 'token/cost waste, missing verification, failure patterns. For each, a concrete recommended_action, and ' +\n 'whether the AGENT (fix its skills/prompt/tools) or the OPERATOR (fix framing/decomposition/config) should act. ' +\n 'Only claim what the trace shows. No findings if the run was clean.'\n\nexport interface Observation {\n findings: AnalystFinding[]\n /** Facts persisted to the corpus (empty when no corpus was supplied). */\n learned: CorpusRecord[]\n /** Operator-facing markdown: what the observer noticed + what to change. */\n report: string\n}\n\n/** Compact the trace into the lines the observer reasons over — tool calls,\n * errors, and statuses, in order. Keeps the model call bounded + grounded. */\nfunction summarizeTrace(trace: ReadonlyArray<unknown>, maxLines: number): string {\n const lines: string[] = []\n for (const ev of trace) {\n const e = ev as { type?: string; data?: Record<string, unknown> }\n const t = (e.type ?? '').toLowerCase()\n const d = e.data ?? {}\n const part = (d.part ?? {}) as { type?: string; tool?: string; state?: { status?: string } }\n if (part.type === 'tool')\n lines.push(`tool:${part.tool}${part.state?.status ? `(${part.state.status})` : ''}`)\n else if (t.includes('error'))\n lines.push(`ERROR: ${String(d.message ?? d.detail ?? '').slice(0, 200)}`)\n else if (t === 'status' && typeof d.status === 'string') lines.push(`status:${d.status}`)\n else if (t.includes('tool')) lines.push(`tool-event:${t}`)\n }\n // Collapse runs of identical lines into \"xN\" so repeated thrash is visible + short.\n const out: string[] = []\n for (const ln of lines) {\n const prev = out[out.length - 1]\n const m = prev?.match(/^(.*?)(?: x(\\d+))?$/)\n if (m && m[1] === ln) out[out.length - 1] = `${ln} x${(Number(m[2]) || 1) + 1}`\n else out.push(ln)\n }\n return out.slice(0, maxLines).join('\\n') || '(no tool/error events in trace)'\n}\n\nconst findingsSchema = {\n name: 'observer_findings',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n findings: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n area: {\n type: 'string',\n description: 'tool-use | cost | verification | process | failure | latency',\n },\n severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },\n claim: {\n type: 'string',\n description: 'what you OBSERVED in the trace (a fact, with the evidence)',\n },\n recommended_action: {\n type: 'string',\n description: 'the concrete change for the agent or operator',\n },\n audience: {\n type: 'string',\n enum: ['agent', 'operator'],\n description: 'who should act on this',\n },\n confidence: { type: 'number' },\n },\n required: ['area', 'severity', 'claim', 'recommended_action', 'audience', 'confidence'],\n },\n },\n },\n required: ['findings'],\n },\n} as const\n\nexport async function observe(input: ObserveInput, opts: ObserveOptions): Promise<Observation> {\n const traceSummary = summarizeTrace(input.trace, opts.maxTraceLines ?? 80)\n const res = await opts.chat.chat(\n {\n ...(opts.model ? { model: opts.model } : {}),\n jsonSchema: findingsSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\n {\n role: 'system',\n content: opts.analystInstruction ?? defaultAnalystInstruction,\n },\n {\n role: 'user',\n content:\n `TASK: ${input.task}\\n\\nOUTCOME: ${input.outcome ?? 'unknown'}\\n\\n` +\n `FINAL OUTPUT (truncated):\\n${input.output.slice(0, 1200)}\\n\\n` +\n `TRACE (in order; \"xN\" = repeated):\\n${traceSummary}`,\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n\n const parsed = parseFindings(res.content)\n const producedAt = input.runId ? `${input.runId}` : observerId\n const findings: AnalystFinding[] = parsed.map((f) =>\n makeFinding({\n analyst_id: observerId,\n area: `${f.area}`,\n severity: f.severity,\n claim: f.claim,\n recommended_action: f.recommended_action,\n confidence: typeof f.confidence === 'number' ? f.confidence : 0.5,\n evidence_refs: [],\n // The observer reads BEHAVIOR, never the judge verdict — firewall provenance.\n derived_from_judge: false,\n metadata: { audience: f.audience },\n ...(input.runId ? { subject: input.runId } : {}),\n }),\n )\n\n const learned: CorpusRecord[] = []\n if (opts.corpus) {\n for (const f of findings) {\n const record: CorpusRecord = {\n schemaVersion: '1.0.0',\n id: f.finding_id,\n runId: input.runId ?? observerId,\n producedAt: f.produced_at ?? producedAt,\n area: f.area,\n claim: f.recommended_action ?? f.claim,\n ...(f.claim ? { rationale: f.claim } : {}),\n tags: [...(opts.tags ?? []), `audience:${(f.metadata?.audience as string) ?? 'agent'}`],\n confidence: f.confidence,\n evidence: [{ kind: 'finding', uri: f.finding_id }],\n }\n const r = await opts.corpus.append(record)\n if (r.succeeded) learned.push(record)\n }\n }\n\n return { findings, learned, report: renderReport(findings) }\n}\n\ninterface RawFinding {\n area: string\n severity: AnalystFinding['severity']\n claim: string\n recommended_action: string\n audience: 'agent' | 'operator'\n confidence: number\n}\n\nfunction parseFindings(content: string): RawFinding[] {\n let obj: unknown\n try {\n obj = JSON.parse(content)\n } catch {\n const m = content.match(/\\{[\\s\\S]*\\}/)\n obj = m ? JSON.parse(m[0]) : { findings: [] }\n }\n const arr = (obj as { findings?: unknown }).findings\n return Array.isArray(arr) ? (arr as RawFinding[]) : []\n}\n\n/** Operator-facing report, split by who should act. The agent block is the\n * steer; the operator block is the advice. */\nexport function renderReport(findings: ReadonlyArray<AnalystFinding>): string {\n if (findings.length === 0) return '✓ clean run — the observer found nothing to change.'\n const audience = (f: AnalystFinding): string => (f.metadata?.audience as string) ?? 'agent'\n const forAgent = findings.filter((f) => audience(f) === 'agent')\n const forOperator = findings.filter((f) => audience(f) === 'operator')\n const block = (title: string, fs: ReadonlyArray<AnalystFinding>): string =>\n fs.length === 0\n ? ''\n : `**${title}**\\n${fs\n .map((f) => `- [${f.severity}] ${f.claim}\\n → ${f.recommended_action ?? ''}`)\n .join('\\n')}\\n`\n return [\n block('For the agent (fix skills / prompt / tools)', forAgent),\n block('For you (the operator)', forOperator),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n","/**\n * harvestCorpus — production traces → corpus, the G2 bridge (the playbook's step 6).\n * The flywheel's write side, batched: run the firewalled `observe()` analyst over a\n * stream of completed runs (yesterday's production traces, a benchmark's rollouts, a\n * fleet's day) and accrete the trace-derived facts into the durable corpus.\n *\n * Store-agnostic by design: the caller maps its trace store's rows (a\n * `ProductionTraceSink` ndjson, OTLP spans, RunRecords) to `ObserveInput` — task text,\n * final output, the event trace, terminal outcome. The analyst reads BEHAVIOR only\n * (the firewall is structural: the input carries no judge verdict), and corpus appends\n * are idempotent on (claim + tags), so re-harvesting the same window is safe.\n *\n * The nightly product job is then three lines:\n * const runs = mapSinkRowsToObserveInputs(await readSink(yesterday))\n * const report = await harvestCorpus({ runs, chat, corpus, tags: ['gtm-agent'] })\n * log(report) // runsObserved / findings / learned / failures\n *\n * NOTE on the read side: harvesting is safe and cheap; *injecting* facts back into runs\n * is the measured danger zone — naive unconditional priming tested NEGATIVE (−11.6pp,\n * context pollution; result now in .evolve/current.json + memory). Gate any priming design on its\n * own A/B; the corpus's first consumers are operators and optimizers, not prompts.\n */\n\nimport type { ChatClient } from '@tangle-network/agent-eval'\nimport { type Observation, type ObserveInput, observe } from './observe'\nimport type { Corpus } from './personify/wave-types'\n\nexport interface HarvestCorpusOptions {\n /** The completed runs to analyze — map your store's rows to `ObserveInput`. */\n runs: AsyncIterable<ObserveInput> | Iterable<ObserveInput>\n /** The model-call seam (agent-eval `createChatClient`). */\n chat: ChatClient\n model?: string\n /** The durable corpus the facts accrete into. */\n corpus: Corpus\n /** Tags written onto learned facts (the product/domain key the read side queries by). */\n tags?: ReadonlyArray<string>\n /** Override the analyst instruction (the GEPA-tunable knob). */\n analystInstruction?: string\n /** Runs analyzed in parallel. Default 4. */\n concurrency?: number\n /** Hard cap on runs consumed from the stream (a cost guard for unbounded stores). */\n maxRuns?: number\n signal?: AbortSignal\n}\n\nexport interface HarvestFailure {\n runId: string\n error: string\n}\n\nexport interface HarvestReport {\n runsObserved: number\n /** Total findings the analyst produced (including ones already known). */\n findings: number\n /** NEW facts actually appended (idempotent dedup excludes re-learned ones). */\n learned: number\n /** Per-run analysis failures — reported, never silently dropped. */\n failures: HarvestFailure[]\n}\n\nexport async function harvestCorpus(opts: HarvestCorpusOptions): Promise<HarvestReport> {\n const concurrency = Math.max(1, opts.concurrency ?? 4)\n const report: HarvestReport = { runsObserved: 0, findings: 0, learned: 0, failures: [] }\n\n // Normalize to an async iterator and pull cooperatively from N workers.\n const iterator = (\n Symbol.asyncIterator in Object(opts.runs)\n ? (opts.runs as AsyncIterable<ObserveInput>)[Symbol.asyncIterator]()\n : (async function* () {\n yield* opts.runs as Iterable<ObserveInput>\n })()\n ) as AsyncIterator<ObserveInput>\n\n let consumed = 0\n let done = false\n const next = async (): Promise<ObserveInput | null> => {\n if (done || (opts.maxRuns !== undefined && consumed >= opts.maxRuns)) return null\n const r = await iterator.next()\n if (r.done) {\n done = true\n return null\n }\n consumed += 1\n return r.value\n }\n\n const workers = Array.from({ length: concurrency }, async () => {\n for (let input = await next(); input !== null; input = await next()) {\n if (opts.signal?.aborted) return\n try {\n const obs: Observation = await observe(input, {\n chat: opts.chat,\n ...(opts.model ? { model: opts.model } : {}),\n corpus: opts.corpus,\n tags: opts.tags ?? [],\n ...(opts.analystInstruction ? { analystInstruction: opts.analystInstruction } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n report.runsObserved += 1\n report.findings += obs.findings.length\n report.learned += obs.learned.length\n } catch (e) {\n report.failures.push({\n runId: input.runId ?? `run-${consumed}`,\n error: e instanceof Error ? e.message.slice(0, 300) : String(e),\n })\n }\n }\n })\n await Promise.all(workers)\n\n // Fail loud when the whole batch failed — that's an infra problem, not a quiet no-op.\n if (report.runsObserved === 0 && report.failures.length > 0) {\n throw new Error(\n `harvestCorpus: every run failed analysis (${report.failures.length}) — first: ${report.failures[0]?.error}`,\n )\n }\n return report\n}\n","/**\n * The ONE in-process pseudo-box: present a plain user callback as a\n * `SandboxClient` so an example or test can drive `runLoop` / `openSandboxRun`\n * with zero credentials and zero network — without re-faking a box at each call\n * site via `as unknown as SandboxInstance`.\n *\n * It is the structural sibling of {@link inlineSandboxClient}: that one adapts an\n * `Executor` (router / bridge / BYO) into a box; this one adapts a single\n * `onPrompt(prompt, round)` callback into a box. Both exist because\n * `SandboxInstance` is a `declare class` with private fields — a plain object\n * literal can NEVER structurally satisfy it, so every offline seam was forced to\n * write `as unknown as SandboxInstance`. The one unavoidable cast now lives HERE,\n * documented and tested, instead of in every example.\n *\n * What the box implements is exactly the subset `runLoop` + `openSandboxRun`\n * actually call on a box:\n * - `id` — stable per box, used for trace correlation.\n * - `streamPrompt(prompt, opts?)` — runs `onPrompt` and streams its events.\n * - `fs.read` / `fs.write` — over the optional real `workdir` (the deliverable\n * artifact + any seeded fixtures live there). Present only when a `workdir`\n * is given.\n * - `exec(command)` — runs the command in `workdir`. Present only when a\n * `workdir` is given.\n * - `delete()` — removes the per-box temp dir (when one was minted) and is a\n * no-op otherwise; `deleteBoxSafe` calls it at teardown.\n *\n * The `SandboxEvent` shape the callback returns — `{ type, data }` — is the\n * runtime metering protocol the kernel reads: emit a flat `llm_call`\n * (`{ tokensIn, tokensOut, costUsd }`) or a terminal `done`\n * (`{ tokenUsage, totalCostUsd }`) / `result` event and the kernel's cost ledger\n * picks it up. No cast is needed on the events (the union is structural); only\n * the box object is cast, once, inside this file.\n */\nimport { mkdtempSync, rmSync } from 'node:fs'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport type { SandboxClient } from './types'\n\n/** Context handed to each `onPrompt` call. */\nexport interface InProcessPromptCtx {\n /** 0-based round index — increments per `streamPrompt` on the SAME box (so a\n * refine driver's round N can differ from round N-1). Fresh boxes start at 0. */\n round: number\n /** Absolute path of this box's workspace, when a `workdir` was configured.\n * Write the deliverable / fixtures here; `fs.read`/`fs.write`/`exec` operate\n * over it. `undefined` for pure event-only boxes. */\n workdir?: string\n /** Cooperative cancellation channel for this turn. */\n signal: AbortSignal\n}\n\n/**\n * The user callback: given a prompt and its round, produce the box's event\n * stream for that turn. Return a plain `SandboxEvent[]` (the common case) or an\n * async iterable for streaming. The callback may also write files into\n * `ctx.workdir` (read back via `fs.read` or graded by `exec`).\n */\nexport type InProcessOnPrompt = (\n prompt: string,\n ctx: InProcessPromptCtx,\n) => SandboxEvent[] | AsyncIterable<SandboxEvent> | Promise<SandboxEvent[]>\n\n/** @experimental */\nexport interface InProcessSandboxClientOptions {\n /** The per-turn behavior — see {@link InProcessOnPrompt}. */\n onPrompt: InProcessOnPrompt\n /**\n * Opt in to a REAL filesystem-backed box. When set, each `create()` mints a\n * fresh temp directory (prefixed `<workdir>-`) and the box exposes\n * `fs.read`/`fs.write` and `exec` over it; `delete()` removes the dir. Omit\n * for a pure event-only box (no `fs`/`exec` members), which is all a driver\n * or fanout loop needs.\n */\n workdir?: string\n /**\n * Override the box `id`. A string is used verbatim; a function receives the\n * 0-based create-sequence and returns the id (e.g. machine-keyed placement\n * demos). Default `in-process-<seq>`. The id is the value `describePlacement`\n * tags, so set it when a demo's output reads on a meaningful sandbox id.\n */\n id?: string | ((seq: number) => string)\n}\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<SandboxEvent> {\n return typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n}\n\n/**\n * Adapt a single `onPrompt(prompt, ctx)` callback into a `SandboxClient` for\n * `runLoop` / `openSandboxRun`. Returns a PROPERLY-TYPED `SandboxClient`: the\n * lone `SandboxInstance` cast (object literal → `declare class`) lives inside\n * this function, so call sites stay cast-free.\n *\n * @experimental\n */\nexport function inProcessSandboxClient(options: InProcessSandboxClientOptions): SandboxClient {\n const { onPrompt, workdir: workdirPrefix, id: idOption } = options\n let seq = 0\n return {\n async create(_options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const current = seq++\n const id =\n typeof idOption === 'function' ? idOption(current) : (idOption ?? `in-process-${current}`)\n const boxWorkdir =\n workdirPrefix !== undefined ? mkdtempSync(join(tmpdir(), `${workdirPrefix}-`)) : undefined\n let round = 0\n\n const fsMembers =\n boxWorkdir !== undefined\n ? {\n fs: {\n async read(path: string): Promise<string> {\n return readFile(join(boxWorkdir, path), 'utf8')\n },\n async write(path: string, content: string): Promise<void> {\n const abs = join(boxWorkdir, path)\n await mkdir(dirname(abs), { recursive: true })\n await writeFile(abs, content, 'utf8')\n },\n },\n async exec(\n command: string,\n ): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n const { exec: execCb } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const execAsync = promisify(execCb)\n try {\n const { stdout, stderr } = await execAsync(command, {\n cwd: boxWorkdir,\n timeout: 30_000,\n })\n return { exitCode: 0, stdout, stderr }\n } catch (err) {\n const e = err as {\n code?: number\n stdout?: string\n stderr?: string\n message?: string\n }\n return {\n exitCode: e.code ?? 1,\n stdout: e.stdout ?? '',\n stderr: e.stderr ?? e.message ?? '',\n }\n }\n },\n }\n : {}\n\n const box = {\n id,\n async *streamPrompt(\n message: string | unknown[],\n opts?: { signal?: AbortSignal },\n ): AsyncGenerator<SandboxEvent> {\n const prompt = typeof message === 'string' ? message : JSON.stringify(message)\n const signal = opts?.signal ?? new AbortController().signal\n const ctx: InProcessPromptCtx = { round, workdir: boxWorkdir, signal }\n round += 1\n const produced = await onPrompt(prompt, ctx)\n if (isAsyncIterable(produced)) {\n for await (const ev of produced) yield ev\n } else {\n for (const ev of produced) yield ev\n }\n },\n ...fsMembers,\n async delete(): Promise<void> {\n if (boxWorkdir !== undefined) rmSync(boxWorkdir, { recursive: true, force: true })\n },\n }\n // The ONE unavoidable cast: `SandboxInstance` is a `declare class` with\n // private fields, so an object implementing only the called subset cannot\n // structurally satisfy it. Contained here so call sites never cast.\n return box as unknown as SandboxInstance\n },\n }\n}\n","/**\n * The ONE pseudo-box adapter: present any one-shot `Executor` (router / bridge /\n * BYO) as a `SandboxClient` so the round-synchronous `runLoop` can drive it\n * without each call site re-faking a box. This is the single shell that\n * `bench/src/router-executor.ts`, generate-eval's old `bridgeSandboxClient`, and\n * the search-bench bridge transport were each re-implementing.\n *\n * It is deliberately for NON-box executors only — a real sandbox harness already\n * IS a `SandboxClient` (boxes, sessions, fs, fork are real there). Here each\n * `streamPrompt` runs the executor once and emits the terminal\n * `{type:'result', data:{finalText, tokenUsage, costUsd}}` event that\n * `answerOutput`/the kernel's cost ledger already parse — no sessions, no fs,\n * no fork (those degrade gracefully via the optional `SandboxClient` methods).\n */\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport type { AgentSpec, Executor, ExecutorFactory, ExecutorResult } from './supervise/types'\nimport type { SandboxClient } from './types'\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<unknown> {\n return typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n}\n\n/** Drive a (possibly streaming) executor to its terminal artifact. */\nasync function settle(\n exec: Executor<unknown>,\n task: unknown,\n signal: AbortSignal,\n): Promise<ExecutorResult<unknown>> {\n const r = exec.execute(task, signal)\n if (isAsyncIterable(r)) {\n for await (const _ of r) {\n // streaming executors meter as they run; the artifact is read after drain.\n }\n return exec.resultArtifact()\n }\n return r\n}\n\n/**\n * Adapt an `ExecutorFactory` into a `SandboxClient` for `runLoop`. The factory is\n * instantiated fresh per `streamPrompt` (mirrors the per-spawn executor lifecycle):\n * run once on the prompt, emit the terminal result event, tear down.\n */\nexport function inlineSandboxClient(factory: ExecutorFactory<unknown>): SandboxClient {\n let seq = 0\n return {\n async create(options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const id = `inline-${seq++}`\n // The `create(options)` backend override is threaded to the factory through\n // the `ExecutorContext.seams` channel (the designed opaque-seam extension\n // point), so a BYO executor that varies per-cell — e.g. the cli-bridge\n // executor reading its harness/model off `backend.type`/`backend.model.model`\n // — sees the same per-create config a real sandbox executor gets, without a\n // second client per cell.\n const createOptions = options\n return {\n id,\n async *streamPrompt(message: string): AsyncGenerator<SandboxEvent> {\n const controller = new AbortController()\n const spec: AgentSpec = { profile: { name: id }, harness: null }\n const exec = factory(spec, { signal: controller.signal, seams: { createOptions } })\n try {\n const artifact = await settle(exec, message, controller.signal)\n const out = artifact.out as { content?: string } | undefined\n // Speak the runtime's metering protocol: `extractLlmCallEvent` reads\n // flat `llm_call` events, not the nested result payload — without\n // this the kernel meters the iteration as a fabricated $0 / 0 tokens.\n const tokensIn = artifact.spent.tokens.input\n const tokensOut = artifact.spent.tokens.output\n const costUsd = artifact.spent.usd\n if (tokensIn || tokensOut || costUsd) {\n yield {\n type: 'llm_call',\n data: { tokensIn, tokensOut, costUsd },\n } as unknown as SandboxEvent\n }\n yield {\n type: 'result',\n data: {\n finalText: out?.content ?? '',\n tokenUsage: {\n inputTokens: tokensIn,\n outputTokens: tokensOut,\n },\n costUsd,\n },\n } as unknown as SandboxEvent\n } finally {\n await exec.teardown('brutalKill').catch(() => {})\n }\n },\n async delete(): Promise<void> {},\n } as unknown as SandboxInstance\n },\n }\n}\n","/**\n * Bridge a finished `runLoop` into an agent-eval campaign / profile-matrix\n * dispatch.\n *\n * `runProfileMatrix` (and `runCampaign`) run the backend-integrity guard over\n * the token usage a dispatch reports through `ctx.cost`. A dispatch that wraps\n * `runLoop` must forward the loop's cost AND token usage, or the guard reads\n * the run as a stub and throws. `reportLoopUsage` is that one line:\n *\n * const dispatch: ProfileDispatchFn<S, A> = async (profile, scenario, ctx) => {\n * const result = await runLoop({ ...optsFor(profile, scenario), ctx: loopCtx })\n * reportLoopUsage(ctx, result)\n * return result.winner?.output as A\n * }\n *\n * Typed structurally against the campaign `DispatchContext.cost` so this module\n * stays free of an agent-eval import — it works with any cost meter exposing\n * `observe` + `observeTokens`.\n */\n\nimport type { LoopResult, LoopTokenUsage } from './types'\n\n/** The slice of an agent-eval campaign `DispatchContext.cost` this needs. */\nexport interface UsageSink {\n observe(amountUsd: number, source: string): void\n observeTokens(usage: LoopTokenUsage): void\n}\n\n/**\n * Forward a `LoopResult`'s aggregated cost + token usage into a campaign cost\n * meter so the backend-integrity guard sees real LLM activity. `source`\n * defaults to `'loop'`.\n */\nexport function reportLoopUsage<Task, Output, Decision>(\n cost: UsageSink,\n result: Pick<LoopResult<Task, Output, Decision>, 'costUsd' | 'tokenUsage'>,\n source = 'loop',\n): void {\n cost.observe(result.costUsd, source)\n cost.observeTokens(result.tokenUsage)\n}\n","/**\n * `loopDispatch` — turn `runLoop` into an agent-eval campaign dispatch.\n *\n * Without this adapter a consumer wiring `runLoop` into `runProfileMatrix` /\n * `runCampaign` has to, by hand, every time: (a) build an `ExecCtx` with a\n * sandbox client, (b) adapt the campaign `DispatchContext.trace` into a\n * `LoopTraceEmitter` (or lose all loop trace correlation), and (c) remember to\n * forward the loop's cost + tokens via `ctx.cost` (forgetting it yields a\n * `{0,0}` cell the backend-integrity guard reads as a stub). Three foot-guns,\n * the third silent. The fleet's products skipped (c) and fell back to a\n * `workerRecords[]` side-channel — the exact anti-pattern the substrate exists\n * to kill.\n *\n * `loopDispatch` collapses all three into one typed call:\n *\n * const dispatch = loopDispatch({\n * sandboxClient,\n * toLoopOptions: (scenario, profile) => ({ driver, agentRun, output, validator, task }),\n * })\n * await runProfileMatrix({ profiles, scenarios, dispatch, judges, commitSha })\n *\n * Usage is reported automatically; trace events are forwarded automatically;\n * the ctx is built automatically. The seam becomes impossible to mis-wire.\n *\n * Typed structurally against the campaign `DispatchContext` (imported type-only\n * from `@tangle-network/agent-eval/campaign`) — a downward dependency, never an\n * inversion.\n */\n\n// agent-eval's AgentProfile (the eval-harness unit of variation, `model: string`)\n// — NOT sandbox's AgentProfile. ProfileDispatchFn is keyed on the former.\nimport type { AgentProfile } from '@tangle-network/agent-eval'\nimport type {\n CampaignTraceWriter,\n DispatchContext,\n DispatchFn,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { reportLoopUsage } from './report-usage'\nimport { type RunLoopOptions, runLoop } from './run-loop'\nimport type { LoopResult, LoopTraceEmitter, SandboxClient } from './types'\n\n/** runLoop options minus the `ctx` (loopDispatch builds the ctx). */\nexport type LoopOptionsForDispatch<Task, Output, Decision> = Omit<\n RunLoopOptions<Task, Output, Decision>,\n 'ctx'\n>\n\nexport interface LoopDispatchOptions<\n Task,\n Output,\n Decision,\n TScenario extends Scenario,\n TArtifact,\n> {\n /** Sandbox client used for every cell's `runLoop`. Supplied once. */\n sandboxClient: SandboxClient\n /** Build the per-cell runLoop options from the scenario (+ profile, when\n * used with `runProfileMatrix`). */\n toLoopOptions: (\n scenario: TScenario,\n profile: AgentProfile,\n ) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the judges score. Default:\n * `result.winner?.output`. A loop with no winner yields `undefined` (judges\n * skip the cell) — but the loop's token usage is STILL reported, so the\n * integrity guard sees real activity. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace so loop\n * spans correlate with the cell. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n}\n\n/** Bridge a campaign `DispatchContext.trace` to a `LoopTraceEmitter` so every\n * `loop.*` event lands as a span under the cell's scoped trace. */\nfunction campaignTraceToLoopEmitter(trace: CampaignTraceWriter): LoopTraceEmitter {\n return {\n emit(event) {\n trace\n .span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload })\n .end()\n },\n }\n}\n\nasync function runLoopForCell<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n scenario: TScenario,\n profile: AgentProfile,\n ctx: DispatchContext,\n): Promise<TArtifact> {\n const loopOptions = opts.toLoopOptions(scenario, profile)\n return runLoopWithCampaignContext(opts, loopOptions, ctx)\n}\n\nasync function runLoopWithCampaignContext<Task, Output, Decision, TArtifact>(\n opts: {\n sandboxClient: SandboxClient\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n forwardTrace?: boolean\n costSource?: string\n },\n loopOptions: LoopOptionsForDispatch<Task, Output, Decision>,\n ctx: DispatchContext,\n): Promise<TArtifact> {\n const result = await runLoop<Task, Output, Decision>({\n ...loopOptions,\n ctx: {\n sandboxClient: opts.sandboxClient,\n signal: ctx.signal,\n traceEmitter: opts.forwardTrace === false ? undefined : campaignTraceToLoopEmitter(ctx.trace),\n },\n })\n reportLoopUsage(ctx.cost, result, opts.costSource ?? 'loop')\n const toArtifact =\n opts.toArtifact ?? ((r: LoopResult<Task, Output, Decision>) => r.winner?.output as TArtifact)\n return toArtifact(result)\n}\n\n/** Options for adapting plain agent-eval campaign scenarios into runtime `runLoop` cells. */\nexport interface LoopCampaignDispatchOptions<\n Task,\n Output,\n Decision,\n TScenario extends Scenario,\n TArtifact,\n> {\n /** Sandbox client used for every campaign cell's `runLoop`. */\n sandboxClient: SandboxClient\n /** Build the per-cell runLoop options from the campaign scenario. */\n toLoopOptions: (scenario: TScenario) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the campaign judges score. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n}\n\n/**\n * Adapter for plain `runCampaign` scenarios. This is the runtime-side pair for\n * agent-eval fixture scenarios: load fixtures in `agent-eval/campaign`, build\n * the runtime loop here, and keep cost + token + trace reporting automatic.\n */\nexport function loopCampaignDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopCampaignDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): DispatchFn<TScenario, TArtifact> {\n return (scenario, ctx) => runLoopWithCampaignContext(opts, opts.toLoopOptions(scenario), ctx)\n}\n\n/**\n * Adapter for `runProfileMatrix` (profile is an axis). Returns a\n * `ProfileDispatchFn` that runs `runLoop` per (profile, scenario) cell and\n * reports usage automatically.\n */\nexport function loopDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx)\n}\n","/**\n * createMcpEnvironment — wrap any MCP server as an `Environment` (the product-adoption\n * primitive: a product's agent tools are usually already an MCP surface, so the domain\n * only writes the lifecycle hooks — open a scoped artifact, score it with a deployable\n * check, close it — and the tool plumbing is derived from the server).\n *\n * What the helper owns (the generic 80%, hardened on the EnterpriseOps gym):\n * - JSON-RPC `tools/list` → `AgenticTool[]`, with schemas coerced to the\n * OpenAI-tool-valid shape (top-level oneOf/anyOf/allOf/enum/not are rejected by\n * tool-calling providers; nested combinators are fine).\n * - JSON-RPC `tools/call` → the tool's text content (errors surfaced as `ERROR: …`\n * strings — a bad call is the agent's outcome, not an infra fault).\n * - SSE response parsing (streamable-HTTP MCP servers answer with `data:` lines).\n * - Bounded retry with backoff on thrown fetches (transient network ≠ task failure).\n *\n * What the domain supplies: `open` (create/seed the per-task artifact and return its\n * MCP endpoint — url + headers carry the per-artifact scoping, e.g. a database id\n * header), `score` (the deployable check), and optional `close`/`selectTools`.\n */\n\nimport type { Environment } from './run-benchmark'\nimport type { AgenticTask, AgenticTool, ArtifactHandle, SurfaceScore } from './strategy'\n\n/** Where a handle's MCP server lives; headers carry per-artifact scoping. */\nexport interface McpEndpoint {\n url: string\n headers?: Record<string, string>\n}\n\nexport interface McpEnvironmentOptions {\n name: string\n /** Create/seed the per-task artifact; return its handle + the MCP endpoint scoped to it. */\n open(task: AgenticTask): Promise<{ handle: ArtifactHandle; endpoint: McpEndpoint }>\n /** The deployable check over the artifact's current state. */\n score(task: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore>\n /** Teardown (delete the seeded artifact). Optional — omit for stateless servers. */\n close?(handle: ArtifactHandle): Promise<void>\n /** Restrict/order the server's tools per task (e.g. the task's selected_tools). Default: all. */\n selectTools?(task: AgenticTask, all: AgenticTool[]): AgenticTool[]\n /** Cap on a tool result's text fed back to the worker. Default 1500 chars. */\n maxResultChars?: number\n}\n\n/** POST JSON-RPC and parse a JSON body OR the last `data:` line of an SSE stream.\n * Retries thrown fetches (transient network) with linear backoff; HTTP status and\n * JSON-RPC errors are returned to the caller, not retried. */\nasync function rpc(\n endpoint: McpEndpoint,\n body: unknown,\n): Promise<{ status: number; json: unknown }> {\n let lastErr: unknown\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try {\n const r = await fetch(endpoint.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...(endpoint.headers ?? {}) },\n body: JSON.stringify(body),\n })\n const text = await r.text()\n const dataLines = text\n .split('\\n')\n .filter((l) => l.startsWith('data:'))\n .map((l) => l.slice(5).trim())\n const payload = dataLines.length ? dataLines[dataLines.length - 1] : text\n try {\n return { status: r.status, json: JSON.parse(payload ?? 'null') }\n } catch {\n return { status: r.status, json: text }\n }\n } catch (err) {\n lastErr = err\n await new Promise((res) => setTimeout(res, 1000 * (attempt + 1)))\n }\n }\n throw new Error(\n `mcp rpc ${endpoint.url} failed after 4 attempts: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`,\n )\n}\n\n/** Coerce an MCP inputSchema to an OpenAI-tool-valid top-level object schema. */\nfunction sanitizeSchema(s: unknown): Record<string, unknown> {\n const o = s && typeof s === 'object' ? (s as Record<string, unknown>) : {}\n const banned = o.oneOf || o.anyOf || o.allOf || o.not || o.enum\n if (o.type === 'object' && !banned && o.properties && typeof o.properties === 'object') {\n return {\n type: 'object',\n properties: o.properties as Record<string, unknown>,\n ...(Array.isArray(o.required) ? { required: o.required as string[] } : {}),\n }\n }\n return { type: 'object', properties: {} }\n}\n\nexport function createMcpEnvironment(opts: McpEnvironmentOptions): Environment {\n const endpoints = new Map<string, McpEndpoint>()\n const maxChars = opts.maxResultChars ?? 1500\n\n return {\n name: opts.name,\n\n async open(task) {\n const { handle, endpoint } = await opts.open(task)\n endpoints.set(handle.id, endpoint)\n return handle\n },\n\n async tools(task, handle) {\n const endpoint = endpoints.get(handle.id)\n if (!endpoint) throw new Error(`${opts.name}: tools() before open() for ${handle.id}`)\n const { json } = await rpc(endpoint, {\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/list',\n params: {},\n })\n const all = (\n (\n json as {\n result?: {\n tools?: Array<{ name: string; description?: string; inputSchema?: unknown }>\n }\n }\n ).result?.tools ?? []\n ).map(\n (t): AgenticTool => ({\n type: 'function',\n function: {\n name: t.name,\n description: (t.description ?? '').slice(0, 1000),\n parameters: sanitizeSchema(t.inputSchema),\n },\n }),\n )\n return opts.selectTools ? opts.selectTools(task, all) : all\n },\n\n async call(handle, name, args) {\n const endpoint = endpoints.get(handle.id)\n if (!endpoint) return 'ERROR: workspace closed'\n const { json } = await rpc(endpoint, {\n jsonrpc: '2.0',\n id: 2,\n method: 'tools/call',\n params: { name, arguments: args },\n })\n const result =\n (json as {\n result?: { content?: Array<{ text?: string }>; isError?: boolean }\n error?: unknown\n }) ?? {}\n if (result.error) return `ERROR: ${JSON.stringify(result.error).slice(0, 300)}`\n const text =\n result.result?.content?.map((c) => c.text ?? '').join('\\n') ??\n JSON.stringify(result.result ?? json)\n return text.slice(0, maxChars)\n },\n\n score: (task, handle) => opts.score(task, handle),\n\n async close(handle) {\n endpoints.delete(handle.id)\n await opts.close?.(handle)\n },\n }\n}\n","/**\n * @experimental\n *\n * Analyst-on-scope (G1) — the analyze→findings→steer wire over the reactive `Scope`.\n *\n * The analyst runs over the children drained so far and hands its findings to the steer\n * decision behind a provenance firewall (`assertTraceDerivedFindings`) that keeps the external\n * write-only judge out of that decision (selector ≠ judge). The reactive `Scope` has no rounds:\n * a combinator's `act` asks a `ScopeAnalyst` to turn the children it has drained off\n * `scope.next()` SO FAR into `AnalystFinding[]`, and steers from THOSE findings through a single\n * `SteerContext`.\n *\n * The analyst itself is not a new type — it is \"just an `Agent<unknown, AnalystFinding[]>`\" the\n * combinator spawns over a child's trace (harness `null`/`cli`). `createScopeAnalyst` spawns that\n * agent through `Scope.spawn` (so its compute is metered by the conserved pool like any child),\n * drains its settlement, then enforces the firewall on the way out — a judge-derived finding\n * ABORTS, it is never filtered. Fail loud: a down analyst, a non-array result, or a tainted finding\n * throws; there is no silent empty-findings path that would let a combinator steer on nothing.\n */\n\nimport type { AnalystFinding, AnalystRunInputs } from '@tangle-network/agent-eval'\nimport type { AnalystRegistryLike } from '../../analyst-loop/types'\nimport { AnalystError, PlannerError } from '../../errors'\nimport type { Agent, Budget, DefaultVerdict, NodeId, Scope, Settled } from '../supervise/types'\nimport { stringifySafe } from '../util'\nimport type {\n AssertTraceDerivedFindings,\n Outcome,\n ScopeAnalyst,\n ScopeAnalyzeInput,\n SteerContext,\n} from './wave-types'\n\n// ── The steer firewall (selector ≠ judge) — the single canonical impl ───────\n\n/**\n * The diagnosis a combinator steers from must be TRACE-derived, never JUDGE-derived. A finding\n * whose evidence is a judge/verdict score (an `EvidenceRef` of `kind:'metric'` with a\n * verdict/judge/score uri scheme) would smuggle the external write-only judge back into steering —\n * the one coupling the architecture forbids. This is a PROVENANCE check, not a content check:\n * span/event/artifact/finding refs and empty-evidence findings are allowed; only a judge-scheme\n * metric ref is rejected. Fail loud — a tainted finding aborts.\n */\nconst judgeEvidenceUri = /^(verdict|judge|score)\\b/i\n\nexport const assertTraceDerivedFindings: AssertTraceDerivedFindings = (findings) => {\n for (const f of findings) {\n for (const ref of f.evidence_refs ?? []) {\n if (ref.kind === 'metric' && judgeEvidenceUri.test(ref.uri)) {\n throw new PlannerError(\n `steer-firewall: finding ${stringifySafe(f.finding_id)} cites judge-derived evidence ` +\n `(${stringifySafe(ref.uri)}); findings fed to a combinator's steer decision must be ` +\n 'trace-derived, not judge-derived (selector ≠ judge)',\n )\n }\n }\n }\n}\n\n// ── The reactive analyst — an Agent the combinator spawns over the trace so far ───────\n\n/**\n * The analyst run an `Agent<unknown, AnalystFinding[]>` performs over the children settled so far.\n * The combinator supplies the analyst's task projection (how to frame the drained settlements as\n * the analyst's input) — the analyst's `act` reads the trace and returns its raw findings; the\n * firewall is enforced afterwards by `createScopeAnalyst`, not by the analyst itself.\n */\nexport interface CreateScopeAnalystOptions<D> {\n /** The analyst agent the combinator spawns over the trace. `harness` is the persona's choice\n * (`null` for an inline router analyst, a `BackendType` for a sandboxed one). Its `act` returns\n * the RAW findings; this module asserts the firewall on them before returning. */\n readonly analyst: Agent<unknown, ReadonlyArray<AnalystFinding>>\n /** Build the analyst agent's task from the analyze input (the root-task framing + the children\n * drained so far). Pure projection — the analyst interprets it, this never reads it. */\n buildTask(input: ScopeAnalyzeInput<D>): unknown\n /** The conserved budget reserved for one analyst spawn. The pool reserves against it and fails\n * closed; an analyst that cannot be admitted is a fail-loud abort, never silent empty findings. */\n readonly budget: Budget\n /** Trace/journal label for the spawned analyst child. Default `'analyst'`. */\n readonly label?: string\n}\n\n/**\n * Build a `ScopeAnalyst` that spawns the analyst agent through `Scope.spawn` (so its compute is\n * metered by the conserved pool), drains its single settlement, and enforces the trace-derived\n * firewall before returning. The `scope` is the SAME scope the combinator is draining its children\n * from — the analyst is spawned as a sibling and its result is read off `scope.next()` in cursor\n * order, replay-safe like any other child.\n *\n * Fail loud (no silent empty findings):\n * - the pool refuses the analyst spawn → `AnalystError` (the steer would otherwise run on nothing)\n * - the analyst settles `down` → `AnalystError` (a broken capture path, not a verdict)\n * - the analyst returns a non-array → `PlannerError`\n * - any finding cites judge-derived metric evidence → `PlannerError` via the firewall\n */\nexport function createScopeAnalyst<D>(\n scope: Scope<Outcome<D>>,\n options: CreateScopeAnalystOptions<D>,\n): ScopeAnalyst<D> {\n if (!options.analyst || typeof options.analyst.act !== 'function') {\n throw new AnalystError('createScopeAnalyst: analyst must be an Agent with an act() method')\n }\n const label = options.label ?? 'analyst'\n return {\n async analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>> {\n const task = options.buildTask(input)\n // The analyst is spawned into the combinator's own scope so its tokens are charged to the\n // conserved pool. The pool fails closed; an analyst it cannot admit is a hard abort, not an\n // excuse to steer on an empty diagnosis. The analyst's `Out` is `AnalystFinding[]`, not the\n // scope's `Outcome<D>` — a genuinely heterogeneous child; the cast through `unknown` mirrors\n // the keystone `spawnChild` seam, and the settlement is narrowed back by `readAnalystFindings`.\n const spawned = scope.spawn(options.analyst as unknown as Agent<unknown, Outcome<D>>, task, {\n budget: options.budget,\n label,\n })\n if (!spawned.ok) {\n throw new AnalystError(\n `createScopeAnalyst: analyst spawn refused by the conserved pool (${spawned.reason}); ` +\n `cannot steer node ${stringifySafe(input.nodeId)} on an unrun analyst`,\n )\n }\n const settled = await drainAnalystSettlement(scope, spawned.handle.id)\n const findings = readAnalystFindings(settled)\n assertTraceDerivedFindings(findings)\n return findings\n },\n }\n}\n\n/**\n * Drain `scope.next()` until the analyst child's own settlement is yielded, matching on its node\n * id so an unrelated sibling that settles first is skipped, not mistaken for the analyst. A\n * `ScopeAnalyst` is invoked AFTER a combinator has drained its workers, so in practice the analyst\n * is the only live child; the id match keeps it correct even when it is not. Fails loud if the\n * scope empties before the analyst settles (the steer would otherwise run on nothing).\n */\nasync function drainAnalystSettlement<D>(\n scope: Scope<Outcome<D>>,\n analystId: NodeId,\n): Promise<Settled<Outcome<D>>> {\n for (;;) {\n const settled = await scope.next()\n if (settled === null) {\n throw new AnalystError(\n `createScopeAnalyst: scope drained before analyst ${stringifySafe(analystId)} settled`,\n )\n }\n if (settled.handle.id === analystId) return settled\n }\n}\n\n/**\n * Read the analyst child's settlement into its `AnalystFinding[]`. A `down` analyst is a broken\n * capture path (fail loud — not \"no findings\"); a `done` analyst whose `out` is not an array is a\n * malformed analyst (fail loud — the dynamic driver's `runAnalyze` contract, carried across).\n */\nfunction readAnalystFindings<D>(settled: Settled<Outcome<D>>): ReadonlyArray<AnalystFinding> {\n if (settled.kind === 'down') {\n throw new AnalystError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} settled down ` +\n `(${settled.infra ? 'infra' : 'result'}): ${stringifySafe(settled.reason)}`,\n )\n }\n const out = settled.out as unknown\n if (!Array.isArray(out)) {\n throw new PlannerError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} must return ` +\n `AnalystFinding[], got ${stringifySafe(out)}`,\n )\n }\n return out as ReadonlyArray<AnalystFinding>\n}\n\n// ── The panel-of-analysts adapter — N analyst KINDS merged into one ScopeAnalyst ───────\n\n/**\n * Project a `ScopeAnalyzeInput` into the `AnalystRegistry.run` arguments. The registry runs over a\n * `runId` + `AnalystRunInputs` (a trace store / run record / artifact dir), NOT in-memory scope\n * settlements — so the CALLER owns the projection from the combinator's drained children to the\n * registry's inputs (e.g. the trace store the run already wrote). This adapter never invents that\n * bridge; it only runs the projected inputs and firewalls the merged findings.\n */\nexport interface RegistryAnalyzeProjection {\n readonly runId: string\n readonly inputs: AnalystRunInputs\n /** Optional `run` opts (e.g. `priorFindings`) forwarded verbatim to the registry. */\n readonly opts?: Parameters<AnalystRegistryLike['run']>[2]\n}\n\n/**\n * A `ScopeAnalyst` backed by an `AnalystRegistry` — the panel-of-analysts seam. The registry merges\n * N analyst KINDS into one `AnalystRunResult.findings`; `analyze` runs it over the caller-projected\n * `{ runId, inputs }` and pipes the merged findings through the SAME `assertTraceDerivedFindings`\n * firewall `createScopeAnalyst` uses (single-sourced selector≠judge). Distinct from `panel()`\n * (judges-vs-one-artifact) — this is analysts-over-a-trace, the diagnosis side of the wire.\n *\n * Fail loud: a registry that throws propagates; a judge-derived finding aborts via the firewall.\n * The projection is the caller's (`buildInputs`) — if the scope settlements do not cleanly map to\n * the registry's `AnalystRunInputs`, that is a caller-side contract gap, surfaced there, not papered\n * over with a fabricated input here.\n */\nexport function registryScopeAnalyst<D>(\n registry: AnalystRegistryLike,\n buildInputs: (input: ScopeAnalyzeInput<D>) => RegistryAnalyzeProjection,\n): ScopeAnalyst<D> {\n return {\n async analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>> {\n const projection = buildInputs(input)\n const result = await registry.run(projection.runId, projection.inputs, projection.opts)\n const findings = result.findings\n assertTraceDerivedFindings(findings)\n return findings\n },\n }\n}\n\n// ── The single firewalled steer surface every combinator funnels through ──────────────\n\n/**\n * Build the `SteerContext` a combinator reads to steer (its `loopUntil.until`, `widen` gate, any\n * future steer). One place enforces the firewall: `findings` is asserted trace-derived before it is\n * surfaced, and `lastValidScore` is provided for OBSERVABILITY only — a combinator that steers off\n * it re-introduces selector = judge, the coupling the architecture forbids.\n *\n * `findings` is re-asserted here even when it came from `createScopeAnalyst` (which already asserted\n * it): the assertion is cheap and idempotent, and a `SteerContext` may be built from findings that\n * arrived by another path (a caller-supplied diagnosis). Belt-and-suspenders on the one coupling\n * that must never leak.\n */\nexport function buildSteerContext<D>(\n findings: ReadonlyArray<AnalystFinding>,\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): SteerContext<D> {\n assertTraceDerivedFindings(findings)\n const lastValidScore = observedBestScore(settledSoFar)\n return {\n findings,\n settledSoFar,\n ...(lastValidScore !== undefined ? { lastValidScore } : {}),\n }\n}\n\n/**\n * The best valid score among the drained children — OBSERVABILITY ONLY. Read for rendering/traces,\n * never to make a steer decision (that is the selector = judge coupling). Reads `verdict.score` off\n * `done` settlements whose verdict is `valid`; a `down` child carries no verdict and contributes\n * nothing.\n */\nfunction observedBestScore<D>(\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): number | undefined {\n let best: number | undefined\n for (const s of settledSoFar) {\n if (s.kind !== 'done') continue\n const v: DefaultVerdict | undefined = s.verdict\n if (!v || v.valid !== true || typeof v.score !== 'number') continue\n if (best === undefined || v.score > best) best = v.score\n }\n return best\n}\n","/**\n * @experimental\n *\n * The generic combinator library — the content-free act-bodies the wave's §1 contract froze.\n *\n * Each export is a `CombinatorShape<Task, D>` (an alias of `LoopShape<Task, D>`): a factory\n * `(ShapeContext) => Agent<Task, Outcome<D>>` whose `act` runs ONE composition shape over the\n * keystone `Scope` — spawn children through `ctx.spawnChild` + `scope.spawn`, drain settlements\n * via `scope.next()`, select across `done` children with the SINGLE-SOURCED `settledToIteration`\n * + `defaultSelectWinner` (selector≠judge — never a re-rank behind the driver), and synthesize a\n * terminal `Outcome<D>`.\n *\n * The shapes carry NO domain: a \"research sweep over angles\" is `fanout(angles, { synthesize })`\n * under a research persona; a \"code build test\" is `pipeline([plan, implement, integrate])` under\n * a coder persona. The SHAPE is here; the model/prompt/role/goal live on the `Persona` + task,\n * threaded to each child verbatim by the spec-objects the builders take. No model name, prompt,\n * role, or domain noun appears below.\n *\n * Two fail-loud invariants every combinator honors: a child the conserved pool cannot admit is a\n * CONCRETE blocker (never an eager over-fan, never a silent drop), and a `blocked` outcome always\n * names at least one blocker (a shape that cannot finish MUST say why — `blocked([])` throws).\n */\n\nimport { ValidationError } from '../../errors'\nimport { defaultSelectWinner } from '../run-loop'\nimport { settledToIteration } from '../supervise/scope'\nimport type { Agent, Scope, Settled } from '../supervise/types'\nimport type { Iteration } from '../types'\nimport type { Outcome, ShapeContext } from './types'\nimport type {\n CombinatorShape,\n FanoutOptions,\n FanoutWinnerSelector,\n LoopUntilSpec,\n LoopUntilState,\n PanelJudge,\n PanelSpec,\n PanelVerdict,\n PipelineStage,\n ScopeWidenGate,\n VerifySpec,\n WidenDecision,\n WidenSpec,\n WinnerStrategy,\n} from './wave-types'\n\n// ── selectValidWinner — the one shared valid-only fanout selector ─────────────────\n\n/**\n * The single content-free valid-only winner selector. Among the gated-VALID children only\n * (`verdict.valid === true`), pick by `strategy` — best score / smallest delivered artifact /\n * earliest — ties broken by earliest index; returns `undefined` when NONE is valid (an ungated\n * output can never win — the deliverable gate is the point). `sizeOf` (for `'smallest-artifact'`)\n * reads the child's settled deliverable — the raw value a leaf settles, or the unwrapped `Outcome<D>`\n * a delegate path produces; a domain passes e.g. patch diff-lines. This is the de-duplicated home of\n * the selection logic previously copied per role.\n */\nexport function selectValidWinner<D>(opts?: {\n strategy?: WinnerStrategy\n sizeOf?: (deliverable: D) => number\n}): FanoutWinnerSelector<D> {\n const strategy = opts?.strategy ?? 'highest-score'\n const sizeOfIter = (iter: Iteration<unknown, Outcome<D>>): number => {\n const out = iter.output\n if (out === undefined || opts?.sizeOf === undefined) return Number.POSITIVE_INFINITY\n // The worktree-CLI leaf settles the RAW deliverable as iter.output (settledToIteration sets\n // `output = settled.out`); the MCP delegate path wraps it in an Outcome<D>. Accept both: unwrap\n // a `done` Outcome, else the settled value IS the deliverable. A raw artifact carries no `kind`\n // discriminant, so the branch is unambiguous.\n const deliverable = out.kind === 'done' ? out.deliverable : (out as unknown as D)\n return opts.sizeOf(deliverable)\n }\n return (iterations) => {\n const valid = iterations.filter(\n (iter) => iter.output !== undefined && !iter.error && iter.verdict?.valid === true,\n )\n if (valid.length === 0) return undefined\n switch (strategy) {\n case 'first-valid':\n return [...valid].sort((a, b) => a.index - b.index)[0]\n case 'smallest-artifact':\n return [...valid].sort((a, b) => sizeOfIter(a) - sizeOfIter(b) || a.index - b.index)[0]\n default:\n return [...valid].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )[0]\n }\n }\n}\n\n// ── pipeline — sequential composition, first blocked stage short-circuits ─────────\n\n/**\n * `pipeline(stages)` — run the stages in order, feeding each stage's `done` deliverable into the\n * next stage's task. The first stage that ends `blocked` (a child that went down, a child the\n * pool would not admit, or a stage whose `collect` chose to block) short-circuits — its blockers\n * ARE the pipeline's blockers, never coerced past a failed stage. The terminal stage's `done`\n * deliverable is the pipeline's deliverable.\n */\nexport function pipeline<Task, D>(\n stages: ReadonlyArray<PipelineStage<Task, unknown, unknown>>,\n): CombinatorShape<Task, D> {\n if (stages.length === 0) {\n throw new ValidationError('pipeline: at least one stage is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/pipeline`,\n async act(task, scope): Promise<Outcome<D>> {\n let carry: unknown = task\n for (const stage of stages) {\n const child = ctx.spawnChild(stage.label, ctx.persona.root)\n const res = scope.spawn(child, stage.feed(carry, ctx, task), {\n budget: ctx.budget.perChild,\n label: stage.label,\n })\n if (!res.ok) {\n return blocked([`${stage.label}: not admitted (${res.reason})`])\n }\n const settled = await drainOne(scope, stage.label)\n const out = stage.collect(settled as Settled<Outcome<unknown>>)\n if (out.kind === 'blocked') return out\n carry = out.deliverable\n }\n return { kind: 'done', deliverable: carry as D }\n },\n })\n}\n\n// ── fanout — N children in one round, optional single synthesis child ─────────────\n\n/**\n * `fanout(items, opts)` — spawn one child per item in a single round (bounded by the conserved\n * pool's fail-closed admission), drain via `scope.next()`, then either synthesize over the\n * gathered settlements (one SEPARATE synthesis child) or return the best-valid child via the\n * single-sourced selector. A round that admitted zero children, or whose synthesis child could\n * not be admitted, is a concrete blocker.\n */\nexport function fanout<Task, Item, D>(\n items: ReadonlyArray<Item>,\n opts: FanoutOptions<Item, D>,\n): CombinatorShape<Task, D> {\n if (opts.synthesize && opts.selectWinner) {\n throw new ValidationError('fanout: pass at most one of `synthesize` or `selectWinner`')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/fanout`,\n async act(_task, scope): Promise<Outcome<D>> {\n const rejected: string[] = []\n let opened = 0\n for (const [i, item] of items.entries()) {\n const label = opts.label ? opts.label(item, i) : `item:${i}`\n const spec = opts.itemSpec ? opts.itemSpec(item, i, ctx) : ctx.persona.root\n const child = ctx.spawnChild(label, spec)\n const res = scope.spawn(child, opts.itemTask(item, i, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (res.ok) opened += 1\n else rejected.push(`${label}: not admitted (${res.reason})`)\n }\n if (opened === 0) {\n return blocked(\n rejected.length > 0\n ? rejected\n : ['fanout: budget admitted no item (fanout fully rejected)'],\n )\n }\n\n const drained = await drain<D>(scope)\n if (drained.done.length === 0) {\n return blocked(\n orderedBlockers(\n drained.blockers,\n rejected,\n 'fanout: every item settled without a usable result',\n ),\n )\n }\n\n if (!opts.synthesize) {\n const select = opts.selectWinner ?? defaultSelectWinner\n const winner = select(drained.iterations)\n if (!winner || winner.output === undefined) {\n return blocked(\n orderedBlockers(drained.blockers, rejected, 'fanout: no item survived selection'),\n )\n }\n return { kind: 'done', deliverable: winner.output as D }\n }\n\n const synthLabel = 'synthesize'\n const synthChild = ctx.spawnChild(synthLabel, ctx.persona.root)\n const synthRes = scope.spawn(synthChild, opts.synthesize.synthesisTask(drained.done, ctx), {\n budget: ctx.budget.perChild,\n label: synthLabel,\n })\n if (!synthRes.ok) {\n return blocked([...drained.blockers, `${synthLabel}: not admitted (${synthRes.reason})`])\n }\n const synthSettled = await drainOne(scope, synthLabel)\n const out = opts.synthesize.collect(synthSettled)\n if (out.kind === 'blocked') return out\n return out\n },\n })\n}\n\n// ── loopUntil — budget-bounded iterative deepening, deployable non-oracle stop ────\n\n/**\n * `loopUntil(seed, spec)` — one `step` child per round; `fold` accumulates each settlement into\n * the running state; `until` (reading the round's trace findings, NOT a fresh raw verdict) is\n * the deployable stop. The conserved pool IS the loop bound: once `spawn` fails closed the loop\n * stops. A loop that exhausted the pool without `until` ever satisfying is a concrete blocker.\n *\n * When `ctx.analyst` is set, each round runs it over the children settled so far and steers\n * `until` on the resulting trace-derived findings (the analyst spawns into THIS scope, so its\n * compute is conserved-pooled — equal-k holds by construction). Absent an analyst the findings\n * argument is the empty array — never a fabricated finding (fail-loud honesty over a silent default).\n */\nexport function loopUntil<Task, State, D>(\n seed: State,\n spec: LoopUntilSpec<Task, State, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/loopUntil`,\n async act(task, scope): Promise<Outcome<D>> {\n let state: LoopUntilState<State> = { round: 0, value: seed }\n const blockers: string[] = []\n const settledSoFar: Settled<Outcome<D>>[] = []\n for (;;) {\n const label = spec.label ? spec.label(state.round) : `step:${state.round}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.step(task, state, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (!res.ok) {\n if (state.round === 0) return blocked([`${label}: not admitted (${res.reason})`])\n break\n }\n const settled = await drainOne(scope, label)\n if (settled.kind === 'down') blockers.push(blockerFromDown(settled))\n settledSoFar.push(settled)\n state = spec.fold(state, settled)\n // Wired analyst ⇒ steer `until` on trace-derived findings; absent ⇒ the dormant empty\n // default (the analyst spawns into THIS scope, so its compute is conserved-pooled).\n const findings = ctx.analyst\n ? await ctx.analyst.analyze({ task, settledSoFar, nodeId: scope.view.root })\n : []\n const reached = spec.until(state, findings)\n if (reached) return reached\n state = { round: state.round + 1, value: state.value }\n }\n return blocked(\n blockers.length > 0\n ? blockers\n : ['loopUntil: budget exhausted before the satisfiability gate was reached'],\n )\n },\n })\n}\n\n// ── panel — M judges over ONE artifact, write-only merge (selector≠judge limit) ───\n\n/**\n * `panel(spec)` — spawn the M judge children over the SAME artifact, drain their settlements,\n * and fold them into a panel verdict via the pure WRITE-ONLY `merge` (a judge's output never\n * reaches another judge's task; the merge never spawns or re-ranks). A `down` judge carries no\n * verdict and is excluded from the merge denominator. A panel that admitted no judge is a\n * concrete blocker before `merge` is consulted.\n */\nexport function panel<Task, Artifact, D>(spec: PanelSpec<Artifact, D>): CombinatorShape<Task, D> {\n if (spec.judges.length === 0) {\n throw new ValidationError('panel: at least one judge is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/panel`,\n async act(task, scope): Promise<Outcome<D>> {\n const artifact = task as unknown as Artifact\n const byLabel = new Map<string, PanelJudge>()\n const rejected: string[] = []\n let opened = 0\n for (const judge of spec.judges) {\n const child = ctx.spawnChild(judge.label, ctx.persona.root)\n const res = scope.spawn(child, spec.judgeTask(artifact, judge, ctx), {\n budget: ctx.budget.perChild,\n label: judge.label,\n })\n if (res.ok) {\n byLabel.set(judge.label, judge)\n opened += 1\n } else {\n rejected.push(`${judge.label}: not admitted (${res.reason})`)\n }\n }\n if (opened === 0) {\n return blocked(rejected.length > 0 ? rejected : ['panel: budget admitted no judge'])\n }\n\n const verdicts: PanelVerdict[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n const judge = byLabel.get(s.handle.label)\n if (!judge) {\n throw new ValidationError(\n `panel: settled child \"${s.handle.label}\" has no judge descriptor`,\n )\n }\n if (s.kind === 'down') {\n verdicts.push({ judge, down: true })\n continue\n }\n verdicts.push({\n judge,\n down: false,\n ...(s.verdict ? { verdict: s.verdict } : {}),\n output: s.out,\n })\n }\n return spec.merge(verdicts, artifact)\n },\n })\n}\n\n// ── verify — 2-node implement→verifier gate (selector≠judge) ──────────────────────\n\n/**\n * `verify(spec)` — an IMPLEMENT child produces a candidate, then a SEPARATE VERIFIER child grades\n * it; only a `valid` verifier verdict ships. Any other outcome (implement down, verifier down,\n * verifier verdict absent or not `valid`) is a concrete blocker carrying the failure verbatim —\n * never a coerced \"done\". The implement child does not grade itself.\n */\nexport function verify<Task, Candidate, D>(\n spec: VerifySpec<Task, Candidate, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/verify`,\n async act(task, scope): Promise<Outcome<D>> {\n const implementLabel = spec.implementLabel ?? 'implement'\n const implChild = ctx.spawnChild(implementLabel, ctx.persona.root)\n const implRes = scope.spawn(implChild, spec.implement(task, ctx), {\n budget: ctx.budget.perChild,\n label: implementLabel,\n })\n if (!implRes.ok) return blocked([`${implementLabel}: not admitted (${implRes.reason})`])\n const candidate = await drainOne(scope, implementLabel)\n if (candidate.kind === 'down') return blocked([blockerFromDown(candidate)])\n\n const verifierLabel = spec.verifierLabel ?? 'verify'\n const verifierChild = ctx.spawnChild(verifierLabel, ctx.persona.root)\n const verifierRes = scope.spawn(\n verifierChild,\n spec.verifier(candidate as Settled<Outcome<Candidate>>, ctx),\n { budget: ctx.budget.perChild, label: verifierLabel },\n )\n if (!verifierRes.ok)\n return blocked([`${verifierLabel}: not admitted (${verifierRes.reason})`])\n const gate = await drainOne(scope, verifierLabel)\n if (gate.kind === 'down') return blocked([blockerFromDown(gate)])\n if (!gate.verdict || gate.verdict.valid !== true) {\n return blocked([`${verifierLabel}: gate rejected the candidate (${verdictDetail(gate)})`])\n }\n return spec.collect(candidate as Settled<Outcome<Candidate>>, gate.verdict)\n },\n })\n}\n\n// ── widen — streaming progressive widening (G5), FLAT by default ──────────────────\n\n/**\n * `widen(spec)` — the streaming spawn-on-completion driver. Spawns the seed lineages, then REACTS\n * to each `scope.next()`: on every settled child it consults `spec.gate.decide` and, when the gate\n * returns `widen`, spawns AT MOST ONE more child toward the chosen lineage under the remaining\n * conserved pool. `promising` is derived from the round's trace findings (the analyst seam),\n * never a child's raw `verdict` — and the default gate (`flatWidenGate`) never widens, so the R2\n * firewall stays dormant. Terminal selection is `spec.synthesize` over every settled lineage.\n *\n * When `ctx.analyst` is set, `decide` is consulted with that round's trace-derived findings;\n * absent an analyst the findings argument is the empty array a flat gate ignores. The analyst\n * spawns into THIS scope (conserved-pooled, so equal-k holds). Streaming caveat: a wired analyst\n * drains its own child off the SHARED cursor by id-match, so on a NON-flat gate (which spawns\n * widen children that are live concurrently) the analyst can consume a sibling's settlement before\n * the widen loop sees it. The shipped default (`flatWidenGate`) never widens, so no widen child is\n * ever live when the analyst runs and the wire is exact; a non-flat gate must drive the analyst on\n * a scope whose siblings are quiesced, or read findings without the shared-cursor drain.\n */\nexport function widen<Task, Seed, D>(spec: WidenSpec<Seed, D>): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/widen`,\n async act(_task, scope): Promise<Outcome<D>> {\n let opened = 0\n for (const [i, seed] of spec.seeds.entries()) {\n const label = `seed:${i}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.seedTask(seed, i, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (res.ok) opened += 1\n }\n if (opened === 0) {\n return blocked(['widen: budget admitted no seed lineage'])\n }\n\n const gathered: Settled<Outcome<D>>[] = []\n let widenIndex = 0\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n gathered.push(s)\n // Wired analyst ⇒ steer the gate on trace-derived findings; absent ⇒ the dormant empty\n // default the flat gate ignores. The analyst spawns into THIS scope (conserved-pooled).\n const findings = ctx.analyst\n ? await ctx.analyst.analyze({\n task: _task,\n settledSoFar: gathered,\n nodeId: scope.view.root,\n })\n : []\n const decision: WidenDecision<D> = spec.gate.decide(s, findings, scope.budget)\n if (decision.kind !== 'widen') continue\n const label = `widen:${widenIndex}`\n widenIndex += 1\n const child = ctx.spawnChild(label, ctx.persona.root)\n // Fail-closed admission bounds the widening — a rejected widen is simply not opened\n // (the gate may widen again off a later settlement); the budget is the breadth bound.\n scope.spawn(child, spec.widenTask(decision.toward, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n }\n\n const done = gathered.filter(isDone)\n if (done.length === 0) {\n return blocked(\n orderedBlockers(\n gathered.filter(isDown).map(blockerFromDown),\n [],\n 'widen: every lineage settled without a usable result',\n ),\n )\n }\n return spec.synthesize(done, ctx)\n },\n })\n}\n\n/**\n * The flat default `ScopeWidenGate` — never widens, keeping the R2 selector≠judge collision\n * dormant. A gate run passes this explicitly; a test asserts the default is flat.\n */\nexport function flatWidenGate<D>(): ScopeWidenGate<D> {\n return {\n decide(): WidenDecision<D> {\n return { kind: 'stop' }\n },\n }\n}\n\n// ── Shared drain / select / blocker microstructure ────────────────────────────────\n\n/** Drain every remaining settlement: project `done` children into kernel `Iteration`s for the\n * single-sourced selector + keep the `done` settlements (for a synthesis child), and collect\n * `down` children as concrete blockers (their reason surfaced verbatim). */\nasync function drain<D>(scope: Scope<Outcome<D>>): Promise<{\n iterations: Iteration<unknown, Outcome<D>>[]\n done: Settled<Outcome<D>>[]\n blockers: string[]\n}> {\n const iterations: Iteration<unknown, Outcome<D>>[] = []\n const done: Settled<Outcome<D>>[] = []\n const blockers: string[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n if (s.kind === 'down') {\n blockers.push(blockerFromDown(s))\n continue\n }\n iterations.push(settledToIteration(s))\n done.push(s)\n }\n return { iterations, done, blockers }\n}\n\n/**\n * Drain exactly one settlement off a scope whose prior children are fully drained, so `next()`\n * yields precisely the child just spawned. Fail loud if it yields nothing — a spawned child that\n * never settles is a keystone invariant violation, not a result the combinator may swallow.\n */\nasync function drainOne<D>(scope: Scope<Outcome<D>>, label: string): Promise<Settled<Outcome<D>>> {\n const s = await scope.next()\n if (s === null) {\n throw new ValidationError(`combinator: child \"${label}\" was spawned but never settled`)\n }\n return s\n}\n\nfunction isDone<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'done' }> {\n return s.kind === 'done'\n}\n\nfunction isDown<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'down' }> {\n return s.kind === 'down'\n}\n\nfunction blockerFromDown<D>(s: Extract<Settled<Outcome<D>>, { kind: 'down' }>): string {\n return `${s.handle.label}: ${s.infra ? 'infra' : 'failed'} — ${s.reason}`\n}\n\nfunction verdictDetail<D>(s: Extract<Settled<Outcome<D>>, { kind: 'done' }>): string {\n if (!s.verdict) return 'no verdict'\n return s.verdict.notes ?? `score ${s.verdict.score}`\n}\n\n/** Compose the round's drained blockers + rejected-admission reasons, falling back to a named\n * default ONLY when neither produced a reason — a `blocked` outcome must never be vacuous. */\nfunction orderedBlockers(drained: string[], rejected: string[], fallback: string): string[] {\n const all = [...drained, ...rejected]\n return all.length > 0 ? all : [fallback]\n}\n\n/** Build a `blocked` outcome, failing loud on the empty-blocker contract violation (a shape that\n * cannot finish MUST name at least one concrete blocker — never a vacuous block). */\nfunction blocked<D>(blockers: string[]): Extract<Outcome<D>, { kind: 'blocked' }> {\n if (blockers.length === 0) {\n throw new ValidationError('combinator: a blocked outcome must name at least one blocker')\n }\n return { kind: 'blocked', blockers }\n}\n","/**\n * @experimental\n *\n * The cross-run corpus (G2) — the learning-flywheel's durable accreted-fact store.\n *\n * `Corpus` is DISTINCT from the per-run `SpawnJournal` (decisions/replay) and `ResultBlobStore`\n * (payloads): a `CorpusRecord` is a FACT one run LEARNED that a FUTURE run reads back (the\n * world-model), not a replay input. This module owns the two impls the wave surface pins —\n * `InMemoryCorpus` and `FileCorpus` (JSONL, append-only) — plus `renderCorpusToInstructions`,\n * the READ side that projects accreted facts into a fresh `AgentProfile`'s instruction seams.\n *\n * The boundary is fail-loud, typed-outcome: `append` is idempotent on an identical record and\n * returns a typed error (never throws, never a silent overwrite) on a conflicting re-append under\n * the same `id`. Malformed records — a structurally-invalid `CorpusRecord` from disk or a caller —\n * fail loud (the validator throws), since a corpus that silently accepts garbage would poison\n * every downstream run that reads it back.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type {\n Corpus,\n CorpusFilter,\n CorpusRecord,\n RenderCorpusToInstructionsOptions,\n} from './wave-types'\n\n// ── Record validation ────────────────────────────────────────────────────────\n\nconst corpusSchemaVersion = '1.0.0'\n\n/**\n * Assert a value is a well-formed `CorpusRecord`. A PROVENANCE-and-shape check: every\n * identity/render-gating field must be present and typed, `confidence` must be a finite 0..1,\n * `evidence` (when present) must be `{ kind, uri }[]`. Throws on any violation — a corpus that\n * silently accepted a malformed fact would project garbage into a future run's prompt. The\n * thrown message names the offending field so a bad on-disk line is diagnosable.\n */\nexport function assertCorpusRecord(value: unknown, where: string): asserts value is CorpusRecord {\n if (typeof value !== 'object' || value === null) {\n throw new Error(`${where}: corpus record is not an object`)\n }\n const r = value as Record<string, unknown>\n if (r.schemaVersion !== corpusSchemaVersion) {\n throw new Error(\n `${where}: corpus record schemaVersion '${String(r.schemaVersion)}' != '${corpusSchemaVersion}'`,\n )\n }\n requireNonEmptyString(r.id, `${where}.id`)\n requireNonEmptyString(r.runId, `${where}.runId`)\n requireNonEmptyString(r.producedAt, `${where}.producedAt`)\n requireNonEmptyString(r.area, `${where}.area`)\n requireNonEmptyString(r.claim, `${where}.claim`)\n if (r.rationale !== undefined && typeof r.rationale !== 'string') {\n throw new Error(`${where}.rationale: expected string, got ${typeof r.rationale}`)\n }\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new Error(`${where}.tags: expected string[]`)\n }\n if (typeof r.confidence !== 'number' || !Number.isFinite(r.confidence)) {\n throw new Error(`${where}.confidence: expected a finite number, got ${String(r.confidence)}`)\n }\n if (r.confidence < 0 || r.confidence > 1) {\n throw new Error(`${where}.confidence: ${r.confidence} is outside the [0, 1] range`)\n }\n if (r.evidence !== undefined) {\n if (!Array.isArray(r.evidence)) {\n throw new Error(`${where}.evidence: expected an array`)\n }\n for (let i = 0; i < r.evidence.length; i++) {\n const ev = r.evidence[i] as Record<string, unknown> | null\n if (typeof ev !== 'object' || ev === null) {\n throw new Error(`${where}.evidence[${i}]: not an object`)\n }\n requireNonEmptyString(ev.kind, `${where}.evidence[${i}].kind`)\n requireNonEmptyString(ev.uri, `${where}.evidence[${i}].uri`)\n }\n }\n}\n\nfunction requireNonEmptyString(value: unknown, where: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${where}: expected a non-empty string, got ${describe(value)}`)\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return 'undefined'\n if (value === null) return 'null'\n if (typeof value === 'string') return `'${value}'`\n return typeof value\n}\n\n// ── Identity + idempotence ───────────────────────────────────────────────────\n\n/**\n * Two records collide IFF they share an `id`. An append under an already-stored `id` is idempotent\n * only when the new record is byte-identical to the stored one (same fact, re-learned); any other\n * field differing under the same `id` is a CONFLICT — a typed-error append, never a silent\n * overwrite. The identity field is `id`; the producer mints it over its identity-defining fields\n * (claim + tags) so a re-learned fact dedups.\n */\nfunction recordsEqual(a: CorpusRecord, b: CorpusRecord): boolean {\n return stableStringify(a) === stableStringify(b)\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Query ─────────────────────────────────────────────────────────────────────\n\n/**\n * Apply a `CorpusFilter` as an AND-narrowing over a record list and sort most-confident first\n * (ties → most-recent `producedAt`, so the freshest of two equally-confident facts wins). Pure —\n * the in-mem and file impls both route their reads through this so query semantics are\n * single-sourced. An empty result is valid (not an error).\n */\nfunction applyFilter(\n records: ReadonlyArray<CorpusRecord>,\n filter: CorpusFilter,\n): ReadonlyArray<CorpusRecord> {\n const matched = records.filter((r) => {\n if (filter.area !== undefined && r.area !== filter.area) return false\n if (filter.runId !== undefined && r.runId !== filter.runId) return false\n if (filter.minConfidence !== undefined && r.confidence < filter.minConfidence) return false\n if (filter.tags !== undefined && !filter.tags.every((t) => r.tags.includes(t))) return false\n return true\n })\n const ordered = [...matched].sort((a, b) =>\n b.confidence !== a.confidence\n ? b.confidence - a.confidence\n : b.producedAt < a.producedAt\n ? -1\n : b.producedAt > a.producedAt\n ? 1\n : 0,\n )\n if (filter.limit !== undefined) {\n if (!Number.isInteger(filter.limit) || filter.limit < 0) {\n throw new Error(\n `corpus query: filter.limit must be a non-negative integer, got ${filter.limit}`,\n )\n }\n return ordered.slice(0, filter.limit)\n }\n return ordered\n}\n\n// ── In-memory corpus ────────────────────────────────────────────────────────\n\n/**\n * In-memory `Corpus`. Keyed by record `id`; `append` validates the record, is idempotent on an\n * identical re-append, and returns a typed `{ succeeded: false }` on a conflicting re-append under\n * the same `id` (never overwrites). `query` routes through the single-sourced `applyFilter`.\n */\nexport class InMemoryCorpus implements Corpus {\n private readonly byId = new Map<string, CorpusRecord>()\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n try {\n assertCorpusRecord(record, 'append: record')\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n const existing = this.byId.get(record.id)\n if (existing) {\n if (recordsEqual(existing, record)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${record.id}' is already stored with a different record; ` +\n 'a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n this.byId.set(record.id, freeze(record))\n return { succeeded: true }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n return applyFilter([...this.byId.values()], filter)\n }\n}\n\n// ── File corpus (JSONL, append-only) ──────────────────────────────────────────\n\n/**\n * JSONL on disk — one validated `CorpusRecord` per line, append-only. `query` replays the whole\n * file, validating every line (a malformed line fails loud — a corrupted corpus must never read\n * back silently) and folding by `id`: a later identical line dedups, a later conflicting line\n * under the same `id` is a corruption (fail loud). `append` first replays to enforce the same\n * idempotence/conflict contract as the in-mem impl, then fsyncs the new line so a crash between\n * writes never loses an acknowledged fact. Shares the JSONL append-line spine with the spawn\n * journal, but the interface stays separate (a learned fact is not a replay record).\n */\nexport class FileCorpus implements Corpus {\n constructor(private readonly path: string) {}\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n try {\n assertCorpusRecord(record, 'append: record')\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n let stored: Map<string, CorpusRecord>\n try {\n stored = await this.load()\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n const existing = stored.get(record.id)\n if (existing) {\n if (recordsEqual(existing, record)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${record.id}' is already stored in ${this.path} with a different ` +\n 'record; a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n await this.appendLine(record)\n return { succeeded: true }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n const stored = await this.load()\n return applyFilter([...stored.values()], filter)\n }\n\n private async load(): Promise<Map<string, CorpusRecord>> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return new Map()\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n const byId = new Map<string, CorpusRecord>()\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] as string\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new Error(\n `corpus corrupted: ${this.path} line ${i + 1} is not valid JSON: ` +\n (err instanceof Error ? err.message : String(err)),\n )\n }\n assertCorpusRecord(parsed, `corpus ${this.path} line ${i + 1}`)\n const existing = byId.get(parsed.id)\n if (existing && !recordsEqual(existing, parsed)) {\n throw new Error(\n `corpus corrupted: ${this.path} has two different records for id '${parsed.id}'; ` +\n 'an append-only corpus must never hold a conflicting re-append under one id',\n )\n }\n byId.set(parsed.id, freeze(parsed))\n }\n return byId\n }\n\n private async appendLine(record: CorpusRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\n// ── Render-back: project accreted facts into a profile's instruction seams ─────\n\n/**\n * The learning-flywheel READ side. Queries the corpus through `filter`, renders the matching facts\n * (most-confident first, capped by `maxLines`) into instruction lines, and returns a FRESH\n * `AgentProfile` with them merged in — never mutates the input profile. Default `target: 'prompt'`\n * appends the lines to `prompt.instructions[]` (the additive append-line seam); `target:\n * 'resources'` folds them into the single-blob `resources.instructions` string (preserving any\n * existing blob, but failing loud on a non-string existing blob — a `resources.instructions` that\n * was already an `AgentProfileResourceRef` cannot be string-appended without dropping it).\n *\n * An empty query result returns a fresh COPY of the profile with no instruction change (a valid\n * \"nothing learned yet\" read, not an error).\n */\nexport async function renderCorpusToInstructions(\n opts: RenderCorpusToInstructionsOptions,\n): Promise<AgentProfile> {\n const { corpus, filter, profile, target = 'prompt', maxLines } = opts\n if (maxLines !== undefined && (!Number.isInteger(maxLines) || maxLines < 0)) {\n throw new Error(\n `renderCorpusToInstructions: maxLines must be a non-negative integer, got ${maxLines}`,\n )\n }\n const matched = await corpus.query(filter)\n const capped = maxLines !== undefined ? matched.slice(0, maxLines) : matched\n const lines = capped.map(renderLine)\n\n if (lines.length === 0) return structuredClone(profile)\n\n const next = structuredClone(profile)\n if (target === 'resources') {\n const resources = next.resources ?? {}\n const prior = resources.instructions\n if (prior !== undefined && typeof prior !== 'string') {\n throw new Error(\n 'renderCorpusToInstructions: resources.instructions is an AgentProfileResourceRef, not a ' +\n 'string; cannot string-append corpus facts without dropping the ref (pass target: ' +\n \"'prompt' or pre-resolve the ref)\",\n )\n }\n const blob = [prior, ...lines].filter((s): s is string => typeof s === 'string' && s.length > 0)\n next.resources = { ...resources, instructions: blob.join('\\n') }\n return next\n }\n\n const prompt = next.prompt ?? {}\n next.prompt = { ...prompt, instructions: [...(prompt.instructions ?? []), ...lines] }\n return next\n}\n\n/** One corpus fact → one instruction line. The claim is the line; a rationale (when present) is\n * appended in parentheses so a reader sees the why without a second line. Content-only — no\n * metric/score/verdict text is synthesized (the corpus holds facts, not selector evidence). */\nfunction renderLine(record: CorpusRecord): string {\n return record.rationale ? `${record.claim} (${record.rationale})` : record.claim\n}\n\n// ── Internal helpers ───────────────────────────────────────────────────────────\n\nfunction freeze(record: CorpusRecord): CorpusRecord {\n return Object.freeze({ ...record })\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n * @experimental\n *\n * The loop-shape registry — the OPEN, content-free extension point for the personify layer.\n *\n * A `LoopShape` is reusable STRUCTURE (how to decompose / fan out / verify / synthesize),\n * parameterized by a persona's CONTENT. The registry lets a caller resolve a composed shape by\n * NAME: register a factory once, then `runPersonified({ shape: '<name>' })` resolves it with zero\n * edits elsewhere. `register` fails loud on a duplicate; `resolve` returns a typed outcome so an\n * unknown name is a named error, never a silent default.\n *\n * No shape is pre-registered: the generic combinators (`pipeline`/`fanout`/`loopUntil`/`panel`/\n * `verify`/`widen`) take spec arguments, so they are not bare zero-arg factories — a caller that\n * wants name-resolution registers its own COMPOSED shape (a combinator already applied to its\n * spec) on a registry instance. The registry carries SHAPE only; the domain lives on the persona.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { LoopShape, ShapeRegistry } from './types'\n\n/**\n * Build a fresh open `ShapeRegistry`. A factory is stored type-erased and re-cast on resolve — the\n * caller asserts the `<Task, D>` it expects, exactly as the executor registry stores its factories.\n */\nexport function createShapeRegistry(): ShapeRegistry {\n const shapes = new Map<string, LoopShape<unknown, unknown>>()\n return {\n register<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n if (shapes.has(name)) {\n throw new ValidationError(`shape registry: shape \"${name}\" already registered`)\n }\n shapes.set(name, factory as LoopShape<unknown, unknown>)\n },\n resolve<Task, D>(name: string) {\n const factory = shapes.get(name)\n if (!factory) {\n return { succeeded: false as const, error: `shape registry: unknown shape \"${name}\"` }\n }\n return { succeeded: true as const, value: factory as LoopShape<Task, D> }\n },\n names(): string[] {\n return [...shapes.keys()]\n },\n }\n}\n\n/** The default registry `runPersonified` resolves a shape name against. Empty by construction —\n * a caller registers its own composed shapes; the engine ships no domain shape. */\nexport const builtinShapes: ShapeRegistry = createShapeRegistry()\n\n/** Register a composed shape on the default `builtinShapes` registry — the one-call extension\n * point a caller invokes so its shape is resolvable by name with zero edits to the engine. */\nexport function registerShape<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n builtinShapes.register(name, factory)\n}\n","/**\n * @experimental\n *\n * The personify layer impl — `definePersona` (the thin builder) + `runPersonified` (composes\n * the persona + chosen shape onto the keystone `Supervisor`), plus `createShapeContext`, the\n * seam that hands a shape its spawn helpers without it touching the registry.\n *\n * This file adds NO engine: `runPersonified` is `createSupervisor().run(rootAgent, task, …)`\n * where `rootAgent` is the persona's chosen `LoopShape` applied to a `ShapeContext`. All the\n * conserved-budget / journal / abort / typed-result machinery is the keystone's; this layer\n * only wires the persona's CONTENT (root spec + directive + context + seams) into it.\n *\n * One non-obvious invariant it must honor: `createSupervisor().run` builds the root `Scope`\n * with an EMPTY seam bag (`seams: {}`), so the built-in metered runtimes (router/sandbox/cli)\n * cannot read their seams off `ExecutorContext` through the default supervisor path. A persona\n * that supplies raw `seams` is therefore wrapped here into a registry whose resolved factories\n * receive a ctx with the persona seams merged in — so a persona never has to pre-close its\n * factories by hand. A persona may instead supply a fully-built `registry` and skip the wrap.\n */\n\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { withDriverExecutor } from '../supervise/driver-executor'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createSupervisor } from '../supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n Runtime,\n SupervisedResult,\n SupervisorOpts,\n} from '../supervise/types'\nimport { builtinShapes } from './registry'\nimport type {\n DefinePersonaInput,\n LoopShape,\n Outcome,\n Persona,\n RunPersonifiedOptions,\n ShapeBudget,\n ShapeContext,\n} from './types'\nimport type { ScopeAnalyst } from './wave-types'\n\n// ── definePersona ─────────────────────────────────────────────────────────────\n\n/**\n * Build a frozen `Persona`. Fails loud on the executors-supplied invariant: a persona with\n * neither a pre-built registry nor a seam bag cannot resolve its built-in runtimes, so it is\n * unrunnable — refuse it at definition time, not at the first spawn. Pure; no I/O.\n */\nexport function definePersona<D = unknown>(input: DefinePersonaInput<D>): Persona<D> {\n if (!input.executors.registry && !input.executors.seams) {\n throw new ValidationError(\n `definePersona(\"${input.name}\"): executors must supply a registry or a seams bag ` +\n '(built-in runtimes read their seams off ExecutorContext; neither was provided)',\n )\n }\n if (!input.root || typeof input.root !== 'object' || !('harness' in input.root)) {\n throw new ValidationError(`definePersona(\"${input.name}\"): root must be an AgentSpec`)\n }\n return Object.freeze({\n name: input.name,\n root: input.root,\n directive: input.directive,\n context: input.context,\n executors: input.executors,\n ...(input.extensions ? { extensions: input.extensions } : {}),\n }) as Persona<D>\n}\n\n// ── ShapeContext construction ───────────────────────────────────────────────────\n\n/**\n * Build the `ShapeContext` a `LoopShape` factory consumes. `spawnChild` wraps an `AgentSpec`\n * into a leaf `Agent` carrying it as `executorSpec` (the structural field `scope.spawn`\n * reads); `childSpec` derives a narrower child spec from the persona's root by overriding the\n * profile. The shape never touches the registry — resolution stays single-sourced in the\n * scope/registry the supervisor owns.\n */\nexport function createShapeContext<D>(\n persona: Persona<D>,\n budget: ShapeBudget,\n analyst?: ScopeAnalyst<D>,\n): ShapeContext<D> {\n return {\n persona,\n budget,\n ...(analyst ? { analyst } : {}),\n spawnChild(name, spec): Agent<unknown, Outcome<D>> {\n // The wrapped agent is SPAWNED, not run — the resolved Executor drives it. The\n // executor is a LEAF for a plain spec OR the recursive driver-executor for a\n // `role:'driver'` spec (a child that is itself a driver — agents drive agents). `act`\n // is never invoked by the keystone for a spawned child (the executor drives it); it\n // throws if mis-used as a root (fail loud), never a vacuous outcome.\n const agent = {\n name,\n executorSpec: spec,\n act(): Promise<Outcome<D>> {\n throw new ValidationError(\n `personify: spawned child \"${name}\" was run directly; its executorSpec drives it ` +\n '(a leaf, or — for a driver child — a nested scope through the recursive driver-executor)',\n )\n },\n }\n return agent as Agent<unknown, Outcome<D>> & { executorSpec: AgentSpec }\n },\n childSpec(profile, harness): AgentSpec {\n return {\n profile,\n harness: harness === undefined ? persona.root.harness : harness,\n ...(persona.root.executor ? { executor: persona.root.executor } : {}),\n }\n },\n }\n}\n\n// ── runPersonified ──────────────────────────────────────────────────────────────\n\n/**\n * Compose the persona + chosen shape onto a fresh keystone `Supervisor`. Resolves the shape\n * (a factory verbatim, or a registered name through `builtinShapes`), applies it to a\n * `ShapeContext`, and runs the resulting root `Agent` to a typed `SupervisedResult<Outcome>`.\n * Fail loud on an unknown shape name or an unresolvable persona registry — never a silent\n * default-shape fallback.\n */\nexport async function runPersonified<Task, D>(\n options: RunPersonifiedOptions<Task, D>,\n): Promise<SupervisedResult<Outcome<D>>> {\n const { persona } = options\n const shape = resolveShape<Task, D>(options.shape)\n const shapeBudget = resolveShapeBudget(options.budget, options.shapeBudget)\n const ctx = createShapeContext(persona, shapeBudget, options.analyst)\n const rootAgent = shape(ctx)\n\n const executors = personaRegistry(persona)\n const supervisor = createSupervisor<Task, Outcome<D>>()\n if (options.handle) supervisor.attach(options.handle)\n\n const supervisorOpts: SupervisorOpts = {\n budget: options.budget,\n runId: options.runId ?? `${persona.name}:${shapeName(options.shape, shape)}`,\n journal: options.journal ?? new InMemorySpawnJournal(),\n blobs: options.blobs ?? new InMemoryResultBlobStore(),\n executors,\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.maxRestarts !== undefined ? { maxRestarts: options.maxRestarts } : {}),\n ...(options.withinMs !== undefined ? { withinMs: options.withinMs } : {}),\n ...(options.now ? { now: options.now } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.hooks ? { hooks: options.hooks } : {}),\n }\n return supervisor.run(rootAgent, options.task, supervisorOpts)\n}\n\n// ── Resolution helpers ──────────────────────────────────────────────────────────\n\nfunction resolveShape<Task, D>(shape: LoopShape<Task, D> | string): LoopShape<Task, D> {\n if (typeof shape !== 'string') return shape\n const resolved = builtinShapes.resolve<Task, D>(shape)\n if (!resolved.succeeded) {\n throw new ValidationError(\n `runPersonified: ${resolved.error} (registered: ${builtinShapes.names().join(', ')})`,\n )\n }\n return resolved.value\n}\n\nfunction shapeName<Task, D>(\n shape: LoopShape<Task, D> | string,\n _resolved: LoopShape<Task, D>,\n): string {\n return typeof shape === 'string' ? shape : shape.name || 'shape'\n}\n\n/**\n * Default the shape's per-child sizing + fanout width from the root budget when the caller\n * omits them. The per-child token ceiling is the root divided across the fanout so the\n * conserved pool can admit a full round; iterations default to the root's. A caller override\n * wins per-field.\n */\nfunction resolveShapeBudget(root: Budget, over?: Partial<ShapeBudget>): ShapeBudget {\n const fanout = over?.fanout ?? defaultFanout\n const perChild: Budget = over?.perChild ?? {\n maxIterations: Math.max(1, Math.floor(root.maxIterations / fanout)),\n maxTokens: Math.max(1, Math.floor(root.maxTokens / fanout)),\n ...(root.maxUsd !== undefined ? { maxUsd: root.maxUsd / fanout } : {}),\n ...(root.deadlineMs !== undefined ? { deadlineMs: root.deadlineMs } : {}),\n }\n return { perChild, fanout }\n}\n\nconst defaultFanout = 3\n\n/**\n * Resolve the persona's executor resolution into a single `ExecutorRegistry`. A pre-built\n * `registry` is used verbatim; otherwise the persona's raw `seams` are wrapped so resolved\n * factories receive an `ExecutorContext` with the persona seams merged in — the supervisor\n * threads an empty bag, so this is the one place the persona seams reach the built-ins.\n */\nfunction personaRegistry<D>(persona: Persona<D>): ExecutorRegistry {\n const { registry, seams } = persona.executors\n // `withDriverExecutor` routes a `role:'driver'` child to the recursive driver-executor\n // (a child that drives its own children) BEFORE the base leaf resolution — so a persona\n // shape can spawn a driver child and the recursion composes. A plain leaf child falls\n // through to the base registry unchanged.\n if (registry) return withDriverExecutor(registry)\n if (!seams) {\n throw new ValidationError(\n `personify: persona \"${persona.name}\" supplies neither a registry nor seams`,\n )\n }\n return withDriverExecutor(withSeams(createExecutorRegistry(), seams))\n}\n\n/**\n * Wrap a registry so every resolved `ExecutorFactory` receives a ctx whose `seams` are\n * the persona seams merged over whatever the scope threaded (the scope threads `{}`, so the\n * persona seams win). A BYO `spec.executor` still resolves to a trivial factory that ignores\n * ctx — so this wrap is transparent for BYO and only matters for the metered built-ins.\n */\nfunction withSeams(\n base: ExecutorRegistry,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorRegistry {\n return {\n register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void {\n base.register(runtime, factory)\n },\n resolve<Out>(spec: AgentSpec) {\n const resolved = base.resolve<Out>(spec)\n if (!resolved.succeeded) return resolved\n const inner = resolved.value\n const wrapped: ExecutorFactory<Out> = (s, ctx) => inner(s, mergeSeams(ctx, seams))\n return { succeeded: true, value: wrapped }\n },\n }\n}\n\nfunction mergeSeams(\n ctx: ExecutorContext,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorContext {\n return { signal: ctx.signal, seams: { ...seams, ...ctx.seams } }\n}\n","/**\n * @experimental\n *\n * Trajectory trace + cost ledger — the post-hoc tree reconstructor (§4 of `wave-types`).\n *\n * `trajectoryReport` rebuilds the WHOLE realized spawn tree from the durable\n * `SpawnJournal` (+ optionally the `ResultBlobStore` for `done` artifacts): every node\n * (driver AND leaf), the real parent/child edges, each node's terminal status, its OWN\n * conserved `Spend`, and the `Spend` ROLLED UP over its subtree. Roll-up is a post-order\n * fold over the parent edges: a node's `rolledUpSpend` is its own spend plus every\n * descendant's, so a driver is charged for the fanout it caused — the root's roll-up is\n * the whole run's conserved total (tokens + usd + iterations + ms).\n *\n * `equalKOnCost` compares separate runs (arms) on that conserved COST, not on raw\n * iteration COUNT. The sandbox executor reports tokens/usd INCLUSIVE of a leaf's internal\n * sub-agent fanout, so charging an arm by `total.tokens`/`total.usd` (not by how many\n * `next()` cursors it logged) closes the leaf-fanout confound: a treatment leaf that fanned\n * out internally pays for it in cost, where a per-iteration count would hide it. The\n * within-run conserved pool already guarantees `Σk` equal by construction; this check is the\n * CROSS-run analogue the pool cannot reach — proving equal compute before any win is claimed.\n *\n * Pure over the journal/blobs — no live agent calls; safe to run on a finished run's log.\n */\n\nimport type {\n DefaultVerdict,\n NodeId,\n ResultBlobStore,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from '../supervise/types'\nimport { addTokenUsage, zeroTokenUsage } from '../util'\nimport type {\n EqualKArm,\n EqualKOnCostOptions,\n EqualKVerdict,\n TrajectoryNode,\n TrajectoryReport,\n TrajectoryReportOptions,\n} from './wave-types'\n\nconst defaultEqualKTolerance = 0.05\n\n/**\n * Reconstruct the whole spawn tree for `root` with per-node + rolled-up `Spend`. Reads the\n * journal for structure + spend and, when `withOutputs`, the blob store for each `done`\n * node's artifact. Fail loud on a tree that was never journaled, a settle/cancel for an\n * un-spawned node (a corrupted log), or — under `withOutputs` — a `done` node whose blob the\n * store cannot rehydrate (a silent gap would mis-cost or mis-evidence the tree).\n */\nexport async function trajectoryReport(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n options: TrajectoryReportOptions = {},\n): Promise<TrajectoryReport> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`trajectoryReport: no journaled tree for root '${root}'`)\n }\n\n // Spawns (ordinal seq) create the nodes; settlements/cancellations (cursor seq) close\n // them. The two seq namespaces overlap, so create every node from its `spawned` event\n // first, then apply settlements/cancellations — mirrors `materializeTreeView`.\n const spawns = events.filter(isSpawned).sort(bySeq)\n // `metered` events (driver inference) are folded onto each node in a separate pass below, so\n // they accumulate ONTO the settled child-work base regardless of seq order; closes are the\n // settlements/cancellations that set node status.\n const closes = events.filter((ev) => ev.kind !== 'spawned' && ev.kind !== 'metered').sort(bySeq)\n\n const nodes = new Map<NodeId, MutableNode>()\n for (const ev of spawns) {\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n runtime: ev.runtime,\n status: 'pending',\n ownSpend: zeroSpend(),\n children: [],\n })\n }\n for (const ev of closes) {\n const node = requireNode(nodes, ev.id, root)\n if (ev.kind === 'cancelled') {\n node.status = 'cancelled'\n continue\n }\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.ownSpend = ev.spent\n node.verdict = ev.verdict\n node.outRef = ev.outRef\n }\n // Driver inference: add each `metered` event onto its node's ownSpend. Because a driver re-homes\n // its nested subtree's inference up the tree, this single tree's events already carry the whole\n // sub-tree's driver cost — so `total` matches `SupervisedResult.spentTotal` directly, with no\n // caller plumbing.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id, root)\n node.ownSpend = addNodeSpend(node.ownSpend, ev.spend)\n }\n\n if (!nodes.has(root)) {\n throw new Error(\n `trajectoryReport: root '${root}' has no spawned event in its journaled tree (corrupted log)`,\n )\n }\n\n // Wire the realized parent/child edges in spawn order, then roll spend up the tree.\n for (const ev of spawns) {\n if (ev.parent === undefined) continue\n requireNode(nodes, ev.parent, root).children.push(ev.id)\n }\n const rolledUp = rollUpSpend(nodes, root)\n\n if (options.withOutputs) {\n await attachOutputs(nodes, blobs)\n }\n\n // Emit in spawn order so the node list reads as the realized tree, root first.\n const ordered = spawns.map((ev) => nodes.get(ev.id)).filter(isNode)\n const reported: TrajectoryNode[] = ordered.map((node) =>\n freezeNode(node, requireSpend(rolledUp, node.id, root)),\n )\n\n return {\n root,\n nodes: reported,\n total: requireSpend(rolledUp, root, root),\n statusCounts: countStatuses(reported),\n }\n}\n\n/**\n * Assert the arms are comparable at EQUAL conserved COST (tokens + usd), NOT raw iteration\n * count. Compares each arm's root-rolled-up `total` on the two conserved channels: an arm is\n * within-tolerance when the per-channel spread (max − min across arms) over the median is\n * `≤ tolerance`. Pure over the reports — no I/O. Fails loud on an empty arm list (nothing to\n * compare) so a vacuous \"equal\" is never returned.\n */\nexport function equalKOnCost(\n arms: ReadonlyArray<EqualKArm>,\n options: EqualKOnCostOptions = {},\n): EqualKVerdict {\n if (arms.length === 0) {\n throw new Error('equalKOnCost: no arms to compare')\n }\n const tolerance = options.tolerance ?? defaultEqualKTolerance\n\n const armCosts = arms.map((arm) => ({\n label: arm.label,\n tokens: arm.report.total.tokens.input + arm.report.total.tokens.output,\n usd: arm.report.total.usd,\n iterations: arm.report.total.iterations,\n }))\n\n const tokenValues = armCosts.map((a) => a.tokens)\n const usdValues = armCosts.map((a) => a.usd)\n const spread = {\n tokens: spreadOf(tokenValues),\n usd: spreadOf(usdValues),\n }\n const withinTolerance =\n fractionalSpread(tokenValues) <= tolerance && fractionalSpread(usdValues) <= tolerance\n\n return {\n withinTolerance,\n arms: armCosts,\n spread,\n tolerance,\n }\n}\n\n// ── Tree fold internals ────────────────────────────────────────────────────────\n\ninterface MutableNode {\n id: NodeId\n parent?: NodeId\n label: string\n runtime: string\n status: TrajectoryNode['status']\n ownSpend: Spend\n children: NodeId[]\n verdict?: DefaultVerdict\n output?: unknown\n outRef?: string\n}\n\n/**\n * Post-order fold: a node's rolled-up spend is its own spend plus every child's rolled-up\n * spend. Iterative (an explicit stack) so a deep tree never overflows the call stack; a node\n * is finalized only after all its children are, so the parent edges are honored exactly.\n */\nfunction rollUpSpend(nodes: Map<NodeId, MutableNode>, root: NodeId): Map<NodeId, Spend> {\n const rolled = new Map<NodeId, Spend>()\n const stack: { id: NodeId; expanded: boolean }[] = [{ id: root, expanded: false }]\n while (stack.length > 0) {\n const frame = stack.pop()\n if (frame === undefined) continue\n const node = requireNode(nodes, frame.id, root)\n if (!frame.expanded) {\n stack.push({ id: frame.id, expanded: true })\n for (const child of node.children) stack.push({ id: child, expanded: false })\n continue\n }\n const sum = cloneSpend(node.ownSpend)\n for (const child of node.children) addSpend(sum, requireSpend(rolled, child, root))\n rolled.set(frame.id, sum)\n }\n return rolled\n}\n\n/**\n * Rehydrate each `done` node's artifact from the blob store. Fail loud on a `done` node whose\n * blob the store cannot resolve — a missing payload under `withOutputs` is a corrupted store,\n * not an absent output (a `down`/`cancelled` node legitimately has none).\n */\nasync function attachOutputs(\n nodes: Map<NodeId, MutableNode>,\n blobs: ResultBlobStore,\n): Promise<void> {\n for (const node of nodes.values()) {\n if (node.status !== 'done' || node.outRef === undefined) continue\n const out = await blobs.get(node.outRef)\n if (out === undefined) {\n throw new Error(\n `trajectoryReport: blob store has no artifact for outRef '${node.outRef}' (node '${node.id}')`,\n )\n }\n node.output = out\n }\n}\n\nfunction freezeNode(node: MutableNode, rolledUpSpend: Spend): TrajectoryNode {\n return {\n id: node.id,\n parent: node.parent,\n children: [...node.children],\n label: node.label,\n runtime: node.runtime,\n status: node.status,\n ownSpend: node.ownSpend,\n rolledUpSpend,\n verdict: node.verdict,\n output: node.output,\n outRef: node.outRef,\n }\n}\n\nfunction countStatuses(\n reported: ReadonlyArray<TrajectoryNode>,\n): Readonly<Record<TrajectoryNode['status'], number>> {\n const counts: Record<TrajectoryNode['status'], number> = {\n done: 0,\n failed: 0,\n cancelled: 0,\n pending: 0,\n }\n for (const node of reported) counts[node.status] += 1\n return counts\n}\n\n// ── Spend arithmetic (single-sourced on `addTokenUsage`) ─────────────────────────\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Add a `metered` event's spend onto a node's accumulated ownSpend (per channel). */\nfunction addNodeSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\nfunction cloneSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: { input: spend.tokens.input, output: spend.tokens.output },\n usd: spend.usd,\n ms: spend.ms,\n }\n}\n\n/** Add `delta` into `acc` in place across every conserved channel. */\nfunction addSpend(acc: Spend, delta: Spend): void {\n acc.iterations += delta.iterations\n addTokenUsage(acc.tokens, delta.tokens)\n acc.usd += delta.usd\n acc.ms += delta.ms\n}\n\n// ── Cross-arm spread ─────────────────────────────────────────────────────────────\n\nfunction spreadOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) return 0\n return Math.max(...values) - Math.min(...values)\n}\n\n/**\n * Fractional spread on one channel: `(max − min) / median`. A zero-median channel (every arm\n * spent zero on it) is trivially equal — spread is also zero, so it never trips the tolerance.\n */\nfunction fractionalSpread(values: ReadonlyArray<number>): number {\n const spread = spreadOf(values)\n if (spread === 0) return 0\n const median = medianOf(values)\n if (median === 0) {\n throw new Error(\n 'equalKOnCost: arms have a non-zero cost spread on a zero-median channel; cannot express it as a fraction',\n )\n }\n return spread / median\n}\n\nfunction medianOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) {\n throw new Error('equalKOnCost: cannot take the median of an empty channel')\n }\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n const hi = sorted[mid] as number\n if (sorted.length % 2 !== 0) return hi\n const lo = sorted[mid - 1] as number\n return (lo + hi) / 2\n}\n\n// ── Guards + narrowers ───────────────────────────────────────────────────────────\n\nfunction isSpawned(ev: SpawnEvent): ev is Extract<SpawnEvent, { kind: 'spawned' }> {\n return ev.kind === 'spawned'\n}\n\nfunction isNode(node: MutableNode | undefined): node is MutableNode {\n return node !== undefined\n}\n\nfunction bySeq(a: SpawnEvent, b: SpawnEvent): number {\n return a.seq - b.seq\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableNode>, id: NodeId, root: NodeId): MutableNode {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(\n `trajectoryReport: tree '${root}' references node '${id}' with no prior spawn (corrupted log)`,\n )\n }\n return node\n}\n\nfunction requireSpend(rolled: Map<NodeId, Spend>, id: NodeId, root: NodeId): Spend {\n const spend = rolled.get(id)\n if (!spend) {\n throw new Error(\n `trajectoryReport: node '${id}' was never rolled up in tree '${root}' (unreachable from root)`,\n )\n }\n return spend\n}\n","/**\n * promotionGate — the statistical promotion decision over a holdout benchmark: does the\n * candidate strategy beat the incumbent on held-out tasks by a margin the task noise\n * cannot fake? The statistics are the substrate's (`heldoutSignificance`): a SEEDED\n * paired bootstrap over per-task (candidate − incumbent) deltas — deterministic verdict,\n * a minimum-evidence floor, and the CI lower bound must clear `deltaThreshold`. A raw\n * h1>h0 point comparison on m≈8 holdout tasks certifies false champions at near\n * coin-flip rates; this gate is the instrument-grade replacement.\n */\nimport { heldoutSignificance } from '@tangle-network/agent-eval/campaign'\nimport type { BenchmarkReport } from './run-benchmark'\n\nexport interface PromotionGateOptions {\n /** The HOLDOUT report — must carry per-task cells for both strategy names. */\n report: BenchmarkReport\n /** The incumbent champion's strategy name. */\n incumbent: string\n /** The challenger's strategy name. */\n candidate: string\n /** 'superiority' (default): the candidate must score significantly BETTER.\n * 'non-inferiority': the candidate must prove its score is not worse than the\n * incumbent by more than `scoreTolerance` AND its cost savings are significant —\n * the gate for \"same quality, cheaper\" claims. */\n mode?: 'superiority' | 'non-inferiority'\n /** non-inferiority: the score CI lower bound must clear −scoreTolerance. Default 0.05. */\n scoreTolerance?: number\n /** The CI lower bound on the paired lift must EXCEED this (score scale). Default 0. */\n deltaThreshold?: number\n /** Minimum paired tasks before significance can be claimed. Default 6 — below that\n * the bootstrap CI is too wide to separate a real lift from the per-task noise. */\n minPairedTasks?: number\n /** Bootstrap statistic over the paired deltas. Default 'mean'. */\n statistic?: 'mean' | 'median'\n /** Fixed by the substrate by default — the same report always yields the same verdict. */\n seed?: number\n resamples?: number\n}\n\nexport interface PromotionVerdict {\n promoted: boolean\n reason:\n | 'identical-champion'\n | 'few-tasks'\n | 'no-margin'\n | 'significant'\n | 'non-inferior-and-cheaper'\n | 'non-inferiority-unproven'\n | 'not-cheaper'\n mode: 'superiority' | 'non-inferiority'\n /** Paired tasks that carried both strategies' cells. */\n n: number\n /** Paired (candidate − incumbent) lift across the holdout tasks. */\n lift: { mean: number; median: number; low: number; high: number }\n /** non-inferiority mode: paired (incumbent − candidate) cost SAVINGS per task (usd) —\n * positive means the candidate is cheaper; significant iff the CI low clears zero. */\n costSavings?: { mean: number; median: number; low: number; high: number }\n /** Paired (candidate − incumbent) wall-clock per task (ms) — negative = the candidate\n * is FASTER. Informational in every mode (never gates); the latency answer to \"what\n * does this win actually cost the user?\". */\n latency?: { mean: number; median: number; low: number; high: number }\n}\n\nexport function promotionGate(opts: PromotionGateOptions): PromotionVerdict {\n const mode = opts.mode ?? 'superiority'\n if (opts.candidate === opts.incumbent) {\n return {\n promoted: false,\n reason: 'identical-champion',\n mode,\n n: 0,\n lift: { mean: 0, median: 0, low: 0, high: 0 },\n }\n }\n const before: number[] = []\n const after: number[] = []\n const incUsd: number[] = []\n const candUsd: number[] = []\n const incMs: number[] = []\n const candMs: number[] = []\n const cellIds: string[] = []\n for (const row of opts.report.perTask) {\n const inc = row.cells?.[opts.incumbent]\n const cand = row.cells?.[opts.candidate]\n if (!inc || !cand) continue\n before.push(inc.score)\n after.push(cand.score)\n incUsd.push(inc.usd)\n candUsd.push(cand.usd)\n incMs.push(inc.ms)\n candMs.push(cand.ms)\n cellIds.push(row.taskId)\n }\n if (before.length === 0) {\n throw new Error(\n `promotionGate: no holdout task carried cells for both \"${opts.incumbent}\" and \"${opts.candidate}\" — the report must come from a run that included both strategies`,\n )\n }\n const sig = heldoutSignificance(\n { before, after, cellIds },\n {\n deltaThreshold: opts.deltaThreshold ?? 0,\n minProductiveRuns: opts.minPairedTasks ?? 6,\n statistic: opts.statistic ?? 'mean',\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.resamples !== undefined ? { resamples: opts.resamples } : {}),\n },\n )\n const lift = {\n mean: sig.bootstrap.mean,\n median: sig.bootstrap.median,\n low: sig.bootstrap.low,\n high: sig.bootstrap.high,\n }\n const latSig = heldoutSignificance(\n { before: incMs, after: candMs, cellIds },\n {\n deltaThreshold: 0,\n minProductiveRuns: 1,\n statistic: opts.statistic ?? 'mean',\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.resamples !== undefined ? { resamples: opts.resamples } : {}),\n },\n )\n const latency = {\n mean: latSig.bootstrap.mean,\n median: latSig.bootstrap.median,\n low: latSig.bootstrap.low,\n high: latSig.bootstrap.high,\n }\n if (mode === 'superiority') {\n if (sig.fewRuns) return { promoted: false, reason: 'few-tasks', mode, n: sig.n, lift, latency }\n return sig.significant\n ? { promoted: true, reason: 'significant', mode, n: sig.n, lift, latency }\n : { promoted: false, reason: 'no-margin', mode, n: sig.n, lift, latency }\n }\n // non-inferiority: (a) score not worse than −scoreTolerance, proven (CI low clears\n // −tolerance); (b) cost SAVINGS (incumbent − candidate, usd/task) significantly > 0.\n const tolerance = opts.scoreTolerance ?? 0.05\n const scoreSig = heldoutSignificance(\n { before, after, cellIds },\n {\n deltaThreshold: -tolerance,\n minProductiveRuns: opts.minPairedTasks ?? 6,\n statistic: opts.statistic ?? 'mean',\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.resamples !== undefined ? { resamples: opts.resamples } : {}),\n },\n )\n const costSig = heldoutSignificance(\n { before: candUsd, after: incUsd, cellIds },\n {\n deltaThreshold: 0,\n minProductiveRuns: opts.minPairedTasks ?? 6,\n statistic: opts.statistic ?? 'mean',\n ...(opts.seed !== undefined ? { seed: opts.seed } : {}),\n ...(opts.resamples !== undefined ? { resamples: opts.resamples } : {}),\n },\n )\n const costSavings = {\n mean: costSig.bootstrap.mean,\n median: costSig.bootstrap.median,\n low: costSig.bootstrap.low,\n high: costSig.bootstrap.high,\n }\n if (scoreSig.fewRuns)\n return { promoted: false, reason: 'few-tasks', mode, n: scoreSig.n, lift, costSavings, latency }\n if (!scoreSig.significant)\n return {\n promoted: false,\n reason: 'non-inferiority-unproven',\n mode,\n n: scoreSig.n,\n lift,\n costSavings,\n latency,\n }\n if (!costSig.significant)\n return {\n promoted: false,\n reason: 'not-cheaper',\n mode,\n n: scoreSig.n,\n lift,\n costSavings,\n latency,\n }\n return {\n promoted: true,\n reason: 'non-inferior-and-cheaper',\n mode,\n n: scoreSig.n,\n lift,\n costSavings,\n latency,\n }\n}\n","/**\n * runBenchmark — the packaged optimization suite. Define a domain by implementing an\n * `Environment` (open / tools / call / score / close); get the optimization strategies\n * compared, scored by your own deployable check, with a paired-bootstrap report — free.\n *\n * The mental model: you have a TASK + a deployable CHECK + a compute BUDGET. A strategy\n * is how you spend the budget to beat the check. Two built-ins:\n *\n * sample — N independent attempts, keep the best-verifying one. (best-of-N / resample)\n * refine — attempt → a critic reads the trace → steer the next → repeat. (iterate-with-feedback)\n *\n * Both run at equal budget through the Supervisor's conserved pool; the headline is the\n * paired lift of refine over sample. Author your own strategy with `defineStrategy`.\n */\n\nimport { pairedBootstrap, paretoFrontier } from '@tangle-network/agent-eval'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport {\n type AgenticOptions,\n type AgenticSurface,\n type AgenticTask,\n refine,\n runAgentic,\n type Strategy,\n sample,\n} from './strategy'\n\n/** A checkable task domain — implement these 5 hooks and the suite does the rest. The\n * same seam as `AgenticSurface`; `Environment` is the RL/gym-standard name for it. */\nexport type Environment = AgenticSurface\n\nexport interface BenchmarkConfig {\n /** The task domain (5 hooks). */\n environment: Environment\n /** The tasks to score across. */\n tasks: AgenticTask[]\n /** The worker: model + router + (optional) the critic's instruction (the steerer knob). */\n worker: AgenticOptions\n /** Which strategies to compare. Pass the built-ins (`refine`, `sample`) or your own.\n * Default: [sample, refine]. */\n strategies?: Strategy[]\n /** Shots (refine) / width (sample) — the equal compute budget per strategy. Default 3. */\n budget?: number\n /** Tasks scored in parallel. Default 3. */\n concurrency?: number\n /** Progress hook — fires as each task settles (the live-monitoring seam: append to a\n * progress file, render a tree, stream to a dashboard). `done` counts settled tasks. */\n onTask?: (row: BenchmarkTaskRow, done: number, total: number) => void\n /** Lifecycle observability — every spawn/settle of every cell's shots/analysts streams\n * here live (the watchdog/route-auditor seam, passed through to `runAgentic`). */\n hooks?: RuntimeHooks\n}\n\nexport interface BenchmarkLift {\n /** Mean of paired deltas (refine − sample). */\n mean: number\n low: number\n high: number\n n: number\n}\n\n/** One strategy's outcome on one task — the per-task cell an optimizer consumes. */\nexport interface BenchmarkCell {\n score: number\n resolved: boolean\n /** The progress curve (refine: score per shot; sample: best-so-far per rollout). */\n progression: number[]\n usd: number\n ms: number\n tokens: { input: number; output: number }\n}\n\nexport interface BenchmarkTaskRow {\n taskId: string\n /** Per-strategy cells; absent when the task errored before completing all strategies. */\n cells?: Record<string, BenchmarkCell>\n /** Per-strategy failures on this task: the strategy competed, threw, and scored an\n * honest zero — it loses, it does not poison the row. The message is kept so a later\n * generation's author can see WHY a candidate died. */\n errors?: Record<string, string>\n /** Why the task was excluded (infra/setup failure) — never silently dropped. */\n error?: string\n}\n\nexport interface BenchmarkStrategySummary {\n /** Mean verifier score (0..1). */\n score: number\n /** Fraction of tasks fully resolved. */\n resolved: number\n /** Mean cost vector per task. */\n usd: number\n ms: number\n}\n\nexport interface BenchmarkReport {\n n: number\n excluded: number\n /** Per-strategy means (keyed by strategy.name). */\n perStrategy: Record<string, BenchmarkStrategySummary>\n /** The full per-task × per-strategy table — the LOSSES an optimizer (GEPA, a\n * strategy-author, an operator) consumes. Includes errored tasks with the reason. */\n perTask: BenchmarkTaskRow[]\n /** The non-dominated strategies on (score ↑, $/task ↓) — collapse-last, per the canon:\n * a strategy that ties on score at half the cost WINS and a scalar would hide it. */\n pareto: string[]\n /** The headline when both `refine` and `sample` ran: paired-bootstrap lift of refine over sample. */\n refineVsSample?: BenchmarkLift\n}\n\n/** Bounded-concurrency map preserving order. */\nasync function pool<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, i: number) => Promise<R>,\n): Promise<R[]> {\n const out: R[] = new Array(items.length)\n let next = 0\n const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {\n while (next < items.length) {\n const i = next\n next += 1\n out[i] = await fn(items[i] as T, i)\n }\n })\n await Promise.all(workers)\n return out\n}\n\n/** Run the requested strategies over the tasks, scored by the Environment's own check.\n * Resilient: a task whose rollouts fail (transient infra) is excluded from the stats but\n * reported in `perTask` with the error — never silently dropped. */\nexport async function runBenchmark(cfg: BenchmarkConfig): Promise<BenchmarkReport> {\n const strategies = cfg.strategies ?? [sample, refine]\n const budget = cfg.budget ?? 3\n const concurrency = cfg.concurrency ?? 3\n\n let settled = 0\n const perTask = await pool(cfg.tasks, concurrency, async (task): Promise<BenchmarkTaskRow> => {\n const cells: Record<string, BenchmarkCell> = {}\n const errors: Record<string, string> = {}\n let row: BenchmarkTaskRow\n try {\n // Per-strategy isolation: one strategy throwing (a broken authored candidate, a\n // hallucinated tool name) must not destroy the other strategies' cells for the\n // task. The thrower scores an honest zero — it competed, it failed, it loses.\n for (const s of strategies) {\n try {\n const r = await runAgentic({\n ...cfg.worker,\n surface: cfg.environment,\n task,\n strategy: s,\n budget,\n ...(cfg.hooks ? { hooks: cfg.hooks } : {}),\n })\n cells[s.name] = {\n score: r.score,\n resolved: r.resolved,\n progression: r.progression,\n usd: r.usd,\n ms: r.ms,\n tokens: r.tokens,\n }\n } catch (e) {\n errors[s.name] = e instanceof Error ? e.message.slice(0, 300) : String(e)\n cells[s.name] = {\n score: 0,\n resolved: false,\n progression: [],\n usd: 0,\n ms: 0,\n tokens: { input: 0, output: 0 },\n }\n }\n }\n row = {\n taskId: task.id,\n cells,\n ...(Object.keys(errors).length > 0 ? { errors } : {}),\n }\n } catch (e) {\n row = { taskId: task.id, error: e instanceof Error ? e.message.slice(0, 300) : String(e) }\n }\n settled += 1\n cfg.onTask?.(row, settled, cfg.tasks.length)\n return row\n })\n\n const ok = perTask.filter(\n (r): r is BenchmarkTaskRow & { cells: Record<string, BenchmarkCell> } => !!r.cells,\n )\n const mean = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : 0)\n const perStrategy: Record<string, BenchmarkStrategySummary> = {}\n for (const s of strategies) {\n const cells = ok.map((r) => r.cells[s.name]).filter((c): c is BenchmarkCell => !!c)\n perStrategy[s.name] = {\n score: mean(cells.map((c) => c.score)),\n resolved: mean(cells.map((c) => (c.resolved ? 1 : 0))),\n usd: mean(cells.map((c) => c.usd)),\n ms: mean(cells.map((c) => c.ms)),\n }\n }\n\n const frontier = paretoFrontier(\n Object.entries(perStrategy).map(([name, v]) => ({ name, score: v.score, usd: v.usd })),\n [\n { name: 'score', direction: 'maximize', value: (c) => c.score },\n { name: 'usd', direction: 'minimize', value: (c) => c.usd },\n ],\n ).frontier.map((c) => c.name)\n\n const report: BenchmarkReport = {\n n: ok.length,\n excluded: perTask.length - ok.length,\n perStrategy,\n perTask,\n pareto: frontier,\n }\n const names = strategies.map((s) => s.name)\n if (names.includes('refine') && names.includes('sample') && ok.length >= 2) {\n const b = pairedBootstrap(\n ok.map((r) => r.cells.sample?.score ?? 0),\n ok.map((r) => r.cells.refine?.score ?? 0),\n )\n report.refineVsSample = { mean: b.mean, low: b.low, high: b.high, n: b.n }\n }\n return report\n}\n\n/** Pretty-print a report — the \"free optimization\" verdict, with the cost vector. */\nexport function printBenchmarkReport(report: BenchmarkReport): void {\n const pct = (x: number) => `${(x * 100).toFixed(1)}%`\n const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`\n console.log(\n `\\n=== benchmark · n=${report.n}${report.excluded ? ` (excluded ${report.excluded})` : ''} ===`,\n )\n console.log(\n ` ${'strategy'.padEnd(16)} ${'score'.padStart(7)} ${'resolved'.padStart(9)} ${'$/task'.padStart(8)} ${'s/task'.padStart(7)}`,\n )\n for (const [s, v] of Object.entries(report.perStrategy))\n console.log(\n ` ${(report.pareto.includes(s) ? `${s} *` : s).padEnd(16)} ${pct(v.score).padStart(7)} ${pct(v.resolved).padStart(9)} ${`$${v.usd.toFixed(3)}`.padStart(8)} ${(v.ms / 1000).toFixed(0).padStart(6)}s`,\n )\n if (report.pareto.length) console.log(` * = on the (score, $) Pareto frontier`)\n for (const row of report.perTask)\n if (row.error) console.log(` ⚠ ${row.taskId}: ${row.error.slice(0, 120)}`)\n const l = report.refineVsSample\n if (l) {\n const sig = l.low > 0 ? 'SIGNIF +' : l.high < 0 ? 'SIGNIF -' : 'n.s.'\n console.log(` refine − sample: ${pp(l.mean)} CI [${pp(l.low)}, ${pp(l.high)}] (${sig})`)\n }\n}\n","/**\n * The general agentic primitive — sequential (depth) and parallel (breadth) over a shared,\n * checkable artifact, driven through the keystone Supervisor as one recursive `Agent.act`.\n *\n * The domain lives behind ONE seam — `AgenticSurface` (open an artifact, list tools, call a tool,\n * score the artifact, close it). EnterpriseOps implements it (seed a gym DB, MCP tools, SQL\n * verifier); Commit0/AppWorld/terminal-bench implement it the same way (a repo workspace, shell\n * tools, the test suite). The drivers below are domain-blind: they run over any surface.\n *\n * Two shapes, the agent's POMDP rollout as the unit:\n * - DEPTH one persistent artifact carried across shots. Each shot the agent works the tool loop;\n * between shots a trace-analyst (selector≠judge: reads the trajectory, never the score)\n * steers the resumed session toward what's unfinished. shot n stands on shot n-1's\n * artifact state + history. This is continuation — long-horizon, same artifact.\n * - BREADTH K independent artifacts, each a fresh rollout, the deployable verifier picks the best.\n *\n * Both are an `Agent` whose `act` spawns leaf shots through `scope.spawn` and reacts via\n * `scope.next()` — so the conserved budget pool meters them (equal-k by construction), the journal\n * records the tree, and the same primitive nests. `runAgentic` runs the chosen driver through\n * `createSupervisor().run`. The leaf (one shot over a handle) is resolved per-spawn from a\n * surface-closed registry — the open `Executor` seam, not bespoke per-benchmark glue.\n */\n\nimport { createChatClient, estimateCost, isModelPriced } from '@tangle-network/agent-eval'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../durable/spawn-journal'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport { observe } from './observe'\nimport type { Outcome } from './personify/types'\nimport type { Corpus } from './personify/wave-types'\nimport { routerToolLoop } from './router-client'\nimport { withDriverExecutor } from './supervise/driver-executor'\nimport { createSupervisor } from './supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n Scope,\n Settled,\n} from './supervise/types'\n\n// ── The general surface seam (the only thing a new benchmark implements) ─────────\n\nexport interface AgenticTask {\n readonly id: string\n readonly systemPrompt: string\n readonly userPrompt: string\n /** Opaque domain payload the surface reads (EOPS: servers/verifiers/tools). Drivers never read it. */\n readonly meta?: Record<string, unknown>\n}\n\nexport interface ArtifactHandle {\n readonly id: string\n readonly surface: string\n /** Opaque per-artifact context the surface stashes (EOPS: the seeded gym server + db id). */\n readonly ctx?: unknown\n}\n\nexport interface AgenticTool {\n readonly type: 'function'\n readonly function: { name: string; description?: string; parameters: Record<string, unknown> }\n}\n\nexport interface SurfaceScore {\n passes: number\n total: number\n /** Checks excluded as malformed (data defect, not the agent). `total === 0` ⇒ unscoreable. */\n errored: number\n}\n\n/** A stateful, checkable environment an agent operates over with tools. Open behind one interface. */\nexport interface AgenticSurface {\n readonly name: string\n open(task: AgenticTask): Promise<ArtifactHandle>\n tools(task: AgenticTask, handle: ArtifactHandle): Promise<AgenticTool[]>\n call(handle: ArtifactHandle, name: string, args: Record<string, unknown>): Promise<string>\n score(task: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore>\n close(handle: ArtifactHandle): Promise<void>\n}\n\nexport interface AgenticOptions {\n routerBaseUrl: string\n routerKey: string\n model: string\n /** Optional completion transport (see `RouterConfig.complete`): when set, BOTH legs of an\n * offline run use it instead of `fetch`-ing the router — the worker's tool loop (threaded into\n * its `routerToolLoop` cfg) AND the analyst's critic (its `ChatClient` is bound to this same\n * transport). One injected responder serves both, as a localhost mock endpoint would. Absent ⇒\n * the live router fetch path (the default). */\n complete?: (body: Record<string, unknown>) => Promise<unknown>\n temperature?: number\n /** Completion cap per worker turn — REQUIRED for thinking models (they burn unbounded\n * budgets on reasoning and return empty content without it). Omitted ⇒ provider default. */\n maxTokens?: number\n /** Turns the agent may take within ONE shot before the driver intervenes. */\n innerTurns?: number\n /** The depth STEERER's analyst instruction (observe()'s system prompt). The knob a\n * prompt optimizer (GEPA) tunes — the analyst IS the steerer. Omitted ⇒ the default. */\n analystInstruction?: string\n /** The critic's model — lets the analyst be a stronger (or cheaper) model than the\n * worker. Omitted ⇒ the worker's `model`. */\n analystModel?: string\n /** Across-run learning: when set, the analyst's observe() pass appends trace-derived\n * facts here (the flywheel write side). Priming (the read side) is the caller's move —\n * query the corpus and fold facts into the task's systemPrompt before runAgentic. */\n corpus?: Corpus\n /** Tags written onto learned facts (and used by the caller's priming query). */\n corpusTags?: string[]\n}\n\n// ── The unit: one agentic shot (a bounded tool loop) over a handle ───────────────\n\ntype Msg = Record<string, unknown>\ninterface ToolCall {\n id: string\n function: { name: string; arguments: string }\n}\n\ninterface ShotTask {\n task: AgenticTask\n handle?: ArtifactHandle // present ⇒ DEPTH (shared artifact); absent ⇒ BREADTH (open own)\n messages?: Msg[] // carried conversation (depth); fresh when absent\n steer?: string // analyst-derived steer injected before this shot (depth)\n persona?: ShotPersona // role override — multi-agent loops give each shot its own hat\n tools?: string[] // restrict THIS shot to these domain tools (names); unknown names throw\n /** analyst leaf only: a RAW instruction — the analyst answers it over the trajectory\n * directly (no findings schema). The verdict-capable channel. */\n rawInstruction?: string\n}\n\ninterface ShotOut {\n messages: Msg[]\n completions: number\n toolCalls: number\n toolErrors: number\n /** Real router usage summed over the shot's turns; zeros only when the provider omits usage. */\n tokens: { input: number; output: number }\n}\n\nconst taskNudge =\n 'Use the available tools to bring the artifact to the required final state. Address EVERY distinct ' +\n 'change the request implies. After each tool result, check what remains and continue. Re-read the ' +\n 'values you set to confirm they took. Reply DONE only once every required change is made and verified.'\n\n/** One shot: run the agent's tool loop (≤ innerTurns) over the handle, mutating the artifact via\n * `surface.call`, carrying `messages`. Returns the updated conversation + counts. */\nasync function runShot(\n surface: AgenticSurface,\n _task: AgenticTask,\n handle: ArtifactHandle,\n tools: AgenticTool[],\n messages: Msg[],\n opts: AgenticOptions,\n modelOverride?: string,\n): Promise<ShotOut> {\n // The canonical off-box tool loop (routerToolLoop) drives the turns; this shot supplies\n // the carried conversation (depth continuation, via initialMessages) and the tool dispatch\n // (surface.call). An ERROR:-prefixed result or a thrown call is a real tool outcome —\n // counted as a toolError and fed back to the model, never thrown to kill the shot.\n let toolErrors = 0\n const execute = async (name: string, args: Record<string, unknown>): Promise<string> => {\n try {\n const out = await surface.call(handle, name, args)\n if (out.startsWith('ERROR:')) toolErrors += 1\n return out\n } catch (e) {\n toolErrors += 1\n return `ERROR: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n const r = await routerToolLoop(\n {\n routerBaseUrl: opts.routerBaseUrl,\n routerKey: opts.routerKey,\n model: modelOverride ?? opts.model,\n ...(opts.complete ? { complete: opts.complete } : {}),\n },\n '',\n '',\n tools,\n execute,\n {\n maxTurns: opts.innerTurns ?? 4,\n temperature: opts.temperature ?? 0.7,\n initialMessages: messages,\n ...(opts.maxTokens ? { maxTokens: opts.maxTokens } : {}),\n },\n )\n return {\n messages: r.messages,\n completions: r.turns,\n toolCalls: r.toolCalls,\n toolErrors,\n tokens: r.usage,\n }\n}\n\n/** The trace-analyst (selector≠judge): reads ONLY the trajectory + task, never the score. */\n/** The depth STEERER, on the CANONICAL analyst: agent-eval's `observe()` (makeFinding +\n * ChatClient + the derived_from_judge firewall) reads the agent's tool-call trajectory\n * (behavior, never the score) and returns findings; we steer on their recommended_actions.\n * The trajectory (calls + RESULTS) rides in `output` so the analyst sees what actually\n * happened, not just tool names. No actionable findings ⇒ COMPLETE (depth self-terminates). */\ninterface AnalyzeOut {\n steer: string\n tokens: { input: number; output: number }\n}\n\n/** The firewall's input shape: the trajectory as compacted text — calls, results,\n * assistant text. NEVER scores, NEVER check internals. Shared by both analyst channels. */\nfunction compactTrajectory(messages: Msg[]): string {\n return messages\n .filter((m) => m.role === 'assistant' || m.role === 'tool')\n .map((m) => {\n if (m.role === 'tool') return `RESULT ${String(m.content).slice(0, 280)}`\n const calls = (m.tool_calls as ToolCall[] | undefined)\n ?.map((c) => `${c.function.name}(${c.function.arguments})`)\n .join(', ')\n return calls ? `CALL ${calls}` : `SAY ${String(m.content).slice(0, 200)}`\n })\n .join('\\n')\n .slice(0, 7000)\n}\n\n/** The analyst's chat seam: the live router by default, or — when a `complete` transport is\n * injected — that SAME transport, so an offline run drives the critic with no network too (the\n * worker and the analyst share the one injected responder, exactly as a localhost mock would\n * serve both). The critic speaks the OpenAI request shape; we forward it to `complete` and lift\n * the parsed `/chat/completions` JSON back into a `ChatResponse`. */\nfunction analystChat(\n opts: AgenticOptions,\n defaultModel: string,\n): ReturnType<typeof createChatClient> {\n if (!opts.complete) {\n return createChatClient({\n transport: 'router',\n apiKey: opts.routerKey,\n baseUrl: opts.routerBaseUrl,\n defaultModel,\n })\n }\n const complete = opts.complete\n return createChatClient({\n transport: 'mock',\n defaultModel,\n handler: async (req) => {\n const raw = (await complete({\n model: req.model ?? defaultModel,\n messages: req.messages,\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.maxTokens !== undefined ? { max_tokens: req.maxTokens } : {}),\n })) as {\n choices?: Array<{ message?: { content?: string | null }; finish_reason?: string | null }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const content = raw.choices?.[0]?.message?.content ?? ''\n const promptTokens = raw.usage?.prompt_tokens ?? 0\n const completionTokens = raw.usage?.completion_tokens ?? 0\n return {\n content,\n usage: {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n },\n costUsd: null,\n model: req.model ?? defaultModel,\n durationMs: 0,\n finishReason: raw.choices?.[0]?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n raw: raw as Record<string, unknown>,\n }\n },\n })\n}\n\n/** The RAW analyst channel: the firewalled critic answers `instruction` over the\n * trajectory directly — no findings schema, no recommended-action extraction. The\n * channel for verdict-shaped steering (budget controllers, calibrated predictions)\n * whose output format the findings protocol would strip. Same firewall as analyze():\n * trajectory in, never scores. */\nasync function consultAnalyst(\n task: AgenticTask,\n messages: Msg[],\n instruction: string,\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystModel = opts.analystModel ?? opts.model\n const chat = analystChat(opts, analystModel)\n const res = await chat.chat({\n model: analystModel,\n temperature: 0.2,\n maxTokens: 1024,\n messages: [\n { role: 'system', content: instruction },\n {\n role: 'user',\n content: `TASK: ${task.userPrompt.slice(0, 1500)}\\n\\nTRAJECTORY:\\n${trajectory}`,\n },\n ],\n })\n const usage = (\n res as {\n usage?: {\n promptTokens?: number\n prompt_tokens?: number\n completionTokens?: number\n completion_tokens?: number\n }\n }\n ).usage\n return {\n steer: res.content.trim(),\n tokens: {\n input: usage?.promptTokens ?? usage?.prompt_tokens ?? 0,\n output: usage?.completionTokens ?? usage?.completion_tokens ?? 0,\n },\n }\n}\n\nasync function analyze(\n task: AgenticTask,\n messages: Msg[],\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystModel = opts.analystModel ?? opts.model\n const inner = analystChat(opts, analystModel)\n // The critic's calls are REAL spend — capture usage so the cost vector bills them\n // (an unbilled critic makes every steering-vs-sampling cost comparison dishonest).\n const tokens = { input: 0, output: 0 }\n const chat: typeof inner = {\n ...inner,\n chat: async (req, callOpts) => {\n const res = await inner.chat(req, callOpts)\n const u = (\n res as {\n usage?: {\n promptTokens?: number\n completionTokens?: number\n prompt_tokens?: number\n completion_tokens?: number\n }\n }\n ).usage\n if (u) {\n tokens.input += u.promptTokens ?? u.prompt_tokens ?? 0\n tokens.output += u.completionTokens ?? u.completion_tokens ?? 0\n }\n return res\n },\n }\n const obs = await observe(\n {\n task: task.userPrompt,\n output: trajectory,\n trace: messages,\n outcome: 'failed',\n runId: task.id,\n },\n {\n chat,\n model: analystModel,\n ...(opts.analystInstruction ? { analystInstruction: opts.analystInstruction } : {}),\n ...(opts.corpus ? { corpus: opts.corpus, tags: opts.corpusTags ?? [] } : {}),\n },\n )\n // The steer = the analyst's recommended actions for the agent. Empty ⇒ nothing left to do.\n const steer = obs.findings\n .map((f) => f.recommended_action)\n .filter((a): a is string => typeof a === 'string' && a.trim().length > 0)\n .join('\\n')\n .trim()\n return { steer: steer || 'COMPLETE', tokens }\n}\n\n// ── Leaf executors (one shot / one analyst), resolved per-spawn from the surface ──\n\ninterface ShotResult {\n messages: Msg[]\n score: number\n passes: number\n total: number\n completions: number\n toolErrors: number\n}\n\n/** Resolve a shot: if `handle` given, operate on the SHARED artifact (depth); else open+score+close\n * an OWN artifact (breadth). Always scores the artifact's final state as the deployable verdict. */\nfunction shotExecutor(surface: AgenticSurface, opts: AgenticOptions): Executor<unknown> {\n let artifact: ExecutorResult<unknown> | undefined\n return {\n runtime: 'agentic-shot',\n async execute(task: unknown): Promise<ExecutorResult<unknown>> {\n const t = task as ShotTask\n const own = !t.handle\n const handle = t.handle ?? (await surface.open(t.task))\n try {\n const allTools = await surface.tools(t.task, handle)\n // Tool SELECTION is a strategy decision (which of the domain's tools this shot\n // sees) — restriction-only: a strategy can focus a shot, never grant a tool the\n // domain didn't offer. Unknown names fail loud (an authored typo must not\n // silently become an unrestricted shot).\n let tools = allTools\n if (t.tools) {\n const known = new Set(allTools.map((tool) => tool.function.name))\n const unknown = t.tools.filter((name) => !known.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `shot tools: unknown tool name(s) ${unknown.join(', ')} — domain offers: ${[...known].join(', ')}`,\n )\n }\n const want = new Set(t.tools)\n tools = allTools.filter((tool) => want.has(tool.function.name))\n }\n // An EMPTY messages array means \"fresh\" too — an authored body passing\n // `messages: []` must not silently blank the worker's system/task prompt.\n const messages: Msg[] = t.messages?.length\n ? t.messages\n : [\n { role: 'system', content: t.persona?.systemPrompt ?? t.task.systemPrompt },\n { role: 'user', content: `${t.task.userPrompt}\\n\\n${taskNudge}` },\n ]\n // On a CARRIED conversation, a persona switch arrives as a role hand-off message.\n if (t.messages?.length && t.persona?.systemPrompt) {\n messages.push({\n role: 'user',\n content: `[hand-off] You are now acting as: ${t.persona.systemPrompt}`,\n })\n }\n if (t.steer) messages.push({ role: 'user', content: t.steer })\n const shot = await runShot(surface, t.task, handle, tools, messages, opts, t.persona?.model)\n const s = await surface.score(t.task, handle)\n const score = s.total > 0 ? s.passes / s.total : 0\n const out: ShotResult = {\n messages: shot.messages,\n score,\n passes: s.passes,\n total: s.total,\n completions: shot.completions,\n toolErrors: shot.toolErrors,\n }\n artifact = {\n outRef: `shot:${handle.id}:${shot.completions}:${s.passes}/${s.total}`,\n out,\n verdict: { valid: s.total > 0 && s.passes === s.total, score },\n // Real usage to the conserved pool: tokens from the router responses; usd only\n // when the model is in the price table (never a fabricated number).\n spent: {\n iterations: shot.completions,\n tokens: shot.tokens,\n usd: isModelPriced(opts.model)\n ? estimateCost(shot.tokens.input, shot.tokens.output, opts.model)\n : 0,\n ms: 0,\n },\n }\n return artifact\n } finally {\n if (own) await surface.close(handle)\n }\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('shotExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\nfunction analystExecutor(opts: AgenticOptions): Executor<unknown> {\n let artifact: ExecutorResult<unknown> | undefined\n return {\n runtime: 'agentic-analyst',\n async execute(task: unknown): Promise<ExecutorResult<unknown>> {\n const t = task as { task: AgenticTask; messages: Msg[]; rawInstruction?: string }\n const { steer, tokens } = t.rawInstruction\n ? await consultAnalyst(t.task, t.messages, t.rawInstruction, opts)\n : await analyze(t.task, t.messages, opts)\n const analystModel = opts.analystModel ?? opts.model\n artifact = {\n outRef: `analyst:${steer.length}`,\n out: steer,\n spent: {\n iterations: 1,\n tokens,\n usd: isModelPriced(analystModel)\n ? estimateCost(tokens.input, tokens.output, analystModel)\n : 0,\n ms: 0,\n },\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('analystExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\n/**\n * Registry dispatching on the child's role tag — fresh executor per spawn (no\n * shared-instance race). `withDriverExecutor` wraps it so a `role:'driver'` child resolves\n * to the recursive driver-executor (a child that drives its OWN children — agents drive\n * agents) before this leaf dispatch; `shot`/`analyst` children resolve to their leaf\n * executors here unchanged.\n */\nfunction agenticRegistry(surface: AgenticSurface, opts: AgenticOptions): ExecutorRegistry {\n const leaves: ExecutorRegistry = {\n register() {\n throw new Error('agenticRegistry: register unsupported')\n },\n resolve<Out>(spec: AgentSpec) {\n const role = (spec.profile.metadata as { role?: string } | undefined)?.role\n const factory: ExecutorFactory<Out> = (_s: AgentSpec, _ctx: ExecutorContext) =>\n (role === 'analyst' ? analystExecutor(opts) : shotExecutor(surface, opts)) as Executor<Out>\n return { succeeded: true as const, value: factory }\n },\n }\n return withDriverExecutor(leaves)\n}\n\nfunction leaf(name: string, role: 'shot' | 'analyst'): Agent<unknown, Outcome<unknown>> {\n const agent = {\n name,\n executorSpec: { profile: { name, metadata: { role } }, harness: null } as unknown as AgentSpec,\n act(): Promise<Outcome<unknown>> {\n // SPAWNED, not run: its `executorSpec` (role shot/analyst) resolves a leaf executor\n // the scope drives. `act` is never called for a spawned child; it fails loud if\n // mis-used as a root. A `role:'driver'` child instead resolves to the recursive\n // driver-executor (agents drive agents) — see `withDriverExecutor`.\n throw new Error(`agentic: spawned child \"${name}\" was run directly (the executor drives it)`)\n },\n }\n return agent as Agent<unknown, Outcome<unknown>>\n}\n\n/** Drain exactly one settlement (the just-spawned child). */\nasync function drainOne(scope: Scope<Outcome<unknown>>): Promise<Settled<Outcome<unknown>>> {\n const s = await scope.next()\n if (!s) throw new Error('agentic: spawned child never settled')\n return s\n}\n\n// ── The result + the two drivers (domain-blind Agents run by the Supervisor) ─────\n\nexport interface AgenticRunResult {\n /** The strategy name (built-in 'depth'/'breadth' or a custom strategy's name). */\n mode: string\n score: number\n resolved: boolean\n completions: number\n /** DEPTH: score after each shot — the progress-over-rounds curve. BREADTH: best-so-far per rollout. */\n progression: number[]\n shots: number\n /** The cost vector, stamped by `runAgentic` from the Supervisor's conserved pool: real\n * router tokens, priced usd (0 when the model is unpriced — never fabricated), wall ms. */\n usd: number\n ms: number\n tokens: { input: number; output: number }\n}\n\nconst perChild = (innerTurns: number): Budget => ({\n maxIterations: innerTurns + 1,\n maxTokens: 1_000_000,\n})\n\n/** DEPTH: one persistent artifact, carried across analyst-steered shots. */\nexport function depthStrategy(\n surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n cfg: { maxShots: number },\n): Agent<unknown, Outcome<unknown>> {\n const innerTurns = opts.innerTurns ?? 4\n let pendingSteer: string | undefined // analyst-derived steer carried between shots\n return {\n name: 'depth',\n async act(_t, scope): Promise<Outcome<unknown>> {\n const handle = await surface.open(task)\n const progression: number[] = []\n let messages: Msg[] | undefined\n let completions = 0\n let shots = 0\n try {\n for (shots = 0; shots < cfg.maxShots; shots += 1) {\n const child = leaf(`shot:${shots}`, 'shot')\n const steer = shots === 0 ? undefined : pendingSteer\n const res = scope.spawn(child, { task, handle, messages, steer } as ShotTask, {\n budget: perChild(innerTurns),\n label: `shot:${shots}`,\n })\n if (!res.ok) break\n const settled = await drainOne(scope)\n if (settled.kind === 'down') break\n const out = settled.out as unknown as ShotResult\n messages = out.messages\n completions += out.completions\n progression.push(out.score)\n if (out.score >= 1 || shots === cfg.maxShots - 1) break\n // Analyst reads the trajectory (firewalled) → steer the resumed session.\n const aChild = leaf(`analyst:${shots}`, 'analyst')\n const aRes = scope.spawn(\n aChild,\n { task, messages },\n { budget: perChild(1), label: `analyst:${shots}` },\n )\n if (!aRes.ok) break\n const aSettled = await drainOne(scope)\n completions += 1\n if (aSettled.kind === 'down') break\n const findings = aSettled.out as unknown as string\n if (/^\\s*COMPLETE\\b/i.test(findings)) break\n pendingSteer = `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`\n }\n const final = await surface.score(task, handle)\n const score = final.total > 0 ? final.passes / final.total : 0\n return {\n kind: 'done',\n deliverable: {\n mode: 'depth',\n score,\n resolved: final.total > 0 && final.passes === final.total,\n completions,\n progression,\n shots: shots + 1,\n },\n }\n } finally {\n await surface.close(handle)\n }\n },\n }\n}\n\n/** BREADTH: K independent rollouts (each own artifact), verifier picks the best. */\nexport function breadthStrategy(\n _surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n cfg: { width: number },\n): Agent<unknown, Outcome<unknown>> {\n const innerTurns = opts.innerTurns ?? 4\n return {\n name: 'breadth',\n async act(_t, scope): Promise<Outcome<unknown>> {\n let opened = 0\n for (let k = 0; k < cfg.width; k += 1) {\n const res = scope.spawn(leaf(`rollout:${k}`, 'shot'), { task } as ShotTask, {\n budget: perChild(innerTurns),\n label: `rollout:${k}`,\n })\n if (res.ok) opened += 1\n }\n if (opened === 0) return { kind: 'blocked', blockers: ['breadth: pool admitted no rollout'] }\n let best = -1\n let bestResolved = false\n let completions = 0\n const progression: number[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n if (s.kind === 'down') continue\n const out = s.out as unknown as ShotResult\n completions += out.completions\n if (out.score > best) best = out.score\n if (out.total > 0 && out.passes === out.total) bestResolved = true\n progression.push(best)\n }\n if (best < 0) return { kind: 'blocked', blockers: ['breadth: every rollout went down'] }\n return {\n kind: 'done',\n deliverable: {\n mode: 'breadth',\n score: best,\n resolved: bestResolved,\n completions,\n progression,\n shots: opened,\n },\n }\n },\n }\n}\n\n/**\n * A Strategy is HOW you spend the compute budget to beat the Environment's check — it\n * builds the driver `Agent` the Supervisor runs. This is the OPEN extension point: a dev\n * authors their own by implementing `driver()` to return an Agent whose `act()` spawns\n * shots/analysts via `scope.spawn` / `scope.next` / `scope.send`. The two built-ins are\n * the reference implementations to copy:\n * sample — K INDEPENDENT attempts, keep the best-verifying (best-of-N / resample).\n * refine — attempt → observe() reads the trace → steer the next → repeat (iterate).\n * (A multi-agent \"team\" is just a Strategy whose driver spawns several different agents.)\n */\nexport interface Strategy {\n readonly name: string\n driver(\n surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n budget: number,\n ): Agent<unknown, Outcome<unknown>>\n}\n\nexport const sample: Strategy = {\n name: 'sample',\n driver: (surface, task, opts, budget) => breadthStrategy(surface, task, opts, { width: budget }),\n}\nexport const refine: Strategy = {\n name: 'refine',\n driver: (surface, task, opts, budget) => depthStrategy(surface, task, opts, { maxShots: budget }),\n}\n\n// ── The composable LEGO: author a strategy in ~15 lines from two steps ───────────\n//\n// A strategy body gets `shot()` (run one worker attempt over an artifact) and\n// `critique()` (the firewalled analyst reads the trace → a steer). Compose them — no\n// Supervisor/Scope ceremony. This is the skillifiable unit: an agent can emit a\n// `defineStrategy(name, body)` of a few step-calls; it can't reliably emit a 70-line\n// driver. (depthStrategy/breadthStrategy are the hand-written reference impls; refine/sample\n// stay on them — proven — while NEW strategies are authored compactly here.)\n\n/** A role for one shot — multi-agent loops (researcher + engineer, a panel of k\n * researchers) give each shot its own system prompt and optionally its own model. */\nexport interface ShotPersona {\n /** Replaces the task's systemPrompt for a FRESH shot; on a carried conversation it is\n * injected as a hand-off message (the transcript's earlier roles stay intact). */\n systemPrompt?: string\n /** Per-shot model override (e.g. a stronger model for the engineer shot). */\n model?: string\n}\n\nexport interface ShotSpec {\n /** present ⇒ continue this artifact (depth); absent ⇒ the shot opens a fresh one (sample/restart). */\n handle?: ArtifactHandle\n messages?: Msg[]\n steer?: string\n persona?: ShotPersona\n /** Restrict THIS shot to a subset of the domain's tools (by name) — focus a shot on\n * the relevant capabilities. Restriction-only; unknown names throw. Omitted ⇒ all. */\n tools?: string[]\n}\nexport interface StrategyResult {\n score: number\n resolved: boolean\n completions: number\n progression: number[]\n shots: number\n}\n/** Artifact lifecycle a strategy may manage itself — open/close ONLY. Raw `call`/`score`\n * are withheld: scores reach the body solely through `shot()`'s ShotResult (the\n * harness-verified channel), so a body cannot peek the check or fabricate around it. */\nexport interface StrategyArtifacts {\n readonly name: string\n open(task: AgenticTask): Promise<ArtifactHandle>\n close(handle: ArtifactHandle): Promise<void>\n}\n\n/** What a strategy body composes with: the artifact lifecycle, the budget, and the two steps. */\nexport interface StrategyCtx {\n /** Open/close artifacts the body manages itself (e.g. one persistent handle for depth). */\n readonly surface: StrategyArtifacts\n readonly task: AgenticTask\n readonly opts: AgenticOptions\n readonly budget: number\n readonly scope: Scope<Outcome<unknown>>\n /** Run ONE worker shot; its harness-scored result, or null if it went down. */\n shot(spec?: ShotSpec): Promise<ShotResult | null>\n /** The firewalled critic reads the trajectory → a steer string, or null on COMPLETE/down. */\n critique(messages: Msg[]): Promise<string | null>\n /** The RAW analyst channel: the firewalled critic answers `instruction` over the\n * trajectory verbatim — no findings extraction, so verdict-shaped formats\n * (CONTINUE/STOP decisions, calibrated predictions) survive. Same firewall:\n * trajectory in, never scores. Null when the analyst went down. */\n consult(messages: Msg[], instruction: string): Promise<string | null>\n /** The tools THIS artifact's task actually offers (names + descriptions only — never\n * the implementations). Tool sets vary per task on heterogeneous domains; a strategy\n * that restricts shots MUST select from this list, never from hardcoded names. */\n listTools(handle: ArtifactHandle): Promise<Array<{ name: string; description?: string }>>\n}\n\n/** Author a Strategy from the composable steps — the open, compact way. */\nexport function defineStrategy(\n name: string,\n run: (ctx: StrategyCtx) => Promise<StrategyResult>,\n): Strategy {\n return {\n name,\n driver: (surface, task, opts, budget) => ({\n name,\n async act(_t, scope): Promise<Outcome<unknown>> {\n let seq = 0\n const innerTurns = opts.innerTurns ?? 4\n // HARNESS-VERIFIED scoring: the deliverable score is computed HERE from the shots\n // the harness actually brokered + scored via surface.score() — NEVER the value the\n // (possibly authored / adversarial) body returns. An authored strategy cannot\n // fabricate a win; it can only report what its real shots achieved. Keep-best.\n let verifiedBest = 0\n let verifiedResolved = false\n // Close is IDEMPOTENT by construction for the body: authored code double-closes\n // (often as a floating promise inside a finally), and a second close must be a\n // no-op rather than a domain error that escapes as an unhandled rejection and\n // kills the whole benchmark run. A close failure on a LIVE handle still throws.\n const openHandles = new Set<string>()\n const ctx: StrategyCtx = {\n // Narrowed to open/close — the body gets no raw call()/score() access.\n surface: {\n name: surface.name,\n open: async (t) => {\n const h = await surface.open(t)\n openHandles.add(h.id)\n return h\n },\n close: async (h) => {\n if (!h || !openHandles.has(h.id)) return\n openHandles.delete(h.id)\n await surface.close(h)\n },\n },\n task,\n opts,\n budget,\n scope,\n async shot(spec) {\n const child = leaf(`shot:${seq}`, 'shot')\n seq += 1\n const res = scope.spawn(\n child,\n {\n task,\n handle: spec?.handle,\n messages: spec?.messages,\n steer: spec?.steer,\n persona: spec?.persona,\n tools: spec?.tools,\n } as ShotTask,\n { budget: perChild(innerTurns), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n const out = settled.out as unknown as ShotResult\n if (out.score > verifiedBest) verifiedBest = out.score\n if (out.total > 0 && out.passes === out.total) verifiedResolved = true\n return out\n },\n async listTools(handle) {\n const tools = await surface.tools(task, handle)\n return tools.map((t) => ({\n name: t.function.name,\n ...(t.function.description ? { description: t.function.description } : {}),\n }))\n },\n async critique(messages) {\n const child = leaf(`analyst:${seq}`, 'analyst')\n seq += 1\n const res = scope.spawn(\n child,\n { task, messages },\n { budget: perChild(1), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n const findings = settled.out as unknown as string\n return /^\\s*COMPLETE\\b/i.test(findings) ? null : findings\n },\n async consult(messages, instruction) {\n const child = leaf(`analyst:${seq}`, 'analyst')\n seq += 1\n const res = scope.spawn(\n child,\n { task, messages, rawInstruction: instruction },\n { budget: perChild(1), label: child.name },\n )\n if (!res.ok) return null\n const settled = await drainOne(scope)\n if (settled.kind === 'down') return null\n return settled.out as unknown as string\n },\n }\n const r = await run(ctx)\n // Override the body's self-reported score/resolved with the harness-verified\n // values. The body's progression/completions/shots are advisory (display only) —\n // but NORMALIZED: an authored body that omits them must not poison downstream\n // consumers (losses tables, anytime curves) with undefined.\n return {\n kind: 'done',\n deliverable: {\n mode: name,\n ...r,\n progression: Array.isArray(r.progression) ? r.progression : [],\n completions: typeof r.completions === 'number' ? r.completions : 0,\n shots: typeof r.shots === 'number' ? r.shots : 0,\n score: verifiedBest,\n resolved: verifiedResolved,\n },\n }\n },\n }),\n }\n}\n\n/** A NEW strategy, authored from the steps (~20 lines): refine, but when a steered shot\n * fails to improve the score it ABANDONS that line and restarts fresh (branch-when-stuck)\n * — the widen/MCTS idea the depth-stuck failure motivated. Scored keep-best (the best\n * checkpoint across all lines), the deployable metric. This is the \"experts build BETTER\n * optimizations\" path: a new technique, compact, with zero Supervisor ceremony. */\nexport const adaptiveRefine = defineStrategy(\n 'adaptiveRefine',\n async ({ surface, task, budget, shot, critique }) => {\n let handle = await surface.open(task)\n const progression: number[] = []\n let messages: Msg[] | undefined\n let steer: string | undefined\n let completions = 0\n let best = -1\n let shots = 0\n try {\n for (shots = 0; shots < budget; shots += 1) {\n const out = await shot({ handle, messages, steer })\n if (!out) break\n completions += out.completions\n progression.push(out.score)\n if (out.score >= 1) break\n if (out.score <= best) {\n // Stuck: steering isn't improving this line — abandon it, restart fresh.\n await surface.close(handle)\n handle = await surface.open(task)\n messages = undefined\n steer = undefined\n continue\n }\n best = out.score\n messages = out.messages\n const findings = await critique(out.messages)\n completions += 1\n if (!findings) break\n steer = `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`\n }\n const score = progression.length ? Math.max(...progression) : 0\n return { score, resolved: score >= 1, completions, progression, shots }\n } finally {\n await surface.close(handle)\n }\n },\n)\n\n/** The explore-then-exploit MIX: spend ⌈budget/2⌉ on independent samples (kept open),\n * then refine the best-verifying line with the remaining budget. Sample's basin escape +\n * refine's accumulation — the third built-in, authored from the public steps. */\nexport const sampleThenRefine = defineStrategy(\n 'sampleThenRefine',\n async ({ surface, task, budget, shot, critique }) => {\n const explore = Math.max(1, Math.ceil(budget / 2))\n const open = new Set<ArtifactHandle>()\n const progression: number[] = []\n let completions = 0\n let shots = 0\n try {\n // Explore: independent lines on handles we own (kept open so the best can continue).\n let best: { handle: ArtifactHandle; out: ShotResult } | undefined\n for (let i = 0; i < explore; i += 1) {\n const handle = await surface.open(task)\n open.add(handle)\n const out = await shot({ handle })\n if (!out) continue\n shots += 1\n completions += out.completions\n progression.push(out.score)\n if (!best || out.score > best.out.score) best = { handle, out }\n if (out.score >= 1) break\n }\n if (!best) return { score: 0, resolved: false, completions, progression, shots }\n // Exploit: close the losers, refine the winner with the remaining budget.\n for (const h of [...open]) {\n if (h !== best.handle) {\n await surface.close(h)\n open.delete(h)\n }\n }\n let messages = best.out.messages\n let topScore = best.out.score\n for (let i = explore; i < budget && topScore < 1; i += 1) {\n const findings = await critique(messages)\n completions += 1\n if (!findings) break\n const out = await shot({\n handle: best.handle,\n messages,\n steer: `A reviewer flagged unfinished items:\\n${findings}\\n\\nAddress each with the tools, verify they took, then continue.`,\n })\n if (!out) break\n shots += 1\n completions += out.completions\n progression.push(out.score)\n messages = out.messages\n if (out.score > topScore) topScore = out.score\n }\n const score = progression.length ? Math.max(...progression) : 0\n return { score, resolved: score >= 1, completions, progression, shots }\n } finally {\n for (const h of open) await surface.close(h)\n }\n },\n)\n\nexport interface RunAgenticOptions extends AgenticOptions {\n surface: AgenticSurface\n task: AgenticTask\n /** Lifecycle observability — every spawn/settle (shots, analysts) streams here live.\n * The seam online watchdogs/route-auditors subscribe to. */\n hooks?: RuntimeHooks\n /** A Strategy (the open way) — author/pass your own. Overrides `mode` when present. */\n strategy?: Strategy\n /** Built-in shorthand: 'depth'→refine, 'breadth'→sample. Default 'depth'. */\n mode?: 'depth' | 'breadth'\n /** budget: refine→max shots; sample→rollout width. */\n budget: number\n rootBudget?: Budget\n}\n\n/** Run a Strategy through the keystone Supervisor — `Agent.act` over a conserved-budget Scope. */\nexport async function runAgentic(opts: RunAgenticOptions): Promise<AgenticRunResult> {\n const strategy: Strategy = opts.strategy ?? (opts.mode === 'breadth' ? sample : refine)\n const driver = strategy.driver(opts.surface, opts.task, opts, opts.budget)\n const supervisor = createSupervisor<unknown, Outcome<unknown>>()\n const root: Budget = opts.rootBudget ?? {\n maxIterations: opts.budget * ((opts.innerTurns ?? 4) + 2),\n maxTokens: 1_000_000_000,\n }\n const started = Date.now()\n const result = await supervisor.run(driver, undefined, {\n budget: root,\n runId: `agentic:${strategy.name}:${opts.task.id}`,\n journal: new InMemorySpawnJournal(),\n blobs: new InMemoryResultBlobStore(),\n executors: agenticRegistry(opts.surface, opts),\n maxDepth: 3,\n ...(opts.hooks ? { hooks: opts.hooks } : {}),\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const reason =\n result.kind === 'winner'\n ? `blocked: ${(result.out as { blockers?: string[] }).blockers?.join('; ')}`\n : `no-winner: ${result.reason}`\n throw new Error(`runAgentic(${strategy.name}) produced no result — ${reason}`)\n }\n // Drivers deliver the strategy outcome; the cost vector is stamped here from `result.spentTotal`\n // (the journal aggregate: settled child work + metered driver inference) + wall clock.\n const core = result.out.deliverable as Omit<AgenticRunResult, 'usd' | 'ms' | 'tokens'>\n return {\n ...core,\n usd: result.spentTotal.usd,\n tokens: result.spentTotal.tokens,\n ms: Date.now() - started,\n }\n}\n","/**\n * `openSandboxRun` — the ONE harness-agnostic seam for running an agent in a\n * sandbox over a persistent artifact: run it, stream it, RESUME the same session\n * across turns. Domain-agnostic: a coding agent, a research agent, a tax/legal\n * agent — all flow through this; the domain lives only in the `Deliverable<Out>`\n * the caller supplies, never in a per-domain copy of this function.\n *\n * It is a thin facade (NOT a new layer) over code that already exists and is\n * already hardened:\n * - `acquireSandbox` — cold-start / 502-503-504 / gateway-timeout recovery,\n * - `buildBackendOptions` — the harness IS `backend.type` (opencode / codex /\n * claude-code / kimi-code / hermes / pi); the only \"which agent\" knob,\n * - `createSandboxLineage` — `start` mints a session; `resume` continues the\n * SAME server-side session with a fail-loud `assertSessionLive`.\n *\n * The one genuinely-new piece is {@link Deliverable}: it widens the pure\n * `OutputAdapter.parse(events)` to ALSO admit a post-turn read off the box FS —\n * the structural gap that made the bench gates hand-roll `box.fs.read`, because a\n * large produced file (a git diff, a generated document) truncates in the chat\n * stream and a pure events-parser cannot reach the workspace. Per the SDK, a\n * RELATIVE `deliverable.path` resolves from the workspace root and an ABSOLUTE one\n * (e.g. `/tmp/solution.patch`) reads the container filesystem directly — both are\n * valid; pick the one the agent actually wrote to. Avoid `..` traversal segments.\n *\n * What this deliberately does NOT do (so it stays a facade, not slop): no custom\n * reconnect/replay (the SDK + platform own per-session buffering + `Last-Event-ID`);\n * no fork verb (platform CRIU is probe-gated and currently absent — fork lives in\n * `SandboxLineage.fork` behind the capability probe, surfaced only if it returns).\n * It is also distinct from `runLoop`: `runLoop` is the multi-round, driver-driven\n * kernel (fresh box per round, events deliverable); this is a SINGLE rollout +\n * artifact-or-events deliverable + resume over ONE persistent box.\n */\n\nimport type { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport type { RuntimeHooks, RuntimeHookTarget } from '../runtime-hooks'\nimport { notifyRuntimeHookEvent } from '../runtime-hooks'\nimport { probeSandboxCapabilities } from './sandbox-capabilities'\nimport { createSandboxLineage, type SandboxLineageHandle } from './sandbox-lineage'\nimport type { AgentRunSpec, SandboxClient } from './types'\nimport { isAbortError, randomSuffix, sleep } from './util'\n\n/**\n * @experimental\n * How a typed deliverable `Out` is materialized from a finished turn.\n * - `events` — pure parse over the event array (identical to `OutputAdapter`).\n * - `artifact` — read a file off the box AFTER the turn drains, then map it (+ the\n * events). For diffs/codebases/documents that don't fit the chat\n * stream. `path` relative ⇒ workspace root; absolute ⇒ container FS.\n */\nexport type Deliverable<Out> =\n | { kind: 'events'; fromEvents: (events: SandboxEvent[]) => Out }\n | { kind: 'artifact'; path: string; fromArtifact: (raw: string, events: SandboxEvent[]) => Out }\n\n/**\n * @experimental\n * One finished turn over the artifact. A failed FS read is surfaced in `readError`\n * (never masked as an empty deliverable) so a caller distinguishes \"agent produced\n * nothing\" from a transport/FS fault.\n */\nexport interface TurnResult<Out> {\n out: Out\n events: SandboxEvent[]\n readError?: string\n}\n\n/**\n * @experimental\n * Thrown when a turn is aborted/timed-out mid-settle. Carries the events drained\n * BEFORE the abort fired (and any in-progress `readError`) so an aborted run is\n * DIAGNOSABLE — the caller can tell never-started (`events: []`) from looped\n * (many events, no terminal `result`) from produced-nothing-then-cancelled.\n *\n * `name === 'AbortError'`, so existing `err.name === 'AbortError'` callers (the\n * loop kernel, scope, supervise runtime) keep matching it unchanged.\n */\nexport class SandboxRunAbortError extends Error {\n override readonly name = 'AbortError'\n /** Events drained from the stream before the abort interrupted the turn. */\n readonly events: SandboxEvent[]\n /** The last artifact read error, if the abort fired during the retry loop. */\n readonly readError?: string\n constructor(events: SandboxEvent[], readError?: string) {\n super('aborted')\n this.events = events\n if (readError !== undefined) this.readError = readError\n }\n}\n\n/** @experimental A live run over ONE persistent artifact (box + session). Close it\n * when done — `close()` tears the box down. */\nexport interface SandboxRun<Out> {\n readonly box: SandboxInstance\n readonly sessionId: string\n /** First turn over the fresh box (mints the session). Throws if already started. */\n start(prompt: string): Promise<TurnResult<Out>>\n /** Continue THE SAME session over THE SAME artifact — a resumed turn/rollout. */\n resume(prompt: string): Promise<TurnResult<Out>>\n close(): Promise<void>\n}\n\n/** @experimental */\nexport interface OpenSandboxRunOptions {\n /** Profile + sandbox env/overrides. `sandboxOverrides.backend.type` is the harness. */\n agentRun: AgentRunSpec<string>\n signal: AbortSignal\n /** Optional execution-scoped observers. Hook failures never fail the run. */\n hooks?: RuntimeHooks\n /** Stable run id for trace joins. Defaults to a short runtime-minted id. */\n runId?: string\n /** Optional benchmark/scenario id carried into emitted hook events. */\n scenarioId?: string\n /** Test seam for deterministic hook timestamps. Defaults to `Date.now`. */\n now?: () => number\n /** Bounds box-creation bursts inside lineage fanout. Default from lineage. */\n maxConcurrency?: number\n /** Base backoff (ms) for retrying a transient artifact `fs.read` failure; the i-th\n * retry waits `readRetryDelayMs * i`. Default 1000. Set 0 to disable the wait (tests). */\n readRetryDelayMs?: number\n}\n\n/**\n * @experimental\n * Open a sandbox run. Harness-agnostic: the harness lives in\n * `options.agentRun.sandboxOverrides.backend.type`, so opencode/codex/claude-code/\n * kimi-code all flow through this one entrypoint with identical env/auth wiring.\n */\nexport async function openSandboxRun<Out>(\n client: SandboxClient,\n options: OpenSandboxRunOptions,\n deliverable: Deliverable<Out>,\n): Promise<SandboxRun<Out>> {\n const runId = options.runId ?? `sandbox-run-${randomSuffix()}`\n const now = options.now ?? Date.now\n const capabilities = await probeSandboxCapabilities(client)\n const lineage = createSandboxLineage(client, capabilities, {\n ...(options.maxConcurrency !== undefined ? { maxConcurrency: options.maxConcurrency } : {}),\n })\n let handle: SandboxLineageHandle | undefined\n let started = false\n let runStartedAt: number | undefined\n let failed = false\n let turnCount = 0\n\n function emit(event: {\n target: RuntimeHookTarget\n phase: 'before' | 'after' | 'error'\n timestamp: number\n stepIndex?: number\n payload?: Record<string, unknown>\n }): void {\n notifyRuntimeHookEvent(\n options.hooks,\n {\n id: `${runId}:${event.target}:${event.phase}${\n event.stepIndex === undefined ? '' : `:${event.stepIndex}`\n }`,\n runId,\n scenarioId: options.scenarioId,\n target: event.target,\n phase: event.phase,\n timestamp: event.timestamp,\n stepIndex: event.stepIndex,\n payload: event.payload,\n metadata: { producer: 'openSandboxRun' },\n },\n { signal: options.signal },\n )\n }\n\n const runPayload = (): Record<string, unknown> => ({\n agentName: options.agentRun.name ?? options.agentRun.profile.name ?? 'agent',\n profileName: options.agentRun.profile.name,\n backendType: backendType(options.agentRun),\n deliverableKind: deliverable.kind,\n ...(deliverable.kind === 'artifact' ? { deliverablePath: deliverable.path } : {}),\n ...(handle ? { sessionId: handle.sessionId, sandboxId: handle.box.id } : {}),\n })\n\n const turnPayload = (\n prompt: string,\n turnKind: 'start' | 'resume',\n startedAt: number,\n result?: TurnResult<Out>,\n error?: unknown,\n ): Record<string, unknown> => ({\n ...runPayload(),\n turnKind,\n promptChars: prompt.length,\n promptHash: hashText(prompt),\n ...(result !== undefined || error !== undefined\n ? { durationMs: Math.max(0, now() - startedAt) }\n : {}),\n ...(result\n ? {\n eventCount: result.events.length,\n eventTypes: eventTypeCounts(result.events),\n ...(result.readError !== undefined ? { readError: result.readError } : {}),\n }\n : {}),\n ...(error !== undefined ? { error: errorMessage(error) } : {}),\n })\n\n // `box` is passed in (not read from the closed-over `handle`) so the invariant\n // is type-level, not call-order discipline.\n async function settle(\n box: SandboxInstance,\n events: AsyncIterable<SandboxEvent>,\n ): Promise<TurnResult<Out>> {\n const collected: SandboxEvent[] = []\n // The stream itself can throw an AbortError when the run is cancelled mid-drain;\n // re-throw it carrying the events drained so far so the partial trace is not lost.\n try {\n for await (const ev of events) collected.push(ev)\n } catch (err) {\n if (isAbortError(err)) throw new SandboxRunAbortError(collected)\n throw err\n }\n if (deliverable.kind === 'events') {\n return { out: deliverable.fromEvents(collected), events: collected }\n }\n if (options.signal.aborted) throw new SandboxRunAbortError(collected)\n let raw = ''\n let readError: string | undefined\n // The data plane can transiently 404 a just-written artifact (write not yet\n // flushed, or an edge-read blip) — retry a few times with backoff before\n // declaring the deliverable empty, so a transient read failure is not recorded\n // as \"the agent produced nothing\".\n const readAttempts = 4\n const readDelayMs = options.readRetryDelayMs ?? 1000\n for (let attempt = 0; attempt < readAttempts; attempt += 1) {\n if (options.signal.aborted) throw new SandboxRunAbortError(collected, readError)\n try {\n raw = await box.fs.read(deliverable.path)\n readError = undefined\n break\n } catch (err) {\n readError = err instanceof Error ? err.message : String(err)\n if (attempt < readAttempts - 1 && readDelayMs > 0)\n await sleep(readDelayMs * (attempt + 1), options.signal)\n }\n }\n return {\n out: deliverable.fromArtifact(raw, collected),\n events: collected,\n ...(readError !== undefined ? { readError } : {}),\n }\n }\n\n return {\n get box(): SandboxInstance {\n if (!handle) throw new Error('openSandboxRun: box unavailable before start()')\n return handle.box\n },\n get sessionId(): string {\n if (!handle) throw new Error('openSandboxRun: sessionId unavailable before start()')\n return handle.sessionId\n },\n async start(prompt) {\n if (started)\n throw new Error(\n 'openSandboxRun: start() already called — use resume() to continue the session',\n )\n started = true\n runStartedAt = now()\n emit({\n target: 'agent.run',\n phase: 'before',\n timestamp: runStartedAt,\n payload: { ...runPayload(), turnCount: 0 },\n })\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt),\n })\n // lineage.start uses only spec.profile + sandboxOverrides (the prompt is passed\n // directly, not via taskToPrompt), so the task type is irrelevant here.\n try {\n const r = await lineage.start(\n options.agentRun as AgentRunSpec<unknown>,\n prompt,\n options.signal,\n )\n handle = r.handle\n const result = await settle(handle.box, r.events)\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async resume(prompt) {\n if (!handle) throw new Error('openSandboxRun: resume() called before start()')\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt),\n })\n try {\n const result = await settle(\n handle.box,\n await lineage.continue(handle, prompt, options.signal),\n )\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async close() {\n await lineage.teardown()\n if (runStartedAt !== undefined) {\n emit({\n target: 'agent.run',\n phase: 'after',\n timestamp: now(),\n payload: {\n ...runPayload(),\n turnCount,\n status: failed ? 'error' : 'completed',\n durationMs: Math.max(0, now() - runStartedAt),\n },\n })\n }\n },\n }\n}\n\nfunction backendType<Task>(spec: AgentRunSpec<Task>): unknown {\n const backend = spec.sandboxOverrides?.backend as { type?: unknown } | undefined\n return backend?.type\n}\n\nfunction eventTypeCounts(events: SandboxEvent[]): Record<string, number> {\n const counts: Record<string, number> = {}\n for (const event of events) counts[event.type] = (counts[event.type] ?? 0) + 1\n return counts\n}\n\nfunction hashText(value: string): string {\n let hash = 2166136261\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * @experimental\n *\n * Leak-free steering drivers — the non-LLM controls for the driven loop.\n *\n * These are the two sibling `Driver`s of the `refine` reference driver\n * (examples/driver-loop/driver-loop.ts), differing ONLY in how much of the\n * prior `verdict` their `plan()` is allowed to read. The amount of the verdict\n * a driver reads IS the experimental axis:\n *\n * • refine — reads `verdict.notes` (and/or `verdict.scores`): the grader's\n * findings. A reviewer/judge LLM turns those findings into the\n * next prompt. This is the \"coached\" condition.\n * • dumb — reads ONLY `verdict.valid` (the pass/fail boolean). No findings,\n * no scores, no LLM. The next prompt is one of two fixed strings\n * keyed on pass/fail. This is the leak-free pass/fail control.\n * • naive — reads NOTHING from the verdict. The next prompt is one fixed\n * continuation string every round. This is the leak-free\n * no-signal control.\n *\n * The `dumb → refine` gap measured on the same task therefore isolates how much\n * the grader's findings (its notes/scores) inflate the result beyond a bare\n * pass/fail signal: it is exactly the delta between reading `verdict.valid` and\n * reading `verdict.notes`. The `naive → dumb` gap isolates the value of the\n * pass/fail bit alone. Run all three against one task to attribute a loop's\n * lift to its actual source instead of crediting it to the grader for free.\n *\n * GENERALITY CONTRACT\n * -------------------\n * These builders carry ZERO domain coupling:\n * • The continuation strings are PARAMETERS. The caller passes its own text;\n * the substrate hardcodes none.\n * • The Task shape is OPAQUE. The builder never assumes a `prompt` field (or\n * any field). The caller supplies `applyContinuation(task, text) → Task`,\n * which folds a steering string into the caller's own Task shape — exactly\n * symmetric with the caller-supplied `AgentRunSpec.taskToPrompt`. For a Task\n * that is `{ prompt: string; … }`, the fold is the one-liner\n * `(task, text) => ({ ...task, prompt: text })`.\n *\n * They consume nothing the loop kernel does not already give `plan()`/`decide()`\n * — `runLoop` requires no change. A benchmark picks a driver by name and the\n * kernel does the rest.\n */\n\nimport type { Driver, Iteration } from './types'\n\n/**\n * Terminal-or-continue decision shared by all three steering drivers. The\n * non-terminal `'refine'` keeps the loop running another shot; the terminal\n * `'pick-winner'`/`'fail'` stop it (`isTerminalDecision` in run-loop.ts treats\n * `'pick-winner'` and `'fail'` as terminal and any other string as a request\n * for another round). Identical to the reference refine driver's decision set.\n */\nexport type SteeringDecision = 'refine' | 'pick-winner' | 'fail'\n\n/**\n * Fold a steering string into the caller's Task shape, producing the Task for\n * the next shot. The substrate never assumes how a Task carries its prompt, so\n * the caller supplies this — the same way it supplies `taskToPrompt`. The\n * original `task` is passed so the fold can preserve task-level fields (ids,\n * fixtures, feature names) and replace only the instruction.\n */\nexport type ApplyContinuation<Task> = (task: Task, continuation: string) => Task\n\n/**\n * Shared `decide()` for the steering drivers. Verbatim semantics of the\n * reference refine driver: a valid iteration anywhere → terminal `'pick-winner'`;\n * otherwise `'refine'` (non-terminal, run another shot) while history is under\n * the shot cap, else terminal `'fail'`. Pure over history; reads only\n * `verdict.valid` (never notes/scores) so it adds no leak of its own.\n */\nfunction decideUntilValidOrCapped<Task, Output>(\n history: ReadonlyArray<Iteration<Task, Output>>,\n maxIterations: number,\n): SteeringDecision {\n if (history.some((it) => it.verdict?.valid)) return 'pick-winner'\n return history.length < maxIterations ? 'refine' : 'fail'\n}\n\n/** Options for {@link naiveDriver}. */\nexport interface NaiveDriverOptions<Task> {\n /**\n * The fixed continuation issued every round after shot 0. The same string is\n * sent whether the prior shot passed inspection or not — the naive driver\n * reads no part of the verdict. Domain text is the caller's; the substrate\n * supplies none.\n */\n continuation: string\n /** Folds `continuation` into the caller's Task shape for the next shot. */\n applyContinuation: ApplyContinuation<Task>\n /** Hard shot cap. The loop stops refining once history reaches this length. */\n maxIterations: number\n /** Trace-event identifier. Default `'naive'`. */\n name?: string\n}\n\n/**\n * `naiveDriver` — the no-signal steering control.\n *\n * `plan()` runs the initial `task` at shot 0, then issues the SAME fixed\n * `continuation` every subsequent round until a shot is valid or the cap is\n * hit. It reads NOTHING from `history[last].verdict` — not `.valid`, not\n * `.notes`, not `.scores`. It is the floor a coached loop must beat to earn its\n * coaching: any lift over naive that is not also present in `dumb` is\n * attributable to the pass/fail bit, and any lift of `refine` over `dumb` is\n * attributable to the grader's findings.\n */\nexport function naiveDriver<Task, Output>(\n options: NaiveDriverOptions<Task>,\n): Driver<Task, Output, SteeringDecision> {\n const { continuation, applyContinuation, maxIterations, name = 'naive' } = options\n return {\n name,\n plan(task, history) {\n if (history.length === 0) return Promise.resolve([task])\n const last = history[history.length - 1]\n // Stop once a shot is valid or the cap is reached. The verdict is read\n // ONLY for `.valid` here, never to compose the prompt — the continuation\n // is fixed regardless of how the prior shot scored.\n if (last?.verdict?.valid) return Promise.resolve([])\n if (history.length >= maxIterations) return Promise.resolve([])\n return Promise.resolve([applyContinuation(task, continuation)])\n },\n decide(history) {\n return decideUntilValidOrCapped(history, maxIterations)\n },\n // Pure refine topology (one task per round) — render the steer move.\n describePlan() {\n return { kind: 'refine', rationale: 'naive fixed continuation (no grade signal)' }\n },\n }\n}\n\n/** Options for {@link dumbDriver}. */\nexport interface DumbDriverOptions<Task> {\n /**\n * Continuation issued when the prior shot's verdict is valid. In a\n * stop-on-pass loop this is rarely reached (a valid shot ends the loop), but\n * it is required so the driver is total over the pass/fail bit; pass a\n * confirmation/keep-going string.\n */\n onPass: string\n /** Continuation issued when the prior shot's verdict is NOT valid. */\n onFail: string\n /** Folds the chosen continuation into the caller's Task shape. */\n applyContinuation: ApplyContinuation<Task>\n /** Hard shot cap. The loop stops refining once history reaches this length. */\n maxIterations: number\n /** Trace-event identifier. Default `'dumb'`. */\n name?: string\n}\n\n/**\n * `dumbDriver` — the pass/fail-only steering control.\n *\n * `plan()` runs the initial `task` at shot 0, then reads ONLY\n * `history[last].verdict.valid` (the boolean) and issues `onPass` or `onFail`\n * accordingly. It MUST NOT read `.notes` or `.scores` — that boundary is the\n * leak-free firewall. A `verdict` with no `valid` set (or no verdict) is\n * treated as not-valid, so the driver is total and never throws on a\n * grader/transport gap.\n *\n * The `dumb → refine` gap is the headline measurement: refine reads the\n * grader's `notes`, dumb reads only the pass/fail bit, so the difference is\n * exactly the value the findings add over a bare boolean.\n */\nexport function dumbDriver<Task, Output>(\n options: DumbDriverOptions<Task>,\n): Driver<Task, Output, SteeringDecision> {\n const { onPass, onFail, applyContinuation, maxIterations, name = 'dumb' } = options\n return {\n name,\n plan(task, history) {\n if (history.length === 0) return Promise.resolve([task])\n const last = history[history.length - 1]\n const passed = last?.verdict?.valid === true\n if (passed) return Promise.resolve([])\n if (history.length >= maxIterations) return Promise.resolve([])\n // The ONLY verdict read in the steering path: the pass/fail boolean.\n // `.notes`/`.scores` are deliberately never touched.\n const continuation = passed ? onPass : onFail\n return Promise.resolve([applyContinuation(task, continuation)])\n },\n decide(history) {\n return decideUntilValidOrCapped(history, maxIterations)\n },\n describePlan() {\n return { kind: 'refine', rationale: 'dumb pass/fail-only continuation (no grader findings)' }\n },\n }\n}\n","/**\n * authorStrategy — the agent-authored layer as a package primitive (software-3.0): an\n * LLM reads a benchmark's per-task LOSSES + the defineStrategy contract and writes a NEW\n * optimization strategy as code; the caller gates it like any human-built candidate\n * (runBenchmark + a frozen holdout).\n *\n * Structurally safe by construction: the authored body composes shot()/critique() and\n * spends through the Supervisor's conserved pool — it can be wrong, but it cannot\n * Goodhart the check (it never sees the verifiers) and it cannot win by overspending.\n *\n * The authored module is written to `outDir` and dynamically imported — run under a\n * TS-capable loader (tsx) since models often emit type annotations.\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ChatClient } from '@tangle-network/agent-eval'\nimport type { Strategy } from './strategy'\n\n/** The compressed consumable a skill carries: everything an author needs to emit a loop. */\nexport const strategyAuthorContract = `\nYou author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to\nspend a compute budget to beat a task's deployable check. You compose exactly two steps:\n\n shot(spec?: { handle?, messages?, steer?, persona?, tools? }): Promise<ShotResult | null>\n Runs ONE worker attempt (a bounded tool loop) over an artifact.\n - omit handle => the shot opens its OWN fresh artifact and closes it after (a sample).\n - pass handle => the shot CONTINUES that artifact (state accumulates across shots).\n - messages => the carried conversation (pass the previous ShotResult.messages to continue).\n - steer => a corrective instruction injected before the shot.\n - persona => { systemPrompt?, model? } — give THIS shot its own role and/or model\n (multi-agent strategies: a researcher shot then an engineer shot, a panel of k\n personas over one budget). On a fresh shot the systemPrompt replaces the task's; on\n a carried conversation it arrives as a hand-off message. Same conserved budget.\n - tools => string[] — restrict THIS shot to a subset of the task's tools by\n name (focus an explore shot on read-only tools, an execute shot on write tools).\n Restriction-only; unknown names make the shot fail. ALWAYS select from\n await listTools(handle) — never hardcode. Omitted => the shot sees every tool.\n ShotResult = { messages, score (0..1 on the task's check), passes, total, completions, toolErrors }\n Returns null if the attempt failed infra-wise.\n\n critique(messages): Promise<string | null>\n A firewalled trace-analyst reads the attempt's trajectory and returns ONE corrective\n instruction (or null when it judges the work complete). Costs ~1 completion.\n\n consult(messages, instruction): Promise<string | null>\n The RAW analyst channel: the same firewalled critic answers YOUR instruction over the\n trajectory verbatim (no reformatting) — use it when you need a specific reply format\n (a decision, a prediction). Costs ~1 completion.\n\n surface.open(task) / surface.close(handle)\n Open a persistent artifact you manage yourself (remember to close in a finally).\n close is idempotent — closing an already-closed handle is a safe no-op.\n\n listTools(handle): Promise<Array<{ name, description? }>>\n The tools THIS task actually offers. TOOL SETS VARY PER TASK — if you restrict a\n shot with \\`tools\\`, you MUST pick names from await listTools(handle); hardcoding\n names from an example kills your shots on every task whose tools differ.\n\nRules:\n- ALWAYS await every shot/critique/surface call — a floating promise that rejects\n crashes the whole benchmark run.\n- Stay within ~budget total shots; every shot/critique spends from a conserved pool.\n- For a FRESH attempt OMIT \\`messages\\` entirely (never pass \\`[]\\` — an empty array is a\n fresh conversation too, but be explicit). To CONTINUE, pass the previous\n ShotResult.messages unchanged.\n- Return { score, resolved, completions, progression, shots } — score = the BEST checkpoint\n you reached (keep-best, never final-state), progression = score after each shot.\n- The module must be EXACTLY this shape (no other imports, no commentary outside code):\n\nimport { defineStrategy } from '@tangle-network/agent-runtime/loops'\nexport default defineStrategy('your-strategy-name', async ({ surface, task, budget, shot, critique, listTools }) => {\n // your composition (listTools comes from the destructured context — it is NOT a global)\n})\n`\n\nexport interface AuthorStrategyOptions {\n /** The model-call seam (agent-eval `createChatClient`). */\n chat: ChatClient\n model?: string\n /** A NAMED fallback author tried once when the primary call fails or returns no code\n * block (thinking models time out at the edge on long authoring prompts, or return\n * empty content without `maxTokens`). Opt-in — absent means the primary's failure\n * propagates. */\n fallbackModel?: string\n /** The contract text shown to the author. Default `strategyAuthorContract`. The\n * meta-optimization coordinate: a GEPA/skill loop can evolve this text and gate each\n * variant on the same frozen holdout as any strategy. */\n contract?: string\n /** The environment the losses came from (orientation only — never the verifiers). */\n environmentName: string\n /** The per-task losses table (e.g. JSON.stringify(report.perTask)) — the gradient. */\n lossesJson: string\n /** The budget the strategy must respect (shots/width). */\n budget: number\n /** Where the authored module file is written (created if missing). */\n outDir: string\n temperature?: number\n /** Completion cap — required by thinking-model authors that stream reasoning first. */\n maxTokens?: number\n signal?: AbortSignal\n}\n\n/** Static CONTRACT lint over an authored strategy module — the module-boundary\n * enforcement of the harness's two measurement invariants:\n * - author blindness: the only import allowed is the loops surface. A body that could\n * reach the filesystem, network, or process could read or mutate verifier/artifact\n * state outside the brokered shots, and the harness-verified score would stop\n * meaning \"what the shots achieved\".\n * - conserved dose: no out-of-band compute (fetch/require/eval) — every unit a\n * strategy spends is metered by the Supervisor's pool, which is what makes\n * equal-budget comparisons between strategies valid.\n * A lint, not a sandbox: its job is keeping the benchmark numbers interpretable. */\nexport function assertStrategyContract(code: string): void {\n const allowedImport =\n /^\\s*import\\s+\\{[^}]*\\}\\s+from\\s+['\"]@tangle-network\\/agent-runtime\\/loops['\"]/\n for (const line of code.split('\\n')) {\n if (/^\\s*import\\s/.test(line) && !allowedImport.test(line)) {\n throw new Error(`authored code rejected: foreign import — ${line.trim().slice(0, 120)}`)\n }\n }\n const banned: Array<[RegExp, string]> = [\n [/\\brequire\\s*\\(/, 'require()'],\n [/\\bimport\\s*\\(/, 'dynamic import()'],\n [/\\beval\\s*\\(/, 'eval()'],\n [/new\\s+Function\\s*\\(/, 'new Function()'],\n [/\\bprocess\\s*[.[]/, 'process access'],\n [/\\bglobalThis\\s*[.[]/, 'globalThis access'],\n [/\\bfetch\\s*\\(/, 'network access'],\n [/child_process|node:fs|node:net|node:http|worker_threads/, 'node builtin access'],\n ]\n for (const [re, what] of banned) {\n if (re.test(code)) throw new Error(`authored code rejected: ${what}`)\n }\n}\n\nexport interface AuthoredStrategy {\n strategy: Strategy\n file: string\n code: string\n}\n\n/** One authoring attempt: chat with the given model, extract the fenced module. Throws\n * when the reply carries no code block. */\nasync function requestAuthoredCode(\n opts: AuthorStrategyOptions,\n model: string | undefined,\n): Promise<string> {\n const res = await opts.chat.chat(\n {\n ...(model ? { model } : {}),\n ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),\n messages: [\n {\n role: 'system',\n content:\n 'You are a senior engineer authoring optimization strategies for agent loops. Output exactly one fenced ```ts code block and nothing else.',\n },\n {\n role: 'user',\n content: `${opts.contract ?? strategyAuthorContract}\\n\\nBASELINE RESULTS on the \"${opts.environmentName}\" environment (budget=${opts.budget}):\\n${opts.lossesJson}\\n\\nAuthor ONE new strategy that you expect to beat the baselines on THIS environment at the same budget. Use the losses to target the observed failure mode. Output only the module code block.`,\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n const match = res.content.match(/```(?:ts|typescript)?\\s*\\n([\\s\\S]*?)```/)\n if (!match?.[1]) {\n throw new Error(\n `authorStrategy: no code block in the author's reply (model=${model ?? 'default'}): ${res.content.slice(0, 300)}`,\n )\n }\n return match[1]\n}\n\n/** Author + load a strategy from losses. Throws when the author emits no loadable module;\n * with `fallbackModel` set, the named fallback gets one attempt first. */\nexport async function authorStrategy(opts: AuthorStrategyOptions): Promise<AuthoredStrategy> {\n let code: string\n try {\n code = await requestAuthoredCode(opts, opts.model)\n } catch (primaryError) {\n if (!opts.fallbackModel) throw primaryError\n code = await requestAuthoredCode(opts, opts.fallbackModel)\n }\n assertStrategyContract(code)\n mkdirSync(opts.outDir, { recursive: true })\n const file = join(opts.outDir, `authored-${Date.now()}.mts`)\n writeFileSync(file, code)\n const mod = (await import(`file://${file}`)) as { default?: Strategy }\n if (!mod.default || typeof mod.default.driver !== 'function' || !mod.default.name) {\n throw new Error(`authorStrategy: ${file} does not export a default Strategy`)\n }\n return { strategy: mod.default, file, code }\n}\n","/**\n * runStrategyEvolution — the multi-generation strategy search: per generation the system\n * authors a POPULATION of candidate strategies from the current tournament's losses,\n * plays them against the incumbent at equal budget, and advances a champion; one final\n * promotion decision runs on a NEVER-BEFORE-USED holdout slice through `promotionGate`.\n *\n * Measurement invariants (the reasons this design is shaped the way it is):\n * - The author sees TRAIN losses only. The holdout slice is drawn fresh (disjoint task\n * offsets) after all authoring is done — one promotion decision, one untouched slice,\n * so adaptive reuse of evaluation data never enters the verdict.\n * - Every tournament runs at the same per-strategy budget through the conserved pool;\n * candidates cannot win by overspending.\n * - Champion selection within the search is a SEARCH policy (configurable, default\n * cost-aware: ties on score go to the cheapest strategy — a scalar hides a strategy\n * that ties at half the cost). The promotion verdict never comes from search\n * selection; it comes from the gate on the fresh slice.\n * - Every authored artifact's description length (gzip bits) is recorded, so the\n * artifact-complexity-vs-holdout-gap relation is analyzable from any run's report.\n *\n * Lineage fields (`parent`, `generation`) are recorded on every archive node so a\n * descendant-productivity parent-selection policy can be added without changing the\n * report schema; the v1 search authors from the latest tournament's losses.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { gzipSync } from 'node:zlib'\nimport type { ChatClient } from '@tangle-network/agent-eval'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport { type PromotionVerdict, promotionGate } from './promotion-gate'\nimport {\n type BenchmarkReport,\n type BenchmarkTaskRow,\n type Environment,\n runBenchmark,\n} from './run-benchmark'\nimport {\n type AgenticOptions,\n type AgenticTask,\n refine,\n type Strategy,\n sample,\n sampleThenRefine,\n} from './strategy'\nimport { authorStrategy, strategyAuthorContract } from './strategy-author'\n\nexport interface EvolutionAuthor {\n /** The model-call seam (agent-eval `createChatClient`). */\n chat: ChatClient\n model?: string\n fallbackModel?: string\n temperature?: number\n maxTokens?: number\n}\n\nexport type ChampionPolicy = 'score' | 'costAware'\n\nexport interface StrategyEvolutionConfig {\n environment: Environment\n /** Task supply by DISJOINT slice: `(offset, n)` must return n tasks unique to that\n * offset range. Train draws [0, trainN); the holdout draws [trainN + holdoutOffset,\n * …) — tasks the search never touched. */\n tasks: (offset: number, n: number) => Promise<AgenticTask[]>\n trainN: number\n holdoutN: number\n /** Extra offset past the train slice for the holdout draw (rotate across runs). */\n holdoutOffset?: number\n worker: AgenticOptions\n author: EvolutionAuthor\n /** Rollouts (sample) / shots (refine) per strategy per task. Default 3. */\n budget?: number\n concurrency?: number\n /** Author→tournament rounds after gen0. Default 2. */\n generations?: number\n /** Authored candidates per generation. Default 2. */\n populationSize?: number\n /** The gen0 field. Default [sample, refine, sampleThenRefine]. */\n baselines?: Strategy[]\n /** What \"better\" means for PROMOTION. 'score' (default): the candidate must beat the\n * incumbent's score (superiority gate). 'cost': the candidate must prove score\n * NON-INFERIORITY (not worse by more than `scoreTolerance`) plus significant cost\n * savings — the \"same quality, cheaper\" objective. The author is told the objective\n * and sees per-task spend either way. */\n objective?: 'score' | 'cost'\n /** Cost objective: the score CI lower bound must clear −scoreTolerance. Default 0.05. */\n scoreTolerance?: number\n /** Search-side champion selection. Default 'costAware'. */\n champion?: ChampionPolicy\n /** Score band treated as a tie under 'costAware'. Default 0.01. */\n championEpsilon?: number\n /** Where authored modules are written. */\n outDir: string\n /** Promotion-gate evidence floor (paired holdout tasks). */\n minPairedTasks?: number\n /** BAND-AWARE scoring — concentrate the measurement where lift is possible.\n * Holdout: draw `holdoutPoolN` candidate tasks and run `baselines[0]` once at the run\n * budget as an INDEPENDENT reference screen; keep tasks scoring ≤ `maxRefScore`\n * (headroom exists) and take the first `holdoutN`. Band membership is decided before\n * either finalist touches a task and both finalists then face the SAME tasks — the\n * estimand becomes \"paired lift on headroom tasks\", pre-registered by this config.\n * Train: champion selection ignores zero-spread tasks (every field strategy scored\n * identically — zero selection information, pure noise dilution). */\n band?: {\n holdoutPoolN: number\n /** Keep holdout tasks where the reference scores ≤ this. Default 0.99 — drop only\n * tasks the reference already solves fully (no headroom, a candidate can only tie). */\n maxRefScore?: number\n }\n /** What the author learns from a tournament. 'exact' (default) = scores + progressions\n * per task; 'binary' = pass/fail only — the leakage-bounded channel (one bit per cell\n * per generation reaches the author from the evaluation data). */\n lossesDetail?: 'exact' | 'binary'\n /** Reproducer certification (arXiv:2606.11045): when the final champion is AUTHORED,\n * compress it to a short natural-language summary, have a fresh author re-implement\n * from the summary alone (no losses, no code), and score the reproduction on the same\n * holdout. A reproduction gap is an overfitting signal (their detector: 100%\n * sensitivity / 91% specificity in the ML-agent setting) — recorded on the report,\n * never gate-blocking in v1. */\n reproducerCheck?: {\n /** Word budget for the strategy summary. Default 64. */\n summaryMaxWords?: number\n /** Reproduction counts as faithful when reproducedScore ≥ championScore − tolerance.\n * Default 0.05. */\n tolerance?: number\n }\n /** Endurance: write the run state after every completed phase; with `resume`, a\n * restart skips completed phases (authored modules re-imported from their files).\n * Worst case after a mid-run death is re-paying ONE phase, never the run. */\n checkpoint?: {\n path: string\n resume?: boolean\n }\n /** Called before each benchmark phase (gen0, gen1…, band-screen, holdout, reproduce).\n * The seam for environment recycling — no artifacts span phases, so a runner may\n * recreate a wedge-prone environment container here. */\n onPhase?: (phase: string) => Promise<void>\n onTask?: (phase: string, row: BenchmarkTaskRow, done: number, total: number) => void\n hooks?: RuntimeHooks\n}\n\n/** The on-disk phase ledger — everything needed to skip completed phases on resume. */\ninterface EvolutionCheckpoint {\n gen0?: BenchmarkReport\n gen0Champion?: ChampionPick\n generations: EvolutionGeneration[]\n archive: EvolutionArchiveNode[]\n trajectory: Array<{ generation: number; champion: string; score: number; usd: number }>\n holdout?: BenchmarkReport\n verdict?: PromotionVerdict\n band?: EvolutionBandInfo\n}\n\nexport interface ChampionPick {\n name: string\n score: number\n usd: number\n}\n\nexport interface EvolutionCandidate {\n name: string\n file?: string\n gzipBits?: number\n codeChars?: number\n /** Present when this author attempt failed (recorded, never silent). */\n error?: string\n}\n\nexport interface EvolutionGeneration {\n generation: number\n candidates: EvolutionCandidate[]\n report: BenchmarkReport\n champion: ChampionPick\n}\n\nexport interface EvolutionArchiveNode {\n name: string\n source: 'baseline' | 'authored'\n generation: number\n /** The champion whose tournament losses this candidate was authored from. */\n parent?: string\n gzipBits?: number\n file?: string\n /** Latest measured tournament result — 0 until the node's first tournament settles\n * (an authored node is created before its generation's benchmark runs). */\n score: number\n usd: number\n}\n\nexport interface ReproductionCheck {\n /** The compressed strategy description the reproducer implemented from. */\n summary: string\n reproducedName: string\n file?: string\n championHoldoutScore: number\n reproducedHoldoutScore: number\n /** champion − reproduced (positive = the reproduction fell short). */\n gap: number\n /** reproducedScore ≥ championScore − tolerance. A failed reproduction is an\n * overfitting signal: the champion's win did not fit through the summary. */\n reproducible: boolean\n /** Infra failure during reproduction (distinct from a semantic reproduction failure). */\n error?: string\n}\n\nexport interface EvolutionBandInfo {\n /** Tasks screened by the reference on the holdout pool. */\n screened: number\n /** Tasks kept (reference score ≤ maxRefScore) before truncating to holdoutN. */\n inBand: number\n /** Reference scores per screened task (the screening record). */\n refScores: Array<{ taskId: string; score: number }>\n}\n\nexport interface EvolutionReport {\n gen0: BenchmarkReport\n gen0Champion: ChampionPick\n generations: EvolutionGeneration[]\n archive: EvolutionArchiveNode[]\n finalChampion: ChampionPick\n holdout: BenchmarkReport\n verdict: PromotionVerdict\n /** Present when band screening ran — the verdict's estimand is then \"paired lift on\n * headroom tasks\" (band membership fixed by the reference screen, pre-registered). */\n band?: EvolutionBandInfo\n /** Present when reproducerCheck ran (final champion was authored). */\n reproduction?: ReproductionCheck\n /** SEARCH TELEMETRY, not evidence: each entry is that generation's own train-slice\n * re-measurement, so cross-generation deltas mix true drift with run-to-run variance\n * (entries are unpaired across generations). The only evidence-grade comparison in\n * this report is `verdict` — both finalists measured fresh, paired, on the holdout. */\n trajectory: Array<{ generation: number; champion: string; score: number; usd: number }>\n}\n\n/** Strategy means recomputed over the DISCRIMINATING tasks only — tasks where the field\n * strategies did not all score identically. Zero-spread tasks (everyone 1.0, everyone\n * 0.0, everyone tied) carry no selection information; averaging over them dilutes real\n * differences toward zero. Search-side denoising only — the gate never uses this. */\nexport function discriminatingMeans(\n report: BenchmarkReport,\n fieldOrder: string[],\n): Record<string, { score: number; usd: number }> | null {\n const rows = report.perTask.filter((r) => {\n if (!r.cells) return false\n const scores = fieldOrder.map((n) => r.cells?.[n]?.score).filter((s) => s !== undefined)\n if (scores.length < fieldOrder.length) return false\n return Math.max(...scores) - Math.min(...scores) > 0\n })\n if (rows.length === 0) return null\n const out: Record<string, { score: number; usd: number }> = {}\n for (const name of fieldOrder) {\n const cells = rows.map((r) => r.cells?.[name]).filter((c) => !!c)\n out[name] = {\n score: cells.reduce((s, c) => s + c.score, 0) / cells.length,\n usd: cells.reduce((s, c) => s + c.usd, 0) / cells.length,\n }\n }\n return out\n}\n\n/** The champion pick over a means table. 'score' takes the best mean score (ties →\n * field order). 'costAware' treats scores within `epsilon` of the best as tied and\n * takes the cheapest — the (score, $) Pareto rule collapsed to one pick. */\nexport function pickChampion(\n means: Record<string, { score: number; usd: number }>,\n fieldOrder: string[],\n policy: ChampionPolicy,\n epsilon: number,\n): ChampionPick {\n const entries = fieldOrder\n .map((name) => ({ name, summary: means[name] }))\n .filter((e): e is { name: string; summary: NonNullable<typeof e.summary> } => !!e.summary)\n if (entries.length === 0)\n throw new Error('pickChampion: the means table carries none of the field strategies')\n const best = Math.max(...entries.map((e) => e.summary.score))\n const pick =\n policy === 'score'\n ? entries.find((e) => e.summary.score === best)\n : entries\n .filter((e) => e.summary.score >= best - epsilon)\n .sort((a, b) => a.summary.usd - b.summary.usd || b.summary.score - a.summary.score)[0]\n if (!pick) throw new Error('pickChampion: empty pick (unreachable)')\n return { name: pick.name, score: pick.summary.score, usd: pick.summary.usd }\n}\n\n/** Search-side champion selection over a tournament report. */\nexport function selectChampion(\n report: BenchmarkReport,\n fieldOrder: string[],\n policy: ChampionPolicy,\n epsilon: number,\n): ChampionPick {\n return pickChampion(report.perStrategy, fieldOrder, policy, epsilon)\n}\n\nconst fieldSummary = (archive: EvolutionArchiveNode[]): string =>\n archive\n .map(\n (n) =>\n `- ${n.name} (${n.source}, gen ${n.generation}, last score ${(n.score * 100).toFixed(0)}%)`,\n )\n .join('\\n')\n\n/** The author-visible losses: EVERY train task in compact form (score/resolved/\n * progression per cell). A pretty-printed prefix slice would hide the tail tasks from\n * the author and bias which failure modes it can target; the hard cap stays only as a\n * guard against enormous fields. */\nconst compactLosses = (report: BenchmarkReport, detail: 'exact' | 'binary'): string => {\n const r2 = (x: number) => Math.round(x * 100) / 100\n const rows = report.perTask.map((row) =>\n row.cells\n ? {\n task: row.taskId,\n ...(row.errors\n ? {\n errors: Object.fromEntries(\n Object.entries(row.errors).map(([n, msg]) => [n, msg.slice(0, 100)]),\n ),\n }\n : {}),\n cells: Object.fromEntries(\n Object.entries(row.cells).map(([name, c]) => [\n name,\n // 'binary' is the leakage-bounded channel: the author learns pass/fail per\n // task and nothing else — the per-generation leak from the evaluation data\n // is capped at one bit per cell (arXiv:2606.11045 measured that exploration\n // survives this; whether AUTHORING does is the E1-coarse A/B).\n detail === 'binary'\n ? { resolved: c.resolved, usd: Math.round(c.usd * 10000) / 10000 }\n : {\n score: r2(c.score),\n resolved: c.resolved,\n usd: Math.round(c.usd * 10000) / 10000,\n progression: (c.progression ?? []).map(r2),\n },\n ]),\n ),\n }\n : { task: row.taskId, error: row.error?.slice(0, 80) },\n )\n return JSON.stringify(rows).slice(0, 12000)\n}\n\n/** Rename a strategy AND the deliverable's mode label its driver closes over — report\n * keys and observability labels must never diverge for a renamed candidate. */\nfunction renameStrategy(orig: Strategy, unique: string): Strategy {\n if (orig.name === unique) return orig\n return {\n name: unique,\n driver: (s, t, o, b) => {\n const agent = orig.driver(s, t, o, b)\n return {\n ...agent,\n name: unique,\n act: async (task, scope) => {\n const out = await agent.act(task, scope)\n if (out.kind !== 'done') return out\n const deliverable = { ...(out.deliverable as Record<string, unknown>), mode: unique }\n return { ...out, deliverable }\n },\n }\n },\n }\n}\n\nexport async function runStrategyEvolution(cfg: StrategyEvolutionConfig): Promise<EvolutionReport> {\n const budget = cfg.budget ?? 3\n const concurrency = cfg.concurrency ?? 3\n const generations = cfg.generations ?? 2\n const populationSize = cfg.populationSize ?? 2\n const baselines = cfg.baselines ?? [sample, refine, sampleThenRefine]\n const policy = cfg.champion ?? 'costAware'\n // FUNNEL ALIGNMENT: the search-side tie band must be no stricter than the promotion\n // criterion, or the gate never sees the candidates it was designed to judge. Under the\n // cost objective the gate accepts score within −scoreTolerance; a candidate that the\n // gate would promote must therefore be able to DISPLACE in search at that same band.\n const epsilon =\n cfg.championEpsilon ?? (cfg.objective === 'cost' ? (cfg.scoreTolerance ?? 0.05) : 0.01)\n const byName = new Map<string, Strategy>(baselines.map((s) => [s.name, s]))\n const codeByName = new Map<string, string>()\n\n // Endurance: the phase ledger. Resume refuses a checkpoint from a different design\n // (silently mixing configs would corrupt every downstream comparison).\n const fingerprint = {\n trainN: cfg.trainN,\n holdoutN: cfg.holdoutN,\n budget,\n generations,\n populationSize,\n }\n let ckpt: EvolutionCheckpoint | undefined\n if (cfg.checkpoint?.resume && existsSync(cfg.checkpoint.path)) {\n const raw = JSON.parse(readFileSync(cfg.checkpoint.path, 'utf8')) as EvolutionCheckpoint & {\n fingerprint?: typeof fingerprint\n }\n if (JSON.stringify(raw.fingerprint) !== JSON.stringify(fingerprint)) {\n throw new Error(\n `evolution resume: checkpoint design mismatch — checkpoint ${JSON.stringify(raw.fingerprint)} vs config ${JSON.stringify(fingerprint)}; delete ${cfg.checkpoint.path} or match the config`,\n )\n }\n ckpt = raw\n }\n const save = (state: EvolutionCheckpoint): void => {\n if (cfg.checkpoint)\n writeFileSync(cfg.checkpoint.path, JSON.stringify({ ...state, fingerprint }, null, 1))\n }\n\n const bench = async (phase: string, tasks: AgenticTask[], strategies: Strategy[]) => {\n await cfg.onPhase?.(phase)\n return runBenchmark({\n environment: cfg.environment,\n tasks,\n worker: cfg.worker,\n strategies,\n budget,\n concurrency,\n ...(cfg.onTask\n ? { onTask: (row, done, total) => cfg.onTask?.(phase, row, done, total) }\n : {}),\n ...(cfg.hooks ? { hooks: cfg.hooks } : {}),\n })\n }\n\n const train = await cfg.tasks(0, cfg.trainN)\n // One probe round-trip lists the domain's tools so the author can write tool-focused\n // shots (shot({tools})) — names + descriptions, never the implementations.\n const probeTask = train[0]\n if (!probeTask) throw new Error('runStrategyEvolution: empty train slice')\n const probe = await cfg.environment.open(probeTask)\n let toolCatalog: string\n try {\n const tools = await cfg.environment.tools(probeTask, probe)\n toolCatalog = tools\n .map(\n (t) =>\n `- ${t.function.name}${t.function.description ? ` — ${t.function.description.slice(0, 120)}` : ''}`,\n )\n .join('\\n')\n } finally {\n await cfg.environment.close(probe)\n }\n const gen0 = ckpt?.gen0 ?? (await bench('gen0', train, baselines))\n const archive: EvolutionArchiveNode[] = ckpt?.archive\n ? [...ckpt.archive]\n : baselines.map((s) => ({\n name: s.name,\n source: 'baseline' as const,\n generation: 0,\n score: gen0.perStrategy[s.name]?.score ?? 0,\n usd: gen0.perStrategy[s.name]?.usd ?? 0,\n }))\n const gen0Champion =\n ckpt?.gen0Champion ??\n selectChampion(\n gen0,\n baselines.map((s) => s.name),\n policy,\n epsilon,\n )\n\n const generationRows: EvolutionGeneration[] = ckpt?.generations ? [...ckpt.generations] : []\n const trajectory = ckpt?.trajectory\n ? [...ckpt.trajectory]\n : [\n {\n generation: 0,\n champion: gen0Champion.name,\n score: gen0Champion.score,\n usd: gen0Champion.usd,\n },\n ]\n // Re-import resumed authored modules from their files (the collision rename re-applied\n // so report keys stay stable across the restart).\n for (const row of generationRows) {\n for (const c of row.candidates) {\n if (!c.file || c.error) continue\n const mod = (await import(`file://${c.file}`)) as { default?: Strategy }\n if (!mod.default || typeof mod.default.driver !== 'function') {\n throw new Error(\n `evolution resume: ${c.file} no longer exports a Strategy — cannot restore \"${c.name}\"`,\n )\n }\n byName.set(c.name, renameStrategy(mod.default, c.name))\n codeByName.set(c.name, readFileSync(c.file, 'utf8'))\n }\n }\n let authoredOk = generationRows.reduce(\n (n, row) => n + row.candidates.filter((c) => !c.error).length,\n 0,\n )\n const lastRow = generationRows[generationRows.length - 1]\n let incumbent = lastRow ? lastRow.champion : gen0Champion\n let latestReport = lastRow ? lastRow.report : gen0\n if (!ckpt) save({ gen0, gen0Champion, generations: generationRows, archive, trajectory })\n\n for (let g = generationRows.length + 1; g <= generations; g += 1) {\n const lossesJson = compactLosses(latestReport, cfg.lossesDetail ?? 'exact')\n const candidates: EvolutionCandidate[] = []\n const newStrategies: Strategy[] = []\n for (let i = 0; i < populationSize; i += 1) {\n const objectiveNote =\n cfg.objective === 'cost'\n ? `\\n\\nYOUR OBJECTIVE: match or exceed the incumbent's SCORE while spending LESS (the losses include usd per task). Promotion requires proven score non-inferiority PLUS significant cost savings — a strategy that ties the score at half the cost WINS; a cheaper strategy that loses score by more than ${((cfg.scoreTolerance ?? 0.05) * 100).toFixed(0)}pp LOSES.`\n : ''\n const contract = `${strategyAuthorContract}${objectiveNote}\\n\\nEXAMPLE TOOLS FROM ONE TASK (tool sets VARY per task on this domain — a strategy MUST select tool names from await listTools(handle) at runtime; hardcoding these example names will zero your score on most tasks):\\n${toolCatalog}\\n\\nSTRATEGIES ALREADY IN THE TOURNAMENT (author something MEANINGFULLY different — a new composition, not a rename):\\n${fieldSummary(archive)}\\n\\nYou are authoring candidate ${i + 1} of ${populationSize} this generation; explore a distinct region of the strategy space from your siblings.`\n try {\n const authored = await authorStrategy({\n chat: cfg.author.chat,\n ...(cfg.author.model ? { model: cfg.author.model } : {}),\n ...(cfg.author.fallbackModel ? { fallbackModel: cfg.author.fallbackModel } : {}),\n ...(cfg.author.temperature !== undefined ? { temperature: cfg.author.temperature } : {}),\n ...(cfg.author.maxTokens !== undefined ? { maxTokens: cfg.author.maxTokens } : {}),\n contract,\n environmentName: cfg.environment.name,\n lossesJson,\n budget,\n outDir: cfg.outDir,\n })\n // A name collision with the archive would silently overwrite a report cell —\n // disambiguate the strategy key. The defineStrategy driver closes over the\n // ORIGINAL name for its deliverable's `mode` label, so the wrapper must rename\n // the returned agent AND its deliverable or observability labels diverge from\n // the report keys.\n const unique = byName.has(authored.strategy.name)\n ? `${authored.strategy.name}-g${g}c${i + 1}`\n : authored.strategy.name\n const strategy: Strategy = renameStrategy(authored.strategy, unique)\n byName.set(unique, strategy)\n codeByName.set(unique, authored.code)\n newStrategies.push(strategy)\n archive.push({\n name: unique,\n source: 'authored',\n generation: g,\n parent: incumbent.name,\n gzipBits: gzipSync(Buffer.from(authored.code)).length * 8,\n file: authored.file,\n score: 0,\n usd: 0,\n })\n candidates.push({\n name: unique,\n file: authored.file,\n gzipBits: gzipSync(Buffer.from(authored.code)).length * 8,\n codeChars: authored.code.length,\n })\n authoredOk += 1\n } catch (e) {\n candidates.push({\n name: `(author-failed g${g}c${i + 1})`,\n error: e instanceof Error ? e.message.slice(0, 300) : String(e),\n })\n }\n }\n\n const incumbentStrategy = byName.get(incumbent.name)\n if (!incumbentStrategy)\n throw new Error(`evolution: incumbent \"${incumbent.name}\" missing from the field`)\n const field = [incumbentStrategy, ...newStrategies]\n const report = await bench(`gen${g}`, train, field)\n for (const node of archive) {\n const cell = report.perStrategy[node.name]\n if (cell) {\n node.score = cell.score\n node.usd = cell.usd\n }\n }\n // With banding on, the champion is picked over the DISCRIMINATING tasks (any\n // zero-spread task carries no selection information). Falls back to full means\n // when every task tied — a degenerate generation, not an error.\n const fieldNames = field.map((s) => s.name)\n const means = cfg.band\n ? (discriminatingMeans(report, fieldNames) ?? report.perStrategy)\n : report.perStrategy\n const champion = pickChampion(means, fieldNames, policy, epsilon)\n generationRows.push({ generation: g, candidates, report, champion })\n trajectory.push({\n generation: g,\n champion: champion.name,\n score: champion.score,\n usd: champion.usd,\n })\n incumbent = champion\n latestReport = report\n save({ gen0, gen0Champion, generations: generationRows, archive, trajectory })\n }\n\n if (authoredOk === 0) {\n throw new Error(\n 'runStrategyEvolution: every author attempt failed across all generations — no search happened; see the candidates[].error entries',\n )\n }\n\n // The promotion decision: ONE fresh slice the search never touched, drawn after all\n // authoring is done. The gate, not the search policy, owns this verdict.\n const holdoutOffset = cfg.trainN + (cfg.holdoutOffset ?? 0)\n let holdoutTasks: AgenticTask[] = []\n let bandInfo: EvolutionBandInfo | undefined\n if (ckpt?.holdout && ckpt.verdict) {\n // Gate already settled before the restart. Reconstruct the exact gate tasks only if\n // the reproducer still needs to bench on them.\n bandInfo = ckpt.band\n if (cfg.reproducerCheck && codeByName.has(incumbent.name)) {\n const pool = await cfg.tasks(holdoutOffset, cfg.band?.holdoutPoolN ?? cfg.holdoutN)\n const gateIds = new Set(ckpt.holdout.perTask.map((r) => r.taskId))\n holdoutTasks = pool.filter((t) => gateIds.has(t.id))\n }\n } else if (cfg.band) {\n // Reference screening: baselines[0] runs once over the pool; tasks it already fully\n // solves carry no headroom (a candidate can only tie there) and are dropped. The\n // screen is independent of both finalists' gate runs — band membership is fixed\n // before either touches a task, and both then face the SAME kept tasks.\n const maxRef = cfg.band.maxRefScore ?? 0.99\n const reference = baselines[0]\n if (!reference)\n throw new Error('evolution band: baselines[0] required as the screening reference')\n const pool = await cfg.tasks(holdoutOffset, cfg.band.holdoutPoolN)\n const screen = await bench('band-screen', pool, [reference])\n const refScores = screen.perTask\n .filter((r) => r.cells?.[reference.name])\n .map((r) => ({ taskId: r.taskId, score: r.cells?.[reference.name]?.score ?? 0 }))\n const inBandIds = new Set(refScores.filter((r) => r.score <= maxRef).map((r) => r.taskId))\n const kept = pool.filter((t) => inBandIds.has(t.id))\n if (kept.length < cfg.holdoutN) {\n throw new Error(\n `evolution band: only ${kept.length}/${cfg.holdoutN} holdout tasks have headroom (pool ${cfg.band.holdoutPoolN}, reference \"${reference.name}\" ≤ ${maxRef}) — widen holdoutPoolN or raise maxRefScore`,\n )\n }\n holdoutTasks = kept.slice(0, cfg.holdoutN)\n bandInfo = { screened: refScores.length, inBand: kept.length, refScores }\n } else {\n holdoutTasks = await cfg.tasks(holdoutOffset, cfg.holdoutN)\n }\n let holdout: BenchmarkReport\n let verdict: PromotionVerdict\n if (ckpt?.holdout && ckpt.verdict) {\n holdout = ckpt.holdout\n verdict = ckpt.verdict\n } else {\n const finalists = [...new Set([gen0Champion.name, incumbent.name])]\n .map((n) => byName.get(n))\n .filter((s): s is Strategy => !!s)\n holdout = await bench('holdout', holdoutTasks, finalists)\n verdict = promotionGate({\n report: holdout,\n incumbent: gen0Champion.name,\n candidate: incumbent.name,\n ...(cfg.objective === 'cost'\n ? {\n mode: 'non-inferiority' as const,\n ...(cfg.scoreTolerance !== undefined ? { scoreTolerance: cfg.scoreTolerance } : {}),\n }\n : {}),\n ...(cfg.minPairedTasks !== undefined ? { minPairedTasks: cfg.minPairedTasks } : {}),\n })\n save({\n gen0,\n gen0Champion,\n generations: generationRows,\n archive,\n trajectory,\n holdout,\n verdict,\n ...(bandInfo ? { band: bandInfo } : {}),\n })\n }\n\n let reproduction: ReproductionCheck | undefined\n const championCode = codeByName.get(incumbent.name)\n if (cfg.reproducerCheck && championCode) {\n const words = cfg.reproducerCheck.summaryMaxWords ?? 64\n const tolerance = cfg.reproducerCheck.tolerance ?? 0.05\n const championHoldoutScore = holdout.perStrategy[incumbent.name]?.score ?? 0\n try {\n const summaryRes = await cfg.author.chat.chat({\n ...(cfg.author.model ? { model: cfg.author.model } : {}),\n temperature: 0.2,\n maxTokens: 512,\n messages: [\n {\n role: 'system',\n content: `Summarize the optimization strategy implemented by this code in at most ${words} words. Describe the COMPOSITION (shots, critique, artifact handling, restarts, stopping) — not the code. Output only the summary.`,\n },\n { role: 'user', content: championCode },\n ],\n })\n const summary = summaryRes.content.trim()\n // The reproducer sees the summary and the contract — never the losses, never the\n // original code. If its implementation matches the champion on the SAME holdout,\n // the champion's win fits through the summary and cannot be holdout-specific.\n const reproduced = await authorStrategy({\n chat: cfg.author.chat,\n ...(cfg.author.model ? { model: cfg.author.model } : {}),\n ...(cfg.author.fallbackModel ? { fallbackModel: cfg.author.fallbackModel } : {}),\n ...(cfg.author.maxTokens !== undefined ? { maxTokens: cfg.author.maxTokens } : {}),\n temperature: 0.2,\n contract: `${strategyAuthorContract}\\n\\nIMPLEMENT EXACTLY THIS STRATEGY (a colleague's description — do not invent a different approach):\\n${summary}`,\n environmentName: cfg.environment.name,\n lossesJson: '[]',\n budget,\n outDir: cfg.outDir,\n })\n const reproStrategy: Strategy = {\n name: `${incumbent.name}-reproduced`,\n driver: reproduced.strategy.driver,\n }\n const reproReport = await bench('reproduce', holdoutTasks, [reproStrategy])\n const reproducedHoldoutScore = reproReport.perStrategy[reproStrategy.name]?.score ?? 0\n reproduction = {\n summary,\n reproducedName: reproStrategy.name,\n file: reproduced.file,\n championHoldoutScore,\n reproducedHoldoutScore,\n gap: championHoldoutScore - reproducedHoldoutScore,\n reproducible: reproducedHoldoutScore >= championHoldoutScore - tolerance,\n }\n } catch (e) {\n reproduction = {\n summary: '',\n reproducedName: '',\n championHoldoutScore,\n reproducedHoldoutScore: 0,\n gap: championHoldoutScore,\n reproducible: false,\n error: e instanceof Error ? e.message.slice(0, 300) : String(e),\n }\n }\n }\n\n return {\n gen0,\n gen0Champion,\n generations: generationRows,\n archive,\n finalChampion: incumbent,\n holdout,\n verdict,\n ...(bandInfo ? { band: bandInfo } : {}),\n ...(reproduction ? { reproduction } : {}),\n trajectory,\n }\n}\n","/**\n * @experimental\n *\n * The ONLINE analyst: watch a `TraceSource` and fold each tool span through agent-eval's published\n * streaming detector kernel (`repeatedActionDetector`/`errorStreakDetector` — the SAME kernel the\n * control loop folds), firing `onSignal` the moment a worker loops or error-storms. Substrate-\n * agnostic: it consumes spans from any source (owned router/bridge loop OR a sandbox box session),\n * never the raw tool seam. Detection logic + the failure taxonomy live in agent-eval; not reimplemented.\n */\n\nimport {\n argHash,\n type DetectorSignal,\n errorStreakDetector,\n observeAll,\n repeatedActionDetector,\n type StreamingDetector,\n type ToolSpan,\n} from '@tangle-network/agent-eval'\nimport type { TraceSource } from './trace-source'\n\nexport interface WatchTraceOptions {\n /** The detectors to run online. Defaults to a stuck-loop + error-streak panel. */\n readonly detectors?: ReadonlyArray<StreamingDetector>\n /** Fired for each signal a detector raises — the seam that raises a `finding` on the bus. */\n readonly onSignal?: (signal: DetectorSignal, span: ToolSpan) => void | Promise<void>\n}\n\n/** The default online panel for a tool-call pipe: a worker repeating the same call, or hammering\n * consecutive errors. (No-progress needs a domain progress-probe, so it is opt-in, not default.)\n *\n * Coverage note: `repeated-action` works for EVERY harness (it needs only tool name + args, which\n * every adapter provides). `error-streak` needs per-call status — opencode carries it inline\n * (`state.status`, VALIDATED live), but claude-code/codex tool-call parts do NOT (their errors live\n * in separate result blocks not yet decoded), so error-streak is silent for those until result-block\n * decoding is added + live-validated. It is in the panel because it is correct where status exists. */\nexport function defaultToolDetectors(): StreamingDetector[] {\n return [repeatedActionDetector({ maxRepeated: 3 }), errorStreakDetector({ maxErrors: 3 })]\n}\n\n/** Subscribe to a `TraceSource` and run the streaming detectors over its live spans. Returns an\n * unsubscribe. A defensive `argHash` failure (circular args) never throws out of the side-channel. */\nexport function watchTrace(source: TraceSource, opts: WatchTraceOptions = {}): () => void {\n const detectors = opts.detectors ?? defaultToolDetectors()\n return source.onSpan((span) => {\n let fingerprint: string\n try {\n // Same fingerprint scheme as agent-eval's batch stuck-loop view: tool name + hashed args.\n fingerprint = `${span.toolName}|${argHash(span.args)}`\n } catch {\n fingerprint = `${span.toolName}|<unhashable>`\n }\n const signals = observeAll(detectors, {\n actionFingerprint: fingerprint,\n ...(span.status ? { status: span.status } : {}),\n label: span.toolName,\n })\n for (const s of signals) void opts.onSignal?.(s, span)\n })\n}\n","/**\n * @experimental\n *\n * The mechanical patch gate — the SINGLE source of the no-op / always-on secret-path floor /\n * forbidden-path / diff-size / test / typecheck checks over a captured diff. No I/O: it scores a\n * patch plus its already-derived test/typecheck PASS signals. The generic worktree-CLI deliverable\n * (`patchDelivered`, which runs the commands itself) calls this, so the gate logic never forks.\n *\n * The always-on safety floors (no-op rejection + secret-path) are also exported standalone\n * (`isNonEmptyPatch` / `touchesSecretPath`) for reuse outside the full scorer.\n */\n\nimport type { DefaultVerdict } from '../types'\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/**\n * Default-on credential-path floor: a patch that touches a credential-shaped path is rejected\n * regardless of the per-task `forbiddenPaths` config. Catches `.env`, private keys, keystores,\n * wallets, and the common secret/credential JSON files.\n */\nconst secretPathPattern =\n /(^|\\/)(\\.env(\\.|$)|.*\\.(pem|key|p12|pfx|keystore|wallet)|id_rsa|id_ed25519|secrets?\\.json|credentials?\\.json)$/i\n\n/** @experimental The patch + its derived PASS signals the mechanical gate decides on. */\nexport interface CoderCheckInput {\n /** The unified diff produced by the run. */\n patch: string\n /** Did `testCmd` exit clean? */\n testsPassed: boolean\n /** Did `typecheckCmd` exit clean? */\n typecheckPassed: boolean\n}\n\n/** @experimental The per-task constraints the mechanical gate enforces. */\nexport interface CoderCheckConstraints {\n /** Default 400. Hard cap; gate fails when exceeded. */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch. */\n forbiddenPaths?: string[]\n}\n\n/** The unified-diff paths the patch touches — the `+++`/`---` headers, de-`a/`/`b/`-prefixed,\n * with `/dev/null` (a delete's other side) dropped. */\nexport function touchedPathsFromPatch(patch: string): string[] {\n const out = new Set<string>()\n for (const line of patch.split(/\\r?\\n/)) {\n if (line.startsWith('+++ ') || line.startsWith('--- ')) {\n const rest = line.slice(4).trim()\n if (rest === '/dev/null') continue\n const stripped = rest.startsWith('a/') || rest.startsWith('b/') ? rest.slice(2) : rest\n out.add(stripped)\n }\n }\n return [...out]\n}\n\n/** Count the added/removed content lines in a unified diff (excludes the `+++`/`---` headers). */\nexport function countDiffLines(patch: string): number {\n let count = 0\n for (const line of patch.split(/\\r?\\n/)) {\n if (\n (line.startsWith('+') || line.startsWith('-')) &&\n !line.startsWith('+++') &&\n !line.startsWith('---')\n ) {\n count += 1\n }\n }\n return count\n}\n\n/** True when the patch actually changes something — at least one touched path AND non-blank body.\n * An empty patch can trivially \"pass\" tests/typecheck (nothing changed) yet does no work. */\nexport function isNonEmptyPatch(patch: string): boolean {\n return touchedPathsFromPatch(patch).length > 0 && patch.trim().length > 0\n}\n\n/** The credential-shaped paths the patch touches (always-on floor, independent of `forbiddenPaths`). */\nexport function touchesSecretPath(patch: string): string[] {\n return touchedPathsFromPatch(patch).filter((p) => secretPathPattern.test(p))\n}\n\n/**\n * @experimental\n *\n * The pure mechanical gate — the SINGLE source of the no-op / always-on secret-path floor /\n * diff-size / forbidden-path / test / typecheck checks. No I/O: it scores a patch + its\n * already-derived pass signals.\n *\n * Checks in order: (1) no-op rejection, (2) always-on secret-path floor (independent of\n * `forbiddenPaths`), (3) forbidden-path, (4) diff-size cap, (5) tests, (6) typecheck.\n * Aggregate score: `0.5*tests + 0.3*typecheck + 0.2*(1 - diffLines/maxDiff)`; `valid` is the\n * conjunction of all six.\n */\nexport function runCoderChecks(\n input: CoderCheckInput,\n constraints: CoderCheckConstraints = {},\n): DefaultVerdict {\n const maxDiff = constraints.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = constraints.forbiddenPaths ?? []\n const scores: Record<string, number> = {}\n const notes: string[] = []\n let pass = true\n\n const touched = touchedPathsFromPatch(input.patch)\n\n // No-op rejection: an empty patch can trivially \"pass\" tests/typecheck (nothing changed) yet\n // does no work — never a valid result.\n if (touched.length === 0 || input.patch.trim().length === 0) {\n pass = false\n scores.nonEmpty = 0\n notes.push('empty patch — no files changed')\n } else {\n scores.nonEmpty = 1\n }\n\n // Secret-path floor: always-on, independent of `forbiddenPaths`.\n const touchedSecrets = touched.filter((p) => secretPathPattern.test(p))\n if (touchedSecrets.length > 0) {\n pass = false\n scores.noSecrets = 0\n notes.push(`touched secret-shaped paths: ${touchedSecrets.join(', ')}`)\n } else {\n scores.noSecrets = 1\n }\n\n const touchedForbidden = forbidden.filter((path) => {\n const prefix = path.endsWith('/') ? path : `${path}/`\n const exact = prefix.slice(0, -1)\n return touched.some((p) => p === exact || p.startsWith(prefix))\n })\n if (touchedForbidden.length > 0) {\n pass = false\n scores.forbiddenPath = 0\n notes.push(`touched forbidden paths: ${touchedForbidden.join(', ')}`)\n } else {\n scores.forbiddenPath = 1\n }\n\n const diffLines = countDiffLines(input.patch)\n if (diffLines > maxDiff) {\n pass = false\n scores.diffSize = 0\n notes.push(`diff ${diffLines} lines exceeds cap ${maxDiff}`)\n } else {\n scores.diffSize = maxDiff === 0 ? 0 : Math.max(0, 1 - diffLines / maxDiff)\n }\n\n scores.tests = input.testsPassed ? 1 : 0\n scores.typecheck = input.typecheckPassed ? 1 : 0\n if (!input.testsPassed) {\n pass = false\n notes.push('tests failed')\n }\n if (!input.typecheckPassed) {\n pass = false\n notes.push('typecheck failed')\n }\n\n const score = 0.5 * scores.tests + 0.3 * scores.typecheck + 0.2 * scores.diffSize\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n}\n","/**\n * @experimental\n *\n * `patchDelivered` — the mechanical patch gate as a generic `DeliverableSpec` over the worktree-CLI\n * artifact. It is one construction of a `DeliverableSpec` (a plain `check(artifact) => boolean`\n * function); a domain customizes \"is it done\" by building its own spec, not by extending this one.\n * The canonical use: a `fanout(createWorktreeCliExecutor)` of authored harness profiles, each\n * `gateOnDeliverable(patchDelivered(...))`.\n *\n * The checks themselves are NOT re-implemented here — `runCoderChecks` (`./patch-checks`) is the\n * single source of the no-op / always-on secret-path floor / forbidden-path / diff-size / test /\n * typecheck logic. This factory only adapts the `WorktreePatchArtifact` shape (its `checks` carry\n * the test/typecheck PASS signals the executor derived in the live worktree) into the check inputs\n * and returns the boolean the gate consumes.\n *\n * Test/typecheck enforcement is OPT-IN per `require`: when a command was not run in the worktree\n * (the executor's `testCmd`/`typecheckCmd` were omitted) the corresponding signal is treated as\n * passed UNLESS `require` lists it — so a gate that demands a tests-pass on an artifact that never\n * ran tests fails closed (the honest outcome) rather than passing on a missing signal.\n */\n\nimport type { DeliverableSpec } from './completion-gate'\nimport { type CoderCheckConstraints, type CoderCheckInput, runCoderChecks } from './patch-checks'\nimport type { WorktreePatchArtifact } from './worktree-cli-executor'\n\n/** @experimental */\nexport interface PatchDeliverableOptions extends CoderCheckConstraints {\n /**\n * Which verification signals the gate REQUIRES to be present-and-passing. A required signal\n * that the artifact never derived (the command was not configured on the executor) fails the\n * gate closed. Unlisted signals default to passed-when-absent (the executor simply didn't run\n * that command). Default `[]` — gate on no-op / secret / forbidden / diff-size only.\n */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n}\n\n/**\n * Build the `DeliverableSpec<WorktreePatchArtifact>`: `check(artifact)` runs the shared mechanical\n * gate (`runCoderChecks`) over the captured patch + the worktree-derived pass signals and returns\n * whether the patch is DELIVERED (the `valid` conjunction).\n *\n * @experimental\n */\nexport function patchDelivered(\n options: PatchDeliverableOptions = {},\n): DeliverableSpec<WorktreePatchArtifact> {\n const require = new Set(options.require ?? [])\n const constraints: CoderCheckConstraints = {\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n }\n return {\n describe: 'patch: no-op/secret/forbidden/diff-size + required test/typecheck pass',\n check(artifact) {\n const input: CoderCheckInput = {\n patch: artifact.patch,\n testsPassed: signalPass(artifact.checks?.tests?.passed, require.has('tests')),\n typecheckPassed: signalPass(artifact.checks?.typecheck?.passed, require.has('typecheck')),\n }\n return runCoderChecks(input, constraints).valid === true\n },\n }\n}\n\n/**\n * Resolve a derived PASS signal into the boolean the gate folds in:\n * - signal present → its value (true/false).\n * - signal absent + required → false (fail closed: the gate demanded a signal that was never run).\n * - signal absent + not required → true (the executor simply didn't run that command).\n */\nfunction signalPass(value: boolean | undefined, required: boolean): boolean {\n if (value !== undefined) return value\n return !required\n}\n","/**\n * @experimental\n *\n * `TraceSource` — the ONE substrate-agnostic source of a worker's tool-call trace. The online\n * detectors and the settle-time analyzers consume agent-eval `ToolSpan`s from here, regardless of\n * whether the worker is:\n * - an OWNED tool loop (router-tools, cli-bridge tool dispatch) → push spans as we dispatch them;\n * - a SANDBOX / fleet box → read the harness's tool calls off the session (`streamPrompt` parts\n * live, `session.messages()` / `findCompletedTurn` at settle).\n *\n * The common currency is agent-eval's `ToolSpan` (so the same detectors + `buildTrajectory`/\n * `stuckLoopView`/`toolWasteView` run over any source). A source exposes two lanes:\n * - `onSpan` — live spans for ONLINE detection (best-effort; a black-box box may only collect).\n * - `collect` — the full span set at settle for the BATCH analyzers (always available).\n *\n * This module imports NO substrate SDK — it decodes generic message parts / OpenAI tool-call shapes.\n * The sandbox wiring (`sandboxSessionTraceSource`) is the thin adapter that feeds box session parts in.\n */\n\nimport type { ToolSpan } from '@tangle-network/agent-eval'\nimport type { ToolPart, ToolState } from '@tangle-network/agent-interface'\n\nexport interface ToolStepInput {\n readonly toolName: string\n readonly args: unknown\n readonly status?: 'ok' | 'error'\n readonly result?: unknown\n /** Stable id of the tool call — used to de-duplicate the repeated state transitions a harness\n * streams for one call (opencode emits pending→running→completed, plus a `raw`-wrapped copy). */\n readonly callId?: string\n /** Real per-call wall-clock when the source has it (owned tool-loop; opencode parts with `time`).\n * When omitted the span collapses to a single instant (`at`) — order + counts only, no duration. */\n readonly startedAt?: number\n readonly endedAt?: number\n}\n\nexport interface TraceSource {\n /** Subscribe to tool spans as they are produced (ONLINE). Returns an unsubscribe. A source that\n * only exposes its trace at the end registers nothing and returns a no-op. */\n onSpan(handler: (span: ToolSpan) => void): () => void\n /** The full set of tool spans for the run (SETTLE / batch). Always available. */\n collect(): Promise<ToolSpan[]>\n}\n\n/** Project a normalized tool step into the canonical agent-eval `ToolSpan`. When the step carries\n * real wall-clock (`startedAt`/`endedAt`) the span gets a true duration; otherwise it collapses to\n * the single instant `at` (order + counts only — the historical behavior). */\nexport function toToolSpan(input: ToolStepInput, runId: string, seq: number, at: number): ToolSpan {\n const startedAt = typeof input.startedAt === 'number' ? input.startedAt : at\n const endedAt = typeof input.endedAt === 'number' ? input.endedAt : startedAt\n return {\n spanId: `${runId}-t${seq}`,\n runId,\n kind: 'tool',\n name: input.toolName,\n toolName: input.toolName,\n args: input.args,\n status: input.status ?? 'ok',\n startedAt,\n endedAt,\n ...(input.result !== undefined ? { result: input.result } : {}),\n }\n}\n\n/** Decode one harness message part into a tool step, or `undefined` if it is not a (completed) tool\n * call. ONE adapter per harness family — each owns its real wire shape; the flow downstream is\n * identical. Add a harness = add a decoder + register it; no other code changes. */\nexport type ToolPartDecoder = (part: Record<string, unknown>) => ToolStepInput | undefined\n\nconst obj = (v: unknown): Record<string, unknown> | undefined =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : undefined\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\n/** opencode parts ARE agent-interface's canonical `ToolPart` (`{ type:'tool', tool, callID?,\n * state: ToolState }`) — the shape every adc sdk-provider normalizes its harness output into. We\n * decode against that published type (single source of truth) rather than a re-derived shape; the\n * `ToolState` union drives the status mapping, so a status that adc adds/renames is a compile error\n * here, not a silent miss. The same call streams pending→running→terminal; only a terminal state\n * (`completed` / `error` / `failed`) is a finished call. */\nexport const decodeOpencodePart: ToolPartDecoder = (raw) => {\n if (str(raw.type)?.toLowerCase() !== 'tool' || !str(raw.tool)) return undefined\n const part = raw as Partial<ToolPart>\n const state = obj(part.state) as ToolState | undefined\n const status = state?.status\n if (!status || status === 'pending' || status === 'running') return undefined\n return {\n toolName: part.tool as string,\n args: state?.input ?? {},\n // ToolStateError carries 'error' OR 'failed' — the reverse-engineered decoder missed 'failed'.\n status: status === 'error' || status === 'failed' ? 'error' : 'ok',\n ...(str(part.callID) ? { callId: part.callID as string } : {}),\n }\n}\n\n/** Anthropic / claude-code (also kimi's tool_use variant): a `{ type:'tool_use', id|tool_use_id,\n * name|tool, input }` content block. CONFIRMED against the cli-bridge's authoritative parsers\n * (claude.ts reads `block.type==='tool_use', block.id, block.name, block.input`; kimi.ts adds the\n * `tool_use_id`/`tool` fallbacks) — the canonical readers of these harnesses' real native output. */\nexport const decodeAnthropicPart: ToolPartDecoder = (p) => {\n if (str(p.type)?.toLowerCase() !== 'tool_use') return undefined\n const name = str(p.name) ?? str(p.tool)\n if (!name) return undefined\n const id = str(p.id) ?? str(p.tool_use_id)\n return {\n toolName: name,\n args: p.input ?? {},\n ...(id ? { callId: id } : {}),\n }\n}\n\n/** OpenAI-compatible (router / kimi's top-level form / glm): `{ type:'function'|'tool_call', id,\n * function:{ name, arguments:<JSON string> } }`. CONFIRMED against the cli-bridge (kimi.ts surfaces\n * kimi's top-level `tool_calls:[{type:'function', id, function:{name,arguments}}]` exactly this way).\n * NOTE: codex does NOT emit structured tool calls (the bridge's codex.ts never yields `tool_calls` —\n * it runs shell internally and surfaces only text), so per-tool detection is unavailable for codex\n * from any path — a harness property, not a decoder gap. */\nexport const decodeOpenAiPart: ToolPartDecoder = (p) => {\n const type = str(p.type)?.toLowerCase()\n const fn = obj(p.function)\n // Match on the type OpenAI always sets — not the mere presence of a `.function` field (a\n // `{type:'text', function:{…}}` part must not decode). Name is required below.\n if (type !== 'function' && type !== 'tool_call') return undefined\n const name = str(fn?.name) ?? str(p.name)\n if (!name) return undefined\n const rawArgs = fn?.arguments ?? p.arguments\n return {\n toolName: name,\n args: typeof rawArgs === 'string' ? safeParse(rawArgs) : (rawArgs ?? {}),\n ...(str(p.id) ? { callId: p.id as string } : str(fn?.id) ? { callId: fn?.id as string } : {}),\n }\n}\n\n/** The harness → decoder registry. Add a harness by adding one entry. */\nexport const toolPartDecoders: Record<string, ToolPartDecoder> = {\n opencode: decodeOpencodePart,\n 'claude-code': decodeAnthropicPart,\n anthropic: decodeAnthropicPart,\n codex: decodeOpenAiPart,\n openai: decodeOpenAiPart,\n router: decodeOpenAiPart,\n kimi: decodeOpenAiPart,\n}\n\n/** Decode a part with a specific harness's adapter when known, else try every registered adapter\n * (the composite — robust to mixed/unknown streams). Never throws. */\nexport function decodeToolPart(part: unknown, harness?: string): ToolStepInput | undefined {\n const p = obj(part)\n if (!p) return undefined\n const specific = harness ? toolPartDecoders[harness] : undefined\n if (specific) return specific(p)\n for (const decode of new Set(Object.values(toolPartDecoders))) {\n const step = decode(p)\n if (step) return step\n }\n return undefined\n}\n\nfunction safeParse(s: string): unknown {\n try {\n return JSON.parse(s)\n } catch {\n return s\n }\n}\n\nlet runSeq = 0\n\n/** A push source for OWNED tool loops (router-tools / cli-bridge tool dispatch): the loop calls\n * `record(step)` for each tool call; it becomes a span, fan-out to live subscribers + buffered for\n * `collect`. */\nexport function createPushTraceSource(opts: { runId?: string; now?: () => number } = {}): {\n source: TraceSource\n record: (input: ToolStepInput) => ToolSpan\n} {\n const runId = opts.runId ?? `push-${runSeq++}`\n const now = opts.now ?? Date.now\n const spans: ToolSpan[] = []\n const subs = new Set<(span: ToolSpan) => void>()\n return {\n record(input) {\n const span = toToolSpan(input, runId, spans.length, now())\n spans.push(span)\n for (const fn of subs) {\n try {\n fn(span)\n } catch {\n // a throwing subscriber (e.g. a detector onSignal) must never break the producer loop\n }\n }\n return span\n },\n source: {\n onSpan(handler) {\n subs.add(handler)\n return () => subs.delete(handler)\n },\n collect: () => Promise.resolve([...spans]),\n },\n }\n}\n\n/** A source backed by harness message PARTS (sandbox session, cli-bridge). `collect` reads the full\n * part list and decodes the tool calls; `subscribe`, when given, streams parts live for online\n * detection. The caller supplies how to get parts (e.g. `box.session(id).messages()` flat-mapped to\n * parts) — keeping this module free of any substrate SDK. */\nexport function createPartsTraceSource(opts: {\n collectParts: () => Promise<ReadonlyArray<unknown>>\n subscribeParts?: (onPart: (part: unknown) => void) => () => void\n /** The harness whose decoder to use (e.g. 'opencode'); omit to try every registered adapter. */\n harness?: string\n runId?: string\n now?: () => number\n}): TraceSource {\n const runId = opts.runId ?? `parts-${runSeq++}`\n const now = opts.now ?? Date.now\n const subs = new Set<(span: ToolSpan) => void>()\n // De-dup the repeated transitions a harness streams for one call (pending/running/completed + a\n // `raw`-wrapped copy all decode to the same terminal step) — one span per callId.\n const seenLive = new Set<string>()\n let liveSeq = 0\n let unsub: (() => void) | undefined\n const startLive = () => {\n if (unsub || !opts.subscribeParts) return\n unsub = opts.subscribeParts((part) => {\n const step = decodeToolPart(part, opts.harness)\n if (!step) return\n if (step.callId) {\n if (seenLive.has(step.callId)) return\n seenLive.add(step.callId)\n }\n const span = toToolSpan(step, runId, liveSeq++, now())\n for (const fn of subs) {\n try {\n fn(span)\n } catch {\n // a throwing subscriber (e.g. a detector onSignal) must never break the producer loop\n }\n }\n })\n }\n return {\n onSpan(handler) {\n subs.add(handler)\n startLive()\n return () => {\n subs.delete(handler)\n if (subs.size === 0 && unsub) {\n unsub()\n unsub = undefined\n }\n }\n },\n async collect() {\n const parts = await opts.collectParts()\n const spans: ToolSpan[] = []\n const seen = new Set<string>()\n for (const part of parts) {\n const step = decodeToolPart(part, opts.harness)\n if (!step) continue\n if (step.callId) {\n if (seen.has(step.callId)) continue\n seen.add(step.callId)\n }\n spans.push(toToolSpan(step, runId, spans.length, now()))\n }\n return spans\n },\n }\n}\n\n/** A harness session message carrying parts (the shape `box.messages()` returns). Structurally typed\n * so this works with the real `@tangle-network/sandbox` box AND a test double, no SDK import. */\nexport interface SessionMessageLike {\n readonly parts?: ReadonlyArray<unknown>\n}\n\n/** The minimal box surface this needs: list a session's messages (incl. mid-turn partials). */\nexport interface SessionTraceBox {\n messages(opts: { sessionId: string }): Promise<ReadonlyArray<SessionMessageLike>>\n}\n\n/** The SANDBOX / fleet trace source: read a box session's message parts and decode the harness's tool\n * calls into spans. `collect` (settle) is the solid path — `box.messages({sessionId})` → parts → spans;\n * black-box harnesses aren't mid-step interruptible, so online steering is the owned-loop's job and a\n * live `subscribe` is opt-in (pass `subscribeParts` from `streamPrompt` when the harness streams parts). */\nexport function sandboxSessionTraceSource(\n box: SessionTraceBox,\n sessionId: string,\n opts: {\n /** The box's harness (e.g. 'opencode', 'claude-code') → selects its decoder adapter. */\n harness?: string\n subscribeParts?: (onPart: (part: unknown) => void) => () => void\n runId?: string\n now?: () => number\n } = {},\n): TraceSource {\n return createPartsTraceSource({\n collectParts: async () => {\n const msgs = await box.messages({ sessionId })\n return msgs.flatMap((m) => (m.parts ? [...m.parts] : []))\n },\n ...(opts.harness ? { harness: opts.harness } : {}),\n ...(opts.subscribeParts ? { subscribeParts: opts.subscribeParts } : {}),\n runId: opts.runId ?? `box-${sessionId}`,\n ...(opts.now ? { now: opts.now } : {}),\n })\n}\n","/**\n * @experimental\n *\n * The SETTLE-time analyst: when a worker finishes, collect its tool spans from a `TraceSource` and run\n * agent-eval's PUBLISHED batch analyzers over them — `buildTrajectory` (structured run summary),\n * `stuckLoopView` (full-run repeated-call view, complementing the online consecutive detector), and\n * `toolWasteView`. Substrate-agnostic: the spans come from any source (an owned loop's buffer OR a\n * sandbox box session). No analysis reimplemented — this is the thin bridge into agent-eval's analyzers.\n */\n\nimport { buildTrajectory, InMemoryTraceStore } from '@tangle-network/agent-eval'\nimport { stuckLoopView, toolWasteView } from '@tangle-network/agent-eval/pipelines'\nimport type { TraceSource } from './trace-source'\n\nexport interface TrajectoryAnalysis {\n /** Structured run summary (tool-call count, step order). Steps carry a single timestamp, so per-span\n * duration is 0; loop/waste detection keys on call PATTERNS + cross-span windows, not durations. */\n readonly trajectory: Awaited<ReturnType<typeof buildTrajectory>>\n /** Full-run repeated-call view (total occurrences + window) — catches a loop the online consecutive\n * detector interleaves past. */\n readonly stuckLoop: Awaited<ReturnType<typeof stuckLoopView>>\n /** Wasted-vs-total tool-call ratio for the run. */\n readonly toolWaste: Awaited<ReturnType<typeof toolWasteView>>\n}\n\n/** Collect the source's spans and run the agent-eval batch analyzers over them under one `runId`. */\nexport async function analyzeTrace(\n source: TraceSource,\n runId = 'worker',\n): Promise<TrajectoryAnalysis> {\n const spans = await source.collect()\n const store = new InMemoryTraceStore()\n // Re-stamp onto one runId so the runId-filtered analyzers see the whole trace regardless of the\n // source's own id scheme.\n for (let i = 0; i < spans.length; i += 1) {\n const s = spans[i]\n if (s) await store.appendSpan({ ...s, runId, spanId: `${runId}-t${i}` })\n }\n const [trajectory, stuckLoop, toolWaste] = await Promise.all([\n buildTrajectory(store, runId),\n stuckLoopView(store, { runId }),\n toolWasteView(store, { runId }),\n ])\n return { trajectory, stuckLoop, toolWaste }\n}\n","/**\n * @experimental\n *\n * `worktreeFanout` — the GENERIC coding combinator: a `fanout` of N supervisor-authored harness\n * profiles, each on its OWN worktree-CLI leaf, each `gateOnDeliverable(deliverable)`, winner via the\n * shared `selectValidWinner` (valid-only — an ungated patch never wins, the deliverable gate is the\n * point). The `deliverable` is passed as DATA: it defaults to `patchDelivered(opts)` but any\n * `DeliverableSpec<WorktreePatchArtifact>` a domain authors slots in unchanged.\n *\n * The shape is content-free at the `fanout` layer; this builder only assembles the pieces (the\n * worktree-CLI executor + the injected deliverable + the diff-size selector) into the generic\n * combinator's `itemSpec`/`selectWinner` seams. Nothing here re-implements selection, gating, or\n * fanout — it composes the existing primitives.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { fanout, selectValidWinner } from '../personify/combinators'\nimport type { CombinatorShape, WinnerStrategy } from '../personify/wave-types'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { type PatchDeliverableOptions, patchDelivered } from './patch-deliverable'\nimport type { AgentSpec } from './types'\nimport {\n createWorktreeCliExecutor,\n type WorktreeCliExecutorOptions,\n type WorktreePatchArtifact,\n} from './worktree-cli-executor'\n\n/** @experimental One authored harness profile in a worktree fanout: the §1.5 profile + which local\n * harness CLI drives it. The supervisor authors `profile` per sub-task; `harness` chooses the leaf. */\nexport interface AuthoredHarness {\n /** A short label for the worktree branch + trace node. */\n name: string\n /** The supervisor-authored `AgentProfile` (systemPrompt + model reach the harness via §1.5). */\n profile: AgentProfile\n /** Which local harness CLI drives this leaf. */\n harness: 'claude' | 'codex' | 'opencode'\n /** Per-harness model/runId/baseRef overrides flow through the profile + these. */\n runId?: string\n baseRef?: string\n}\n\n/** @experimental */\nexport interface WorktreeFanoutOptions extends PatchDeliverableOptions {\n /** Absolute path to the git checkout each worktree is cut from. */\n repoRoot: string\n /** The per-task instruction handed to every harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The authored harness profiles — one fanout item (and one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /**\n * The completion check each leaf is gated on. Defaults to `patchDelivered(opts)` (the mechanical\n * no-op/secret/forbidden/diff-size + required test/typecheck gate). Pass any\n * `DeliverableSpec<WorktreePatchArtifact>` to customize \"is it delivered\" as DATA.\n */\n deliverable?: DeliverableSpec<WorktreePatchArtifact>\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Wall-clock cap per harness subprocess (ms). */\n harnessTimeoutMs?: number\n /** Winner-selection strategy. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to every worktree-CLI leaf (inject git/harness/command runners so the\n * whole fanout runs offline). Production callers leave these unset. */\n runGit?: WorktreeCliExecutorOptions['runGit']\n runHarness?: WorktreeCliExecutorOptions['runHarness']\n runCommand?: WorktreeCliExecutorOptions['runCommand']\n}\n\n/**\n * Build the worktree fanout combinator. Run it with `runPersonified({ persona, shape, task, budget })`\n * — equal-k holds by construction (the conserved budget pool bounds the N leaves), and selection is\n * the shared valid-only `selectValidWinner` (never a judge).\n *\n * @experimental\n */\nexport function worktreeFanout<Task>(\n options: WorktreeFanoutOptions,\n): CombinatorShape<Task, WorktreePatchArtifact> {\n const deliverable =\n options.deliverable ??\n patchDelivered({\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n })\n\n const itemSpec = (item: AuthoredHarness): AgentSpec => {\n const executor = gateOnDeliverable(\n createWorktreeCliExecutor({\n repoRoot: options.repoRoot,\n profile: item.profile,\n harness: item.harness,\n taskPrompt: options.taskPrompt,\n ...(item.runId ? { runId: item.runId } : {}),\n ...(item.baseRef ? { baseRef: item.baseRef } : {}),\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.harnessTimeoutMs !== undefined\n ? { harnessTimeoutMs: options.harnessTimeoutMs }\n : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n }),\n deliverable,\n )\n return { profile: item.profile, harness: null, executor: executor as AgentSpec['executor'] }\n }\n\n const selectWinner = selectValidWinner<WorktreePatchArtifact>({\n strategy: options.winnerStrategy ?? 'highest-score',\n sizeOf: (a) => a.stats.insertions + a.stats.deletions,\n })\n\n return fanout<Task, AuthoredHarness, WorktreePatchArtifact>(options.harnesses, {\n itemTask: () => options.taskPrompt,\n label: (item, i) => `${item.name}:${i}`,\n itemSpec: (item) => itemSpec(item),\n selectWinner,\n })\n}\n","/**\n * superviseSurface — drive a team of agents to solve a graded `AgenticSurface` task. ONE capability that\n * replaces the worker-seam + \"self-improving supervisor\" wrapper pair: the driver (`profile`) spawns\n * workers that each run `runAgentic` over the surface (`refine` by default), settle on the surface's OWN\n * check (settled ⟺ resolved — a worker that ran but didn't pass settles invalid, so a keep-best driver\n * never counts it done), and feed the driver a self-improvement lens (the still-FAILING tests, by default)\n * so the next spawn targets the persistently-hard cases. Returns the deployable outcome + the full\n * conserved spend.\n *\n * WHY this lives here and not as a `supervise()` backend: `runAgentic` depends on the supervise core\n * (`strategy.ts` → `supervise/`), so a surface-solving worker cannot be a supervise built-in without an\n * import cycle. It is therefore a COMPOSITION of `supervise()` + `runAgentic` at the layer above both —\n * the right home for \"supervise over a graded surface\". The within-run self-improvement is the analyst\n * (authored content, swap `analysts`); the across-run kind wraps this call in `improve()`/`selfImprove`.\n */\nimport type { AgentProfile } from '@tangle-network/sandbox'\nimport type { AnalystRegistry, MakeWorkerAgent } from '../mcp/tools/coordination'\nimport type { RouterConfig } from './router-client'\nimport {\n type AgenticSurface,\n type AgenticTask,\n refine,\n runAgentic,\n type Strategy,\n} from './strategy'\nimport type { DeliverableSpec } from './supervise/completion-gate'\nimport { supervise } from './supervise/supervise'\nimport type { SupervisorProfile } from './supervise/supervisor-agent'\nimport type { Agent, AgentSpec, Budget, Executor, ExecutorResult, Spend } from './supervise/types'\n\n/** What a surface worker settles with — the surface verdict the driver + deliverable read. `resolved` is\n * the surface check's pass/fail (settled ⟺ resolved); `score` is the partial-credit fraction; `failing`\n * carries the tests this worker left red (so the analyst can target them). */\nexport interface SurfaceWorkerOut {\n readonly resolved: boolean\n readonly score: number\n readonly shots: number\n readonly summary: string\n readonly failing?: readonly string[]\n}\n\n/** Remember the worker's LAST `run_tests` output so the analyst can name the still-failing tests — a\n * transparent passthrough for every other surface call. Local to this module (no surface-zoo concept). */\nfunction captureFailures(base: AgenticSurface): {\n surface: AgenticSurface\n failing: () => string[]\n} {\n let lastReport = ''\n const surface: AgenticSurface = {\n name: base.name,\n open: (t) => base.open(t),\n tools: (t, h) => base.tools(t, h),\n async call(h, name, args) {\n const out = await base.call(h, name, args)\n if (name === 'run_tests') lastReport = out\n return out\n },\n score: (t, h) => base.score(t, h),\n close: (h) => base.close(h),\n }\n const failing = () => {\n const body = /FAILING:\\s*(.+)/i.exec(lastReport)?.[1]\n return body\n ? body\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : []\n }\n return { surface, failing }\n}\n\n/** The default self-improvement LENS — authored content, not a code path. On each settled worker it hands\n * the driver the still-FAILING tests (not just a score), so the next spawn targets the persistently-hard\n * cases. Swap `analysts` to change what the driver improves from — that's the one knob. */\nexport function failuresAnalyst(): AnalystRegistry {\n return {\n kinds: [\n {\n id: 'failures',\n description: \"Surface the worker's still-failing tests so the driver targets them next.\",\n area: 'progress',\n },\n ],\n run: async (_kindId: string, trace: unknown) => {\n const w = (trace ?? {}) as Partial<SurfaceWorkerOut>\n if (!(typeof w === 'object' && w !== null && 'resolved' in w))\n return { summary: `worker produced: ${JSON.stringify(trace).slice(0, 300)}` }\n if (w.resolved) return { summary: 'worker RESOLVED — every check passed; stop.' }\n const failing = (w.failing ?? []) as readonly string[]\n const head = `worker did NOT resolve — score ${(100 * (w.score ?? 0)).toFixed(0)}%, ${w.shots ?? '?'} shot(s)`\n return {\n summary: failing.length\n ? `${head}. STILL FAILING (${failing.length}): ${failing.slice(0, 12).join(', ')}. Spawn the next worker to fix exactly these; if a test keeps failing across workers, give it concrete guidance about that case.`\n : `${head}. (no failing-test list available this round)`,\n }\n },\n }\n}\n\n/** How a worker runs the surface task (its router substrate + per-attempt bounds). */\nexport interface SurfaceWorkerConfig {\n readonly routerBaseUrl: string\n readonly routerKey: string\n readonly model: string\n readonly maxTokens?: number\n readonly innerTurns?: number\n /** Refine-shot budget for ONE worker attempt (max steered shots). Default 1. */\n readonly budget?: number\n}\n\n/** One spawned worker = one `runAgentic` attempt over the surface task. The driver's brief is threaded\n * into the attempt (so a re-spawn can take a targeted angle, not an identical retry); `runAgentic` stamps\n * real tokens/usd/ms, forwarded as `Spend`; the still-failing tests are captured for the analyst. */\nfunction surfaceWorkerExecutor(\n surface: AgenticSurface,\n task: AgenticTask,\n worker: SurfaceWorkerConfig,\n strategy: Strategy,\n): Executor<SurfaceWorkerOut> {\n let artifact: ExecutorResult<SurfaceWorkerOut> | undefined\n return {\n runtime: 'surface-worker',\n async execute(brief: unknown): Promise<ExecutorResult<SurfaceWorkerOut>> {\n const guidance = typeof brief === 'string' ? brief.trim() : brief ? JSON.stringify(brief) : ''\n const attemptTask: AgenticTask = guidance\n ? {\n ...task,\n systemPrompt: `${task.systemPrompt ?? ''}\\n\\n— Supervisor guidance for THIS attempt (incorporate it; do not just repeat a prior approach) —\\n${guidance}`,\n }\n : task\n const cap = captureFailures(surface)\n const r = await runAgentic({\n surface: cap.surface,\n task: attemptTask,\n strategy,\n budget: worker.budget ?? 1,\n routerBaseUrl: worker.routerBaseUrl,\n routerKey: worker.routerKey,\n model: worker.model,\n ...(worker.maxTokens !== undefined ? { maxTokens: worker.maxTokens } : {}),\n ...(worker.innerTurns !== undefined ? { innerTurns: worker.innerTurns } : {}),\n })\n const out: SurfaceWorkerOut = {\n resolved: r.resolved,\n score: r.score,\n shots: r.shots,\n summary: `${strategy.name} ${r.shots} shot(s) → ${(100 * r.score).toFixed(0)}% (${r.resolved ? 'resolved' : 'unresolved'})`,\n failing: r.resolved ? [] : cap.failing(),\n }\n const spent: Spend = { iterations: r.completions, tokens: r.tokens, usd: r.usd, ms: r.ms }\n artifact = {\n outRef: `surface-worker:${task.id}:${r.shots}:${r.resolved ? 'ok' : 'no'}`,\n out,\n verdict: { valid: r.resolved, score: r.score },\n spent,\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('surfaceWorkerExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\nexport interface SuperviseSurfaceOptions {\n /** The graded surface workers solve (open/tools/call/score/close). */\n readonly surface: AgenticSurface\n /** Where/how each worker runs the surface task. */\n readonly worker: SurfaceWorkerConfig\n /** The conserved compute pool for the whole supervised run. Default: sized off the worker's inner-loop\n * bounds for a handful of worker spawns — raise it to let the driver try more. */\n readonly budget?: Budget\n /** The driver brain's router substrate (its own inference). Default: the worker's router + model — the\n * driver and workers share one router unless you separate them (e.g. a stronger driver model). */\n readonly router?: RouterConfig\n /** The self-improvement lens fed to the driver on each settled worker. Default `failuresAnalyst()`\n * (target the still-failing tests). Pass a custom registry to change it, or `null` to turn the\n * within-run self-improvement OFF (the driver sees raw settled outputs). */\n readonly analysts?: AnalystRegistry | null\n /** The strategy each worker runs over the surface. Default `refine` (iterate-with-feedback). */\n readonly strategy?: Strategy\n /** Max workers live at once. Default 1 (serial — required when workers share a persistent artifact, so\n * they continue each other instead of racing the file). */\n readonly maxLiveWorkers?: number\n}\n\n/** The deployable outcome of a supervised surface run. */\nexport interface SuperviseSurfaceResult {\n readonly resolved: boolean\n readonly score: number\n readonly usd: number\n readonly tokensIn: number\n readonly tokensOut: number\n readonly ms: number\n /** Total conserved-pool iterations = the driver + worker LLM rounds the run actually spent. */\n readonly completions: number\n}\n\n/** Drive a team of agents (spawned + steered by `profile`) to solve a graded `AgenticSurface` task, and\n * report the deployable outcome + the full conserved spend. This is `supervise()` configured for surfaces\n * — there is no other entrypoint to learn. */\nexport async function superviseSurface(\n profile: SupervisorProfile,\n task: AgenticTask,\n opts: SuperviseSurfaceOptions,\n): Promise<SuperviseSurfaceResult> {\n const strategy = opts.strategy ?? refine\n const innerTurns = opts.worker.innerTurns ?? 6\n // Default the driver to the worker's router (one router unless separated) and the pool to a handful of\n // worker spawns sized off the worker bounds — so the minimal call is\n // `superviseSurface(profile, task, { surface, worker })`.\n const router = opts.router ?? {\n routerBaseUrl: opts.worker.routerBaseUrl,\n routerKey: opts.worker.routerKey,\n model: opts.worker.model,\n }\n const budget = opts.budget ?? {\n maxIterations: (innerTurns + 2) * 5 + 16,\n maxTokens: (opts.worker.maxTokens ?? 4000) * 8,\n }\n\n // Every spawned worker is a BYO executor that runs the surface task; the deliverable is the completion\n // oracle (delivered ⟺ the surface check passed).\n const makeWorkerAgent: MakeWorkerAgent = (rawProfile) => {\n const p = (rawProfile ?? {}) as { name?: unknown }\n const name = typeof p.name === 'string' && p.name.length > 0 ? p.name : 'surface-worker'\n const spec: AgentSpec = {\n profile: rawProfile as AgentProfile,\n harness: null,\n executor: surfaceWorkerExecutor(\n opts.surface,\n task,\n opts.worker,\n strategy,\n ) as Executor<unknown>,\n }\n return { name, act: async () => '', executorSpec: spec } as Agent<unknown, unknown> & {\n executorSpec: AgentSpec\n }\n }\n const deliverable: DeliverableSpec<unknown> = {\n describe: `resolve the surface task ${task.id} (every required check passes)`,\n check: (out) => (out as SurfaceWorkerOut | undefined)?.resolved === true,\n }\n\n // `null` analysts → self-improvement off; otherwise default to the failures lens and fire every kind it\n // declares on each settled worker.\n const analysts = opts.analysts === null ? undefined : (opts.analysts ?? failuresAnalyst())\n\n const result = await supervise(profile, task, {\n makeWorkerAgent,\n deliverable,\n budget,\n maxLiveWorkers: opts.maxLiveWorkers ?? 1,\n // A SMALL per-worker reservation so MULTIPLE workers fit the pool (the default reserves the whole pool\n // per worker → only one ever spawns, defeating the spawn-a-targeted-worker steering).\n perWorker: { maxIterations: innerTurns + 2, maxTokens: opts.worker.maxTokens ?? 4000 },\n router,\n ...(analysts ? { analysts, analyzeOnSettle: analysts.kinds.map((k) => k.id) } : {}),\n })\n\n const out = result.kind === 'winner' ? (result.out as SurfaceWorkerOut | undefined) : undefined\n const sp = result.spentTotal\n return {\n resolved: out?.resolved ?? false,\n score: out?.score ?? 0,\n usd: sp.usd,\n tokensIn: sp.tokens.input,\n tokensOut: sp.tokens.output,\n ms: sp.ms,\n completions: sp.iterations,\n }\n}\n","/**\n * createVerifierEnvironment — ANY checkable task as an `Environment`, no tool surface\n * required. The generalization piece: EOPS/commit0-style domains have tools that mutate\n * an external artifact, but math problems, legal drafts, creative briefs, GTM copy, and\n * QA tasks have a different shape — the artifact IS the worker's answer, and the domain\n * is defined by one function: the deployable check over that answer.\n *\n * const gsm8k = createVerifierEnvironment({\n * name: 'gsm8k',\n * check: (task, answer) => ({\n * passes: extractFinalNumber(answer) === task.meta?.answer ? 1 : 0,\n * total: 1,\n * errored: 0,\n * }),\n * })\n * await runBenchmark({ environment: gsm8k, tasks, worker }) // sample vs refine on math\n *\n * The worker gets one built-in tool — `submit_answer` — plus any read-only domain tools\n * the caller adds (a calculator, a retrieval call, a style guide lookup). Every\n * submission is kept; `score()` checks the BEST submission (keep-best is the measured\n * law: workers reach correct answers then revise past them). The refine strategy's\n * critic reads the submission trajectory like any other trace, so iterate-with-feedback\n * works unchanged on answer domains.\n *\n * The check can be graded (passes/total expresses partial credit — rubric points,\n * sub-answers, unit-test counts), and MUST be deployable (computable without an oracle\n * at serve time): exact/numeric match, schema validation, a compiled rubric — not a\n * peek at held-out labels the production system wouldn't have.\n */\n\nimport type { Environment } from './run-benchmark'\nimport type { AgenticTask, AgenticTool, ArtifactHandle, SurfaceScore } from './strategy'\n\nexport interface VerifierEnvironmentOptions {\n name: string\n /** The deployable check over a submitted answer. Graded via passes/total. */\n check(task: AgenticTask, answer: string): Promise<SurfaceScore> | SurfaceScore\n /** Extra domain tools (read-only helpers: calculator, retrieval, style lookup). */\n extraTools?: AgenticTool[]\n /** Executes the extra tools. Required when `extraTools` is set. */\n callExtra?(\n task: AgenticTask,\n name: string,\n args: Record<string, unknown>,\n ): Promise<string> | string\n}\n\ninterface AnswerState {\n task: AgenticTask\n submissions: string[]\n}\n\nconst submitTool: AgenticTool = {\n type: 'function',\n function: {\n name: 'submit_answer',\n description:\n 'Submit your answer for evaluation. You may submit more than once — the best-scoring submission counts. Submit the COMPLETE final answer, not a fragment.',\n parameters: {\n type: 'object',\n properties: { answer: { type: 'string', description: 'The complete final answer.' } },\n required: ['answer'],\n },\n },\n}\n\nexport function createVerifierEnvironment(opts: VerifierEnvironmentOptions): Environment {\n if (opts.extraTools?.length && !opts.callExtra) {\n throw new Error(`${opts.name}: extraTools requires callExtra`)\n }\n const states = new Map<string, AnswerState>()\n let seq = 0\n\n return {\n name: opts.name,\n\n async open(task) {\n seq += 1\n const handle: ArtifactHandle = { id: `${opts.name}-${seq}`, surface: opts.name }\n states.set(handle.id, { task, submissions: [] })\n return handle\n },\n\n async tools() {\n return [submitTool, ...(opts.extraTools ?? [])]\n },\n\n async call(handle, name, args) {\n const state = states.get(handle.id)\n if (!state) return 'ERROR: workspace closed'\n if (name === 'submit_answer') {\n const answer = String(args.answer ?? '').trim()\n if (!answer) return 'ERROR: empty answer'\n state.submissions.push(answer)\n return `submission ${state.submissions.length} recorded`\n }\n if (opts.callExtra && opts.extraTools?.some((t) => t.function.name === name)) {\n try {\n return await opts.callExtra(state.task, name, args)\n } catch (e) {\n return `ERROR: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n return `ERROR: unknown tool ${name}`\n },\n\n // Keep-best across submissions — the measured law (workers reach correct answers,\n // then revise past them; final-state scoring undersells every strategy).\n async score(task, handle) {\n const state = states.get(handle.id)\n if (!state || state.submissions.length === 0) return { passes: 0, total: 1, errored: 0 }\n let best: SurfaceScore = { passes: 0, total: 1, errored: 0 }\n const ratio = (s: SurfaceScore) => (s.total > 0 ? s.passes / s.total : 0)\n for (const answer of state.submissions) {\n const s = await opts.check(task, answer)\n if (ratio(s) > ratio(best)) best = s\n }\n return best\n },\n\n async close(handle) {\n states.delete(handle.id)\n },\n }\n}\n","/**\n * createWaterfallCollector — 100% trajectory observability from the lifecycle stream:\n * every spawn/settle (shots, analysts, nested agents) becomes one timed, billed span.\n * The sum of spans IS the run's cost story — what each step cost in dollars, tokens,\n * and wall-clock, rendered as a text waterfall or exported as structured rows for any\n * chart. Attach the collector's `hooks` to `runAgentic`/`runBenchmark`; spans accumulate\n * across every task the hooks observe.\n */\nimport type { RuntimeHookEvent, RuntimeHooks } from '../runtime-hooks'\n\nexport interface WaterfallSpan {\n id: string\n /** The spawn label (`shot:0`, `analyst:1`, a nested agent's label) — the row name. */\n label: string\n runId: string\n parentId?: string\n startMs: number\n endMs?: number\n status: 'running' | 'done' | 'down'\n usd: number\n tokens: { input: number; output: number }\n score?: number\n}\n\nexport interface WaterfallReport {\n spans: WaterfallSpan[]\n /** Wall-clock of the observed window (first spawn → last settle). */\n totalMs: number\n totalUsd: number\n totalTokens: { input: number; output: number }\n /** Rollup by label prefix (the part before ':') — shots vs analysts vs anything else. */\n byKind: Record<\n string,\n { count: number; ms: number; usd: number; tokens: { input: number; output: number } }\n >\n}\n\ninterface SpawnPayload {\n childId?: string\n label?: string\n}\ninterface SettlePayload {\n childId?: string\n status?: string\n score?: number\n spent?: { usd?: number; tokens?: { input?: number; output?: number } }\n}\n\nexport interface WaterfallCollector {\n /** Attach these to RunAgenticOptions.hooks / BenchmarkConfig.hooks. */\n hooks: RuntimeHooks\n report(): WaterfallReport\n /** The text waterfall — one row per span, bars scaled to the observed window. */\n render(opts?: { width?: number; maxRows?: number }): string\n reset(): void\n}\n\nexport function createWaterfallCollector(): WaterfallCollector {\n let spans = new Map<string, WaterfallSpan>()\n\n const onEvent = (event: RuntimeHookEvent): void => {\n if (event.target === 'agent.spawn') {\n const p = (event.payload ?? {}) as SpawnPayload\n const id = p.childId ?? event.id\n spans.set(id, {\n id,\n label: p.label ?? id,\n runId: event.runId,\n ...(event.parentId !== undefined ? { parentId: event.parentId } : {}),\n startMs: event.timestamp,\n status: 'running',\n usd: 0,\n tokens: { input: 0, output: 0 },\n })\n return\n }\n if (event.target === 'agent.child') {\n const p = (event.payload ?? {}) as SettlePayload\n const id = p.childId\n if (!id) return\n const span = spans.get(id)\n if (!span) return\n span.endMs = event.timestamp\n span.status = p.status === 'down' ? 'down' : 'done'\n span.usd = p.spent?.usd ?? 0\n span.tokens = {\n input: p.spent?.tokens?.input ?? 0,\n output: p.spent?.tokens?.output ?? 0,\n }\n if (typeof p.score === 'number') span.score = p.score\n }\n }\n\n const report = (): WaterfallReport => {\n const all = [...spans.values()].sort((a, b) => a.startMs - b.startMs)\n const start = all[0]?.startMs ?? 0\n const end = Math.max(start, ...all.map((s) => s.endMs ?? s.startMs))\n const byKind: WaterfallReport['byKind'] = {}\n let totalUsd = 0\n const totalTokens = { input: 0, output: 0 }\n for (const s of all) {\n totalUsd += s.usd\n totalTokens.input += s.tokens.input\n totalTokens.output += s.tokens.output\n const kind = s.label.includes(':') ? (s.label.split(':')[0] as string) : s.label\n let k = byKind[kind]\n if (!k) {\n k = { count: 0, ms: 0, usd: 0, tokens: { input: 0, output: 0 } }\n byKind[kind] = k\n }\n k.count += 1\n k.ms += (s.endMs ?? s.startMs) - s.startMs\n k.usd += s.usd\n k.tokens.input += s.tokens.input\n k.tokens.output += s.tokens.output\n }\n return { spans: all, totalMs: end - start, totalUsd, totalTokens, byKind }\n }\n\n const render = (opts?: { width?: number; maxRows?: number }): string => {\n const { spans: all, totalMs, totalUsd, byKind } = report()\n if (all.length === 0) return '(no spans observed)'\n const width = opts?.width ?? 48\n const maxRows = opts?.maxRows ?? 60\n const start = all[0]?.startMs ?? 0\n const scale = totalMs > 0 ? width / totalMs : 0\n const lines: string[] = []\n const labelWidth = Math.min(24, Math.max(...all.map((s) => s.label.length)) + 1)\n for (const s of all.slice(0, maxRows)) {\n const offset = Math.round((s.startMs - start) * scale)\n const dur = (s.endMs ?? s.startMs) - s.startMs\n const len = Math.max(1, Math.round(dur * scale))\n const bar = `${' '.repeat(Math.min(offset, width))}${(s.status === 'down' ? '░' : '█').repeat(Math.max(1, Math.min(len, width - Math.min(offset, width) + 1)))}`\n const mark =\n s.status === 'down'\n ? ' DOWN'\n : s.score !== undefined\n ? ` ${(s.score * 100).toFixed(0)}%`\n : ''\n lines.push(\n `${s.label.padEnd(labelWidth)}|${bar.padEnd(width + 1)}| ${(dur / 1000).toFixed(1)}s $${s.usd.toFixed(4)} ${s.tokens.input}/${s.tokens.output}tok${mark}`,\n )\n }\n if (all.length > maxRows) lines.push(`… ${all.length - maxRows} more spans`)\n lines.push('—'.repeat(labelWidth + width + 2))\n for (const [kind, k] of Object.entries(byKind)) {\n lines.push(\n `${kind.padEnd(labelWidth)} ×${k.count} ${(k.ms / 1000).toFixed(1)}s busy $${k.usd.toFixed(4)} ${k.tokens.input}/${k.tokens.output}tok`,\n )\n }\n lines.push(\n `TOTAL${' '.repeat(labelWidth - 5)} ${(totalMs / 1000).toFixed(1)}s wall $${totalUsd.toFixed(4)}`,\n )\n return lines.join('\\n')\n }\n\n return {\n hooks: { onEvent },\n report,\n render,\n reset: () => {\n spans = new Map()\n },\n }\n}\n","/** Command runner seam. Host code can use `localShell`; sandbox code can wrap `box.exec`. */\nexport type Shell = (\n args: ReadonlyArray<string>,\n cwd?: string,\n) => Promise<{ stdout: string; stderr: string; code: number }>\n\nexport type WorkspaceCommit =\n | { readonly ok: true; readonly rev: string }\n | { readonly ok: false; readonly conflict: string }\n\nexport interface Workspace {\n readonly ref: string\n materialize(dir: string): Promise<void>\n commit(dir: string, message: string): Promise<WorkspaceCommit>\n head(): Promise<string>\n}\n\nexport function localShell(): Shell {\n return async (args, cwd) => {\n const { execFile } = await import('node:child_process')\n const [bin, ...rest] = args\n return new Promise((resolve) => {\n execFile(\n bin ?? '',\n rest,\n { cwd, encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },\n (err: Error | null, stdout: string, stderr: string) => {\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n code: err ? ((err as { code?: number }).code ?? 1) : 0,\n })\n },\n )\n })\n }\n}\n\nexport interface GitWorkspaceOptions {\n readonly ref: string\n readonly shell?: Shell\n readonly branch?: string\n readonly noHooks?: boolean\n}\n\nexport function gitWorkspace(opts: GitWorkspaceOptions): Workspace {\n const shell = opts.shell ?? localShell()\n const branch = opts.branch ?? 'main'\n const cfg = opts.noHooks === false ? [] : ['-c', 'core.hooksPath=/dev/null']\n const ident = ['-c', 'user.email=workspace@tangle.local', '-c', 'user.name=workspace']\n\n const run = async (args: string[], cwd?: string): Promise<string> => {\n const res = await shell(['git', ...cfg, ...ident, ...args], cwd)\n if (res.code !== 0) {\n throw new Error(\n `git ${args.join(' ')} failed (${res.code}): ${tail(res.stderr || res.stdout)}`,\n )\n }\n return res.stdout\n }\n\n return {\n ref: opts.ref,\n materialize: (dir) => run(['clone', '--branch', branch, opts.ref, dir]).then(() => {}),\n async commit(dir, message) {\n await run(['add', '-A'], dir)\n const status = await run(['status', '--porcelain'], dir)\n if (!status.trim()) return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n await run(['commit', '-m', message], dir)\n const pull = await shell(['git', ...cfg, ...ident, 'pull', '--rebase', 'origin', branch], dir)\n if (pull.code !== 0) {\n await shell(['git', ...cfg, 'rebase', '--abort'], dir).catch(() => {})\n return { ok: false, conflict: tail(pull.stderr || pull.stdout) }\n }\n const push = await shell(['git', ...cfg, ...ident, 'push', 'origin', branch], dir)\n if (push.code !== 0) return { ok: false, conflict: tail(push.stderr || push.stdout) }\n return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n },\n async head() {\n const out = await run(['ls-remote', opts.ref, `refs/heads/${branch}`])\n return out.split(/\\s+/)[0] ?? ''\n },\n }\n}\n\n/** A jj-backed `Workspace` (Jujutsu, colocated with git for the durable remote).\n * Same port, same `Shell` — a drop-in for `gitWorkspace`. jj suits agent loops:\n * no staging area, and a first-class operation log (native resume/undo). Live use\n * requires `jj` on the `Shell`'s host. */\nexport function jjWorkspace(opts: GitWorkspaceOptions): Workspace {\n const shell = opts.shell ?? localShell()\n const branch = opts.branch ?? 'main'\n // jj reads its author identity from config, not per-call flags like git's `-c\n // user.*`; inject it via --config-toml so a throwaway clone is self-contained\n // (parallels gitWorkspace's `ident`). Global flags must precede the subcommand.\n const ident = [\n '--config-toml',\n 'user.name=\"workspace\"',\n '--config-toml',\n 'user.email=\"workspace@tangle.local\"',\n ]\n\n const jj = async (args: string[], cwd?: string): Promise<string> => {\n const res = await shell(['jj', ...ident, ...args], cwd)\n if (res.code !== 0) {\n throw new Error(\n `jj ${args.join(' ')} failed (${res.code}): ${tail(res.stderr || res.stdout)}`,\n )\n }\n return res.stdout\n }\n\n return {\n ref: opts.ref,\n // Colocated clone: jj manages history, git holds the durable remote.\n materialize: (dir) => jj(['git', 'clone', '--colocate', opts.ref, dir]).then(() => {}),\n async commit(dir, message) {\n // jj auto-snapshots the working copy; describe the change, then open a fresh\n // empty change so the next commit doesn't amend this one. A rejected push is\n // surfaced as a typed blocker (conflicts are first-class in jj, not aborted).\n await jj(['describe', '-m', message], dir)\n await jj(['new'], dir)\n const push = await shell(['jj', ...ident, 'git', 'push', '--branch', branch], dir)\n if (push.code !== 0) return { ok: false, conflict: tail(push.stderr || push.stdout) }\n const rev = (await jj(['log', '--no-graph', '-r', '@-', '-T', 'commit_id'], dir)).trim()\n return { ok: true, rev }\n },\n async head() {\n const out = await shell(['git', 'ls-remote', opts.ref, `refs/heads/${branch}`])\n return out.stdout.split(/\\s+/)[0] ?? ''\n },\n }\n}\n\nexport interface WorkspaceRun<T> {\n readonly valid: boolean\n readonly value: T\n /** Present when a commit was attempted (valid, or `commitOnInvalid`). */\n readonly commit?: WorkspaceCommit\n}\n\n/**\n * Run a worker `body` inside a FRESH clone of a shared `Workspace`, then commit its work back\n * so the next worker (or the supervisor) builds on it. This is the seam that turns isolated\n * per-worker cwds into one compounding artifact — `body` gets a real materialized dir, its\n * delivery is committed to the shared ref iff it's valid (a conflict is returned, never thrown).\n * The clone is removed after; durable state lives only in the ref.\n */\nexport async function runInWorkspace<T>(\n ws: Workspace,\n body: (cwd: string) => Promise<{ valid: boolean; value: T; message?: string }>,\n opts: { tmpPrefix?: string; commitOnInvalid?: boolean } = {},\n): Promise<WorkspaceRun<T>> {\n const { mkdtempSync, rmSync } = await import('node:fs')\n const { tmpdir } = await import('node:os')\n const { join } = await import('node:path')\n const dir = mkdtempSync(join(tmpdir(), opts.tmpPrefix ?? 'ws-run-'))\n try {\n await ws.materialize(dir)\n const r = await body(dir)\n if (r.valid || opts.commitOnInvalid) {\n const message = r.message ?? (r.valid ? 'worker: delivered' : 'worker: wip')\n const commit = await ws.commit(dir, message)\n return { valid: r.valid, value: r.value, commit }\n }\n return { valid: r.valid, value: r.value }\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\nfunction tail(s: string): string {\n return s.slice(-400)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAA8B,kBAAkB,eAAAA,oBAAmB;;;AC+CnE,IAAM,SAAS,CAAC,OAAgC;AAC9C,MAAI,GAAG,WAAW,EAAG,QAAO;AAC5B,QAAM,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AACtC,QAAM,MAAM,KAAK,MAAM,EAAE,SAAS,CAAC;AACnC,SAAO,EAAE,SAAS,MAAM,IAAK,EAAE,GAAG,KAAiB,EAAE,MAAM,CAAC,IAAgB,EAAE,GAAG,KAAgB;AACnG;AAMO,SAAS,cACd,OACA,MACe;AACf,QAAM,UAAU,MAAM,WAAW,CAAC,CAAC;AACnC,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,aAAW,KAAK,OAAO;AACrB,QAAI,CAAC,EAAE,MAAM,WAAW,OAAO,EAAG;AAClC,UAAM,OAAO,MAAM,IAAI,EAAE,KAAK,KAAK,CAAC;AACpC,SAAK,KAAK,CAAC;AACX,UAAM,IAAI,EAAE,OAAO,IAAI;AAAA,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G,GAAG,GAAG,KAAK;AACvF,aAAO,EAAE,IAAI,MAAM,IAAI;AAAA,IACzB;AAAA,IACA,MAAM,OAAO;AACX,YAAM,MAAM,MAAM,MAAM,CAAC,OAAO,aAAa,KAAK,KAAK,cAAc,MAAM,EAAE,CAAC;AAC9E,aAAO,IAAI,OAAO,MAAM,KAAK,EAAE,CAAC,KAAK;AAAA,IACvC;AAAA,EACF;AACF;AAgBA,eAAsB,eACpB,IACA,MACA,OAA0D,CAAC,GACjC;AAC1B,QAAM,EAAE,aAAAC,cAAa,QAAAC,QAAO,IAAI,MAAM,OAAO,IAAS;AACtD,QAAM,EAAE,QAAAC,QAAO,IAAI,MAAM,OAAO,IAAS;AACzC,QAAM,EAAE,MAAAC,MAAK,IAAI,MAAM,OAAO,MAAW;AACzC,QAAM,MAAMH,aAAYG,MAAKD,QAAO,GAAG,KAAK,aAAa,SAAS,CAAC;AACnE,MAAI;AACF,UAAM,GAAG,YAAY,GAAG;AACxB,UAAM,IAAI,MAAM,KAAK,GAAG;AACxB,QAAI,EAAE,SAAS,KAAK,iBAAiB;AACnC,YAAM,UAAU,EAAE,YAAY,EAAE,QAAQ,sBAAsB;AAC9D,YAAM,SAAS,MAAM,GAAG,OAAO,KAAK,OAAO;AAC3C,aAAO,EAAE,OAAO,EAAE,OAAO,OAAO,EAAE,OAAO,OAAO;AAAA,IAClD;AACA,WAAO,EAAE,OAAO,EAAE,OAAO,OAAO,EAAE,MAAM;AAAA,EAC1C,UAAE;AACA,IAAAD,QAAO,KAAK,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,EAC9C;AACF;AAEA,SAAS,KAAK,GAAmB;AAC/B,SAAO,EAAE,MAAM,IAAI;AACrB;","names":["makeFinding","ci","obj","isAsyncIterable","fanout","perChild","median","pairedBootstrap","drainOne","mean","pairedBootstrap","pct","settle","join","writeFileSync","writeFileSync","pool","require","out","mkdtempSync","rmSync","tmpdir","join"]}
|