@tangle-network/agent-runtime 0.192.5 → 0.194.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/{activation-CsJctnHp.js → activation-BQFIiyUG.js} +3 -3
- package/dist/{activation-CsJctnHp.js.map → activation-BQFIiyUG.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-B6CDW-fp.js} +4 -4
- package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-B6CDW-fp.js.map} +1 -1
- package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
- package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{coordination-driver-pQobxl2Z.js → coordination-driver-iSN-m3VX.js} +287 -250
- package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
- package/dist/{authoring-D-nXk29K.js → delegate-DCC2muUd.js} +56 -13
- package/dist/delegate-DCC2muUd.js.map +1 -0
- package/dist/delegation-status-BlsbSeOB.js +358 -0
- package/dist/delegation-status-BlsbSeOB.js.map +1 -0
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +3 -3
- package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
- package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
- package/dist/{environment-provider-CJ43FJfJ.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-Ba4ZJ5jU.js → graph-DghidDx5.js} +138 -5
- package/dist/graph-DghidDx5.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +4 -5
- package/dist/graph.js.map +1 -1
- package/dist/{improve-Cbbt3jE6.d.ts → improve-COGzLCiY.d.ts} +3 -3
- package/dist/{improvement-cycle-D9FWTakR.js → improvement-cycle-DeS1ZC5B.js} +6 -6
- package/dist/{improvement-cycle-D9FWTakR.js.map → improvement-cycle-DeS1ZC5B.js.map} +1 -1
- package/dist/{index-B_fEqr5V.d.ts → index-BEPjOPwH.d.ts} +66 -69
- package/dist/{index-COznK4kB.d.ts → index-CrBgLCIf.d.ts} +4 -4
- package/dist/{index-OSRVFARy.d.ts → index-DO6DHgRP.d.ts} +2 -2
- package/dist/index.d.ts +8 -8
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +6 -6
- package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
- package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +11 -12
- package/dist/{knowledge-rzv8sBV9.js → knowledge-B5okOzBQ.js} +6 -6
- package/dist/{knowledge-rzv8sBV9.js.map → knowledge-B5okOzBQ.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DiiZMHw7.d.ts → loop-runner-bin-Clc5IAwu.d.ts} +3 -3
- package/dist/{loop-runner-bin-ClpCHpzR.js → loop-runner-bin-U1J6x_UF.js} +3 -3
- package/dist/{loop-runner-bin-ClpCHpzR.js.map → loop-runner-bin-U1J6x_UF.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
- package/dist/materialization-vZssF9Nx.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +8 -8
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-BNBrKvZr.js → openai-tools-DmvmaG0a.js} +2 -2
- package/dist/{openai-tools-BNBrKvZr.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
- package/dist/{prepare-B5fJ7mLS.js → prepare-C29kNAon.js} +9 -14
- package/dist/prepare-C29kNAon.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-CKYND416.js} +2 -2
- package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-CKYND416.js.map} +1 -1
- package/dist/{provision-supervisor-DiHm_bvQ.js → provision-supervisor-CRPbnJiB.js} +12 -14
- package/dist/provision-supervisor-CRPbnJiB.js.map +1 -0
- package/dist/{redact-Ct7s2j86.js → redact-BOU77QfQ.js} +1120 -64
- package/dist/redact-BOU77QfQ.js.map +1 -0
- package/dist/{researcher-hgPa5p9i.js → researcher-Cp4JRbFp.js} +2 -2
- package/dist/researcher-Cp4JRbFp.js.map +1 -0
- package/dist/{runtime-DI4mJNXI.d.ts → runtime-B8x43nGP.d.ts} +5 -4
- package/dist/{runtime-CVdsAHEN.js → runtime-BVrqSu0-.js} +36 -25
- package/dist/{runtime-CVdsAHEN.js.map → runtime-BVrqSu0-.js.map} +1 -1
- package/dist/server-D6XmE1Du.js +1311 -0
- package/dist/server-D6XmE1Du.js.map +1 -0
- package/dist/{stream-agent-turn-_GgUW49y.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
- package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
- package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
- package/dist/{structural-rollout-NrtKSgCE.js → structural-rollout-BcPXFzVb.js} +16 -43
- package/dist/structural-rollout-BcPXFzVb.js.map +1 -0
- package/dist/{supervise-Cr6JEoIg.js → supervise-C0V3pZXK.js} +179 -1980
- package/dist/supervise-C0V3pZXK.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -13
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-DKA_PDv0.d.ts → types-B_pNTBjK.d.ts} +25 -29
- package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-BCezkeIk.js} +2 -2
- package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-BCezkeIk.js.map} +1 -1
- package/package.json +1 -1
- package/skills/codemode/SKILL.md +2 -2
- package/skills/supervise/SKILL.md +93 -26
- package/dist/authoring-D-nXk29K.js.map +0 -1
- package/dist/coordination-driver-pQobxl2Z.js.map +0 -1
- package/dist/environment-provider-DEwsolvi.js.map +0 -1
- package/dist/executable-spec-DxuiDFAU.js.map +0 -1
- package/dist/graph-Ba4ZJ5jU.js.map +0 -1
- package/dist/jsonl-file-CDfsCI5s.js +0 -59
- package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
- package/dist/materialization-CekWK6OO.js.map +0 -1
- package/dist/prepare-B5fJ7mLS.js.map +0 -1
- package/dist/provision-supervisor-DiHm_bvQ.js.map +0 -1
- package/dist/redact-Ct7s2j86.js.map +0 -1
- package/dist/researcher-hgPa5p9i.js.map +0 -1
- package/dist/snapshot-CTAf4uuA.js +0 -26
- package/dist/snapshot-CTAf4uuA.js.map +0 -1
- package/dist/spawn-journal-B9eTmVAn.js +0 -999
- package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
- package/dist/structural-rollout-NrtKSgCE.js.map +0 -1
- package/dist/supervise-Cr6JEoIg.js.map +0 -1
- package/dist/util-mCNUeboW.js +0 -419
- package/dist/util-mCNUeboW.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-journal-B9eTmVAn.js","names":[],"sources":["../src/durable/content-address.ts","../src/runtime/supervise/trace-evidence.ts","../src/runtime/supervise/tree-key.ts","../src/durable/spawn-journal.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\n\n/** Stable content address shared by result and trace artifacts. */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\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(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n","/**\n * Durable structured tool evidence for supervised workers.\n *\n * The executor-owned `TraceSource` is collected before teardown, snapshotted into the shared\n * content-addressed blob store, and only then referenced by a settlement. Analysis reconstructs\n * agent-eval's bounded `TraceAnalysisStore` from those exact bytes. Worker output is never accepted\n * as a substitute for tool evidence.\n *\n * @experimental\n */\n\nimport {\n isToolSpan,\n type Span,\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { TraceSource } from './trace-source'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** Schema version for content-addressed worker tool-trace artifacts. */\nexport const WORKER_TOOL_TRACE_SCHEMA_VERSION = 1 as const\n\n/** Bytes stored under `WorkerTraceEvidence.traceRef`. */\nexport interface WorkerToolTraceArtifact {\n readonly schemaVersion: typeof WORKER_TOOL_TRACE_SCHEMA_VERSION\n readonly spans: ReadonlyArray<ToolSpan>\n}\n\n/** Structural guard for the official bounded trace-analysis read contract. */\nexport function isTraceAnalysisStore(value: unknown): value is TraceAnalysisStore {\n if (value === null || typeof value !== 'object') return false\n const store = value as Partial<Record<keyof TraceAnalysisStore, unknown>>\n return (\n typeof store.getOverview === 'function' &&\n typeof store.queryTraces === 'function' &&\n typeof store.countTraces === 'function' &&\n typeof store.viewTrace === 'function' &&\n typeof store.viewSpans === 'function' &&\n typeof store.searchTrace === 'function' &&\n typeof store.searchSpan === 'function'\n )\n}\n\n/** Collect and persist one executor's structured tool trace without changing its task outcome. */\nexport async function captureWorkerTraceEvidence(\n readSource: (() => TraceSource | undefined) | undefined,\n blobs: ResultBlobStore,\n executed: boolean,\n): Promise<WorkerTraceEvidence> {\n if (!executed) return unavailable('execution-did-not-start')\n if (readSource === undefined) return unavailable('executor-did-not-expose-trace-source')\n\n let source: TraceSource | undefined\n try {\n source = readSource()\n } catch {\n return unavailable('trace-source-unavailable')\n }\n if (source === undefined) return unavailable('trace-source-unavailable')\n\n let collected: unknown\n try {\n collected = await source.collect()\n } catch {\n return unavailable('trace-collection-failed')\n }\n if (!Array.isArray(collected) || collected.some((span) => !isToolSpanValue(span))) {\n return unavailable('invalid-tool-spans')\n }\n if (collected.length === 0) return unavailable('no-tool-spans-captured')\n\n let artifact: WorkerToolTraceArtifact\n let traceRef: string\n try {\n const snapshot = structuredClone(collected) as ToolSpan[]\n // Use agent-eval's canonical adapter as the full integrity check before the durable receipt\n // claims these spans are analyzable. `isToolSpan` only narrows the discriminated union.\n toolSpansToTraceAnalysisStore(snapshot)\n artifact = {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: snapshot,\n }\n traceRef = contentAddress(artifact)\n } catch {\n return unavailable('invalid-tool-spans')\n }\n try {\n await blobs.put(traceRef, artifact)\n } catch {\n return unavailable('trace-persistence-failed')\n }\n return Object.freeze({ status: 'available', traceRef, spanCount: artifact.spans.length })\n}\n\n/** Rehydrate exact persisted spans through agent-eval's one bounded trace-analysis adapter. */\nexport async function workerTraceAnalysisStore(\n evidence: WorkerTraceEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<TraceAnalysisStore> {\n if (evidence.status === 'unavailable') {\n // The published adapter owns the missing-evidence error and its classification.\n return toolSpansToTraceAnalysisStore(undefined)\n }\n const raw = await blobs.get(evidence.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' is missing; the settlement evidence is incomplete`,\n )\n }\n const artifact = parseWorkerToolTraceArtifact(raw, evidence.traceRef)\n if (artifact.spans.length !== evidence.spanCount) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' has ${artifact.spans.length} spans but its settlement records ${evidence.spanCount}`,\n )\n }\n return toolSpansToTraceAnalysisStore(artifact.spans)\n}\n\n/** Validate a stored trace artifact before an analyst or replay trusts it. */\nexport function parseWorkerToolTraceArtifact(\n value: unknown,\n traceRef = '<unknown>',\n): WorkerToolTraceArtifact {\n if (\n value === null ||\n typeof value !== 'object' ||\n (value as { schemaVersion?: unknown }).schemaVersion !== WORKER_TOOL_TRACE_SCHEMA_VERSION ||\n !Array.isArray((value as { spans?: unknown }).spans)\n ) {\n throw new ValidationError(\n `worker trace blob '${traceRef}' is not a version-${WORKER_TOOL_TRACE_SCHEMA_VERSION} tool trace artifact`,\n )\n }\n const spans = (value as { spans: unknown[] }).spans\n if (spans.length === 0) {\n // Missing spans cannot prove a tool-free run; preserve agent-eval's explicit integrity error.\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n }\n if (spans.some((span) => !isToolSpanValue(span))) {\n throw new ValidationError(`worker trace blob '${traceRef}' contains a non-tool span`)\n }\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n}\n\nfunction unavailable(reason: Extract<WorkerTraceEvidence, { status: 'unavailable' }>['reason']) {\n return Object.freeze({ status: 'unavailable' as const, reason })\n}\n\nfunction isToolSpanValue(value: unknown): value is ToolSpan {\n try {\n return isToolSpan(value as Span)\n } catch {\n return false\n }\n}\n","import type { NodeId } from './types'\n\n/** Runtime tag used only for a child that owns another supervised scope. */\nexport const driverRuntime = 'driver' as const\n\n// Recursive ownership is an executor capability, not a Runtime string. `Runtime` is deliberately\n// open, so a caller-owned leaf may also call itself \"driver\". Keep the capability on the exact\n// Runtime-created executor object and never expose a public lookalike property that a leaf can set.\nconst nestedDriverTreeOwners = new WeakSet<object>()\n\n/** Canonical journal key for the scope owned by one nested driver node. */\nexport function nestedDriverTreeRoot(parentTreeRoot: NodeId, driverNodeId: NodeId): NodeId {\n return `${parentTreeRoot}/${driverNodeId}`\n}\n\n/** Privately mark the exact recursive executor that will create a nested journal tree. */\nexport function attestNestedDriverTreeOwner<T extends object>(owner: T): T {\n nestedDriverTreeOwners.add(owner)\n return owner\n}\n\n/** Return the canonical owned tree only for an exact privately marked recursive executor. */\nexport function runtimeOwnedNestedDriverTreeRoot(\n owner: object,\n parentTreeRoot: NodeId,\n driverNodeId: NodeId,\n): NodeId | undefined {\n return nestedDriverTreeOwners.has(owner)\n ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId)\n : undefined\n}\n","/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @stable\n */\n\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport { workerTraceAnalysisStore } from '../runtime/supervise/trace-evidence'\nimport { nestedDriverTreeRoot } from '../runtime/supervise/tree-key'\nimport type {\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport type { PendingWait } from '../runtime/supervise/wait'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport {\n isNoEntError,\n parseCommittedJsonLines,\n prepareJsonlAppend,\n writeAllBytes,\n} from './jsonl-file'\n\nexport { contentAddress } from './content-address'\n\n/** One journal tree in a recursively loaded supervision forest. */\nexport interface SpawnForestTree {\n readonly root: NodeId\n /** Driver node that owns this tree; absent for the requested root tree. */\n readonly ownerNodeId?: NodeId\n /** Journal tree containing `ownerNodeId`; absent for the requested root tree. */\n readonly parentTreeRoot?: NodeId\n readonly events: ReadonlyArray<SpawnEvent>\n readonly view: TreeView\n}\n\n/** One event with the journal tree that establishes its cursor namespace. */\nexport interface SpawnForestEvent {\n readonly treeRoot: NodeId\n readonly event: SpawnEvent\n}\n\n/** One flattened node with the journal tree that owns its records. */\nexport interface SpawnForestNode extends NodeSnapshot {\n readonly treeRoot: NodeId\n}\n\n/** A spawned worker with no terminal record in a cold snapshot. Resume treats the same state as\n * in-doubt and conservatively retains its reservation. Root nodes and armed waits are excluded. */\nexport interface SpawnForestInDoubtNode {\n readonly treeRoot: NodeId\n readonly nodeId: NodeId\n readonly label: string\n readonly runtime: Runtime\n}\n\n/** A driver spawn whose owned journal tree was never begun before the process stopped. */\nexport interface SpawnForestMissingTree {\n readonly parentTreeRoot: NodeId\n readonly ownerNodeId: NodeId\n readonly root: NodeId\n}\n\n/** Complete cold-readable view of one recursive supervision run. */\nexport interface SpawnForest {\n readonly root: NodeId\n readonly trees: ReadonlyArray<SpawnForestTree>\n readonly nodes: ReadonlyArray<SpawnForestNode>\n readonly events: ReadonlyArray<SpawnForestEvent>\n readonly inDoubt: ReadonlyArray<SpawnForestInDoubtNode>\n readonly missingTrees: ReadonlyArray<SpawnForestMissingTree>\n}\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n *\n * @stable\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n *\n * @stable\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n *\n * @stable\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n *\n * @stable\n */\nexport class FileSpawnJournal implements SpawnJournal {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\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 undefined\n throw err\n }\n let begun = false\n const events: SpawnEvent[] = []\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\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 undefined\n throw err\n }\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const append = this.appendTail.then(() => this.writeRecord(record))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async writeRecord(record: SpawnJournalRecord): 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 needsSeparator = await prepareJsonlAppend(this.path)\n const fh = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\n/**\n * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.\n *\n * Nested driver tree keys are a Runtime implementation detail; callers should use this reader\n * instead of deriving or scanning keys themselves. The reader follows only the explicit\n * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime\n * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are\n * intentionally treated as leaves rather than guessing or scanning convention-derived keys.\n * This preserves each tree's independent cursor namespace on flattened events.\n * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node\n * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work\n * interpretation.\n *\n * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value\n * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot\n * change the result already observed.\n */\nexport async function loadSpawnForest(journal: SpawnJournal, root: NodeId): Promise<SpawnForest> {\n const rootEvents = await journal.loadTree(root)\n if (rootEvents === undefined) {\n throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`)\n }\n\n const trees: SpawnForestTree[] = []\n const nodes: SpawnForestNode[] = []\n const events: SpawnForestEvent[] = []\n const inDoubt: SpawnForestInDoubtNode[] = []\n const missingTrees: SpawnForestMissingTree[] = []\n const visited = new Set<NodeId>()\n const queue: Array<{\n readonly root: NodeId\n readonly events: SpawnEvent[]\n readonly ownerNodeId?: NodeId\n readonly parentTreeRoot?: NodeId\n /** Parent-tree spawn that establishes the root node omitted from an owned journal tree. */\n readonly ownerSpawn?: Extract<SpawnEvent, { kind: 'spawned' }>\n }> = [{ root, events: rootEvents }]\n\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor]!\n if (visited.has(current.root)) {\n throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`)\n }\n visited.add(current.root)\n const stableEvents = detachedSnapshot(\n current.events,\n `loadSpawnForest tree ${JSON.stringify(current.root)}`,\n )\n const viewEvents =\n current.ownerSpawn === undefined ||\n stableEvents.some((event) => event.kind === 'spawned' && event.id === current.ownerSpawn?.id)\n ? [...stableEvents]\n : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents]\n const view = detachedSnapshot(\n materializeTreeView(viewEvents),\n `loadSpawnForest view ${JSON.stringify(current.root)}`,\n )\n trees.push({\n root: current.root,\n ...(current.ownerNodeId === undefined ? {} : { ownerNodeId: current.ownerNodeId }),\n ...(current.parentTreeRoot === undefined ? {} : { parentTreeRoot: current.parentTreeRoot }),\n events: stableEvents,\n view,\n })\n // The owner is already a real node in its parent tree. Keep it in this tree's local view so\n // metered root events have a node, but omit the synthetic duplicate from the flattened list.\n nodes.push(\n ...view.nodes\n .filter((node) => current.ownerNodeId === undefined || node.id !== current.ownerNodeId)\n .map((node) => ({ treeRoot: current.root, ...node })),\n )\n events.push(...stableEvents.map((event) => ({ treeRoot: current.root, event })))\n\n const terminal = new Set<NodeId>()\n for (const event of stableEvents) {\n if (event.kind === 'settled' || event.kind === 'cancelled') terminal.add(event.id)\n }\n const spawns = stableEvents\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> => event.kind === 'spawned',\n )\n .sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))\n for (const spawn of spawns) {\n if (spawn.parent !== undefined && !terminal.has(spawn.id)) {\n inDoubt.push({\n treeRoot: current.root,\n nodeId: spawn.id,\n label: spawn.label,\n runtime: spawn.runtime,\n })\n }\n if (spawn.ownedTreeRoot === undefined) continue\n const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id)\n if (spawn.ownedTreeRoot !== expectedRoot) {\n throw new Error(\n `loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`,\n )\n }\n const nestedRoot = spawn.ownedTreeRoot\n const nestedEvents = await journal.loadTree(nestedRoot)\n if (nestedEvents === undefined) {\n missingTrees.push({\n parentTreeRoot: current.root,\n ownerNodeId: spawn.id,\n root: nestedRoot,\n })\n continue\n }\n queue.push({\n root: nestedRoot,\n events: nestedEvents,\n ownerNodeId: spawn.id,\n parentTreeRoot: current.root,\n ownerSpawn: spawn,\n })\n }\n }\n\n return detachedSnapshot(\n { root, trees, nodes, events, inDoubt, missingTrees },\n 'loadSpawnForest result',\n )\n}\n\n/** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to\n * the parent tree. Supply a view-only parentless copy so strict materialization can fold root\n * metering without weakening its missing-spawn corruption check for ordinary event lists. */\nfunction ownedTreeRootSpawn(\n spawn: Extract<SpawnEvent, { kind: 'spawned' }>,\n): Extract<SpawnEvent, { kind: 'spawned' }> {\n const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn\n return root\n}\n\n/**\n * Aggregate provider-served model evidence across one recursively owned journal forest.\n *\n * The parent tree records an owned driver's terminal summary, while that driver's own inference\n * and descendants live in its owned tree. This reducer follows the forest reader's explicit tree\n * edges and consumes each tree's metered attempts plus terminal leaf settlements exactly once.\n * A summary node is skipped because its owned tree supplies the source records. Plan materialization\n * is intentionally not read: it proves only what Runtime requested, not what a provider served.\n *\n * Missing legacy evidence, an unfinished node, an unopened owned tree, an identity conflict, and a\n * paid attempt without a qualified served snapshot all return unknown. An explicit\n * `providerDispatch: \"not_started\"` arm and Runtime accounting-only metered records are ignored\n * for served-model identity, while absent or malformed legacy data remains unknown here.\n */\nexport function aggregateProviderModelEvidence(\n forest: SpawnForest,\n): ProviderModelExecutionEvidence {\n const attempts: ProviderModelAttemptEvidence[] = []\n const observedModels = new Set<string>()\n const canonicalModels = new Set<string>()\n const nodes = new Map<string, SpawnForestNode>()\n let reason: 'provider-model-missing' | 'provider-model-conflict' | undefined\n let sawProviderEvidence = false\n\n for (const node of forest.nodes) nodes.set(forestNodeKey(node.treeRoot, node.id), node)\n if (forest.missingTrees.length > 0 || forest.inDoubt.length > 0) {\n reason = 'provider-model-missing'\n }\n\n const markMissing = () => {\n reason ??= 'provider-model-missing'\n }\n const markConflict = () => {\n reason = 'provider-model-conflict'\n }\n\n const append = (raw: unknown): void => {\n sawProviderEvidence = true\n if (!isProviderEvidenceObject(raw)) {\n markMissing()\n return\n }\n if (raw.status === 'unknown') {\n if (raw.reason === 'provider-model-conflict') {\n markConflict()\n } else if (!hasOnlyNotStartedAttempts(raw)) {\n markMissing()\n }\n } else if (raw.status !== 'known') {\n markMissing()\n return\n }\n if (!Array.isArray(raw.attempts) || !Array.isArray(raw.models)) {\n markMissing()\n return\n }\n\n const declared = new Set<string>()\n for (const model of raw.models) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n } else {\n declared.add(model)\n }\n }\n const observedInRecord = new Set<string>()\n for (const rawAttempt of raw.attempts) {\n if (!isProviderAttemptEvidence(rawAttempt)) {\n markMissing()\n continue\n }\n if (rawAttempt.identityConflict === true) markConflict()\n const observations = [...rawAttempt.observations]\n if (rawAttempt.providerDispatch === 'not_started') {\n if (observations.length > 0) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n providerDispatch: 'not_started' as const,\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n if (observations.length === 0) {\n markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n let base: string | undefined\n let snapshot: string | undefined\n for (const model of observations) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n continue\n }\n observedInRecord.add(model)\n observedModels.add(model)\n const identity = servedIdentityParts(model)\n if (identity === undefined) {\n markMissing()\n continue\n }\n if (base !== undefined && base !== identity.base) markConflict()\n if (\n snapshot !== undefined &&\n identity.snapshot !== undefined &&\n snapshot !== identity.snapshot\n ) {\n markConflict()\n }\n base = identity.base\n snapshot ??= identity.snapshot\n if (identity.snapshot !== undefined) {\n canonicalModels.add(`${identity.base}@${identity.snapshot}`)\n if (canonicalModels.size > 1) markConflict()\n }\n }\n if (base === undefined || snapshot === undefined) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze(observations),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n }\n if (\n declared.size !== observedInRecord.size ||\n [...declared].some((model) => !observedInRecord.has(model))\n ) {\n markMissing()\n }\n }\n\n const terminal = (\n treeRoot: NodeId,\n event: Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }>,\n ) => {\n const node = nodes.get(forestNodeKey(treeRoot, event.id))\n if (node === undefined) {\n markMissing()\n return\n }\n // This event is a parent-side summary. Its owned tree is the authoritative source and is\n // traversed above; consuming its summary here would count nested attempts twice.\n if (node.ownedTreeRoot !== undefined) return\n if (event.kind === 'cancelled') {\n markMissing()\n return\n }\n append(event.providerModel ?? node.providerModel)\n }\n\n for (const tree of forest.trees) {\n for (const event of tree.events) {\n if (event.kind === 'metered') {\n if (event.accountingOnly === true) {\n if (event.providerModel !== undefined) markMissing()\n continue\n }\n // The parent scope re-homes a driver's nested metered spend onto the driver's parent node.\n // Its owned tree carries the provider attempts; consuming this summary would both\n // double-count and treat the spend-only legacy summary as missing identity evidence.\n const summaryNode = nodes.get(forestNodeKey(tree.root, event.id))\n if (summaryNode?.ownedTreeRoot !== undefined) continue\n const evidence = (event as SpawnEvent & { providerModel?: unknown }).providerModel\n if (evidence === undefined) markMissing()\n else append(evidence)\n } else if (event.kind === 'settled' || event.kind === 'cancelled') {\n terminal(tree.root, event)\n }\n }\n }\n\n if (!sawProviderEvidence || attempts.length === 0 || observedModels.size === 0) {\n reason ??= 'provider-model-missing'\n }\n const models = Object.freeze([...observedModels])\n const frozenAttempts = Object.freeze(attempts)\n return Object.freeze(\n reason === undefined\n ? { status: 'known' as const, attempts: frozenAttempts, models }\n : { status: 'unknown' as const, attempts: frozenAttempts, models, reason },\n )\n}\n\nfunction forestNodeKey(treeRoot: NodeId, nodeId: NodeId): string {\n return `${treeRoot}\\u0000${nodeId}`\n}\n\nfunction isProviderEvidenceObject(value: unknown): value is ProviderModelExecutionEvidence {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && 'status' in value\n}\n\nfunction hasOnlyNotStartedAttempts(evidence: ProviderModelExecutionEvidence): boolean {\n return (\n Array.isArray(evidence.attempts) &&\n evidence.attempts.length > 0 &&\n evidence.attempts.every(\n (attempt) =>\n isProviderAttemptEvidence(attempt) &&\n attempt.providerDispatch === 'not_started' &&\n attempt.observations.length === 0 &&\n attempt.identityConflict !== true,\n )\n )\n}\n\nfunction isProviderAttemptEvidence(value: unknown): value is ProviderModelAttemptEvidence {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Array.isArray((value as { observations?: unknown }).observations) &&\n ((value as { providerDispatch?: unknown }).providerDispatch === undefined ||\n (value as { providerDispatch?: unknown }).providerDispatch === 'not_started')\n )\n}\n\nfunction servedIdentityParts(\n model: string,\n): { readonly base: string; readonly snapshot?: string } | undefined {\n const at = model.lastIndexOf('@')\n const rawBase = at < 0 ? model : model.slice(0, at)\n const base = rawBase.slice(rawBase.lastIndexOf('/') + 1)\n if (base.length === 0) return undefined\n const snapshot = at < 0 ? undefined : model.slice(at + 1)\n if (snapshot !== undefined && snapshot.length === 0) return undefined\n return snapshot === undefined ? { base } : { base, snapshot }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n if (ev.kind === 'materialized') {\n if (events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: duplicate materialization receipt for node '${ev.id}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'spawned' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: materialization for node '${ev.id}' precedes its spawn in tree '${root}'`,\n )\n }\n }\n if (ev.kind === 'execution-bound') {\n if (\n events.some(\n (event) =>\n event.kind === 'execution-bound' &&\n event.id === ev.id &&\n event.binding.attemptId === ev.binding.attemptId,\n )\n ) {\n throw new Error(\n `spawn journal corrupted: duplicate execution binding for node '${ev.id}' attempt '${ev.binding.attemptId}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: execution binding for node '${ev.id}' precedes materialization in tree '${root}'`,\n )\n }\n }\n // `spawned` (ordinal namespace), `waiting` (the wait-ordinal namespace — it CREATES a node, it\n // does not settle one), and `metered` (informational spend, no settlement order) live outside\n // the cursor-uniqueness namespace replay relies on. `woken` IS a settlement and does not.\n if (outsideCursorNamespace(ev)) return\n if (events.some((e) => !outsideCursorNamespace(e) && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n/**\n * The records that CLOSE a node's cursor slot: a settlement, a cancellation, or a wait being\n * woken. The complement question to {@link outsideCursorNamespace}, and the one a resume needs —\n * a kind missing here leaves a finished node looking live, so its budget is never reclaimed and\n * its reservation is replayed as still in doubt.\n */\nexport function closesCursorSlot(ev: SpawnEvent): boolean {\n return ev.kind === 'settled' || ev.kind === 'cancelled' || ev.kind === 'woken'\n}\n\n/**\n * The kinds that sit OUTSIDE the cursor namespace: node-CREATION and informational records. The\n * cursor namespace is the one whose per-node uniqueness replay ordering rests on, so every side of\n * that guard reads this one list — the seq guard, `materializeTreeView`'s settlement split, and\n * `trajectory`'s close list.\n *\n * Declared once as data. `SpawnEvent` is a discriminated union, so the complement below is\n * COMPUTED rather than hand-written: a twelfth kind lands in the cursor namespace by construction\n * instead of by whichever copies its author remembered to update.\n */\nconst outsideCursorNamespaceKinds = [\n 'spawned',\n 'waiting',\n 'metered',\n 'materialized',\n 'execution-bound',\n 'progress',\n 'edge',\n 'teardown-unconfirmed',\n 'trace-unpropagated',\n 'node-inputs-resolved',\n 'edge-verdict',\n 'join-state',\n] as const satisfies ReadonlyArray<SpawnEvent['kind']>\n\ntype OutsideCursorNamespaceKind = (typeof outsideCursorNamespaceKinds)[number]\n\n/** A record that closes or advances a node's cursor slot — the complement of\n * {@link outsideCursorNamespace}, computed from the union rather than restated. */\nexport type CursorNamespaceEvent = Exclude<SpawnEvent, { kind: OutsideCursorNamespaceKind }>\n\nconst outsideKinds: ReadonlySet<string> = new Set<string>(outsideCursorNamespaceKinds)\n\n/** True for a node-CREATION or informational record. Narrows, so a caller keeps the union's arms. */\nexport function outsideCursorNamespace(\n ev: SpawnEvent,\n): ev is Extract<SpawnEvent, { kind: OutsideCursorNamespaceKind }> {\n return outsideKinds.has(ev.kind)\n}\n\n/** True for a record inside the cursor namespace. Narrows to {@link CursorNamespaceEvent}. */\nexport function insideCursorNamespace(ev: SpawnEvent): ev is CursorNamespaceEvent {\n return !outsideKinds.has(ev.kind)\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n *\n * @stable\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n const assignmentIds = new Map<NodeId, string>()\n const identities = new Map<NodeId, NodeExecutionIdentity>()\n const materializations = new Map<NodeId, NodeSnapshot['materialization']>()\n const executionBindings = new Map<\n NodeId,\n NonNullable<NodeSnapshot['executionBindings']>[number][]\n >()\n for (const ev of ordered) {\n if (ev.kind === 'spawned' || ev.kind === 'waiting') labels.set(ev.id, ev.label)\n if (ev.kind === 'spawned' && ev.assignmentId !== undefined) {\n assignmentIds.set(ev.id, ev.assignmentId)\n }\n if (ev.kind === 'spawned' && ev.identity !== undefined) {\n identities.set(ev.id, copyFrozenIdentity(ev.identity))\n }\n if (ev.kind === 'materialized') materializations.set(ev.id, ev.receipt)\n if (ev.kind === 'execution-bound') {\n const bindings = executionBindings.get(ev.id) ?? []\n bindings.push(ev.binding)\n executionBindings.set(ev.id, bindings)\n }\n }\n const handleFor = (id: NodeId, status: NodeStatus) =>\n replayHandle(id, labels.get(id) ?? id, status, {\n assignmentId: assignmentIds.get(id),\n identity: identities.get(id),\n materialization: materializations.get(id),\n executionBindings: executionBindings.get(id),\n })\n const settlementTime = (at: string): { readonly settledAt?: number } => {\n const settledAt = Date.parse(at)\n return Number.isFinite(settledAt) ? { settledAt } : {}\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'waiting') continue // arms a wait node; `woken` is its settlement\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'progress') continue // live observation, not a settlement — irrelevant to replay\n if (ev.kind === 'materialized') continue // wire receipt, not a settlement\n if (ev.kind === 'execution-bound') continue // attempt transport, not a settlement\n if (ev.kind === 'edge') continue // edge-ledger observability, not a settlement\n if (ev.kind === 'teardown-unconfirmed') continue // executor-leak evidence, not a settlement\n if (ev.kind === 'trace-unpropagated') continue // severed-hop marker, not a settlement\n if (ev.kind === 'node-inputs-resolved') continue // graph-engine fold input, not a settlement\n if (ev.kind === 'edge-verdict') continue // graph-engine fold input, not a settlement\n if (ev.kind === 'join-state') continue // graph-engine fold input, not a settlement\n if (ev.kind === 'woken') {\n // A wait that was cancelled carries no outcome blob — it replays as a `down`, exactly as a\n // cancelled worker does. A fired/timed-out wait rehydrates its `WaitOutcome` and costs zero.\n if (ev.by === 'cancelled' || ev.outRef === undefined) {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: 'wait cancelled',\n infra: false,\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n const outcome = await blobs.get(ev.outRef)\n if (outcome === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no wait outcome for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out: outcome,\n outRef: ev.outRef,\n spent: zeroSpend(),\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n trace: { status: 'unavailable', reason: 'execution-did-not-start' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'failed'),\n // `reason` is written by every current scope. The verdict fallback preserves the\n // pre-field convention and the generic text keeps still-older reasonless journals usable.\n reason: ev.reason ?? ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: cloneSpend(ev.spent),\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(\n id: NodeId,\n label: string,\n status: NodeStatus,\n evidence: {\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n readonly materialization?: NodeSnapshot['materialization']\n readonly executionBindings?: ReadonlyArray<\n NonNullable<NodeSnapshot['executionBindings']>[number]\n >\n } = {},\n) {\n return Object.freeze({\n id,\n label,\n status,\n ...(evidence.assignmentId === undefined ? {} : { assignmentId: evidence.assignmentId }),\n ...(evidence.identity === undefined ? {} : { identity: evidence.identity }),\n ...(evidence.materialization === undefined\n ? {}\n : { materialization: evidence.materialization }),\n ...(evidence.executionBindings === undefined\n ? {}\n : { executionBindings: Object.freeze([...evidence.executionBindings]) }),\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n })\n}\n\n/** A replayed handle must not retain mutable references into the loaded journal event. */\nfunction copyFrozenIdentity(identity: NodeExecutionIdentity): NodeExecutionIdentity {\n const correlation =\n identity.correlation === undefined ? undefined : Object.freeze({ ...identity.correlation })\n return Object.freeze({\n ...(identity.profileDigest === undefined ? {} : { profileDigest: identity.profileDigest }),\n ...(identity.taskDigest === undefined ? {} : { taskDigest: identity.taskDigest }),\n ...(identity.candidateDigest === undefined\n ? {}\n : { candidateDigest: identity.candidateDigest }),\n ...(correlation === undefined ? {} : { correlation }),\n })\n}\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter(\n (ev): ev is Extract<SpawnEvent, { kind: 'spawned' | 'waiting' }> =>\n ev.kind === 'spawned' || ev.kind === 'waiting',\n )\n .sort((a, b) => a.seq - b.seq)\n const settlements = events.filter((ev) => insideCursorNamespace(ev)).sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.kind === 'waiting') {\n // An ARMED wait reads `waiting` until a `woken` event lands. That is the whole durability\n // claim: a materialized tree from a journal whose process died mid-wait still shows the wait.\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'waiting',\n runtime: 'wait',\n budget: { maxIterations: 0, maxTokens: 0 },\n spent: zeroSpend(),\n })\n continue\n }\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n ...(ev.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: ev.ownedTreeRoot }),\n ...(ev.assignmentId === undefined ? {} : { assignmentId: ev.assignmentId }),\n ...(ev.identity ? { identity: ev.identity } : {}),\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = cloneSpend(ev.spent)\n node.providerModel = copyProviderModelEvidence(ev.providerModel)\n node.outRef = ev.outRef\n node.trace = traceEvidenceFor(ev)\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else if (ev.kind === 'woken') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.by === 'cancelled' ? 'cancelled' : 'done'\n node.outRef = ev.outRef\n node.trace = { status: 'unavailable', reason: 'not-an-executor' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n node.trace = { status: 'unavailable', reason: 'execution-did-not-start' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n }\n }\n // Materialization is node evidence, not a settlement. Fold it after node creation and before\n // freezing the view; exactly one receipt per node is enforced by the journal corruption guard.\n for (const ev of events) {\n if (ev.kind !== 'materialized') continue\n const node = requireNode(nodes, ev.id)\n node.materialization = ev.receipt\n node.runtime = ev.receipt.runtime\n }\n for (const ev of events) {\n if (ev.kind !== 'execution-bound') continue\n const node = requireNode(nodes, ev.id)\n node.executionBindings ??= []\n node.executionBindings.push(ev.binding)\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n waiting: snapshots.filter((n) => n.status === 'waiting').length,\n }\n}\n\n/**\n * The waits a journaled tree shows as ARMED but never woken — what a resumed run re-arms with the\n * ORIGINAL absolute deadline. Reading it from the journal (rather than from any live state) is\n * what makes \"SIGKILL a waiting tree, a new process keeps waiting to the same instant\" true.\n */\nexport function pendingWaits(events: SpawnEvent[]): PendingWait[] {\n const woken = new Set<NodeId>()\n for (const ev of events) if (ev.kind === 'woken') woken.add(ev.id)\n const pending: PendingWait[] = []\n for (const ev of events) {\n if (ev.kind !== 'waiting' || woken.has(ev.id)) continue\n pending.push({\n id: ev.id,\n label: ev.label,\n spec: ev.spec,\n armedAt: ev.armedAt,\n ordinal: ev.seq,\n })\n }\n return pending.sort((a, b) => a.ordinal - b.ordinal)\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n ownedTreeRoot?: NodeSnapshot['ownedTreeRoot']\n assignmentId?: string\n identity?: NodeSnapshot['identity']\n materialization?: NodeSnapshot['materialization']\n executionBindings?: NonNullable<NodeSnapshot['executionBindings']>[number][]\n spent: Spend\n providerModel?: NodeSnapshot['providerModel']\n outRef?: string\n trace?: NodeSnapshot['trace']\n settledAt?: number\n}\n\n/** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */\nfunction copyProviderModelEvidence(\n evidence: NodeSnapshot['providerModel'],\n): NodeSnapshot['providerModel'] {\n if (evidence === undefined) return undefined\n const attempts = Object.freeze(\n evidence.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...evidence.models])\n return Object.freeze(\n evidence.status === 'unknown'\n ? { status: 'unknown' as const, attempts, models, reason: evidence.reason }\n : { status: 'known' as const, attempts, models },\n )\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n ownedTreeRoot: node.ownedTreeRoot,\n assignmentId: node.assignmentId,\n identity: node.identity,\n materialization: node.materialization,\n executionBindings:\n node.executionBindings === undefined ? undefined : Object.freeze([...node.executionBindings]),\n spent: node.spent,\n providerModel: node.providerModel,\n outRef: node.outRef,\n trace: node.trace,\n settledAt: node.settledAt,\n }\n}\n\nfunction traceEvidenceFor(\n event: Extract<SpawnEvent, { kind: 'settled' }>,\n): NonNullable<NodeSnapshot['trace']> {\n return (\n event.trace ?? {\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n }\n )\n}\n"],"mappings":";;;;;;;;AAGA,SAAgB,eAAe,UAA2B;CAExD,OAAO,UADK,WAAW,QAAQ,CAAC,CAAC,OAAO,gBAAgB,QAAQ,GAAG,OAAO,CAAC,CAAC,OAAO,KAChE;AACrB;AAEA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAK,UAAU,KAAK,KAAK;CACjF,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,GAAG,EAAE;CAI1E,OAAO,IAHS,OAAO,QAAQ,KAAgC,CAAC,CAC7D,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAC/B,CAAC,CAAC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC,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AAS,MAAM,CAAC;CACjD,OAAO,OAAO,OACZ,SAAS,WAAW,YAChB;EAAE,QAAQ;EAAoB;EAAU;EAAQ,QAAQ,SAAS;CAAO,IACxE;EAAE,QAAQ;EAAkB;EAAU;CAAO,CACnD;AACF;AAEA,SAAS,YAAY,OAAqC,IAA6B;CACrF,MAAM,OAAO,MAAM,IAAI,EAAE;CACzB,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,oDAAoD,GAAG,sBAAsB;CAE/F,OAAO;AACT;AAEA,SAAS,eAAe,MAAqC;CAC3D,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,SAAS,KAAK;EACd,QAAQ,KAAK;EACb,eAAe,KAAK;EACpB,cAAc,KAAK;EACnB,UAAU,KAAK;EACf,iBAAiB,KAAK;EACtB,mBACE,KAAK,sBAAsB,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,CAAC,GAAG,KAAK,iBAAiB,CAAC;EAC9F,OAAO,KAAK;EACZ,eAAe,KAAK;EACpB,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,iBACP,OACoC;CACpC,OACE,MAAM,SAAS;EACb,QAAQ;EACR,QAAQ;CACV;AAEJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"structural-rollout-NrtKSgCE.js","names":[],"sources":["../src/improvement/optimizer-prompt.ts","../src/runtime/profile-chat-client.ts","../src/runtime/observe.ts","../src/runtime/strategy.ts","../src/runtime/structural-rollout.ts"],"sourcesContent":["/**\n * The senior scientific-method optimizer doctrine — the ONE substantial prompt\n * core shared by every builder/author surface (tool build, MCP build, codebase\n * improvement, and strategy authoring).\n *\n * Seeded from the proven senior prompts rather than invented: GEPA's\n * `REFLECTION_SYSTEM` (localize → diagnose → minimal generalizable fix →\n * preserve what works), the /evolve loop (one hypothesis with a mechanism and a\n * falsifiable prediction; attack the largest measured gap first), /pursue (one\n * coherent change set, no partial scaffolding), and the self-improving-loop /\n * supervisor doctrine (a keep is decided by a real check, never by the author;\n * observe → rate → decide). Generalized from \"mutate a prompt string\" to\n * \"build a code surface a held-out measurement will grade\".\n */\n\n/**\n * The shared method block every build/author prompt embeds. Domain framing\n * (what a tool/MCP/codebase-edit deliverable looks like) wraps around it; this\n * is the process itself.\n */\nexport const optimizerMethod = [\n 'THE METHOD — you are a senior engineer-scientist improving a measured system, not a code',\n 'generator. Your change is an experiment: it exists to move a real, externally graded number,',\n 'and it will be measured against a baseline on held-out tasks you cannot see. Work in this order:',\n '',\n '1. DIAGNOSE FIRST. Read every finding before touching anything — findings are ranked evidence',\n ' from real failed runs. Name the DOMINANT failure mode (the single mechanism behind the',\n ' largest share of failures) in one sentence. Attack that first; leave long-tail noise until',\n ' the dominant mode is closed. A fix aimed at the wrong mechanism measures zero however clean',\n ' the code is.',\n '2. STATE A HYPOTHESIS WITH A PREDICTED LIFT. Before designing, write down: \"failures like X',\n ' happen because MECHANISM; this change interrupts that mechanism; I predict it addresses',\n ' roughly N of the M findings shown.\" A change you cannot connect to a mechanism is a guess,',\n ' not an experiment.',\n '3. DECOMPOSE INTO SUB-GOALS. Break the work into steps that are each independently checkable',\n ' (it compiles, a test passes, the server answers). Sequence them so the riskiest assumption',\n ' is tested first — if the hypothesis is wrong, find out on step 1, not step 5.',\n '4. DESIGN TO ISOLATE THE MECHANISM. Make the smallest COHERENT change that fully tests the',\n ' hypothesis: small enough that a measured lift is attributable to this change alone, complete',\n ' enough that it actually fires on the real execution path (a lever that exists but never',\n ' fires measures zero). No drive-by refactors, no unrelated cleanup, no speculative scope —',\n ' anything changed alongside confounds the measurement.',\n '5. GENERALIZE, NEVER MEMORIZE. Fix the failure CLASS, not the shown instances: encode rules and',\n ' logic that transfer to unseen tasks. A patch memorized to the quoted examples will not',\n ' survive the held-out measurement — that is overfitting, and the gate will catch it.',\n '6. PRESERVE WHAT WORKS. The baseline already passes tasks; do not delete or weaken the behavior',\n ' those passes depend on. A fix that trades one failure class for a new one measures as noise.',\n '7. VERIFY FOR REAL, THEN REFLECT. Run the verification you were given and make it genuinely',\n ' pass — never weaken a check, stub the thing it exercises, or special-case its inputs; a',\n ' gamed check delivers nothing because promotion is decided by a separate measurement you',\n ' never see. Then record briefly: what you predicted, what the verifier actually showed, and',\n ' what you would try next if the measured lift comes back null.',\n].join('\\n')\n\n/**\n * The senior authoring process for `authorStrategy` — the same method, shaped\n * to the strategy contract (author-blind, conserved budget, one module out).\n */\nexport const strategyAuthorMethod = [\n 'Work as a senior researcher, in this order:',\n '1. DIAGNOSE: read the per-task losses above and name the DOMINANT failure mode in one sentence',\n ' — the single mechanism behind the largest share of lost score (e.g. first attempts near-miss',\n ' and never get corrected; fresh retries discard progress; one persona plateaus).',\n '2. HYPOTHESIS + PREDICTED LIFT: state \"these losses happen because MECHANISM; the composition',\n ' below interrupts it; I predict roughly +N on this environment at the same budget.\"',\n '3. DESIGN TO ISOLATE THE MECHANISM: change ONE coordination mechanism relative to the baselines',\n ' (carry vs fresh, where the critique lands, a persona split, a tool restriction) so any',\n ' measured lift is attributable to it. Do not stack three clever ideas — a tangled win teaches',\n ' nothing and a tangled loss cannot be debugged.',\n '4. DECOMPOSE THE BUDGET: plan how the shots divide across explore / attempt / critique / repair',\n ' before writing code, and spend the whole budget — an early stop on a mid score is a loss.',\n '5. GENERALIZE: the strategy runs on unseen tasks from this environment. Read tools via',\n ' listTools(handle), never hardcode task specifics from the losses shown.',\n '6. PREDICT, THEN REFLECT: put the hypothesis, the mechanism, and the predicted lift in a',\n ' comment at the top of the module — the holdout verdict will be read against it.',\n].join('\\n')\n","import type {\n ChatClient,\n ChatRequest,\n ChatResponse,\n CostReceiptInput,\n CustomTokenPricing,\n} from '@tangle-network/agent-eval'\nimport { costForTokenPricing } from '@tangle-network/agent-eval'\nimport type {\n ExternalOptimizerModelCall,\n ExternalOptimizerModelCallRequest,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { observedModelMatchesDeclared } from './model-identity'\nimport { type CollectedAgentTurn, collectAgentTurn, streamAgentTurn } from './stream-agent-turn'\nimport { executableAgentProfileSnapshot } from './supervise/executable-spec'\nimport {\n concreteModelId,\n enforceTokenLimits,\n type ProfileModelExecutionSettings,\n profileModelExecutionSettings,\n} from './supervise/model-policy'\nimport {\n captureReusableExecutorConfig,\n createExecutor,\n type ExecutorConfig,\n} from './supervise/runtime'\n\n/** Profile-exact adapter for packages that consume agent-eval's ChatClient contract.\n * Every call still enters Runtime through createExecutor -> streamAgentTurn, and every\n * behavioral field is checked against the exact AgentProfile before any transport runs. */\nexport function profileChatClient(args: {\n profile: AgentProfile\n executor: ExecutorConfig\n context: string\n}): ChatClient {\n const binding = bindProfileChat(args)\n\n return {\n transport: 'custom',\n defaultModel: binding.model,\n ...(binding.settings.retry?.maxAttempts !== undefined\n ? { maximumAttempts: binding.settings.retry.maxAttempts }\n : {}),\n async chat(req, callOpts) {\n const run = await runBoundProfileChat(binding, req, callOpts)\n if (!run.succeeded) throw new Error(run.error)\n return run.response\n },\n }\n}\n\n/** Profile-exact adapter for agent-eval's external optimizer callback.\n * Eval validates and freezes the provider-neutral request; Runtime owns the exact\n * AgentProfile, execution route, retries, usage, and finite execution evidence. */\nexport function profileOptimizerModelCall(args: {\n profile: AgentProfile\n executor: ExecutorConfig\n context: string\n pricing?: CustomTokenPricing\n}): ExternalOptimizerModelCall {\n const binding = bindProfileChat(args)\n const profileDigest = canonicalAgentProfileDigest(binding.profile)\n\n return async (request) => {\n const requestDigest = canonicalCandidateDigest({\n callId: request.callId,\n request: request.request,\n endpointFormat: request.endpointFormat ?? null,\n })\n let run: ProfileChatRun\n try {\n run = await runBoundProfileChat(binding, structuredClone(request.request) as ChatRequest, {\n signal: request.signal,\n idempotencyKey: request.callId,\n correlationId: request.callId,\n })\n } catch (error) {\n return {\n succeeded: false,\n error: errorMessage(error),\n receipt: unknownOptimizerReceipt(binding.model),\n execution: {\n kind: 'agent-runtime-profile-model-call',\n profileDigest,\n requestDigest,\n callId: request.callId,\n endpointFormat: request.endpointFormat ?? null,\n executed: false,\n error: errorMessage(error),\n },\n }\n }\n const execution = optimizerExecution(profileDigest, requestDigest, request, run)\n const receiptModel = optimizerReceiptModel(binding.model, run)\n try {\n const receipt = optimizerReceipt(receiptModel, run, args.pricing)\n return run.succeeded\n ? {\n succeeded: true,\n response: { ...run.response, costUsd: optimizerResponseCostUsd(receipt) },\n receipt,\n execution,\n }\n : { succeeded: false, error: run.error, receipt, execution }\n } catch (error) {\n const message = `profile optimizer receipt normalization failed after execution: ${errorMessage(error)}`\n return {\n succeeded: false,\n error: message,\n receipt: rawOptimizerReceipt(receiptModel, run, args.pricing),\n execution: {\n ...execution,\n succeeded: false,\n postCallError: message,\n },\n }\n }\n }\n}\n\ninterface BoundProfileChat {\n readonly profile: AgentProfile\n readonly executor: ExecutorConfig\n readonly context: string\n readonly model: string\n readonly settings: ProfileModelExecutionSettings\n}\n\nexport type ProfileChatRun =\n | { readonly succeeded: true; readonly response: ChatResponse; readonly turn: CollectedAgentTurn }\n | { readonly succeeded: false; readonly error: string; readonly turn: CollectedAgentTurn }\n\nexport function bindProfileChat(args: {\n profile: AgentProfile\n executor: ExecutorConfig\n context: string\n}): BoundProfileChat {\n const profile = executableAgentProfileSnapshot(args.profile, args.context)\n const model = concreteModelId(profile.model?.default)\n if (!model) throw new Error(`${args.context}: AgentProfile.model.default must be concrete`)\n return {\n profile,\n executor: captureReusableExecutorConfig(args.executor, args.context),\n context: args.context,\n model,\n settings: profileModelExecutionSettings(profile, args.context),\n }\n}\n\nexport async function runBoundProfileChat(\n binding: BoundProfileChat,\n req: ChatRequest,\n callOpts?: Parameters<ChatClient['chat']>[1],\n): Promise<ProfileChatRun> {\n assertProfileChatRequest(\n req,\n binding.model,\n binding.profile.model?.reasoningEffort,\n binding.settings,\n binding.context,\n )\n assertSupportedChatCallOptions(callOpts, binding.context)\n const executor = toolCarryingExecutor(binding, req)\n const turnProfile = responseProfile(binding.profile, req, binding.context)\n const startedAt = performance.now()\n const turn = await collectAgentTurn(\n streamAgentTurn(\n {\n kind: 'executor',\n profile: turnProfile,\n factory: createExecutor(executor),\n },\n {\n providerOptions: {\n messages: req.messages,\n },\n },\n {\n ...(req.timeoutMs !== undefined ? { timeoutMs: req.timeoutMs } : {}),\n ...(callOpts?.signal ? { signal: callOpts.signal } : {}),\n ...(callOpts?.idempotencyKey ? { callId: callOpts.idempotencyKey } : {}),\n ...(callOpts?.correlationId ? { correlationId: callOpts.correlationId } : {}),\n },\n ),\n )\n if (turn.status !== 'completed') {\n return {\n succeeded: false,\n error: `${binding.context} failed: ${turn.error?.message ?? turn.status}`,\n turn,\n }\n }\n const observedModel = turn.usage.model\n if (observedModel === undefined) {\n return {\n succeeded: false,\n error: `${binding.context}: Runtime turn did not report the model actually used; refusing to label the response with the requested model`,\n turn,\n }\n }\n if (!observedModelMatchesDeclared(observedModel, binding.model)) {\n return {\n succeeded: false,\n error: `${binding.context}: Runtime reported model ${JSON.stringify(observedModel)} but AgentProfile requires ${JSON.stringify(binding.model)}`,\n turn,\n }\n }\n const resultOut = turn.output as\n | {\n finishReason?: string\n system_fingerprint?: unknown\n toolCalls?: ReadonlyArray<{ id: string; name: string; arguments: string }>\n }\n | undefined\n const toolCalls = (resultOut?.toolCalls ?? []).map((call) => ({\n id: call.id,\n name: call.name,\n argumentsJson: call.arguments,\n }))\n const promptTokens = turn.usage.input\n const completionTokens = turn.usage.output\n return {\n succeeded: true,\n turn,\n response: {\n content: turn.finalText,\n usage: {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n ...(turn.usage.tokensKnown === false ? { captured: false } : {}),\n ...(typeof turn.usage.promptCache?.readTokens === 'number'\n ? { cachedPromptTokens: turn.usage.promptCache.readTokens }\n : {}),\n ...(turn.usage.reasoningTokens !== undefined\n ? { reasoningTokens: turn.usage.reasoningTokens }\n : {}),\n },\n // ChatResponse.costUsd is provider-billed spend only. Runtime keeps catalog estimates in\n // `raw.estimatedCostUsd` and marks the billed channel unknown when no receipt arrived.\n costUsd:\n turn.usage.usdKnown === false || turn.usage.costUsd === undefined\n ? null\n : turn.usage.costUsd,\n model: observedModel,\n durationMs: terminalDurationMs(turn.events, performance.now() - startedAt),\n // The OpenAI wire spells a tool stop `tool_calls`; the canonical vocabulary spells it\n // `tool_use`. Normalizing here keeps one stop cause across transports.\n finishReason:\n resultOut?.finishReason === 'tool_calls' ? 'tool_use' : (resultOut?.finishReason ?? null),\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n contentEmpty: turn.finalText.trim().length === 0,\n raw: {\n ...(turn.usage.estimatedCostUsd !== undefined\n ? { estimatedCostUsd: turn.usage.estimatedCostUsd }\n : {}),\n ...(turn.usage.promptCache ? { promptCache: turn.usage.promptCache } : {}),\n ...(turn.transportAttempts !== undefined\n ? { transportAttempts: turn.transportAttempts }\n : {}),\n ...(typeof resultOut?.system_fingerprint === 'string'\n ? { systemFingerprint: resultOut.system_fingerprint }\n : {}),\n },\n },\n }\n}\n\n/** @internal Exported for the adapter's fail-honest duration contract test. */\nexport function terminalDurationMs(\n events: ReadonlyArray<{ type: string; metadata?: Record<string, unknown> }>,\n measuredWallMs: number,\n): number {\n const final = events.at(-1)?.metadata?.timing\n if (final && typeof final === 'object') {\n const duration = (final as Record<string, unknown>).durationMs\n if (typeof duration === 'number' && Number.isFinite(duration) && duration >= 0) return duration\n }\n if (Number.isFinite(measuredWallMs) && measuredWallMs >= 0) return measuredWallMs\n throw new Error('profileChatClient: measured wall duration must be a finite non-negative number')\n}\n\n/**\n * The executor one call runs on, carrying that call's tools.\n *\n * A request's `tools` reach the wire only through the router seam, so a backend without that seam\n * cannot pass them and is REFUSED by name here, before any transport runs. Answering a\n * tool-carrying request without its tools is contaminated evidence, exactly like a model\n * substitution: the caller reads a tool-free answer and cannot tell it apart from a model that\n * chose not to call one.\n *\n * `toolChoice` has no per-call channel at all — `routerInlineExecutor` reads it from\n * `AgentProfile.model.metadata.toolChoice` — so a request may restate the profile's policy and\n * never change it. The error names both sides, because declaring it on the profile is the fix.\n */\nfunction toolCarryingExecutor(binding: BoundProfileChat, req: ChatRequest): ExecutorConfig {\n const tools = req.tools ?? []\n if (req.toolChoice !== undefined) {\n if (tools.length === 0) {\n throw new Error(\n `${binding.context}: request sets toolChoice with no tools; tool choice is meaningful only with tools`,\n )\n }\n if (typeof req.toolChoice !== 'string') {\n throw new Error(\n `${binding.context}: request toolChoice names one function; Runtime's router turn expresses only auto, required, or none`,\n )\n }\n if (req.toolChoice !== binding.settings.toolChoice) {\n throw new Error(\n `${binding.context}: request toolChoice ${JSON.stringify(req.toolChoice)} conflicts with AgentProfile.model.metadata.toolChoice ${JSON.stringify(binding.settings.toolChoice ?? null)}`,\n )\n }\n }\n if (tools.length === 0) return binding.executor\n if (binding.executor.backend !== 'router') {\n throw new Error(\n `${binding.context}: backend ${JSON.stringify(binding.executor.backend)} cannot pass tools through; refusing a tool-carrying request rather than answering without its tools`,\n )\n }\n const declared = binding.executor.tools\n if (declared !== undefined && JSON.stringify(declared) !== JSON.stringify(tools)) {\n throw new Error(\n `${binding.context}: request tools conflict with the tools already declared on the executor config`,\n )\n }\n return captureReusableExecutorConfig({ ...binding.executor, tools }, binding.context)\n}\n\nfunction assertSupportedChatCallOptions(\n opts: Parameters<ChatClient['chat']>[1],\n context: string,\n): void {\n if (opts?.maxCostUsd !== undefined) {\n throw new Error(\n `${context}: maxCostUsd is not enforced by Runtime's exact turn path; refusing to treat it as a limit`,\n )\n }\n}\n\nfunction responseProfile(profile: AgentProfile, req: ChatRequest, context: string): AgentProfile {\n const responseFormat = req.jsonSchema\n ? { type: 'json_schema', json_schema: req.jsonSchema }\n : req.jsonMode\n ? { type: 'json_object' }\n : undefined\n if (!responseFormat) return profile\n const existing = profile.model?.metadata?.extraBody\n if (\n existing !== undefined &&\n (typeof existing !== 'object' || existing === null || Array.isArray(existing))\n ) {\n throw new Error(`${context}: AgentProfile.model.metadata.extraBody must be an object`)\n }\n const existingFormat = (existing as Record<string, unknown> | undefined)?.response_format\n if (\n existingFormat !== undefined &&\n JSON.stringify(existingFormat) !== JSON.stringify(responseFormat)\n ) {\n throw new Error(`${context}: requested response format conflicts with AgentProfile`)\n }\n return agentProfileSchema.parse({\n ...profile,\n model: {\n ...profile.model,\n metadata: {\n ...(profile.model?.metadata ?? {}),\n extraBody: {\n ...(existing as Record<string, unknown> | undefined),\n response_format: responseFormat,\n },\n },\n },\n })\n}\n\nfunction assertProfileChatRequest(\n req: ChatRequest,\n model: string,\n reasoningEffort: NonNullable<AgentProfile['model']>['reasoningEffort'],\n settings: ProfileModelExecutionSettings,\n context: string,\n): void {\n if (req.model !== undefined && req.model !== model) {\n throw new Error(\n `${context}: request model ${JSON.stringify(req.model)} conflicts with AgentProfile model ${JSON.stringify(model)}`,\n )\n }\n if (req.temperature !== undefined && req.temperature !== settings.temperature) {\n throw new Error(`${context}: request temperature conflicts with AgentProfile model metadata`)\n }\n if (req.maxTokens !== undefined) {\n // Eval callers may restate the profile's ceiling, never widen or narrow it. The comparison is\n // against the visible ceiling the router path actually sends as `max_tokens`.\n const applied = enforceTokenLimits(settings.tokenLimits, 'router', context).applied\n if (req.maxTokens !== applied.maxTokens) {\n throw new Error(\n `${context}: request maxTokens ${req.maxTokens} conflicts with AgentProfile.model.maxVisibleOutputTokens ${applied.maxTokens ?? 'unset'}`,\n )\n }\n }\n if (req.thinking !== undefined) {\n const expected =\n reasoningEffort === undefined\n ? undefined\n : reasoningEffort === 'none'\n ? 'disabled'\n : 'enabled'\n if (req.thinking !== expected) {\n throw new Error(\n `${context}: request thinking conflicts with AgentProfile.model.reasoningEffort`,\n )\n }\n }\n}\n\n/**\n * Which dollar fact a receipt carries, in the one order that never presents an estimate as a\n * measurement: a provider receipt, else this runtime's own estimate, else the catalog rate the\n * caller supplied, else an explicit refusal to state a cost.\n *\n * `pricing` is deliberately withheld on the unknown-usage path. A per-token rate applied to the\n * zero token counts that path reports would produce a fabricated `$0`, which is the one thing\n * `costUnknown` exists to prevent.\n */\nfunction costAttribution(\n usage: ProfileChatRun['turn']['usage'],\n pricing: CustomTokenPricing | undefined,\n): Pick<\n CostReceiptInput,\n 'actualCostUsd' | 'estimatedCostUsd' | 'customTokenPricing' | 'costUnknown'\n> {\n const actualCostUsd = usage.usdKnown === false ? undefined : usage.costUsd\n if (actualCostUsd !== undefined) return { actualCostUsd }\n if (usage.estimatedCostUsd !== undefined) return { estimatedCostUsd: usage.estimatedCostUsd }\n if (pricing) return { customTokenPricing: pricing }\n return { costUnknown: true }\n}\n\nfunction optimizerReceipt(\n model: string,\n run: ProfileChatRun,\n pricing: CustomTokenPricing | undefined,\n): CostReceiptInput {\n const usage = run.turn.usage\n if (usage.tokensKnown === false) {\n return {\n // The receipt model is the served identity when Runtime observed one. Eval and the response\n // must carry the same identity, while this branch still preserves unknown token usage.\n model,\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n ...costAttribution(usage, undefined),\n }\n }\n const cachedTokens = optimizerTokenCount(usage.promptCache?.readTokens, 'cache read tokens')\n const cacheWriteTokens = optimizerTokenCount(usage.promptCache?.writeTokens, 'cache write tokens')\n const inputTokens = usage.input - (cachedTokens ?? 0)\n if (inputTokens < 0) {\n throw new Error('profile optimizer cache reads exceed total input tokens')\n }\n // A cache write annotates fresh input. It is not a third, disjoint prompt-token class.\n if ((cacheWriteTokens ?? 0) > inputTokens) {\n throw new Error('profile optimizer cache writes exceed non-cached input tokens')\n }\n return {\n model,\n inputTokens,\n outputTokens: usage.output,\n ...(cachedTokens !== undefined ? { cachedTokens } : {}),\n ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...costAttribution(usage, pricing),\n }\n}\n\n/** Preserve the observed call totals when finer receipt classification is inconsistent. */\nfunction rawOptimizerReceipt(\n model: string,\n run: ProfileChatRun,\n pricing: CustomTokenPricing | undefined,\n): CostReceiptInput {\n const usage = run.turn.usage\n const tokensKnown = usage.tokensKnown !== false\n return {\n model,\n inputTokens: tokensKnown ? usage.input : 0,\n outputTokens: tokensKnown ? usage.output : 0,\n ...(tokensKnown ? {} : { usageUnknown: true }),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...costAttribution(usage, pricing),\n }\n}\n\nfunction optimizerReceiptModel(model: string, run: ProfileChatRun): string {\n const observedModel = run.succeeded ? run.response.model : run.turn.usage.model\n return observedModel !== undefined && observedModelMatchesDeclared(observedModel, model)\n ? observedModel\n : model\n}\n\nfunction optimizerExecution(\n profileDigest: string,\n requestDigest: string,\n request: ExternalOptimizerModelCallRequest,\n run: ProfileChatRun,\n): Record<string, unknown> {\n return {\n kind: 'agent-runtime-profile-model-call',\n profileDigest,\n requestDigest,\n callId: request.callId,\n endpointFormat: request.endpointFormat ?? null,\n executed: true,\n succeeded: run.succeeded,\n status: run.turn.status,\n model: run.turn.usage.model ?? null,\n transportAttempts: run.turn.transportAttempts ?? null,\n eventTypes: run.turn.events.map((event) => event.type),\n }\n}\n\nfunction unknownOptimizerReceipt(model: string): CostReceiptInput {\n return {\n model,\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n costUnknown: true,\n }\n}\n\nfunction optimizerResponseCostUsd(receipt: CostReceiptInput): number | null {\n if (receipt.actualCostUsd !== undefined) return receipt.actualCostUsd\n if (receipt.estimatedCostUsd !== undefined) return receipt.estimatedCostUsd\n if (receipt.customTokenPricing !== undefined && receipt.usageUnknown !== true) {\n return costForTokenPricing(receipt.customTokenPricing, receipt)\n }\n return null\n}\n\nfunction optimizerTokenCount(value: unknown, label: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new Error(`profile optimizer ${label} must be a non-negative integer`)\n }\n return value as number\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\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 production observations (`proposal_origin:'production'`) and\n * never come from final evaluation (`derived_from_judge:false`). 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 {\n type AnalystFinding,\n makeProposalFinding,\n type ProposalFinding,\n} from '@tangle-network/agent-eval'\nimport { assertProposalFindings } from '@tangle-network/agent-eval/analyst'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { Corpus, CorpusRecord } from './personify/wave-types'\nimport { profileChatClient } from './profile-chat-client'\nimport type { ExecutorConfig } from './supervise/runtime'\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 /** Exact analyst identity. */\n profile: AgentProfile\n /** Execution substrate. All behavior comes from the profile. */\n executor: ExecutorConfig\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}\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: ProposalFinding[]\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 /** Measured model usage for this analysis turn. */\n usage: { input: number; output: number; known: boolean }\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\n/** The third-person trace analyst: read a worker's trace and produce steer findings for the next attempt plus durable `learned` facts for the cross-run corpus. */\nexport async function observe(input: ObserveInput, opts: ObserveOptions): Promise<Observation> {\n const traceSummary = summarizeTrace(input.trace, opts.maxTraceLines ?? 80)\n const res = await profileChatClient({\n profile: opts.profile,\n executor: opts.executor,\n context: 'observe analyst',\n }).chat(\n {\n jsonSchema: findingsSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\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 = assertProposalFindings(\n parsed.map((f) =>\n makeProposalFinding({\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 a final evaluation result.\n derived_from_judge: false,\n proposal_origin: 'production',\n metadata: { audience: f.audience },\n ...(input.runId ? { subject: input.runId } : {}),\n }),\n ),\n 'observe findings',\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 const usage = res.usage\n const inputTokens = usage?.promptTokens\n const outputTokens = usage?.completionTokens\n return {\n findings: [...findings],\n learned,\n report: renderReport(findings),\n usage: {\n input: inputTokens ?? 0,\n output: outputTokens ?? 0,\n known:\n usage?.captured !== false &&\n typeof inputTokens === 'number' &&\n typeof outputTokens === 'number',\n },\n }\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 * 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 type { ChatClient } from '@tangle-network/agent-eval'\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\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 { profileChatClient } from './profile-chat-client'\nimport { collectAgentTurn, streamAgentTurn } from './stream-agent-turn'\nimport { withDriverExecutor } from './supervise/driver-executor'\nimport {\n assertExecutableAgentProfile,\n concreteModelId,\n profileModelExecutionSettings,\n} from './supervise/model-policy'\nimport { createExecutor } from './supervise/runtime'\nimport { createSupervisor } from './supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n ExecutorToolCall,\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 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 /** Exact worker identity. Model and standing instructions are read only from this profile. */\n workerProfile: AgentProfile\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 /** Exact critic identity. Omitted means the exact worker profile also runs the critic. */\n analystProfile?: AgentProfile\n /** Across-run learning: when set, the analyst's observe() pass appends trace-derived\n * facts here (the flywheel write side). Read-back is opt-in via `corpusReadback`\n * because unconditional priming can pollute context on some domains. */\n corpus?: Corpus\n /** Tags written onto learned facts (and used by the caller's priming query). */\n corpusTags?: string[]\n /** In-context learning: when set, query `corpus` before each depth shot and inject\n * the top trace-derived facts as guidance for the active run. No corpus means no read-back. */\n corpusReadback?: CorpusReadbackOptions\n}\n\nexport interface CorpusReadbackOptions {\n /** Minimum confidence for a fact to be injected. Default 0.7. */\n minConfidence?: number\n /** Extra tags a fact must carry, in addition to `corpusTags`. */\n tags?: ReadonlyArray<string>\n /** Max facts injected per shot. Default 3. */\n maxFacts?: number\n /** Default false: only facts tagged `audience:agent` are injected into the worker. */\n includeOperatorFacts?: boolean\n}\n\n// ── The unit: one agentic shot (a bounded tool loop) over a handle ───────────────\n\n/** One provider-neutral conversation record carried between strategy shots. */\nexport type StrategyMessage = 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?: StrategyMessage[] // carried conversation (depth); fresh when absent\n steer?: string // analyst-derived steer injected before this shot (depth)\n profile?: AgentProfile // exact role/model override for this shot\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: StrategyMessage[]\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 /** False when any Router turn omitted usage. */\n tokensKnown?: false\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\nfunction exactAgenticProfile(profile: AgentProfile, context: string): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) throw new Error(`${context}: invalid AgentProfile: ${parsed.error.message}`)\n return parsed.data\n}\n\nfunction requiredProfileModel(profile: AgentProfile, context: string): string {\n assertExecutableAgentProfile(profile, context)\n const model = concreteModelId(profile.model?.default)\n if (!model) {\n throw new Error(\n `${context}: AgentProfile.model.default must name the exact provider model; runtime-selected and missing models are not executable`,\n )\n }\n return model\n}\n\nfunction profileSystemPrompt(profile: AgentProfile): string {\n const sections = [profile.prompt?.systemPrompt, ...(profile.prompt?.instructions ?? [])].filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n const instructions = profile.resources?.instructions\n if (typeof instructions === 'string' && instructions.trim()) sections.push(instructions)\n else if (\n instructions &&\n typeof instructions === 'object' &&\n instructions.kind === 'inline' &&\n instructions.content.trim()\n ) {\n sections.push(instructions.content)\n } else if (instructions && typeof instructions === 'object' && instructions.kind === 'github') {\n throw new Error(\n 'agentic profile: github resource instructions require a workspace materializer; use inline instructions for the direct Router worker',\n )\n }\n return sections.join('\\n\\n')\n}\n\nfunction assertProfileTools(\n profile: AgentProfile,\n tools: ReadonlyArray<AgenticTool>,\n context: string,\n): void {\n const supplied = new Set(tools.map((tool) => tool.function.name))\n const declared = profile.tools ?? {}\n for (const name of supplied) {\n if (declared[name] !== true) {\n throw new Error(\n `${context}: tool ${JSON.stringify(name)} is not enabled by AgentProfile.tools`,\n )\n }\n }\n for (const [name, enabled] of Object.entries(declared)) {\n if (enabled && !supplied.has(name)) {\n throw new Error(\n `${context}: AgentProfile enables tool ${JSON.stringify(name)} but the surface did not supply it`,\n )\n }\n }\n}\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: StrategyMessage[],\n opts: AgenticOptions,\n profileOverride?: AgentProfile,\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 profile = exactAgenticProfile(profileOverride ?? opts.workerProfile, 'agentic shot')\n requiredProfileModel(profile, 'agentic shot')\n profileModelExecutionSettings(profile, 'agentic shot')\n assertProfileTools(profile, tools, 'agentic shot')\n const factory = createExecutor({\n backend: 'router-tools',\n routerBaseUrl: opts.routerBaseUrl,\n routerKey: opts.routerKey,\n tools,\n executeToolCall: execute,\n ...(opts.complete ? { complete: opts.complete } : {}),\n })\n const turn = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', profile, factory },\n {\n providerOptions: {\n messages,\n },\n },\n ),\n )\n if (turn.status !== 'completed') {\n throw new Error(`agentic shot failed: ${turn.error?.message ?? turn.status}`)\n }\n const out = turn.output as\n | { messages?: StrategyMessage[]; turns?: number; toolCalls?: ExecutorToolCall[] }\n | undefined\n return {\n messages: out?.messages ?? messages,\n completions: out?.turns ?? 0,\n toolCalls: out?.toolCalls?.length ?? 0,\n toolErrors,\n tokens: { input: turn.usage.input, output: turn.usage.output },\n ...(turn.usage.tokensKnown === false ? { tokensKnown: false } : {}),\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 /** False when any analyst call omitted usage. */\n tokensKnown?: false\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: StrategyMessage[]): 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(opts: AgenticOptions, profile: AgentProfile): ChatClient {\n return profileChatClient({\n profile,\n context: 'agentic analyst',\n executor: {\n backend: 'router',\n routerBaseUrl: opts.routerBaseUrl,\n routerKey: opts.routerKey,\n ...(opts.complete ? { complete: opts.complete } : {}),\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: StrategyMessage[],\n instruction: string,\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystProfile = exactAgenticProfile(\n opts.analystProfile ?? opts.workerProfile,\n 'agentic analyst',\n )\n const analystModel = requiredProfileModel(analystProfile, 'agentic analyst')\n const chat = analystChat(opts, analystProfile)\n // The profile owns the standing system instruction. This strategy-authored question is task\n // input, so it stays in the user turn even when a trajectory is present.\n const consultMessages = [\n {\n role: 'user' as const,\n content: trajectory\n ? `${instruction}\\n\\nTASK: ${task.userPrompt.slice(0, 1500)}\\n\\nTRAJECTORY:\\n${trajectory}`\n : `${instruction}\\n\\nTASK:\\n${task.userPrompt.slice(0, 1500)}`,\n },\n ]\n const res = await chat.chat({\n model: analystModel,\n messages: consultMessages,\n })\n const usage = (\n res as {\n usage?: {\n promptTokens?: number\n prompt_tokens?: number\n completionTokens?: number\n completion_tokens?: number\n captured?: boolean\n }\n }\n ).usage\n const input = usage?.promptTokens ?? usage?.prompt_tokens\n const output = usage?.completionTokens ?? usage?.completion_tokens\n const tokensKnown =\n usage?.captured !== false && typeof input === 'number' && typeof output === 'number'\n return {\n steer: res.content.trim(),\n tokens: {\n input: input ?? 0,\n output: output ?? 0,\n },\n ...(tokensKnown ? {} : { tokensKnown: false }),\n }\n}\n\nasync function analyze(\n task: AgenticTask,\n messages: StrategyMessage[],\n opts: AgenticOptions,\n): Promise<AnalyzeOut> {\n const trajectory = compactTrajectory(messages)\n const analystProfile = exactAgenticProfile(\n opts.analystProfile ?? opts.workerProfile,\n 'agentic analyst',\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 profile: analystProfile,\n executor: {\n backend: 'router',\n routerBaseUrl: opts.routerBaseUrl,\n routerKey: opts.routerKey,\n ...(opts.complete ? { complete: opts.complete } : {}),\n },\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 {\n steer: steer || 'COMPLETE',\n tokens: { input: obs.usage.input, output: obs.usage.output },\n ...(obs.usage.known ? {} : { tokensKnown: false }),\n }\n}\n\nasync function renderCorpusReadback(opts: AgenticOptions): Promise<string> {\n if (!opts.corpus || !opts.corpusReadback) return ''\n const maxFacts = opts.corpusReadback.maxFacts ?? 3\n if (!Number.isInteger(maxFacts) || maxFacts < 0) {\n throw new Error(`corpusReadback.maxFacts must be a non-negative integer, got ${maxFacts}`)\n }\n if (maxFacts === 0) return ''\n\n const tags = [\n ...(opts.corpusTags ?? []),\n ...(opts.corpusReadback.tags ?? []),\n ...(opts.corpusReadback.includeOperatorFacts ? [] : ['audience:agent']),\n ]\n const facts = await opts.corpus.query({\n ...(tags.length > 0 ? { tags } : {}),\n minConfidence: opts.corpusReadback.minConfidence ?? 0.7,\n limit: maxFacts,\n })\n if (facts.length === 0) return ''\n\n const rendered = facts.map((fact) =>\n fact.rationale ? `- ${fact.claim} (${fact.rationale})` : `- ${fact.claim}`,\n )\n return `Relevant learned facts from prior attempts:\\n${rendered.join('\\n')}`\n}\n\n// ── Leaf executors (one shot / one analyst), resolved per-spawn from the surface ──\n\n/** Measured result of one strategy shot. */\nexport interface StrategyShotResult {\n messages: StrategyMessage[]\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 profile = exactAgenticProfile(t.profile ?? opts.workerProfile, 'agentic shot')\n const systemPrompt = profileSystemPrompt(profile)\n const messages: StrategyMessage[] = t.messages?.length\n ? [...t.messages]\n : [\n ...(systemPrompt ? [{ role: 'system', content: systemPrompt }] : []),\n { role: 'user', content: `${t.task.userPrompt}\\n\\n${taskNudge}` },\n ]\n // On a CARRIED conversation, a profile switch arrives as a role hand-off message.\n if (t.messages?.length && t.profile && systemPrompt) {\n messages.push({\n role: 'user',\n content: `[hand-off] You are now acting as: ${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, profile)\n const s = await surface.score(t.task, handle)\n const score = s.total > 0 ? s.passes / s.total : 0\n const out: StrategyShotResult = {\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 ...(shot.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: 0,\n usdKnown: false,\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: StrategyMessage[]; rawInstruction?: string }\n const { steer, tokens, tokensKnown } = t.rawInstruction\n ? await consultAnalyst(t.task, t.messages, t.rawInstruction, opts)\n : await analyze(t.task, t.messages, opts)\n artifact = {\n outRef: `analyst:${steer.length}`,\n out: steer,\n spent: {\n iterations: 1,\n tokens,\n ...(tokensKnown === false ? { tokensKnown: false } : {}),\n usd: 0,\n usdKnown: false,\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(\n name: string,\n role: 'shot' | 'analyst',\n profile: AgentProfile,\n): Agent<unknown, Outcome<unknown>> {\n const exactProfile = exactAgenticProfile(profile, `agentic ${role}`)\n const agent = {\n name,\n executorSpec: {\n profile: {\n ...exactProfile,\n name,\n metadata: { ...exactProfile.metadata, role },\n },\n harness: null,\n } 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 /** Observed billed subtotal. `usdKnown:false` means it is incomplete, never a measured zero. */\n usd: number\n usdKnown: boolean\n ms: number\n tokens: { input: number; output: number }\n tokensKnown: boolean\n}\n\nconst UNBOUNDED_TURN_RESERVATION = 1_000_000_000\n\nfunction profileTurnLimit(profile: AgentProfile, context: string): number {\n return profileModelExecutionSettings(profile, context).maxTurns ?? 0\n}\n\nconst perChild = (maxTurns: number): Budget => ({\n maxIterations: maxTurns === 0 ? UNBOUNDED_TURN_RESERVATION : maxTurns + 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 = profileTurnLimit(opts.workerProfile, 'depth worker')\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: StrategyMessage[] | 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', opts.workerProfile)\n const memorySteer = await renderCorpusReadback(opts)\n const steer = [shots === 0 ? undefined : pendingSteer, memorySteer]\n .filter((part): part is string => typeof part === 'string' && part.trim().length > 0)\n .join('\\n\\n')\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 StrategyShotResult\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(\n `analyst:${shots}`,\n 'analyst',\n opts.analystProfile ?? opts.workerProfile,\n )\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 = profileTurnLimit(opts.workerProfile, 'breadth worker')\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(\n leaf(`rollout:${k}`, 'shot', opts.workerProfile),\n { task } as ShotTask,\n {\n budget: perChild(innerTurns),\n label: `rollout:${k}`,\n },\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 StrategyShotResult\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 */\ndeclare const strategyResult: unique symbol\n\nexport interface Strategy<Result extends StrategyResult = StrategyResult> {\n readonly name: string\n /** @internal Associates a strategy with its typed result without adding a runtime field. */\n readonly [strategyResult]?: Result\n driver(\n surface: AgenticSurface,\n task: AgenticTask,\n opts: AgenticOptions,\n budget: number,\n ): Agent<unknown, Outcome<unknown>>\n}\n\n/** Built-in `Strategy`: K independent attempts, keep the best-verifying (best-of-N / resample). */\nexport const sample: Strategy = {\n name: 'sample',\n driver: (surface, task, opts, budget) => breadthStrategy(surface, task, opts, { width: budget }),\n}\n/** Built-in `Strategy`: attempt → `observe()` reads the trace → steer the next attempt → repeat (deepen one lineage). */\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\nexport interface ShotSpec {\n /** present ⇒ continue this artifact (depth); absent ⇒ the shot opens a fresh one (sample/restart). */\n handle?: ArtifactHandle\n messages?: StrategyMessage[]\n steer?: string\n /** Exact profile for this shot. Omitted means `AgenticOptions.workerProfile`. */\n profile?: AgentProfile\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 StrategyShotResult (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<StrategyShotResult | null>\n /** The firewalled critic reads the trajectory → a steer string, or null on COMPLETE/down. */\n critique(messages: StrategyMessage[]): 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: StrategyMessage[], 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<Result extends StrategyResult>(\n name: string,\n run: (ctx: StrategyCtx) => Promise<Result>,\n): Strategy<Result> {\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 // 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 profile = spec?.profile ?? opts.workerProfile\n const innerTurns = profileTurnLimit(profile, 'authored strategy shot')\n const child = leaf(`shot:${seq}`, 'shot', profile)\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 profile,\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 StrategyShotResult\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(\n `analyst:${seq}`,\n 'analyst',\n opts.analystProfile ?? opts.workerProfile,\n )\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(\n `analyst:${seq}`,\n 'analyst',\n opts.analystProfile ?? opts.workerProfile,\n )\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: StrategyMessage[] | 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: StrategyShotResult } | 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<Result extends StrategyResult = StrategyResult>\n 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<Result>\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<Result extends StrategyResult = StrategyResult>(\n opts: RunAgenticOptions<Result>,\n): Promise<AgenticRunResult & Result> {\n const workerProfile = exactAgenticProfile(opts.workerProfile, 'runAgentic worker')\n requiredProfileModel(workerProfile, 'runAgentic worker')\n const analystProfile = exactAgenticProfile(\n opts.analystProfile ?? workerProfile,\n 'runAgentic analyst',\n )\n requiredProfileModel(analystProfile, 'runAgentic analyst')\n const exactOpts: RunAgenticOptions<Result> = {\n ...opts,\n workerProfile,\n analystProfile,\n }\n const strategy: Strategy = opts.strategy ?? (opts.mode === 'breadth' ? sample : refine)\n const driver = strategy.driver(opts.surface, opts.task, exactOpts, opts.budget)\n const supervisor = createSupervisor<unknown, Outcome<unknown>>()\n const rootTurnLimit = profileTurnLimit(workerProfile, 'runAgentic worker')\n const root: Budget = opts.rootBudget ?? {\n maxIterations:\n opts.budget * ((rootTurnLimit === 0 ? UNBOUNDED_TURN_RESERVATION : rootTurnLimit) + 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, exactOpts),\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<\n AgenticRunResult & Result,\n 'usd' | 'usdKnown' | 'ms' | 'tokens' | 'tokensKnown'\n >\n return {\n ...core,\n usd: result.spentTotal.usd,\n usdKnown: result.spentTotal.usdKnown !== false,\n tokens: result.spentTotal.tokens,\n tokensKnown: result.spentTotal.tokensKnown !== false,\n ms: Date.now() - started,\n } as AgenticRunResult & Result\n}\n","/**\n * structuralRollout — the measured structural lever as a fourth member of the\n * sample/refine/sampleThenRefine strategy family: k independent samples, selection by\n * TASK-VISIBLE checks only, then a guarded self-repair loop steered by the checks'\n * failure output. Design: docs/design/structural-rollout-integration.md; measured basis\n * (bench/src/hev-structural.mts, bench/src/mbpp-structural.mts): +8.5..+21.3pp hidden-test\n * lift across Llama-3-8B/Qwen2.5-7B × HumanEval/MBPP, null only at saturation.\n *\n * Honesty invariants carried over from the proven rigs:\n * - Visible checks are generated from task-visible information only, BEFORE any\n * candidate exists, and FROZEN for every sample and repair round of the task.\n * - OFFICIAL checks (shown in the task itself) rank lexicographically above\n * model-AUTHORED guesses. This ordering is measured, not stylistic: authored guesses\n * run 17–70% wrong depending on model × spec richness, and unweighted they flipped\n * selection NEGATIVE on MBPP (6 noisy guesses outvoting the one reliable check).\n * - A candidate that crashed before the checks could run ranks below one that ran and\n * failed everything.\n * - Repair sees ONLY the checks' failure output, and never displaces a candidate that\n * passes more official checks with one that passes fewer (wrong visible examples\n * poison repair at saturation — the glm /47,/116 regressions).\n *\n * Placement rule: this is an INFERENCE-TIME capability (it wraps the model call via the\n * strategy seam). It does not belong in `improve()` (training-time); `improve()`\n * may later tune `StructuralRolloutPolicy` as an optimizable surface.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport {\n type AgenticTask,\n defineStrategy,\n type Strategy,\n type StrategyCtx,\n type StrategyResult,\n} from './strategy'\nimport type { SelectionReceipt } from './types'\n\n/** Provider-neutral conversation records read by structural candidate extraction. */\nexport type StructuralRolloutMessage = Record<string, unknown>\n\n// ── Policy ────────────────────────────────────────────────────────────────────────\n\n/** The rollout's compute recipe — promoted from the proven rigs' env vars (K/REPAIRS/\n * TESTGEN/DIVERSE/TEMPERATURE). Defaults are the measured sweet spot: repair value\n * concentrates at low k (~+12pp at k=1, +1–3pp at k=5), so `k=5, repairRounds=2` is the\n * full recipe and `k=1, repairRounds=2` the low-compute preset. */\nexport interface StructuralRolloutPolicy {\n /** Independent samples per task (selection breadth). */\n k: number\n /** Repair shots after selection, each steered by the checks' failure output. */\n repairRounds: number\n /** Model-authored visible checks requested per task; 0 disables authoring. */\n testgen: number\n /** Per-slot strategy-lens prefixes on the k samples (attacks the all-k-fail bucket).\n * Measured as a paired null (+0.6pp) — kept as an optional knob, off by default. */\n diverse?: boolean\n}\n\n/** The measured default recipe: 5 samples, 2 guarded repair rounds, 6 authored checks. */\nexport const defaultStructuralRolloutPolicy: StructuralRolloutPolicy = {\n k: 5,\n repairRounds: 2,\n testgen: 6,\n}\n\nfunction resolvePolicy(overrides?: Partial<StructuralRolloutPolicy>): StructuralRolloutPolicy {\n const policy = { ...defaultStructuralRolloutPolicy, ...overrides }\n if (!Number.isInteger(policy.k) || policy.k < 1) {\n throw new Error(`structuralRollout: policy.k must be an integer >= 1, got ${policy.k}`)\n }\n if (!Number.isInteger(policy.repairRounds) || policy.repairRounds < 0) {\n throw new Error(\n `structuralRollout: policy.repairRounds must be an integer >= 0, got ${policy.repairRounds}`,\n )\n }\n if (!Number.isInteger(policy.testgen) || policy.testgen < 0) {\n throw new Error(\n `structuralRollout: policy.testgen must be an integer >= 0, got ${policy.testgen}`,\n )\n }\n return policy\n}\n\n// ── Visible checks: the CheckSource seam (the only net-new seam of the design) ──────\n\n/** One task-visible executable check (e.g. a single-line Python assert). */\nexport interface VisibleCheck {\n code: string\n /** 'official' = shown in the task itself (docstring example, shown assert);\n * 'authored' = the model's own guess. Official outranks authored in selection. */\n kind: 'official' | 'authored'\n}\n\n/** What a CheckSource composes with. `consult` is the strategy family's raw analyst\n * channel (metered by the conserved pool, offline-injectable via `opts.complete`) —\n * check authoring goes through it rather than a bespoke model client. */\nexport interface CheckSourceCtx {\n /** Authored-check budget for this task (`policy.testgen`). */\n count: number\n /** The symbol authored checks must reference; undefined ⇒ authoring is skipped\n * (no guesses beats guesses pinned to nothing). */\n entrySymbol?: string\n /** One metered LLM call: instruction in, reply text out, null when the channel went\n * down. The task's visible prompt is included by the channel itself. */\n consult(instruction: string): Promise<string | null>\n}\n\n/** Produces the task's visible checks. MUST derive them from agent-visible information\n * only, before any candidate exists — the strategy freezes the returned set for every\n * sample and repair round of the task. */\nexport interface CheckSource {\n generate(task: AgenticTask, ctx: CheckSourceCtx): Promise<VisibleCheck[]>\n}\n\nconst authorInstruction = (count: number, entry: string) =>\n `Read the task below. Write exactly ${count} single-line assert statements that test the ` +\n `function \\`${entry}\\`, based ONLY on the behavior the task itself describes. Each assert ` +\n `must be one physical line of the form \\`assert ${entry}(...) == expected\\` (or a True/False ` +\n 'check). Do NOT implement the function. Do NOT copy shown examples verbatim if you can test ' +\n 'other cases too. Output ONLY the assert lines inside a single ```python code block.'\n\n/** The proven authored-assert filter (lifted from the rigs' generateTests): keep only\n * single-line, paren-balanced asserts that reference the entry symbol — malformed lines\n * are dropped here rather than poisoning every candidate's score identically. */\nexport function filterAuthoredAsserts(reply: string, entrySymbol: string, count: number): string[] {\n const fences = [...reply.matchAll(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/gi)].map((m) =>\n (m[1] ?? '').trim(),\n )\n const block = fences.length > 0 ? fences.join('\\n') : reply\n const balanced = (s: string) => {\n let d = 0\n for (const ch of s) {\n if (ch === '(' || ch === '[' || ch === '{') d += 1\n else if (ch === ')' || ch === ']' || ch === '}') d -= 1\n if (d < 0) return false\n }\n return d === 0\n }\n return block\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.startsWith('assert ') && l.includes(entrySymbol) && balanced(l))\n .slice(0, count)\n}\n\n/** Default authored-check source: one metered LLM call per task, before sampling,\n * filtered through `filterAuthoredAsserts`. Returns [] (no signal, never a fabricated\n * check) when the budget is 0, no entry symbol resolves, or the channel went down. */\nexport function modelAuthoredChecks(overrides: { count?: number } = {}): CheckSource {\n return {\n async generate(_task, ctx): Promise<VisibleCheck[]> {\n const count = overrides.count ?? ctx.count\n if (count <= 0 || !ctx.entrySymbol) return []\n const entry = ctx.entrySymbol\n const reply = await ctx.consult(authorInstruction(count, entry))\n if (!reply) return []\n return filterAuthoredAsserts(reply, entry, count).map((code) => ({\n code,\n kind: 'authored' as const,\n }))\n },\n }\n}\n\n/** Official checks the surface stashed on the task (e.g. MBPP's shown assert). Reads\n * `task.meta[key]` as a string array; anything else means no official checks. */\nexport function officialChecksFromMeta(key = 'visibleChecks'): CheckSource {\n return {\n async generate(task): Promise<VisibleCheck[]> {\n const raw = task.meta?.[key]\n if (!Array.isArray(raw)) return []\n return raw\n .filter((c): c is string => typeof c === 'string' && c.trim().length > 0)\n .map((code) => ({ code, kind: 'official' as const }))\n },\n }\n}\n\n/** Concatenate check sources (official first by convention — ordering does not affect\n * scoring, which reads each check's `kind`). */\nexport function composeCheckSources(...sources: CheckSource[]): CheckSource {\n return {\n async generate(task, ctx): Promise<VisibleCheck[]> {\n const all: VisibleCheck[] = []\n for (const source of sources) all.push(...(await source.generate(task, ctx)))\n return all\n },\n }\n}\n\n/** The symbol authored checks are pinned to: `task.meta.entryPoint` when the surface\n * provides it, else the LAST `def name(` in the visible prompt (a code-completion stub\n * lists helpers first, the entry stub last). Undefined ⇒ authoring is skipped. */\nexport function resolveEntrySymbol(task: AgenticTask): string | undefined {\n const meta = task.meta?.entryPoint\n if (typeof meta === 'string' && meta.trim().length > 0) return meta.trim()\n const defs = [...task.userPrompt.matchAll(/(?:^|\\n)\\s*def\\s+([A-Za-z_]\\w*)\\s*\\(/g)]\n const last = defs[defs.length - 1]\n return last?.[1]\n}\n\n// ── Check execution: the CheckRunner seam ────────────────────────────────────────────\n\n/** How one candidate fared against the frozen visible checks, split by check kind. */\nexport interface CheckOutcome {\n passedOfficial: number\n totalOfficial: number\n passedAuthored: number\n totalAuthored: number\n /** The checks' failure report — the ONLY feedback the repair loop may see. */\n failureOutput: string\n /** True when the candidate crashed before any check could run — ranks below a\n * candidate that ran and failed everything. */\n crashed?: boolean\n}\n\n/** Minimal exec channel the default runner needs. `SandboxInstance` (and therefore\n * `ValidationCtx.box`) satisfies it structurally. */\nexport interface CheckExecChannel {\n exec(\n command: string,\n options?: { timeoutMs?: number },\n ): Promise<{ exitCode: number; stdout: string; stderr: string }>\n}\n\nexport interface CheckRunContext {\n task: AgenticTask\n /** Live exec channel for this run (`ValidationCtx.box` / a sandbox instance). */\n box?: CheckExecChannel\n signal?: AbortSignal\n}\n\n/** Executes the frozen checks against one candidate. Implementations MUST fail loud\n * (throw) when they cannot execute — a silent zero poisons selection. */\nexport interface CheckRunner {\n run(candidate: string, checks: VisibleCheck[], ctx: CheckRunContext): Promise<CheckOutcome>\n}\n\n/** The check program (mirrors the rigs' visible-check judge): candidate executes at\n * module level, then each check runs INDIVIDUALLY in try/except so one malformed line\n * cannot zero the rest; the summary line carries a per-call NONCE so a candidate\n * printing a forged summary cannot be parsed as the verdict. */\nfunction buildCheckProgram(\n candidate: string,\n official: string[],\n authored: string[],\n nonce: string,\n): string {\n const officialB64 = Buffer.from(JSON.stringify(official), 'utf8').toString('base64')\n const authoredB64 = Buffer.from(JSON.stringify(authored), 'utf8').toString('base64')\n return `${candidate}\\n\nimport base64 as _b64, json as _json, sys as _sys\n_official = _json.loads(_b64.b64decode(\"${officialB64}\").decode(\"utf8\"))\n_authored = _json.loads(_b64.b64decode(\"${authoredB64}\").decode(\"utf8\"))\n_lines = []\ndef _run(_tests):\n _att, _fail = 0, 0\n for _t in _tests:\n _att += 1\n try:\n exec(_t, dict(globals()))\n except Exception as _e:\n _fail += 1\n _lines.append(\"CHECK FAILED: %s -> %s: %s\" % (_t.strip()[:200], type(_e).__name__, str(_e)[:200]))\n return _att, _fail\n_o_att, _o_fail = _run(_official)\n_a_att, _a_fail = _run(_authored)\nprint(\"SRCK-${nonce} official=%d/%d authored=%d/%d\" % (_o_att - _o_fail, _o_att, _a_att - _a_fail, _a_att))\n_sys.stdout.write(\"\\\\n\".join(_lines)[-1500:])\n_sys.exit(0 if (_o_fail + _a_fail) == 0 and (_o_att + _a_att) > 0 else 1)\n`\n}\n\n/** Default CheckRunner backend: pipes the check program into `python3` over the sandbox\n * exec channel (`ctx.box`, or one bound at construction). Never shells out to docker\n * itself — the jail is the sandbox's concern. No channel ⇒ throws; it must never\n * silently score 0. Empty check sets short-circuit to a no-signal outcome (nothing to\n * execute, so no channel is required). */\nexport function sandboxCheckRunner(\n options: { box?: CheckExecChannel; python?: string; timeoutMs?: number } = {},\n): CheckRunner {\n const python = options.python ?? 'python3'\n const timeoutMs = options.timeoutMs ?? 20000\n return {\n async run(candidate, checks, ctx): Promise<CheckOutcome> {\n if (checks.length === 0) {\n return {\n passedOfficial: 0,\n totalOfficial: 0,\n passedAuthored: 0,\n totalAuthored: 0,\n failureOutput: '',\n }\n }\n const box = ctx.box ?? options.box\n if (!box) {\n throw new Error(\n 'sandboxCheckRunner: no execution channel — bind one via sandboxCheckRunner({ box }) ' +\n 'or CheckRunContext.box (ValidationCtx.box / a sandbox instance). Refusing to score ' +\n 'without executing: a silent 0 would poison selection.',\n )\n }\n const nonce = randomBytes(8).toString('hex')\n const official = checks.filter((c) => c.kind === 'official').map((c) => c.code)\n const authored = checks.filter((c) => c.kind === 'authored').map((c) => c.code)\n const program = buildCheckProgram(candidate, official, authored, nonce)\n const b64 = Buffer.from(program, 'utf8').toString('base64')\n const r = await box.exec(`printf '%s' '${b64}' | base64 -d | ${python} -`, { timeoutMs })\n const summary = new RegExp(\n `SRCK-${nonce} official=(\\\\d+)/(\\\\d+) authored=(\\\\d+)/(\\\\d+)`,\n ).exec(r.stdout)\n if (!summary) {\n // The candidate crashed (or hung) before the check scaffold could report.\n const detail =\n (r.stderr || r.stdout).slice(-1500) ||\n 'no output (crashed or timed out before the checks could run)'\n return {\n passedOfficial: 0,\n totalOfficial: 0,\n passedAuthored: 0,\n totalAuthored: 0,\n failureOutput: detail,\n crashed: true,\n }\n }\n // Strip the sentinel line from repair feedback — the model must never learn the\n // summary format it could try to forge.\n const failureOutput = r.stdout.replace(summary[0], '').slice(-1500).trim()\n return {\n passedOfficial: Number(summary[1]),\n totalOfficial: Number(summary[2]),\n passedAuthored: Number(summary[3]),\n totalAuthored: Number(summary[4]),\n failureOutput,\n }\n },\n }\n}\n\n// ── Selection order (measured, not stylistic) ────────────────────────────────────────\n\nconst frac = (passed: number, total: number) => (total > 0 ? passed / total : 0)\n\n/** The selection order: crash < ran; then official pass-fraction; authored guesses only\n * break ties. Returns > 0 when `a` outranks `b`. Strictly lexicographic — on MBPP,\n * letting 6 noisy guesses outvote the one official check flipped selection negative. */\nexport function compareCheckOutcomes(a: CheckOutcome, b: CheckOutcome): number {\n const aCrashed = a.crashed === true\n const bCrashed = b.crashed === true\n if (aCrashed !== bCrashed) return aCrashed ? -1 : 1\n if (aCrashed) return 0\n const official = frac(a.passedOfficial, a.totalOfficial) - frac(b.passedOfficial, b.totalOfficial)\n if (official !== 0) return official\n return frac(a.passedAuthored, a.totalAuthored) - frac(b.passedAuthored, b.totalAuthored)\n}\n\n/** Display scalar for receipts/reports (the rigs' `visibleScore` shape): crash = -1,\n * else official fraction + 0.001 × authored fraction. Selection itself uses the exact\n * lexicographic comparator, never this scalar. */\nexport function visibleCheckScore(o: CheckOutcome): number {\n if (o.crashed) return -1\n return frac(o.passedOfficial, o.totalOfficial) + 0.001 * frac(o.passedAuthored, o.totalAuthored)\n}\n\n/** Argmax by `compareCheckOutcomes`, FIRST index wins ties (deterministic; with zero\n * visible coverage every candidate ties at no-signal and index 0 is the blind pick). */\nexport function selectBestIndex(outcomes: ReadonlyArray<CheckOutcome>): number {\n let best = 0\n for (let i = 1; i < outcomes.length; i += 1) {\n if (compareCheckOutcomes(outcomes[i] as CheckOutcome, outcomes[best] as CheckOutcome) > 0) {\n best = i\n }\n }\n return best\n}\n\n/** The repair keep-best guard: a challenger displaces the incumbent only when it is\n * strictly better in the selection order AND passes at least as many official checks.\n * The raw-count clause is deliberate belt-and-braces over the comparator (a custom\n * runner can report shifted totals): repair must NEVER replace a candidate that passes\n * more official checks with one that passes fewer. */\nexport function canDisplace(challenger: CheckOutcome, incumbent: CheckOutcome): boolean {\n if (challenger.crashed === true) return false\n if (challenger.passedOfficial < incumbent.passedOfficial) return false\n return compareCheckOutcomes(challenger, incumbent) > 0\n}\n\nconst totalChecks = (o: CheckOutcome) => o.totalOfficial + o.totalAuthored\n\nconst passesAllChecks = (o: CheckOutcome) =>\n o.crashed !== true &&\n totalChecks(o) > 0 &&\n o.passedOfficial === o.totalOfficial &&\n o.passedAuthored === o.totalAuthored\n\n// ── Candidate extraction ─────────────────────────────────────────────────────────────\n\n/** The candidate a shot produced, read from its conversation: the LAST `submit_answer`\n * tool-call argument (verifier environments submit the artifact explicitly), else the\n * latest assistant reply's fenced code block — preferring a block containing a `def`,\n * because repair replies echo the failure report in a bare fence BEFORE the fixed code\n * (the rigs' extractRepairCode lesson) — else the latest non-empty assistant text. */\nexport function defaultExtractCandidate(messages: ReadonlyArray<StructuralRolloutMessage>): string {\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const calls = messages[i]?.tool_calls as\n | Array<{ function?: { name?: string; arguments?: string } }>\n | undefined\n if (!calls) continue\n for (let j = calls.length - 1; j >= 0; j -= 1) {\n const call = calls[j]\n if (call?.function?.name !== 'submit_answer') continue\n try {\n const args = JSON.parse(call.function.arguments ?? '{}') as { answer?: unknown }\n if (typeof args.answer === 'string' && args.answer.trim()) return args.answer.trim()\n } catch {\n /* malformed arguments — keep scanning */\n }\n }\n }\n const contents: string[] = []\n for (const m of messages) {\n if (m.role === 'assistant' && typeof m.content === 'string' && m.content.trim()) {\n contents.push(m.content)\n }\n }\n const fencesOf = (text: string) =>\n [...text.matchAll(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/gi)].map((m) => (m[1] ?? '').trim())\n for (let i = contents.length - 1; i >= 0; i -= 1) {\n const fences = fencesOf(contents[i] as string)\n for (let j = fences.length - 1; j >= 0; j -= 1) {\n if (/(^|\\n)\\s*def\\s+\\w+/.test(fences[j] as string)) return fences[j] as string\n }\n }\n for (let i = contents.length - 1; i >= 0; i -= 1) {\n const fences = fencesOf(contents[i] as string)\n if (fences.length > 0) return fences[fences.length - 1] as string\n }\n return (contents[contents.length - 1] ?? '').trim()\n}\n\n// ── The strategy ─────────────────────────────────────────────────────────────────────\n\n/** Per-slot approach lenses for `diverse` mode — copied from bench/src/directives.ts\n * (the measured rig plumbing; a paired null there, kept as an optional knob). */\nconst DIVERSE_LENSES: ReadonlyArray<string> = [\n 'Answer directly and decisively from what you already know. State the single best answer without hedging.',\n 'Decompose the question into the sub-facts it depends on. Establish each sub-fact explicitly, then compose them into the answer.',\n 'Reason from first principles. Ignore the most obvious or popular guess; derive the answer from underlying facts and relationships.',\n 'Name the most plausible WRONG answer and the trap that makes it tempting. Rule it out, then commit to the answer that survives.',\n]\n\nfunction slotLens(slot: number): string {\n const lens = DIVERSE_LENSES[slot % DIVERSE_LENSES.length] as string\n const tag =\n slot < DIVERSE_LENSES.length ? '' : ` (variant ${Math.floor(slot / DIVERSE_LENSES.length) + 1})`\n return `${lens}${tag}`\n}\n\nfunction repairSteer(outcome: CheckOutcome): string {\n return [\n 'Your latest solution failed some of the task-visible checks.',\n 'Result of running the visible checks against it:',\n '```',\n outcome.failureOutput.trim() || '(the code crashed before the checks could run)',\n '```',\n 'Fix the solution so the visible checks pass. Provide the COMPLETE corrected solution the',\n 'same way you provided the original (same tool or format) — not a fragment or a diff.',\n ].join('\\n')\n}\n\nfunction describeOutcome(label: string, o: CheckOutcome): string {\n if (o.crashed) return `${label}: crashed before the checks could run`\n return (\n `${label}: official ${o.passedOfficial}/${o.totalOfficial}, ` +\n `authored ${o.passedAuthored}/${o.totalAuthored}`\n )\n}\n\nexport type RepairStop =\n | 'already-passing'\n | 'no-signal'\n | 'repaired-pass'\n | 'rounds-exhausted'\n | 'no-candidates'\n\n/** The body's deliverable — a `StrategyResult` plus selection provenance. The extra\n * fields ride through `defineStrategy`'s deliverable spread onto `AgenticRunResult`\n * (score/resolved stay harness-verified, exactly as for every authored strategy). */\nexport interface StructuralRolloutResult extends StrategyResult {\n /** Exact selected candidate text passed to the visible checks, or null when no shot ran. */\n artifact: string | null\n /** One receipt per scored candidate (k samples, then repairs), `SelectionReceipt`\n * shaped like the kernel's (`types.ts`), selector 'driver'. */\n selection: SelectionReceipt[]\n repairStop: RepairStop\n officialChecks: number\n authoredChecks: number\n}\n\nexport interface StructuralRolloutConfig {\n /** Knobs; missing fields take the measured defaults (k=5, repairRounds=2, testgen=6). */\n policy?: Partial<StructuralRolloutPolicy>\n /** Where the visible checks come from. Default: official checks from\n * `task.meta.visibleChecks` composed with `modelAuthoredChecks()`. */\n checkSource?: CheckSource\n /** How candidates are measured. Default `sandboxCheckRunner()` — it needs an exec\n * channel (bind one to the runner, or pass `box` here) and fails loud without one. */\n checkRunner?: CheckRunner\n /** Exec channel threaded into every check run of this strategy (a sandbox instance /\n * `ValidationCtx.box`). The strategy seam itself carries no sandbox, so the caller\n * who owns one supplies it here or binds it into the runner. */\n box?: CheckExecChannel\n /** Candidate extraction from a shot's conversation. Default `defaultExtractCandidate`. */\n extractCandidate?: (messages: ReadonlyArray<StructuralRolloutMessage>) => string\n}\n\n/**\n * Build the structuralRollout `Strategy`: k shots → score each by the frozen visible\n * checks (official above authored, crash lowest) → argmax with first-index tie-break →\n * up to `repairRounds` repair shots steered by the failure output, keep-best under the\n * official-check guard. Authored via `defineStrategy`, so the deliverable score stays\n * harness-verified and every shot is metered by the conserved pool.\n *\n * Budget note: `runAgentic`'s `budget` sizes the pool — pass at least\n * `k + repairRounds + 1` so the samples, repairs, and the check-author consult all admit.\n */\nexport function structuralRollout(\n config: StructuralRolloutConfig = {},\n): Strategy<StructuralRolloutResult> {\n const policy = resolvePolicy(config.policy)\n const checkSource =\n config.checkSource ?? composeCheckSources(officialChecksFromMeta(), modelAuthoredChecks())\n const checkRunner = config.checkRunner ?? sandboxCheckRunner()\n const extract = config.extractCandidate ?? defaultExtractCandidate\n\n const inner = defineStrategy(\n 'structuralRollout',\n async (ctx: StrategyCtx): Promise<StructuralRolloutResult> => {\n const { task, shot } = ctx\n const progression: number[] = []\n const receipts: SelectionReceipt[] = []\n let completions = 0\n let shots = 0\n\n // Freeze the visible checks BEFORE any candidate exists — every sample and repair\n // round is measured against this same set. Authoring goes through the strategy's\n // raw analyst channel, so its spend is metered and the offline transport applies.\n const consult = async (instruction: string): Promise<string | null> => {\n const reply = await ctx.consult([], instruction)\n completions += 1\n return reply\n }\n const entrySymbol = resolveEntrySymbol(task)\n const checks = await checkSource.generate(task, {\n count: policy.testgen,\n ...(entrySymbol ? { entrySymbol } : {}),\n consult,\n })\n const officialChecks = checks.filter((c) => c.kind === 'official').length\n const authoredChecks = checks.length - officialChecks\n const runCtx: CheckRunContext = { task, ...(config.box ? { box: config.box } : {}) }\n\n interface Candidate {\n index: number\n messages: StructuralRolloutMessage[]\n artifact: string\n outcome: CheckOutcome\n shotScore: number\n shotResolved: boolean\n }\n\n // k independent samples, each on its own artifact, scored by the frozen checks.\n const candidates: Candidate[] = []\n for (let i = 0; i < policy.k; i += 1) {\n const out = await shot(policy.diverse ? { steer: slotLens(i) } : undefined)\n if (!out) break // pool starved — select among what settled\n shots += 1\n completions += out.completions\n progression.push(out.score)\n const artifact = extract(out.messages)\n const outcome = await checkRunner.run(artifact, checks, runCtx)\n candidates.push({\n index: candidates.length,\n messages: out.messages,\n artifact,\n outcome,\n shotScore: out.score,\n shotResolved: out.total > 0 && out.passes === out.total,\n })\n }\n if (candidates.length === 0) {\n return {\n score: 0,\n resolved: false,\n completions,\n progression,\n shots,\n artifact: null,\n selection: receipts,\n repairStop: 'no-candidates',\n officialChecks,\n authoredChecks,\n }\n }\n\n // Argmax by the official-first order; first index wins ties (the blind pick when\n // the task has zero visible coverage).\n let best = candidates[selectBestIndex(candidates.map((c) => c.outcome))] as Candidate\n for (const c of candidates) {\n receipts.push({\n candidateIndex: c.index,\n selected: false,\n score: visibleCheckScore(c.outcome),\n reason: describeOutcome('sample', c.outcome),\n selector: 'driver',\n })\n }\n\n // Guarded repair: steered ONLY by the checks' failure output, keep-best, and a\n // repair never displaces a candidate that passes more official checks.\n let seq = candidates.length\n let repairStop: RepairStop = 'already-passing'\n if (!passesAllChecks(best.outcome)) {\n if (best.outcome.crashed !== true && totalChecks(best.outcome) === 0) {\n repairStop = 'no-signal' // no visible checks ⇒ nothing honest to steer on\n } else {\n repairStop = 'rounds-exhausted'\n for (let r = 0; r < policy.repairRounds; r += 1) {\n const out = await shot({ messages: best.messages, steer: repairSteer(best.outcome) })\n if (!out) break\n shots += 1\n completions += out.completions\n progression.push(out.score)\n const artifact = extract(out.messages)\n const outcome = await checkRunner.run(artifact, checks, runCtx)\n const displaced = canDisplace(outcome, best.outcome)\n const label = displaced\n ? 'repair (displaced the incumbent)'\n : outcome.crashed !== true && outcome.passedOfficial < best.outcome.passedOfficial\n ? 'repair (held out: passes fewer official checks than the incumbent)'\n : 'repair (held out: no improvement)'\n receipts.push({\n candidateIndex: seq,\n selected: false,\n score: visibleCheckScore(outcome),\n reason: describeOutcome(label, outcome),\n selector: 'driver',\n })\n if (displaced) {\n best = {\n index: seq,\n messages: out.messages,\n artifact,\n outcome,\n shotScore: out.score,\n shotResolved: out.total > 0 && out.passes === out.total,\n }\n }\n seq += 1\n if (passesAllChecks(best.outcome)) {\n repairStop = 'repaired-pass'\n break\n }\n }\n }\n }\n\n const winner = receipts.find((r) => r.candidateIndex === best.index)\n if (winner) winner.selected = true\n\n return {\n score: best.shotScore,\n resolved: best.shotResolved,\n completions,\n progression,\n shots,\n artifact: best.artifact,\n selection: receipts,\n repairStop,\n officialChecks,\n authoredChecks,\n }\n },\n )\n\n return inner\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;AAMX,MA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