@tangle-network/agent-runtime 0.165.0 → 0.166.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.
Files changed (38) hide show
  1. package/dist/{activation-DmUIq51m.js → activation-BkO0p4I1.js} +2 -2
  2. package/dist/{activation-DmUIq51m.js.map → activation-BkO0p4I1.js.map} +1 -1
  3. package/dist/agent.js +2 -2
  4. package/dist/{authoring-Cm122Duf.js → authoring-Bt17KOML.js} +2 -2
  5. package/dist/{authoring-Cm122Duf.js.map → authoring-Bt17KOML.js.map} +1 -1
  6. package/dist/durable.js +1 -1
  7. package/dist/graph-E0U0c2YP.js +2668 -0
  8. package/dist/graph-E0U0c2YP.js.map +1 -0
  9. package/dist/graph.d.ts +179 -15
  10. package/dist/graph.js +2 -1819
  11. package/dist/{improvement-cycle-BOd5DFeG.js → improvement-cycle-BAWOyeTA.js} +3 -3
  12. package/dist/{improvement-cycle-BOd5DFeG.js.map → improvement-cycle-BAWOyeTA.js.map} +1 -1
  13. package/dist/index.js +7 -7
  14. package/dist/intelligence.js +3 -3
  15. package/dist/kernel.js +6 -6
  16. package/dist/{knowledge-7_IfyD9R.js → knowledge-Bhhz6lvH.js} +3 -3
  17. package/dist/{knowledge-7_IfyD9R.js.map → knowledge-Bhhz6lvH.js.map} +1 -1
  18. package/dist/knowledge.js +1 -1
  19. package/dist/{loop-runner-bin-Dx-5GZQK.js → loop-runner-bin-BQnpSn0h.js} +3 -3
  20. package/dist/{loop-runner-bin-Dx-5GZQK.js.map → loop-runner-bin-BQnpSn0h.js.map} +1 -1
  21. package/dist/loop-runner-bin.js +1 -1
  22. package/dist/mcp/bin.js +3 -3
  23. package/dist/mcp/index.js +4 -4
  24. package/dist/{openai-tools-CDS7eSww.js → openai-tools-t6spVYKL.js} +2 -2
  25. package/dist/{openai-tools-CDS7eSww.js.map → openai-tools-t6spVYKL.js.map} +1 -1
  26. package/dist/{runtime-DESENUe1.js → runtime-BJoNta1Y.js} +6 -6
  27. package/dist/{runtime-DESENUe1.js.map → runtime-BJoNta1Y.js.map} +1 -1
  28. package/dist/{structural-rollout-DZGDg0yX.js → structural-rollout-B5E0mWCH.js} +2 -2
  29. package/dist/{structural-rollout-DZGDg0yX.js.map → structural-rollout-B5E0mWCH.js.map} +1 -1
  30. package/dist/{supervise-Da20R0PO.js → supervise-CnxqHx1P.js} +2 -2
  31. package/dist/{supervise-Da20R0PO.js.map → supervise-CnxqHx1P.js.map} +1 -1
  32. package/dist/{supervisor-DpIKMlPJ.js → supervisor-C8kgh8mf.js} +21 -2
  33. package/dist/{supervisor-DpIKMlPJ.js.map → supervisor-C8kgh8mf.js.map} +1 -1
  34. package/dist/testing.js +11 -11
  35. package/package.json +1 -1
  36. package/dist/graph-DGri_zJm.js +0 -532
  37. package/dist/graph-DGri_zJm.js.map +0 -1
  38. package/dist/graph.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-DGri_zJm.js","names":[],"sources":["../src/runtime/supervise/graph.ts"],"sourcesContent":["/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * backend-derived worker path (authorized, classified, recursive), conserved-pool budget, and\n * deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n ContinuityMode,\n CoordinationEvent,\n MakeWorkerAgent,\n} from '../../mcp/tools/coordination'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n formatPromptHandle,\n kernelPromptRegistry,\n type PromptHandle,\n type PromptRegistry,\n} from './prompt-registry'\nimport { type SuperviseOptions, supervise, superviseWithTestBrain } from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_agent` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n\nexport interface AgentGraph {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown>\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>` or `analyzes:<analyst>:<over…>-><to>`. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. */\n readonly workerId?: string\n}\n\n/** Default per-edge traversal cap — the cyclic-graph backstop when an edge names none. */\nexport const defaultEdgeTraversalCap = 32\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'continuityByProfile',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'backend',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'isDriverProfile',\n 'router',\n 'driveHarness',\n 'driverRetry',\n 'onDriverAttempt',\n 'childSettleGraceMs',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'perWorker',\n 'maxLiveWorkers',\n 'watchWorkers',\n 'stallAfterMs',\n 'runDir',\n 'probes',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions\n extends Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized LEAF from it; a node declared `role: 'driver'`\n * becomes a nested supervisor instead, whose own leaves are derived the same way. */\n readonly backend?: SuperviseOptions['backend']\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: SuperviseOptions['driverBackend']\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node\n * declared `role: 'driver'` still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\ninterface ValidatedGraph {\n readonly root: GraphNode\n readonly workers: ReadonlyMap<NodeId, GraphNode>\n readonly delegatesByWorker: ReadonlyMap<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>\n readonly analyzes: ReadonlyArray<Extract<GraphEdge, { kind: 'analyzes' }>>\n /** Nodes referenced as an analyzes edge's ANALYST (the analyst-agent form): reachable through\n * their analyzes edge (spawned on settle), never through a delegates edge. */\n readonly analystNodes: ReadonlyMap<NodeId, GraphNode>\n}\n\nfunction edgeId(edge: GraphEdge): string {\n return edge.kind === 'delegates'\n ? `delegates:${edge.from}->${edge.to}`\n : `analyzes:${edge.analyst}:${edge.over.join('+')}->${edge.to}`\n}\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n const byId = new Map<NodeId, GraphNode>()\n for (const node of graph.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError('runGraph: every node needs a non-empty string id')\n }\n if (byId.has(node.id)) throw new ValidationError(`runGraph: duplicate node id '${node.id}'`)\n const parsed = agentProfileSchema.safeParse(node.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has an invalid AgentProfile: ${parsed.error.message}`,\n )\n }\n // The profile NAME is the node identity everywhere downstream: node pinning resolves a\n // spawn's `profile.name` against node ids, and the coordination layer matches analyst\n // routes (`over`/`to`) against the settled worker's PROFILE NAME. A divergent name would\n // make every analyzes edge touching this node silently never match — refuse it up front.\n if (node.profile.name !== node.id) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has profile.name ${JSON.stringify(node.profile.name)} — ` +\n 'profile.name IS the node identity (node pinning and analyst routing match on it) and ' +\n 'must equal the node id',\n )\n }\n byId.set(node.id, node)\n }\n const requireNode = (id: NodeId, where: string): GraphNode => {\n const node = byId.get(id)\n if (!node) throw new ValidationError(`runGraph: ${where} references unknown node '${id}'`)\n return node\n }\n const delegates = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'delegates' }> => edge.kind === 'delegates',\n )\n const analyzes = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'analyzes' }> => edge.kind === 'analyzes',\n )\n if (delegates.length === 0) {\n throw new ValidationError('runGraph: at least one delegates edge is required (who spawns whom)')\n }\n for (const edge of graph.edges) registry.resolve(edge.directive)\n for (const edge of delegates) {\n requireNode(edge.from, edgeId(edge))\n requireNode(edge.to, edgeId(edge))\n if (edge.from === edge.to) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates to itself — the driver↔worker cycle is the ` +\n 'settle-return loop, not a self-edge',\n )\n }\n // The type admits only 'fresh' | 'resume', but a graph is plain data that often arrives\n // through JSON — refuse a nonsense mode here, never let it reach the spawn tool as a string.\n if (\n edge.continuity !== undefined &&\n edge.continuity !== 'fresh' &&\n edge.continuity !== 'resume'\n ) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} has invalid continuity ${JSON.stringify(edge.continuity)} — ` +\n \"a delegates edge's continuity is 'fresh' or 'resume'\",\n )\n }\n }\n // Root: the one node that delegates and is never delegated TO. P0 executes the star/2-node\n // cyclic family (one driver, N workers); nested driver graphs are the recorded P3 absorption.\n const delegatedTo = new Set(delegates.map((edge) => edge.to))\n const roots = [...new Set(delegates.map((edge) => edge.from))].filter(\n (id) => !delegatedTo.has(id),\n )\n if (roots.length !== 1) {\n throw new ValidationError(\n `runGraph: expected exactly ONE root (a node that delegates and is never delegated to), ` +\n `found ${roots.length === 0 ? 'none — delegates edges form a cycle with no entry' : roots.join(', ')}. ` +\n 'P0 executes driver↔worker(s); nested driver graphs are P3.',\n )\n }\n const root = requireNode(roots[0] as string, 'root resolution')\n for (const edge of delegates) {\n if (edge.from !== root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates from a non-root node — P0 executes one driver over ` +\n 'its workers (the 2-node cyclic case, star-generalized); deeper delegation is P3',\n )\n }\n }\n const analystIds = new Set<string>()\n const analystNodes = new Map<NodeId, GraphNode>()\n for (const edge of analyzes) {\n // Continuity is a delegates-edge axis ONLY: analysts (lens or node) are spawned by the\n // analyst-on-settle machinery, each run a fresh session over settled evidence — an analyzes\n // edge carrying continuity would silently mean nothing, so it is refused as data.\n if ((edge as { continuity?: unknown }).continuity !== undefined) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} carries continuity — analysts are spawned by the analyst ` +\n 'machinery (every analyst run is a fresh session over settled evidence), so ' +\n 'continuity is a delegates-edge axis only',\n )\n }\n // The runner's traversal ledger resolves a finding/steer back to its edge BY ANALYST ID\n // alone, so a second edge sharing an analyst would silently absorb the first edge's\n // traversals (last-registered wins). Multi-edge-per-analyst is not yet supported; refuse it\n // rather than mis-ledger it.\n if (analystIds.has(edge.analyst)) {\n throw new ValidationError(\n `runGraph: two analyzes edges share analyst '${edge.analyst}' — one analyzes edge per ` +\n 'analyst lens (traversals are ledgered by analyst id; a second edge would silently ' +\n \"absorb the first's). Register the lens under a second id for a second edge.\",\n )\n }\n analystIds.add(edge.analyst)\n // The analyst REFERENCE has two forms — a registry lens id or a graph node id — and the id\n // itself is what distinguishes them, so an id living in both is refused as ambiguous rather\n // than silently resolved by precedence.\n const analystNode = byId.get(edge.analyst)\n const inRegistry = analysts?.kinds.some((kind) => kind.id === edge.analyst) === true\n if (analystNode !== undefined && inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is BOTH a graph node and a lens in ` +\n 'the analysts registry — the id alone distinguishes the two analyst forms, so this is ' +\n 'ambiguous; rename the node or register the lens under another id',\n )\n }\n if (analystNode !== undefined) {\n // The analyst-AGENT form. Oracle doctrine holds structurally: the analyst node can never\n // receive work — not from the root (a delegates edge to it is refused) and not by being\n // the root (the root delegates by definition).\n if (analystNode.id === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names the ROOT as its analyst — the root is the driver; ` +\n 'give the analyst its own node with no delegates edge pointing at it',\n )\n }\n if (delegatedTo.has(analystNode.id)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names node '${edge.analyst}' as its analyst, but that node ` +\n 'is a delegates target — oracle doctrine: an analyst is never delegated to. An ' +\n 'analyst NODE is legal only with NO delegates edge pointing at it; give the analyst ' +\n 'its own delegates-free node or pass a lens id from RunGraphOptions.analysts.',\n )\n }\n analystNodes.set(analystNode.id, analystNode)\n } else if (!analysts) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is not a graph node, and no ` +\n 'RunGraphOptions.analysts registry was provided to resolve it as a lens',\n )\n } else if (!inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is neither a graph node nor in the ` +\n `analysts registry (known lenses: ${analysts.kinds.map((kind) => kind.id).join(', ') || 'none'})`,\n )\n }\n if (edge.over.length === 0) {\n throw new ValidationError(`runGraph: ${edgeId(edge)} must analyze at least one node`)\n }\n for (const over of edge.over) {\n requireNode(over, edgeId(edge))\n // Analysts observe SETTLED WORKERS, matched by profile name — the root drives and never\n // settles as a worker, so an edge over the root would silently never fire; refuse it.\n if (over === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes the ROOT — analysts observe settled workers, and ` +\n 'the root never settles as one, so this edge would silently never fire; list ' +\n 'delegates-target nodes only',\n )\n }\n }\n requireNode(edge.to, edgeId(edge))\n }\n // Second pass, once every analyst NODE is known: an analyst run's settlement is a FINDING,\n // never a worker settle, so an analyzes edge OVER an analyst node would silently never fire —\n // refuse it rather than let it rot unobserved.\n for (const edge of analyzes) {\n for (const over of edge.over) {\n if (analystNodes.has(over)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes '${over}', which is an analyst node — an analyst ` +\n 'run settles as a finding, never as a worker, so this edge would silently never ' +\n 'fire; analyst nodes are not analyzable',\n )\n }\n }\n }\n const workers = new Map<NodeId, GraphNode>()\n const delegatesByWorker = new Map<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>()\n for (const edge of delegates) {\n if (delegatesByWorker.has(edge.to)) {\n throw new ValidationError(\n `runGraph: node '${edge.to}' is the target of two delegates edges — one delegation ` +\n 'directive per worker node (version the directive instead of forking the edge)',\n )\n }\n delegatesByWorker.set(edge.to, edge)\n workers.set(edge.to, requireNode(edge.to, edgeId(edge)))\n }\n // Every non-root node must be reachable by SOME edge, or it can never run. A worker node is\n // reached by its delegates edge; an analyst node by its analyzes edge (spawned on settle).\n for (const node of graph.nodes) {\n if (node.id !== root.id && !workers.has(node.id) && !analystNodes.has(node.id)) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has no delegates edge to it — an unreachable node never runs`,\n )\n }\n }\n return { root, workers, delegatesByWorker, analyzes, analystNodes }\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\nconst byteLength = (text: string): number => Buffer.byteLength(text, 'utf8')\n\nfunction stringifyPayload(payload: unknown): string {\n if (typeof payload === 'string') return payload\n try {\n return JSON.stringify(payload) ?? String(payload)\n } catch {\n return String(payload)\n }\n}\n\n/**\n * Execute an {@link AgentGraph}. The root node becomes the supervisor (`supervise()` — the\n * execution core), each worker node is spawnable BY NODE ID (`spawn_agent` with\n * `profile: { name: '<node id>' }`; the node's canonical profile is pinned by the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return runGraphInternal(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return runGraphInternal(graph, runtimeOptions, brain)\n}\n\nfunction runGraphInternal(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const { root, workers, delegatesByWorker, analyzes, analystNodes } = validateGraph(\n graph,\n registry,\n opts.analysts,\n )\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse\n // the contradiction before any compute, and refuse a harness-driven root outright — the\n // harness IS that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n const journal = opts.journal ?? new InMemorySpawnJournal()\n const blobs = opts.blobs ?? new InMemoryResultBlobStore()\n const runId =\n opts.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // ── Ledger state ──\n const ledger: EdgeTraversal[] = []\n const journaled = new Set<EdgeTraversal>()\n const traversalCounts = new Map<string, number>()\n const exhausted = new Set<string>()\n // The subset of `exhausted` that REFUSED work. Only a delegates cap closes the spawn cycle, so\n // only it can be the reason a run ended winnerless — an analyzes cap refuses nothing.\n const exhaustedDelegates = new Set<string>()\n const journalWrites: Promise<void>[] = []\n let ledgerSeq = 0\n const appendJournal = (entry: EdgeTraversal, nodeIdForEvent: string): Promise<void> => {\n if (journaled.has(entry)) return Promise.resolve()\n journaled.add(entry)\n const write = journal.appendEvent(runId, {\n kind: 'edge',\n id: nodeIdForEvent,\n edge: { kind: entry.kind, from: entry.from, to: entry.to, directive: entry.directive },\n traversal: entry.traversal,\n outcome: entry.outcome,\n continuity: entry.continuity,\n bytes: entry.bytes,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n journalWrites.push(write)\n return write\n }\n const record = (entry: Omit<EdgeTraversal, 'traversal'>, journalNow: boolean): EdgeTraversal => {\n const count = (traversalCounts.get(entry.edge) ?? 0) + 1\n traversalCounts.set(entry.edge, count)\n const row: EdgeTraversal = { ...entry, traversal: count }\n ledger.push(row)\n if (journalNow) void appendJournal(row, row.workerId ?? `graph:${row.to}`)\n return row\n }\n\n // ── Node pinning + delegates spawn traversals (the authorizeSpawn wrapper) ──\n // Pinning lives in `authorizeSpawn`, which the kernel runs BEFORE it decides whether a child is\n // a leaf or a nested supervisor. That is what lets a node declared `role: 'driver'` become a real\n // supervisor carrying its canonical profile: the kernel's `isDriver` reads the PINNED profile,\n // not the driver-authored `{ name }` stub. (It used to live in `makeWorkerAgent`, a leaf-only\n // seam, which made every node a leaf no matter what its profile declared — #965.)\n const nodeByWorkerId = new Map<string, NodeId>()\n const pendingByAssignment = new Map<string, EdgeTraversal>()\n type SpawnAuthorizationInput = Parameters<NonNullable<SuperviseOptions['authorizeSpawn']>>[0]\n const pinNode = (input: SpawnAuthorizationInput): AgentProfile => {\n const requested =\n typeof (input.profile as { name?: unknown } | undefined)?.name === 'string'\n ? (input.profile as { name: string }).name\n : undefined\n // An analyst-AGENT run: the coordination settle hook — never the driver; the marker is\n // authored by the runtime, not accepted from model arguments — spawns the analyst NODE.\n // Pin the node's canonical profile; the analysis directive travels as the TASK (composed by\n // the coordination layer with the settled worker's trace evidence), so nothing is appended\n // to the profile's instructions here. Its traversal is ledgered on the finding/steer it\n // produces, exactly like a registry analyst's.\n if (input.analyst !== undefined) {\n const analystNode = analystNodes.get(input.analyst)\n if (!analystNode || requested !== analystNode.id) {\n throw new ValidationError(\n `runGraph: analyst run for ${JSON.stringify(input.analyst)} does not name an ` +\n `analyst node of this graph (analyst nodes: ${[...analystNodes.keys()].join(', ') || 'none'})`,\n )\n }\n return analystNode.profile\n }\n const node = requested !== undefined ? workers.get(requested) : undefined\n if (!node) {\n throw new ValidationError(\n `runGraph: spawn_agent named profile ${JSON.stringify(requested)} which is not a worker ` +\n `node of this graph (nodes: ${[...workers.keys()].join(', ')}). Spawn by node id: ` +\n 'profile.name selects the node; the node profile itself is pinned by the graph.',\n )\n }\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const id = edgeId(edge)\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(id) ?? 0\n // The EFFECTIVE spawn mode the coordination layer resolved (per-call override, else this\n // edge's declared default, else fresh) — stamped on the row so the ledger states how each\n // hop continued, never how it was merely configured to.\n const spawnContinuity = input.continuity ?? 'fresh'\n if (used >= cap) {\n exhausted.add(id)\n exhaustedDelegates.add(id)\n record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: 'unpropagated',\n continuity: spawnContinuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${cap})`,\n },\n true,\n )\n throw new ValidationError(\n `runGraph: delegates edge ${id} exhausted its traversal cap (${cap}) — the ` +\n 'cyclic-graph backstop refused this spawn',\n )\n }\n const directiveText = registry.resolve(edge.directive).text\n const taskText = stringifyPayload(input.task)\n const bytes = byteLength(directiveText) + byteLength(taskText)\n const row = record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: bytes === 0 ? 'empty' : 'delivered',\n continuity: spawnContinuity,\n bytes,\n ...(bytes === 0 ? { reason: 'no directive text and no task payload' } : {}),\n },\n false,\n )\n pendingByAssignment.set(input.assignmentId, row)\n // The delegation directive is a STANDING instruction of this traversal: appended to the\n // node's canonical prompt instructions, so the worker runs under node profile + edge\n // directive, and the driver-authored profile contributes ONLY the node selection.\n return directiveText.length === 0\n ? node.profile\n : {\n ...node.profile,\n prompt: {\n ...(node.profile.prompt ?? {}),\n instructions: [\n ...((node.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n directiveText,\n ],\n },\n }\n }\n // The pre-journal gate (a bridge backend's route/admission check) must judge the profile that\n // will run, not the `{ name }` stub — otherwise every graph spawn over a bridge is refused\n // `model-route` before the graph ever pins it. This resolver is PURE: it answers \"which node\"\n // without ledgering, because the gate may refuse and nothing may be journaled for a refusal.\n const resolveSpawnProfile = (authored: AgentProfile): AgentProfile => {\n const requested = typeof authored.name === 'string' ? authored.name : undefined\n const node =\n (requested !== undefined ? workers.get(requested) : undefined) ??\n (requested !== undefined ? analystNodes.get(requested) : undefined)\n // Unknown names fall through to authorizeSpawn, which refuses them with the full message and\n // a ledger row; the gate just sees the stub and lets that later refusal speak.\n return node?.profile ?? authored\n }\n // Graph authority first, then the caller's: a product authorizing spawns sees the CANONICAL\n // node profile (what will actually run), never the driver's `{ name }` stub.\n const graphAuthorizeSpawn: NonNullable<SuperviseOptions['authorizeSpawn']> = (input) => {\n const pinned = pinNode(input)\n if (!opts.authorizeSpawn) return { profile: pinned }\n return opts.authorizeSpawn({ ...input, profile: pinned })\n }\n\n // ── Analyzes edges → analyst-on-settle routes with destinations ──\n // A LENS edge's directive wraps the findings for the recipient (so a driver-destined lens\n // route carries no directive — it becomes the driver brief below). A NODE edge's directive is\n // the analyst AGENT's task, so it always rides the route, wherever the findings go.\n const routes: Array<string | AnalyzeOnSettleRoute> = analyzes.map((edge) => {\n const analystNode = analystNodes.get(edge.analyst)\n if (analystNode) {\n return {\n kind: edge.analyst,\n over: edge.over,\n agent: analystNode.profile,\n directive: registry.resolve(edge.directive).text,\n ...(edge.to === root.id ? {} : { to: edge.to }),\n }\n }\n return edge.to === root.id\n ? { kind: edge.analyst, over: edge.over }\n : {\n kind: edge.analyst,\n over: edge.over,\n to: edge.to,\n directive: registry.resolve(edge.directive).text,\n }\n })\n // Driver-destined analyzes findings are standing knowledge for the ROOT: the findings arrive\n // as bus events. For a lens edge the directive tells the driver what to do with them; for a\n // node edge the directive already went to the analyst agent as its task.\n const driverAnalyzesBriefs = analyzes\n .filter((edge) => edge.to === root.id)\n .map((edge) =>\n analystNodes.has(edge.analyst)\n ? `Findings from analyst '${edge.analyst}' (a tool-equipped analyst agent node, over: ` +\n `${edge.over.join(', ')}) will arrive as finding events.`\n : `Findings from analyst '${edge.analyst}' (over: ${edge.over.join(', ')}) will arrive as ` +\n `finding events.\\n${registry.resolve(edge.directive).text}`,\n )\n\n // ── Edge continuity defaults, threaded to the spawn tool by node id (= profile name) ──\n const continuityByProfile: Record<string, ContinuityMode> = {}\n for (const [nodeId, edge] of delegatesByWorker) {\n if (edge.continuity !== undefined) continuityByProfile[nodeId] = edge.continuity\n }\n\n // ── The driver graph brief: which nodes it may spawn, by exact name ──\n const workerLines = [...workers.values()].map((node) => {\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const description =\n typeof node.profile.description === 'string' && node.profile.description.length > 0\n ? ` — ${node.profile.description}`\n : ''\n const continuityNote =\n edge.continuity === 'resume'\n ? \"; continuity: resume — each spawn after the first re-attaches to this node's latest \" +\n 'settled session (spawn again to continue it; steer while it is live)'\n : ''\n return `- '${node.id}'${description} (delegation cap: ${cap} traversals${continuityNote})`\n })\n const graphBrief = [\n 'AGENT GRAPH: you are the driver node of a fixed topology. You may spawn ONLY these worker',\n \"nodes, by EXACT name (spawn_agent with profile: { name: '<node id>' }; the node's full\",\n 'profile is pinned by the graph — any other profile fields you author are ignored):',\n ...workerLines,\n ...(driverAnalyzesBriefs.length > 0 ? ['', ...driverAnalyzesBriefs] : []),\n ].join('\\n')\n const rootProfile: AgentProfile = {\n ...root.profile,\n prompt: {\n ...(root.profile.prompt ?? {}),\n instructions: [\n ...((root.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n graphBrief,\n ],\n },\n }\n\n // ── Steer + finding observation (delegates steers, analyzes traversals) ──\n // The filter seam: when the caller's authorizeMessage NARROWS an instruction, the delivered\n // bytes differ from the composed bytes — that steer traversal is `stripped` (the VB incident:\n // authored steering silently replaced by boilerplate, byte-indistinguishable downstream).\n const strippedByDigest = new Map<string, { composedBytes: number }>()\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const authorizeMessage: NonNullable<SuperviseOptions['authorizeMessage']> = (input) => {\n if (!opts.authorizeMessage) return { instruction: input.instruction }\n const decision = opts.authorizeMessage(input)\n if (decision.instruction !== input.instruction) {\n strippedByDigest.set(canonicalCandidateDigest(decision.instruction), {\n composedBytes: byteLength(input.instruction),\n })\n }\n return decision\n }\n\n const routedAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n const driverAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n for (const edge of analyzes) {\n ;(edge.to === root.id ? driverAnalyzesByAnalyst : routedAnalyzesByAnalyst).set(\n edge.analyst,\n edge,\n )\n }\n const analyzesCapReached = (edge: Extract<GraphEdge, { kind: 'analyzes' }>): boolean => {\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(edgeId(edge)) ?? 0\n if (used < cap) return false\n exhausted.add(edgeId(edge))\n return true\n }\n const ledgerAnalyzes = (\n edge: Extract<GraphEdge, { kind: 'analyzes' }>,\n outcome: EdgeDeliveryOutcome,\n bytes: number,\n reason: string | undefined,\n workerId: string | undefined,\n ): void => {\n const capped = analyzesCapReached(edge)\n record(\n {\n edge: edgeId(edge),\n kind: 'analyzes',\n from: edge.over.join('+'),\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: capped ? 'unpropagated' : outcome,\n // Every analyzes traversal is a mid-run delivery into an already-live recipient (a\n // routed steer leg, or the finding reaching the live driver) — never a spawn.\n continuity: 'steer',\n bytes,\n ...(capped\n ? {\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals ?? defaultEdgeTraversalCap})`,\n }\n : reason !== undefined\n ? { reason }\n : {}),\n ...(workerId !== undefined ? { workerId } : {}),\n },\n true,\n )\n }\n\n const onCoordinationEvent = async (\n _context: unknown,\n _eventId: unknown,\n recordEnvelope: { readonly event: CoordinationEvent },\n ): Promise<void> => {\n const event = recordEnvelope.event\n if (event.type === 'finding') {\n // A routed edge's traversal is ledgered on its STEER (the delivery); the finding event is\n // its audit copy. A driver-destined edge's traversal IS the finding reaching the bus.\n const edge = driverAnalyzesByAnalyst.get(event.finding.analyst)\n if (!edge) return\n const sourceNode = nodeByWorkerId.get(event.finding.fromWorker)\n if (sourceNode === undefined || !edge.over.includes(sourceNode)) return\n // Absent findings (the analyst returned `undefined` — the producer omits the key so the\n // event stays digestable) contribute ZERO bytes, never the text \"undefined\".\n const findingsText =\n event.finding.findings === undefined ? '' : stringifyPayload(event.finding.findings)\n const directiveBytes = byteLength(registry.resolve(edge.directive).text)\n const empty = findingsText.length === 0\n ledgerAnalyzes(\n edge,\n empty ? 'empty' : 'delivered',\n directiveBytes + byteLength(findingsText),\n empty ? 'analyst returned no findings' : undefined,\n event.finding.fromWorker,\n )\n return\n }\n if (event.type === 'steer') {\n const down = event.down\n if (event.analyst !== undefined) {\n const edge = routedAnalyzesByAnalyst.get(event.analyst)\n if (!edge) return\n ledgerAnalyzes(\n edge,\n down.delivered ? 'delivered' : 'unpropagated',\n byteLength(down.instruction),\n down.delivered ? undefined : down.outcome,\n down.toWorker,\n )\n return\n }\n // A driver-authored steer to a live worker node is a delegates traversal too — the\n // mid-run leg of the same edge (the leg the motivating incident lost).\n const nodeId = nodeByWorkerId.get(down.toWorker)\n if (nodeId === undefined) return\n const edge = delegatesByWorker.get(nodeId)\n if (!edge) return\n const stripped = strippedByDigest.get(down.instructionDigest)\n record(\n {\n edge: edgeId(edge),\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: !down.delivered ? 'unpropagated' : stripped ? 'stripped' : 'delivered',\n // The mid-run leg of the edge: a delivery into the LIVE worker, never a spawn.\n continuity: 'steer',\n bytes: byteLength(down.instruction),\n ...(!down.delivered\n ? { reason: down.outcome }\n : stripped\n ? { reason: `authorization narrowed ${stripped.composedBytes} composed bytes` }\n : {}),\n workerId: down.toWorker,\n },\n true,\n )\n }\n }\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks = {\n onEvent: (event: {\n target?: string\n phase?: string\n payload?: unknown\n }): void | Promise<void> => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n const pending = pendingByAssignment.get(payload.assignmentId)\n if (!pending) return\n pendingByAssignment.delete(payload.assignmentId)\n const bound: EdgeTraversal = { ...pending, workerId: payload.childId }\n ledger[ledger.indexOf(pending)] = bound\n nodeByWorkerId.set(payload.childId, bound.to)\n return appendJournal(bound, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // Every forwarded option the caller set, including the ones nobody thought to list here.\n // `backend` rides along: the kernel derives every authorized LEAF from it, under the graph's\n // pinning. The root driver stays an explicit `driverBackend` choice: `rootDriverFromBackend:\n // false` stops supervise() defaulting one from the other, so where workers run never selects\n // where the root runs (the axis split every graph caller relies on).\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: false,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: graph.deliverable,\n authorizeSpawn: graphAuthorizeSpawn,\n resolveSpawnProfile,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent,\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(routes.length > 0\n ? { analyzeOnSettle: routes, ...(opts.analysts ? { analysts: opts.analysts } : {}) }\n : {}),\n ...(Object.keys(continuityByProfile).length > 0 ? { continuityByProfile } : {}),\n authorizeMessage,\n } satisfies SuperviseOptions\n const result =\n brain === undefined\n ? await supervise(rootProfile, graphTask(graph, root), superviseOptions)\n : await superviseWithTestBrain(rootProfile, graphTask(graph, root), {\n ...superviseOptions,\n brain,\n })\n\n // A spawn row is PROVISIONAL until the `agent.spawn` hook (fired synchronously once a worker\n // exists) binds it to a live worker id. A row still unbound here means the factory ran but no\n // NEW worker went live: the spawn was refused after the factory (identity conflict, runtime\n // floor) or a keyed re-spawn deduplicated to an already-completed result (prepare() runs the\n // factory, no hook fires). Both state the same truth every unpropagated row states — the\n // directive never reached a live worker — so rewrite rather than mint a new outcome. Then\n // settle every journal write, so the ledger's journal twin is complete when this returns.\n for (const pending of pendingByAssignment.values()) {\n const refused: EdgeTraversal = {\n ...pending,\n outcome: 'unpropagated',\n bytes: 0,\n reason: `no-live-worker-bound (spawn refused after the factory, or a keyed re-spawn deduplicated to a completed result; ${pending.bytes} composed bytes never crossed)`,\n }\n ledger[ledger.indexOf(pending)] = refused\n await appendJournal(refused, `graph:${refused.to}`)\n }\n pendingByAssignment.clear()\n await Promise.all(journalWrites)\n\n const exhaustedEdges = Object.freeze([...exhausted])\n const frozenLedger = Object.freeze(ledger.map((row) => Object.freeze({ ...row })))\n // A LIFECYCLE ending (caller abort, exhausted budget) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' || result.reason === 'budget-exhausted')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.size > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(Object.freeze([...exhaustedDelegates]), frozenLedger, result)\n }\n return { result, ledger: frozenLedger, exhaustedEdges, runId }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the graph's deliverable by driving your worker nodes (root: '${root.id}').`\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwKA,MAAa,0BAA0B;;;AAIvC,IAAa,oBAAb,cAAuC,MAAM;CAC3C;CACA;CACA;CACA,YACE,gBACA,QACA,QACA;EACA,MACE,6CAA6C,eAAe,KAAK,IAAI,EAAE,2NAIzE;EACA,KAAK,OAAO;EACZ,KAAK,iBAAiB;EACtB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;;;;;AA2DA,MAAM,oCAAoC;CACxC;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;CACA;CACA;CACA;CACA;CACA;AACF;;;AAkBA,SAAS,0BACP,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OAAO,CAAC,GAAG,kBAAkB,CAAC,GAAG,cAAc,MAAM;EAE1F,OAAO;GAAE;GAAQ,QAAQ;GAAc;GAAgB;EAAM;CAC/D;CAEA,OAAO,MAAM;AACf;;;AAIA,SAAS,UAAU,OAAmB,MAAyB;CAE7D,OADiB,MAAM,YAAY,YAErB,wEAAwE,KAAK,GAAG;AAEhG"}
package/dist/graph.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph.js","names":[],"sources":["../src/runtime/graph/condition.ts","../src/runtime/graph/projection.ts","../src/runtime/graph/registry.ts","../src/runtime/graph/definition.ts","../src/runtime/graph/compile.ts","../src/runtime/graph/kind.ts","../src/runtime/graph/engine.ts","../src/runtime/graph/fold.ts","../src/runtime/graph/kinds.ts","../src/runtime/graph/scheduler.ts"],"sourcesContent":["/**\n * The ONE predicate tree: every guard in a graph — an edge `guard`, a filter projection's\n * predicate — is this shape, evaluated by this evaluator, so `contains`, ordering and equality can\n * never mean two different things on two surfaces (adopted from ADC's `workflow-conditions`,\n * agent-runtime#968). A declarative tree keeps an untrusted predicate incapable of code execution;\n * the size and depth bounds keep a predicate authored once from burning CPU on every settle.\n *\n * No zod: the kernel's grain is a hand-written validator that throws `ValidationError` by name.\n */\nimport { ValidationError } from '../../errors'\n\n/** The leaf comparison operators; `exists`/`truthy` are unary, the rest compare against `value`. */\nexport const CONDITION_OPS = [\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'in',\n 'contains',\n 'exists',\n 'truthy',\n] as const\nexport type ConditionOp = (typeof CONDITION_OPS)[number]\n\n/** Operators that compare against `value`; `exists`/`truthy` are unary and must omit it. */\nconst OPS_NEEDING_VALUE: ReadonlySet<ConditionOp> = new Set(\n CONDITION_OPS.filter((op) => op !== 'exists' && op !== 'truthy'),\n)\n\nexport interface ConditionLeaf {\n /** Dotted path with `[N]` indexing into the guard context, e.g. `out.findings[0].severity`. */\n readonly path: string\n readonly op: ConditionOp\n readonly value?: unknown\n}\n\nexport type Condition =\n | ConditionLeaf\n | { readonly all: ReadonlyArray<Condition> }\n | { readonly any: ReadonlyArray<Condition> }\n | { readonly not: Condition }\n\nexport const MAX_CONDITION_NODES = 40\nexport const MAX_CONDITION_DEPTH = 6\nconst MAX_PATH_LENGTH = 256\nconst MAX_PATH_SEGMENTS = 16\nconst PATH_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$-]*$/u\n\ntype PathStep = string | number\n\n/** Parse `a.b[0].c` into steps; refuse anything outside the bounded grammar. */\nexport function parseConditionPath(path: string, context: string): ReadonlyArray<PathStep> {\n if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH_LENGTH) {\n throw new ValidationError(\n `${context}: path must be a non-empty string of at most ${MAX_PATH_LENGTH} chars`,\n )\n }\n const steps: PathStep[] = []\n for (const part of path.split('.')) {\n const open = part.indexOf('[')\n const head = open === -1 ? part : part.slice(0, open)\n if (head.length > 0) {\n if (!PATH_SEGMENT.test(head)) {\n throw new ValidationError(\n `${context}: path segment ${JSON.stringify(head)} is not addressable`,\n )\n }\n steps.push(head)\n } else if (open !== 0 || steps.length === 0) {\n throw new ValidationError(`${context}: path ${JSON.stringify(path)} has an empty segment`)\n }\n let rest = open === -1 ? '' : part.slice(open)\n while (rest.length > 0) {\n const match = /^\\[(\\d{1,6})\\]/u.exec(rest)\n if (!match) {\n throw new ValidationError(`${context}: path index in ${JSON.stringify(part)} must be [N]`)\n }\n steps.push(Number(match[1]))\n rest = rest.slice(match[0].length)\n }\n if (steps.length > MAX_PATH_SEGMENTS) {\n throw new ValidationError(`${context}: path exceeds ${MAX_PATH_SEGMENTS} segments`)\n }\n }\n if (steps.length === 0) throw new ValidationError(`${context}: path resolves no segment`)\n return steps\n}\n\n/** Walk a parsed path; any miss resolves `undefined`, never a throw — absence is an answer. */\nexport function resolveConditionPath(context: unknown, steps: ReadonlyArray<PathStep>): unknown {\n let current: unknown = context\n for (const step of steps) {\n if (current === null || current === undefined) return undefined\n if (typeof step === 'number') {\n if (!Array.isArray(current)) return undefined\n current = current[step]\n } else {\n if (typeof current !== 'object' || Array.isArray(current)) return undefined\n current = (current as Record<string, unknown>)[step]\n }\n }\n return current\n}\n\nfunction isLeaf(condition: Condition): condition is ConditionLeaf {\n return typeof (condition as ConditionLeaf).path === 'string'\n}\n\n/** Validate shape, bounds, and per-leaf path/operator rules; returns the input for chaining. */\nexport function validateCondition(raw: unknown, context: string): Condition {\n let nodes = 0\n const walk = (value: unknown, depth: number): Condition => {\n nodes += 1\n if (nodes > MAX_CONDITION_NODES) {\n throw new ValidationError(`${context}: condition exceeds ${MAX_CONDITION_NODES} nodes`)\n }\n if (depth > MAX_CONDITION_DEPTH) {\n throw new ValidationError(`${context}: condition exceeds depth ${MAX_CONDITION_DEPTH}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: a condition must be an object`)\n }\n const record = value as Record<string, unknown>\n const combinators = ['all', 'any', 'not'].filter((key) => record[key] !== undefined)\n if (combinators.length > 1) {\n throw new ValidationError(\n `${context}: a condition carries ONE of all/any/not, got ${combinators.join('+')}`,\n )\n }\n if (record.all !== undefined || record.any !== undefined) {\n const key = record.all !== undefined ? 'all' : 'any'\n const branch = record[key]\n if (!Array.isArray(branch) || branch.length === 0) {\n throw new ValidationError(`${context}: ${key} must be a non-empty array`)\n }\n for (const child of branch) walk(child, depth + 1)\n return value as Condition\n }\n if (record.not !== undefined) {\n walk(record.not, depth + 1)\n return value as Condition\n }\n const op = record.op\n if (typeof record.path !== 'string' || typeof op !== 'string') {\n throw new ValidationError(`${context}: a leaf needs { path, op }`)\n }\n if (!(CONDITION_OPS as ReadonlyArray<string>).includes(op)) {\n throw new ValidationError(\n `${context}: unknown op ${JSON.stringify(op)}; known: ${CONDITION_OPS.join(', ')}`,\n )\n }\n parseConditionPath(record.path, context)\n const needsValue = OPS_NEEDING_VALUE.has(op as ConditionOp)\n if (needsValue && !('value' in record)) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} requires a value`)\n }\n if (!needsValue && 'value' in record) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} is unary — remove value`)\n }\n if (op === 'in' && !Array.isArray(record.value)) {\n throw new ValidationError(`${context}: op \"in\" takes an array value`)\n }\n return value as Condition\n }\n return walk(raw, 1)\n}\n\nfunction canonicalEquals(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n\nfunction ordering(op: 'gt' | 'gte' | 'lt' | 'lte', left: unknown, right: unknown): boolean {\n // Numbers order with numbers and strings with strings; a mixed or non-orderable pair is false,\n // never a coercion.\n if (typeof left === 'number' && typeof right === 'number') {\n if (Number.isNaN(left) || Number.isNaN(right)) return false\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n if (typeof left === 'string' && typeof right === 'string') {\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n return false\n}\n\n/** Walk a validated condition over a context to a boolean. Never throws on data shape. */\nexport function evaluateCondition(condition: Condition, context: unknown): boolean {\n if (isLeaf(condition)) {\n const resolved = resolveConditionPath(context, parseConditionPath(condition.path, 'evaluate'))\n switch (condition.op) {\n case 'exists':\n return resolved !== undefined && resolved !== null\n case 'truthy':\n return Boolean(resolved)\n case 'eq':\n return canonicalEquals(resolved, condition.value)\n case 'neq':\n return !canonicalEquals(resolved, condition.value)\n case 'in':\n return Array.isArray(condition.value)\n ? condition.value.some((candidate) => canonicalEquals(resolved, candidate))\n : false\n case 'contains':\n if (Array.isArray(resolved)) {\n return resolved.some((element) => canonicalEquals(element, condition.value))\n }\n return typeof resolved === 'string' && typeof condition.value === 'string'\n ? resolved.includes(condition.value)\n : false\n default:\n return ordering(condition.op, resolved, condition.value)\n }\n }\n if ('all' in condition) return condition.all.every((child) => evaluateCondition(child, context))\n if ('any' in condition) return condition.any.some((child) => evaluateCondition(child, context))\n return !evaluateCondition(condition.not, context)\n}\n","/**\n * The ONE pure projection a `data` edge may carry (agent-runtime#971): the bounded,\n * schema-preserving subset of ADC's collection helpers. Anything richer is a `script` NODE, so it\n * is journaled (`inputRef` → `outRef`), typed, and visible. Exactly one operator per projection.\n */\nimport { ValidationError } from '../../errors'\nimport {\n type Condition,\n evaluateCondition,\n parseConditionPath,\n resolveConditionPath,\n validateCondition,\n} from './condition'\n\nexport type Projection =\n | { readonly path: string }\n | { readonly pick: ReadonlyArray<string> }\n | { readonly map: string }\n | { readonly filter: Condition }\n | { readonly first: true }\n | { readonly last: true }\n | { readonly count: true }\n\nconst PROJECTION_KEYS = ['path', 'pick', 'map', 'filter', 'first', 'last', 'count'] as const\n\n/** Validate a projection: exactly one known operator, its argument well-formed. */\nexport function validateProjection(raw: unknown, context: string): Projection {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new ValidationError(`${context}: a projection must be an object`)\n }\n const record = raw as Record<string, unknown>\n const keys = PROJECTION_KEYS.filter((key) => record[key] !== undefined)\n const unknown = Object.keys(record).filter(\n (key) => !(PROJECTION_KEYS as ReadonlyArray<string>).includes(key),\n )\n if (unknown.length > 0) {\n throw new ValidationError(\n `${context}: unknown projection key(s) ${unknown.join(', ')}; known: ${PROJECTION_KEYS.join(', ')}`,\n )\n }\n if (keys.length !== 1) {\n throw new ValidationError(\n `${context}: a projection carries exactly ONE of ${PROJECTION_KEYS.join('/')}`,\n )\n }\n const key = keys[0]\n if (key === 'path' || key === 'map') parseConditionPath(record[key] as string, context)\n if (key === 'pick') {\n const fields = record.pick\n if (\n !Array.isArray(fields) ||\n fields.length === 0 ||\n fields.some((f) => typeof f !== 'string')\n ) {\n throw new ValidationError(`${context}: pick must be a non-empty array of field names`)\n }\n }\n if (key === 'filter') validateCondition(record.filter, context)\n if ((key === 'first' || key === 'last' || key === 'count') && record[key] !== true) {\n throw new ValidationError(`${context}: ${key} must be literally true`)\n }\n return raw as Projection\n}\n\n/**\n * Apply a validated projection to an admitted payload. Collection operators over a non-array\n * refuse by name — a shape the author did not expect is a graph defect, not an empty result.\n */\nexport function applyProjection(value: unknown, projection: Projection, context: string): unknown {\n if ('path' in projection) {\n return resolveConditionPath(value, parseConditionPath(projection.path, context))\n }\n if ('pick' in projection) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: pick needs an object payload`)\n }\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const field of projection.pick) if (field in record) out[field] = record[field]\n return out\n }\n const collection = value\n if (!Array.isArray(collection)) {\n throw new ValidationError(`${context}: this projection needs an array payload`)\n }\n if ('map' in projection) {\n const steps = parseConditionPath(projection.map, context)\n return collection.map((element) => resolveConditionPath(element, steps))\n }\n if ('filter' in projection) {\n return collection.filter((element) => evaluateCondition(projection.filter, element))\n }\n if ('first' in projection) return collection[0]\n if ('last' in projection) return collection[collection.length - 1]\n return collection.length\n}\n","/**\n * `Registry<T>` — the ONE name→thing shape for the graph engine.\n *\n * The kernel grew fourteen of these (agent-runtime#978) that differ in three properties:\n * whether names can be listed, what a miss does, and whether the table is global. This one\n * fixes all three — enumerable, a miss is refused BY NAME listing what is registered, and every\n * registry is per-instance — and it is lifted from `AgentEnvironmentProviderRegistry`, the\n * richest and best-tested of the fourteen, not invented.\n *\n * Entries are addressed by a versioned handle, `<id>/v<n>`, the same way the prompt registry\n * addresses directives. A graph names a kind by handle; a host registers exact versions; a\n * missing version is refused, never served by a newer one.\n */\n\nimport { ValidationError } from '../../errors'\n\n/** A versioned name: what a graph writes and what a host registers. */\nexport interface RegistryHandle {\n readonly id: string\n readonly version: number\n}\n\n/** `<id>/v<n>` — the only spelling a handle has on the wire, in a journal, or in an error. */\nexport function formatRegistryHandle(handle: RegistryHandle): string {\n return `${handle.id}/v${handle.version}`\n}\n\n/** Parse the wire spelling back. Refuses anything that is not exactly `<id>/v<n>`. */\nexport function parseRegistryHandle(text: string, context: string): RegistryHandle {\n const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)\\/v(\\d+)$/u.exec(text)\n if (!match) {\n throw new ValidationError(\n `${context}: ${JSON.stringify(text)} is not a registry handle; expected \"<id>/v<n>\"`,\n )\n }\n const version = Number(match[2])\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new ValidationError(`${context}: handle version must be a positive integer`)\n }\n return { id: match[1] as string, version }\n}\n\n/** Anything a registry holds carries its own handle, so the table cannot drift from the entry. */\nexport interface Registered extends RegistryHandle {}\n\nexport interface Registry<T extends Registered> {\n /** Add one entry. A second entry under the same handle is refused unless `replace` is set —\n * silently shadowing a registered kind is how a key no caller could produce once survived. */\n register(entry: T, options?: { readonly replace?: boolean }): void\n has(handle: RegistryHandle): boolean\n get(handle: RegistryHandle): T | undefined\n /** The entry, or a refusal that names the handle AND lists every registered handle — a miss\n * must be diagnosable from its message alone. */\n require(handle: RegistryHandle, context?: string): T\n /** Every registered handle, sorted, as wire spellings. The thing the fourteen predecessors\n * mostly could not do and four callers needed. */\n names(): string[]\n /** Every entry, in `names()` order. */\n entries(): T[]\n}\n\n/**\n * Create a registry. Per-instance by construction: two engines in one process may hold\n * different kind sets, a test is hermetic, and a run can print its own table. There is\n * deliberately no module-level singleton — `builtinShapes` was the one mutable global in the\n * kernel and it had zero tests.\n */\nexport function createRegistry<T extends Registered>(\n label: string,\n seed: Iterable<T> = [],\n): Registry<T> {\n const table = new Map<string, T>()\n const registry: Registry<T> = {\n register(entry, options = {}): void {\n if (typeof entry.id !== 'string' || entry.id.length === 0) {\n throw new ValidationError(`${label}: an entry must carry a non-empty id`)\n }\n if (!Number.isSafeInteger(entry.version) || entry.version < 1) {\n throw new ValidationError(\n `${label}: ${JSON.stringify(entry.id)} must carry a positive integer version`,\n )\n }\n const key = formatRegistryHandle(entry)\n if (!options.replace && table.has(key)) {\n throw new ValidationError(`${label}: ${JSON.stringify(key)} is already registered`)\n }\n table.set(key, entry)\n },\n has(handle): boolean {\n return table.has(formatRegistryHandle(handle))\n },\n get(handle): T | undefined {\n return table.get(formatRegistryHandle(handle))\n },\n require(handle, context = label): T {\n const key = formatRegistryHandle(handle)\n const entry = table.get(key)\n if (entry === undefined) {\n const known = registry.names()\n const suffix =\n known.length > 0 ? `; registered: ${known.join(', ')}` : '; nothing is registered'\n throw new ValidationError(`${context}: ${JSON.stringify(key)} is not registered${suffix}`)\n }\n return entry\n },\n names(): string[] {\n return Array.from(table.keys()).sort()\n },\n entries(): T[] {\n return registry.names().map((key) => table.get(key) as T)\n },\n }\n for (const entry of seed) registry.register(entry)\n return registry\n}\n","/**\n * The authored form of an engine graph (agent-runtime#971, #973, #968): typed-port nodes over\n * three edge kinds, each guardable by the one predicate tree; `data` edges may carry one pure\n * projection. ADC's `${steps.<id>.field}` strings are an AUTHORING surface that compiles down to\n * these port references — this is the runtime form, checked before any spend.\n */\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { PromptHandle } from '../supervise/prompt-registry'\nimport type { Budget } from '../supervise/types'\nimport { type Condition, validateCondition } from './condition'\nimport type { NodeFlags, PortSpec } from './kind'\nimport { type Projection, validateProjection } from './projection'\nimport { parseRegistryHandle, type RegistryHandle } from './registry'\n\n/** Which gating-edge outcomes release a node (adopted from ADC, agent-runtime#968). */\nexport const JOIN_RULES = ['all', 'any', 'any_failed', 'all_done'] as const\nexport type JoinRule = (typeof JOIN_RULES)[number]\n\n/** ADC-compatible visit backstop: nothing may be ENTERED more than this many times. */\nexport const DEFAULT_MAX_NODE_VISITS = 25\n/** The hard ceiling an author's `maxVisits`/`maxNodeVisits` override may reach. */\nexport const MAX_MAX_NODE_VISITS = 100\n\nexport type GraphEdgeKind = 'delegates' | 'analyzes' | 'data'\n\nexport interface EngineGraphNode {\n readonly id: string\n /** `<id>/v<n>` into the engine's kind registry. */\n readonly kind: string\n /** This node's config, validated by its kind's `validateConfig` at compile. */\n readonly config?: unknown\n /** Per-node flags — properties of the node, never of its kind (agent-runtime#970). */\n readonly flags?: NodeFlags\n /** Node-level port declarations, merged OVER the kind's. A kind whose surface depends on its\n * config (a script) declares ports here; a typed kind's declared ports stay authoritative. */\n readonly ports?: {\n readonly inputs?: ReadonlyArray<PortSpec>\n readonly outputs?: ReadonlyArray<PortSpec>\n }\n /** Which inbound gating-edge outcomes release this node. Default `all`. */\n readonly join?: JoinRule\n /** Entered more than this many times fails the run `cycle-budget-exceeded`. */\n readonly maxVisits?: number\n /** This node's completion check; a terminal without one (or a kind/graph default) refuses. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Force-mark a terminal. Absent, a node with no outbound gating edge is terminal. */\n readonly terminal?: boolean\n /** Profile fields merged over the engine-authored `{ name: id }` for this node's spawns. */\n readonly profile?: Readonly<Partial<AgentProfile>>\n /** Per-instance reservation for this node's spawns; falls back to the run's `perNode`. */\n readonly budget?: Budget\n}\n\nexport interface EngineGraphEdge {\n /** Stable id for the ledger; defaults to `<from>-><to>#<ordinal>`. */\n readonly id?: string\n readonly kind: GraphEdgeKind\n readonly from: { readonly node: string; readonly port?: string }\n readonly to: { readonly node: string; readonly port?: string }\n /** Evaluated over the source's settle context; absent = satisfied by completion. */\n readonly guard?: Condition\n /** `data` edges only: ONE pure reshape of the admitted payload. */\n readonly projection?: Projection\n /** Refuses the traversal past this many firings (ledgered `unpropagated`). */\n readonly maxTraversals?: number\n /** `delegates`/`analyzes`: the versioned directive appended to the target's task. */\n readonly directive?: PromptHandle\n}\n\nexport interface EngineGraphSpec {\n readonly nodes: ReadonlyArray<EngineGraphNode>\n readonly edges: ReadonlyArray<EngineGraphEdge>\n /** Root node for the graph-level completion check. Defaults to the single entry node. */\n readonly root?: string\n /** Becomes the ROOT node's completion check when the root declares none (#973). */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly maxNodeVisits?: number\n}\n\nexport interface ParsedGraphNode extends EngineGraphNode {\n readonly kindHandle: RegistryHandle\n readonly join: JoinRule\n readonly maxVisits: number\n}\n\n/** Structural validation only — everything a registry is not needed for. */\nexport function validateEngineGraphSpec(spec: EngineGraphSpec, context = 'compileGraph'): void {\n if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) {\n throw new ValidationError(`${context}: a graph needs at least one node`)\n }\n const ids = new Set<string>()\n for (const node of spec.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError(`${context}: every node needs a non-empty id`)\n }\n if (ids.has(node.id))\n throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`)\n ids.add(node.id)\n parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`)\n if (node.join !== undefined && !(JOIN_RULES as ReadonlyArray<string>).includes(node.join)) {\n throw new ValidationError(\n `${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(', ')}`,\n )\n }\n if (node.maxVisits !== undefined) {\n if (\n !Number.isSafeInteger(node.maxVisits) ||\n node.maxVisits < 1 ||\n node.maxVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: node ${node.id} maxVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n }\n if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`)\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}]`\n if (edge.kind !== 'delegates' && edge.kind !== 'analyzes' && edge.kind !== 'data') {\n throw new ValidationError(`${who}: kind must be delegates | analyzes | data`)\n }\n for (const end of ['from', 'to'] as const) {\n const ref = edge[end]\n if (\n typeof ref !== 'object' ||\n ref === null ||\n typeof ref.node !== 'string' ||\n !ids.has(ref.node)\n ) {\n throw new ValidationError(`${who}: ${end}.node must name a node in this graph`)\n }\n }\n if (edge.guard !== undefined) validateCondition(edge.guard, `${who} guard`)\n if (edge.projection !== undefined) {\n if (edge.kind !== 'data') {\n throw new ValidationError(`${who}: only a data edge carries a projection`)\n }\n validateProjection(edge.projection, `${who} projection`)\n }\n if (edge.maxTraversals !== undefined) {\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 1) {\n throw new ValidationError(`${who}: maxTraversals must be a positive integer`)\n }\n }\n if (edge.kind === 'data' && edge.directive !== undefined) {\n throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`)\n }\n }\n if (spec.root !== undefined && !ids.has(spec.root)) {\n throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`)\n }\n if (spec.maxNodeVisits !== undefined) {\n if (\n !Number.isSafeInteger(spec.maxNodeVisits) ||\n spec.maxNodeVisits < 1 ||\n spec.maxNodeVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: maxNodeVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n}\n","/**\n * Compile an authored graph against an engine's kind registry into the schedulable form. Every\n * refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`\n * binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no\n * completion check (agent-runtime#971, #973).\n */\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport {\n DEFAULT_MAX_NODE_VISITS,\n type EngineGraphEdge,\n type EngineGraphSpec,\n type JoinRule,\n validateEngineGraphSpec,\n} from './definition'\nimport type { GraphEngine } from './engine'\nimport type { JsonSchema, NodeKind, PortSpec } from './kind'\nimport { formatRegistryHandle, parseRegistryHandle } from './registry'\n\n/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */\nexport const IMPLICIT_OUTPUT_PORTS = ['out', 'trace'] as const\n\nexport interface CompiledEdge {\n readonly id: string\n readonly spec: EngineGraphEdge\n readonly fromPort: string\n readonly toPort: string\n}\n\nexport interface CompiledNode {\n readonly id: string\n readonly kind: NodeKind\n readonly config: unknown\n readonly join: JoinRule\n readonly maxVisits: number\n readonly oracle: boolean\n readonly pure: boolean\n readonly terminal: boolean\n /** The check this node must pass to count DELIVERED; resolved per #973. */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly inbound: ReadonlyArray<CompiledEdge>\n readonly outbound: ReadonlyArray<CompiledEdge>\n readonly spec: EngineGraphSpec['nodes'][number]\n}\n\nexport interface CompiledGraph {\n readonly nodes: ReadonlyMap<string, CompiledNode>\n readonly edges: ReadonlyArray<CompiledEdge>\n readonly entries: ReadonlyArray<string>\n readonly terminals: ReadonlyArray<string>\n readonly root: string\n readonly maxNodeVisits: number\n}\n\ntype NodePorts = {\n readonly inputs: ReadonlyArray<PortSpec>\n readonly outputs: ReadonlyArray<PortSpec>\n}\n\n/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */\nfunction nodePorts(kind: NodeKind, node: EngineGraphSpec['nodes'][number]): NodePorts {\n const merge = (\n declared: ReadonlyArray<PortSpec>,\n own: ReadonlyArray<PortSpec> | undefined,\n ): ReadonlyArray<PortSpec> => {\n if (own === undefined || own.length === 0) return declared\n const names = new Set(own.map((port) => port.name))\n return [...own, ...declared.filter((port) => !names.has(port.name))]\n }\n return {\n inputs: merge(kind.inputs, node.ports?.inputs),\n outputs: merge(kind.outputs, node.ports?.outputs),\n }\n}\n\nfunction outputPort(ports: NodePorts, port: string): PortSpec | undefined {\n if ((IMPLICIT_OUTPUT_PORTS as ReadonlyArray<string>).includes(port)) {\n return { name: port, schema: {} }\n }\n return ports.outputs.find((candidate) => candidate.name === port)\n}\n\nfunction inputPort(ports: NodePorts, port: string): PortSpec | undefined {\n return ports.inputs.find((candidate) => candidate.name === port)\n}\n\n/**\n * Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no\n * `type` accept anything; object targets require their `required` properties to be present and\n * accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,\n * not a full JSON Schema validator.\n */\nexport function schemaAccepts(source: JsonSchema, target: JsonSchema, depth = 0): boolean {\n if (depth > 6) return true\n const sourceType = source.type\n const targetType = target.type\n if (targetType === undefined || sourceType === undefined) return true\n const targets = Array.isArray(targetType) ? targetType : [targetType]\n const sources = Array.isArray(sourceType) ? sourceType : [sourceType]\n const overlap = sources.filter(\n (candidate) =>\n targets.includes(candidate === 'integer' ? 'number' : candidate) ||\n targets.includes(candidate),\n )\n if (overlap.length === 0) return false\n if (targets.includes('object') && sources.includes('object')) {\n const required = Array.isArray(target.required) ? (target.required as string[]) : []\n const sourceProps = source.properties as Record<string, JsonSchema> | undefined\n const targetProps = target.properties as Record<string, JsonSchema> | undefined\n if (sourceProps !== undefined) {\n for (const name of required) {\n const sourceProp = sourceProps[name]\n if (sourceProp === undefined) return false\n const targetProp = targetProps?.[name]\n if (targetProp !== undefined && !schemaAccepts(sourceProp, targetProp, depth + 1)) {\n return false\n }\n }\n }\n }\n if (targets.includes('array') && sources.includes('array')) {\n const sourceItems = source.items as JsonSchema | undefined\n const targetItems = target.items as JsonSchema | undefined\n if (sourceItems !== undefined && targetItems !== undefined) {\n return schemaAccepts(sourceItems, targetItems, depth + 1)\n }\n }\n return true\n}\n\n/**\n * Lower an authored graph against an engine's kind registry into the schedulable form, refusing\n * every structural defect before any spend.\n */\nexport function compileGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec,\n context = 'compileGraph',\n): CompiledGraph {\n validateEngineGraphSpec(spec, context)\n const kinds = new Map<string, NodeKind>()\n const configs = new Map<string, unknown>()\n for (const node of spec.nodes) {\n const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`)\n const kind = engine.kinds.require(handle, `${context}: node ${node.id}`)\n kinds.set(node.id, kind)\n configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`))\n if (node.flags?.pure && kind.id !== 'script') {\n throw new ValidationError(\n `${context}: node ${node.id} sets pure, which only a script node may claim`,\n )\n }\n }\n\n const compiledEdges: CompiledEdge[] = []\n const inbound = new Map<string, CompiledEdge[]>()\n const outbound = new Map<string, CompiledEdge[]>()\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`\n const fromKind = kinds.get(edge.from.node)\n const toKind = kinds.get(edge.to.node)\n if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`)\n const toNode = spec.nodes.find((node) => node.id === edge.to.node)\n if (edge.kind !== 'analyzes' && toNode?.flags?.oracle) {\n // An edge to a grader leaks the rubric: an oracle is bound only by `analyzes`.\n throw new ValidationError(\n `${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`,\n )\n }\n const fromPort = edge.from.port ?? (edge.kind === 'analyzes' ? 'trace' : 'out')\n if (edge.kind === 'analyzes' && fromPort !== 'trace') {\n throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`)\n }\n const fromNode = spec.nodes.find((node) => node.id === edge.from.node)\n const fromPorts = nodePorts(fromKind, fromNode as EngineGraphSpec['nodes'][number])\n const toPorts = nodePorts(toKind, toNode as EngineGraphSpec['nodes'][number])\n const sourcePort = outputPort(fromPorts, fromPort)\n if (!sourcePort) {\n const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)]\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(', ')}`,\n )\n }\n let toPort = edge.to.port ?? ''\n if (edge.kind === 'data') {\n if (toPort === '') {\n if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? ''\n else {\n throw new ValidationError(\n `${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`,\n )\n }\n }\n const targetPort = inputPort(toPorts, toPort)\n if (!targetPort) {\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(', ') || '(none)'}`,\n )\n }\n // A projection reshapes the payload, so the source schema no longer describes it; the\n // projected shape is checked at admission, not statically.\n if (edge.projection === undefined && !schemaAccepts(sourcePort.schema, targetPort.schema)) {\n throw new ValidationError(\n `${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? 'any')}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? 'any')})`,\n )\n }\n }\n const compiled: CompiledEdge = {\n id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,\n spec: edge,\n fromPort,\n toPort: toPort === '' ? 'out' : toPort,\n }\n compiledEdges.push(compiled)\n outbound.set(edge.from.node, [...(outbound.get(edge.from.node) ?? []), compiled])\n inbound.set(edge.to.node, [...(inbound.get(edge.to.node) ?? []), compiled])\n }\n const dupes = new Set<string>()\n for (const edge of compiledEdges) {\n if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`)\n dupes.add(edge.id)\n }\n\n const entries = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (entries.length === 0) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (entries.length === 1\n ? (entries[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${entries.length} entry nodes (${entries.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n\n const nodes = new Map<string, CompiledNode>()\n const terminals: string[] = []\n for (const node of spec.nodes) {\n const kind = kinds.get(node.id)\n if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`)\n const terminal = node.terminal ?? (outbound.get(node.id) ?? []).length === 0\n const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : undefined)\n if (terminal) terminals.push(node.id)\n nodes.set(node.id, {\n id: node.id,\n kind,\n config: configs.get(node.id),\n join: node.join ?? 'all',\n maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n oracle: node.flags?.oracle ?? false,\n pure: node.flags?.pure ?? false,\n terminal,\n ...(deliverable === undefined ? {} : { deliverable }),\n inbound: inbound.get(node.id) ?? [],\n outbound: outbound.get(node.id) ?? [],\n spec: node,\n })\n }\n const unchecked = terminals.filter((id) => nodes.get(id)?.deliverable === undefined)\n if (unchecked.length === terminals.length) {\n // Termination is mandatory per terminal (#973): a graph none of whose terminals declares a\n // completion check (own, or the graph's on the root) can never prove it is done.\n throw new ValidationError(\n `${context}: no terminal declares a completion check (terminals: ${terminals.join(', ')}); give a node a deliverable or set spec.deliverable`,\n )\n }\n return {\n nodes,\n edges: compiledEdges,\n entries: entries.map((node) => node.id),\n terminals,\n root,\n maxNodeVisits: spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n }\n}\n","/**\n * `NodeKind` — what a consumer registers to add a node kind to the graph engine without forking\n * it (agent-runtime#969, #970).\n *\n * The engine owns the graph: scheduling over typed data edges, guards, joins, cycles, the\n * conserved pool, the journal. It does NOT own execution — `run` returns an `Agent`, the\n * kernel's spawn contract (`Scope.spawn` takes an `Agent { name, act }`; a leaf `Agent` carries its\n * `Executor` as `executorSpec: AgentSpec`, and a supervisor `Agent` is `supervisorAgent(...)`). So\n * every node rides `supervise()`'s machinery unchanged: the pool's reserve/reconcile, the\n * content-addressed journal, the completion gate, `Settled`, trace evidence. An engine that\n * re-implemented any of those would be a second kernel.\n *\n * Every kernel-owned extension contract is a TS interface plus a hand-written validator that\n * throws `ValidationError` by name (the kernel has no zod), and this one follows suit. JSON Schema\n * is the PORTABLE form of a config/port shape — a `Record<string, unknown>`, as `McpToolDescriptor`\n * and `DeliveryBinding` already spell it — so a kind's declaration can be published in a manifest\n * and lifted by a host on another stack.\n *\n * The bar this file is measured against: the scheduler's source names no kind that is not\n * universal. A kind the engine ships (`agent`, `supervisor`, `subgraph`, `script`) is universal by\n * the rule \"the model cannot decide it with the verbs it has\"; everything else — integrations,\n * notifications, sandbox provisioning, human decisions — is registered by a host.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport type { Agent } from '../supervise/types'\nimport type { Registered, RegistryHandle } from './registry'\n\n/** A JSON Schema document as the kernel already spells it: an opaque record, validated by the\n * consumer's own validator, published verbatim. */\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\n/**\n * One declared port on a node. Ports are how a `data` edge binds one node's output to another's\n * input with a type the compiler can check structurally before any spend. A node has two implicit\n * output ports beside its declared ones: `out` (its result) and `trace` (its `WorkerTraceEvidence`\n * by `traceRef`); only an `analyzes` edge may bind `trace`.\n */\nexport interface PortSpec {\n readonly name: string\n readonly schema: JsonSchema\n readonly description?: string\n}\n\n/**\n * What a kind declares it needs from the host. The engine never imports a host capability; it\n * knows only that a kind SAID it needs something under this name and the host PROVIDED something\n * under it. The context a kind receives is narrowed to exactly its declaration — an undeclared\n * effect is `undefined`, never a service locator.\n */\nexport type EffectName = string\n\nexport type EffectContext<Effects extends ReadonlyArray<EffectName>> = Readonly<{\n [K in Effects[number]]: unknown\n}>\n\n/**\n * What happens to a node that was IN FLIGHT when the process died. A settled node is never a\n * per-kind choice — it restores from its content-addressed `outRef` on replay. `'restart'` re-runs\n * from the journaled `inputRef`; `'resume'` is legal only for a kind whose executor can re-attach\n * to the live process (the bridge backend's session re-attachment is the existing instance).\n */\nexport type OnCrash = 'restart' | 'resume'\n\n/**\n * Whether a kind's spend enters the conserved pool. `'metered'`: the executor reports `Spend` and\n * settling without one is an ENGINE ERROR — never \"free\". `'exempt'`: the whole reservation is\n * refunded on settle, keeping the node out of Σk by construction (the kernel's `budgetExempt`).\n */\nexport type BudgetMode = 'metered' | 'exempt'\n\n/** The validated declaration every kind provides. `Config` is the per-node config shape;\n * `Effects` is the tuple of host capabilities it declares, so the context `run` receives is typed\n * to exactly that tuple. */\nexport interface NodeKind<\n Config = unknown,\n Effects extends ReadonlyArray<EffectName> = ReadonlyArray<EffectName>,\n> extends Registered {\n /** Kind id, e.g. `agent`, `integration.invoke`. With `version`, forms the handle `<id>/v<n>`. */\n readonly id: string\n readonly version: number\n readonly description: string\n /** Validate and narrow one node's config. Throw `ValidationError` to refuse; the compiler\n * surfaces the message with the node id prefixed. */\n readonly validateConfig: (raw: unknown, context: string) => Config\n /** The portable form of `validateConfig`'s accepted shape, for manifests and hosts. */\n readonly configSchema: JsonSchema\n /** Declared input ports; a `data` edge may bind only these. Empty for a source node. */\n readonly inputs: ReadonlyArray<PortSpec>\n /** Declared output ports beside the implicit `out` and `trace`. */\n readonly outputs: ReadonlyArray<PortSpec>\n /** Host capabilities this kind reaches for, by name. The context is narrowed to exactly these. */\n readonly effects: Effects\n readonly onCrash: OnCrash\n readonly budget: BudgetMode\n /**\n * Build the agent for one node instance. The kernel spawns it under `Scope.spawn`, so it is\n * authorized, classified, journaled, pooled and gated like any child — the kind owns only what\n * the agent DOES. `profile` is the node's pinned profile (an `agent`/`supervisor` kind runs it;\n * a `script` kind may ignore it); `inputs` are the resolved, content-addressed port values;\n * `effects` is the narrowed host context; `spawn` is the kernel's per-spawn context when the\n * kind needs it (a supervisor kind threads it into `nodeContext`).\n */\n readonly run: (args: {\n readonly config: Config\n readonly profile: AgentProfile\n readonly inputs: Readonly<Record<string, unknown>>\n readonly effects: EffectContext<Effects>\n readonly spawn?: WorkerSpawnContext\n }) => Agent<unknown, unknown>\n}\n\n/** Per-node flags a graph author sets; they are node properties, not kinds (agent-runtime#970). */\nexport interface NodeFlags {\n /** An oracle — a judge, grader, auditor, trace analyst — may be bound only by an `analyzes`\n * edge. The compiler refuses a `delegates` or `data` edge INTO an oracle: an edge to a grader\n * leaks the rubric. */\n readonly oracle?: boolean\n /** `script` only: pure over `(config, inputs)` ⇒ budget exempt, output restorable on replay,\n * runs in-process. A pure script that settles with a different `outRef` for the same inputs\n * has lied, and the first replay mismatch is an engine error. */\n readonly pure?: boolean\n}\n\n/** Validate a kind declaration at registration — so a malformed kind is refused by name once,\n * not at the first node that uses it. */\nexport function validateNodeKind(kind: NodeKind, context = 'registerNodeKind'): NodeKind {\n const who = `${context}: kind ${JSON.stringify(`${kind.id}/v${kind.version}`)}`\n if (typeof kind.id !== 'string' || kind.id.length === 0) {\n throw new ValidationError(`${context}: a kind must carry a non-empty id`)\n }\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(kind.id)) {\n throw new ValidationError(`${who}: id may contain only letters, digits, \".\", \"_\" and \"-\"`)\n }\n if (!Number.isSafeInteger(kind.version) || kind.version < 1) {\n throw new ValidationError(`${who}: version must be a positive integer`)\n }\n if (typeof kind.description !== 'string' || kind.description.trim().length === 0) {\n throw new ValidationError(`${who}: description is required`)\n }\n if (typeof kind.validateConfig !== 'function') {\n throw new ValidationError(`${who}: validateConfig must be a function`)\n }\n if (!isRecord(kind.configSchema)) {\n throw new ValidationError(`${who}: configSchema must be a JSON Schema object`)\n }\n for (const [field, ports] of [\n ['inputs', kind.inputs],\n ['outputs', kind.outputs],\n ] as const) {\n if (!Array.isArray(ports)) throw new ValidationError(`${who}: ${field} must be an array`)\n const seen = new Set<string>()\n for (const port of ports) {\n if (!port || typeof port.name !== 'string' || port.name.length === 0) {\n throw new ValidationError(`${who}: every ${field} port needs a non-empty name`)\n }\n if (field === 'outputs' && (port.name === 'out' || port.name === 'trace')) {\n throw new ValidationError(\n `${who}: output port ${JSON.stringify(port.name)} is implicit on every node and cannot be declared`,\n )\n }\n if (seen.has(port.name)) {\n throw new ValidationError(`${who}: duplicate ${field} port ${JSON.stringify(port.name)}`)\n }\n seen.add(port.name)\n if (!isRecord(port.schema)) {\n throw new ValidationError(\n `${who}: ${field} port ${JSON.stringify(port.name)} needs a JSON Schema`,\n )\n }\n }\n }\n if (\n !Array.isArray(kind.effects) ||\n kind.effects.some((e) => typeof e !== 'string' || e.length === 0)\n ) {\n throw new ValidationError(`${who}: effects must be an array of non-empty names`)\n }\n if (new Set(kind.effects).size !== kind.effects.length) {\n throw new ValidationError(`${who}: effects must not repeat a name`)\n }\n if (kind.onCrash !== 'restart' && kind.onCrash !== 'resume') {\n throw new ValidationError(`${who}: onCrash must be \"restart\" or \"resume\"`)\n }\n if (kind.budget !== 'metered' && kind.budget !== 'exempt') {\n throw new ValidationError(`${who}: budget must be \"metered\" or \"exempt\"`)\n }\n if (typeof kind.run !== 'function') {\n throw new ValidationError(`${who}: run must be a function`)\n }\n return kind\n}\n\n/** The handle a graph writes to name this kind. */\nexport function kindHandle(kind: Pick<NodeKind, 'id' | 'version'>): RegistryHandle {\n return { id: kind.id, version: kind.version }\n}\n\n/**\n * Narrow a host's effect table to exactly what one kind declared. Anything the kind did not\n * declare is absent — `undefined` on read — so a kind cannot reach past its declaration, and the\n * engine can list a graph's required effects before spending a token.\n */\nexport function narrowEffects<Effects extends ReadonlyArray<EffectName>>(\n declared: Effects,\n provided: Readonly<Record<string, unknown>>,\n context: string,\n): EffectContext<Effects> {\n const out: Record<string, unknown> = {}\n const missing: string[] = []\n for (const name of declared) {\n if (!(name in provided)) {\n missing.push(name)\n continue\n }\n out[name] = provided[name]\n }\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: host provides no effect for ${missing.map((m) => JSON.stringify(m)).join(', ')}; provided: ${\n Object.keys(provided).sort().join(', ') || 'none'\n }`,\n )\n }\n return Object.freeze(out) as EffectContext<Effects>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * `createGraphEngine` — one engine instance: its kind registry (core kinds pre-registered, host\n * kinds added by the caller), its effect table, and nothing global.\n *\n * The scheduler (#980), journal fold (#981) and the `runGraph` preset (#982) attach here; this\n * file is the part that must exist first so a host can register kinds and a compiler can ask\n * \"which effects does this graph need\" before a token is spent.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { EffectName, NodeKind } from './kind'\nimport { validateNodeKind } from './kind'\nimport { createRegistry, type Registry } from './registry'\n\nexport interface GraphEngineOptions {\n /** Kinds to register beside the core set. A host adds its own here; nothing is global. */\n readonly kinds?: ReadonlyArray<NodeKind>\n /** The host's effect table, by name. A kind receives only the effects it declared. */\n readonly effects?: Readonly<Record<EffectName, unknown>>\n /** The core set. Injected so a test can substitute, and so the engine never imports a\n * backend-specific factory at module load. */\n readonly coreKinds: ReadonlyArray<NodeKind>\n}\n\nexport interface GraphEngine {\n readonly kinds: Registry<NodeKind>\n readonly effects: Readonly<Record<EffectName, unknown>>\n /** Every effect name any registered kind declares — what a host must provide for this engine's\n * whole kind set to be runnable. Listed, never discovered mid-run. */\n requiredEffects(): string[]\n /** The declared effects no host value covers. Empty means every registered kind is runnable. */\n missingEffects(): string[]\n}\n\n/**\n * Build one engine: a kind registry seeded with the core kinds plus the host's, and the host's\n * effect values. Every kind is validated by name at construction, so a malformed host kind fails\n * here, never at its first node.\n */\nexport function createGraphEngine(options: GraphEngineOptions): GraphEngine {\n const kinds = createRegistry<NodeKind>('graph kinds')\n for (const kind of options.coreKinds) kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n for (const kind of options.kinds ?? [])\n kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n const effects = Object.freeze({ ...(options.effects ?? {}) })\n if (Object.keys(effects).some((name) => name.length === 0)) {\n throw new ValidationError('createGraphEngine: an effect name must be non-empty')\n }\n const engine: GraphEngine = {\n kinds,\n effects,\n requiredEffects(): string[] {\n const names = new Set<string>()\n for (const kind of kinds.entries()) for (const name of kind.effects) names.add(name)\n return Array.from(names).sort()\n },\n missingEffects(): string[] {\n return engine.requiredEffects().filter((name) => !(name in effects))\n },\n }\n return engine\n}\n","/**\n * The fold (agent-runtime#974): scheduler state is a pure function of the journal, reconstructed\n * by replaying events through the SAME reducer the live scheduler feeds — fold, never checkpoint.\n * Kernel events (`spawned`, `settled`, `waiting`, `woken`) carry what the kernel owns; the engine's\n * events (`node-inputs-resolved`, `edge-verdict`, `join-state`) carry what the scheduler decided,\n * each journaled BEFORE its effect was visible. `edge` stays observability and is skipped here\n * exactly as the kernel's own replay skips it.\n *\n * Events are consumed in APPEND order (the journal file's line order), not by `seq`: kernel and\n * engine events carry independent ordinal counters, and append order is the one total order both\n * share.\n */\nimport { ValidationError } from '../../errors'\nimport type { SpawnEvent } from '../supervise/types'\nimport type { CompiledGraph } from './compile'\nimport type { GraphNodeSettle } from './scheduler-types'\n\nexport type FoldEdgeState = 'pending' | 'satisfied' | 'dead' | 'failed'\n\nexport interface FoldEdge {\n state: FoldEdgeState\n /** Set by a `join-state` whose wave this edge was pending inside; cleared when the in-flight\n * completion it refers to settles (absorbed, never re-released). */\n consumedOnce: boolean\n /** Delivered consumptions — what the per-edge cap counts. */\n traversals: number\n /** How many of the source's settles this edge has accounted for — by a journaled verdict or by\n * an absorption. The idempotence key: a kill between a settle and its verdicts re-judges ONLY\n * the unaccounted edges on restart, never a judged or absorbed one twice. */\n judgedSourceSettles: number\n /** The admitted source payload this state reflects (the source settle's outRef). */\n payloadRef?: string\n capped: boolean\n}\n\nexport type FoldInstanceStatus = 'released' | 'live' | 'done' | 'down' | 'suspended'\n\nexport interface FoldInstance {\n readonly node: string\n readonly instance: string\n readonly visit: number\n inputRef?: string\n status: FoldInstanceStatus\n settle?: GraphNodeSettle\n}\n\nexport interface FoldSuspension {\n readonly token: string\n readonly node: string\n readonly instance: string\n readonly onExpire: 'wait' | 'fail' | 'default'\n readonly expiresAtMs?: number\n readonly defaultRef?: string\n status: 'pending' | 'woken' | 'expired'\n}\n\nexport interface FoldNode {\n visits: number\n blocked: boolean\n settles: GraphNodeSettle[]\n}\n\nexport interface GraphFoldState {\n readonly nodes: Map<string, FoldNode>\n readonly edges: Map<string, FoldEdge>\n /** Every node instance the journal knows, keyed by `<node>#<visit>`. */\n readonly instances: Map<string, FoldInstance>\n /** Kernel node id → engine instance label, from `spawned`. */\n readonly spawnedIds: Map<string, string>\n readonly suspensions: Map<string, FoldSuspension>\n readonly exhaustedEdges: Set<string>\n}\n\n/** The reducer's zero: every node unvisited, every edge pending, nothing suspended. */\nexport function emptyFoldState(compiled: CompiledGraph): GraphFoldState {\n const nodes = new Map<string, FoldNode>()\n for (const id of compiled.nodes.keys()) nodes.set(id, { visits: 0, blocked: false, settles: [] })\n const edges = new Map<string, FoldEdge>()\n for (const edge of compiled.edges) {\n edges.set(edge.id, {\n state: 'pending',\n consumedOnce: false,\n traversals: 0,\n judgedSourceSettles: 0,\n capped: false,\n })\n }\n return {\n nodes,\n edges,\n instances: new Map(),\n spawnedIds: new Map(),\n suspensions: new Map(),\n exhaustedEdges: new Set(),\n }\n}\n\nfunction instanceOf(state: GraphFoldState, label: string): FoldInstance | undefined {\n return state.instances.get(label)\n}\n\n/**\n * Apply ONE journal event. The live scheduler calls this right after each append; the restart path\n * calls it over the loaded journal. Unknown kernel events are ignored — the engine folds only what\n * it understands, exactly as the kernel's replay skips the engine's events.\n */\nexport function applyGraphFoldEvent(\n state: GraphFoldState,\n ev: SpawnEvent,\n compiled: CompiledGraph,\n): void {\n switch (ev.kind) {\n case 'node-inputs-resolved': {\n const visit = Number(ev.instance.split('#').at(-1))\n if (!Number.isSafeInteger(visit)) {\n throw new ValidationError(`graph fold: instance ${ev.instance} carries no visit ordinal`)\n }\n state.instances.set(ev.instance, {\n node: ev.node,\n instance: ev.instance,\n visit,\n inputRef: ev.inputRef,\n status: 'released',\n })\n const node = state.nodes.get(ev.node)\n if (node) node.visits = Math.max(node.visits, visit)\n return\n }\n case 'spawned': {\n const instance = instanceOf(state, ev.label)\n if (instance) {\n instance.status = 'live'\n state.spawnedIds.set(ev.id, ev.label)\n }\n return\n }\n case 'settled': {\n const label = state.spawnedIds.get(ev.id)\n const instance = label === undefined ? undefined : instanceOf(state, label)\n if (!instance) return\n instance.status = ev.status\n const settle: GraphNodeSettle = {\n node: instance.node,\n visit: instance.visit,\n status: ev.status,\n ...(ev.outRef !== undefined ? { outRef: ev.outRef } : {}),\n ...(ev.reason !== undefined ? { reason: ev.reason } : {}),\n }\n if (ev.trace?.status === 'available') {\n ;(settle as { traceRef?: string }).traceRef = ev.trace.traceRef\n }\n instance.settle = settle\n state.nodes.get(instance.node)?.settles.push(settle)\n // The settle of an in-flight completion a wave already consumed re-arms its edges silently —\n // and counts as ACCOUNTED, so a restart never re-judges an absorbed completion.\n const node = compiled.nodes.get(instance.node)\n for (const edge of node?.outbound ?? []) {\n const folded = state.edges.get(edge.id)\n if (folded?.consumedOnce && folded.state === 'pending') {\n folded.consumedOnce = false\n folded.judgedSourceSettles += 1\n }\n }\n return\n }\n case 'edge-verdict': {\n const folded = state.edges.get(ev.edge)\n if (!folded) return\n if (ev.capped) {\n folded.capped = true\n state.exhaustedEdges.add(ev.edge)\n const target = compiled.edges.find((edge) => edge.id === ev.edge)?.spec.to.node\n const compiledTarget = target === undefined ? undefined : compiled.nodes.get(target)\n if (\n compiledTarget &&\n (compiledTarget.join === 'all' || compiledTarget.join === 'all_done')\n ) {\n const node = state.nodes.get(target as string)\n if (node) node.blocked = true\n }\n return\n }\n folded.judgedSourceSettles += 1\n if (!ev.fired) {\n folded.state = ev.sourceStatus === 'done' ? 'dead' : 'failed'\n folded.payloadRef = undefined\n return\n }\n folded.state = 'satisfied'\n folded.payloadRef = ev.inputRef\n return\n }\n case 'join-state': {\n // A release consumes its wave: delivered consumptions count a traversal and re-arm; every\n // gating edge still pending is consumed-once.\n for (const edgeId of ev.satisfiedBy) {\n const folded = state.edges.get(edgeId)\n if (!folded) continue\n folded.traversals += 1\n folded.state = 'pending'\n folded.payloadRef = undefined\n }\n const target = compiled.nodes.get(ev.node)\n for (const edge of target?.inbound ?? []) {\n const folded = state.edges.get(edge.id)\n if (!folded) continue\n if (ev.consumedPending.includes(edge.id)) folded.consumedOnce = true\n else if (folded.state !== 'pending' && !ev.satisfiedBy.includes(edge.id)) {\n // Settled but not part of the wave (an `any` join's losers): re-arm without a traversal.\n folded.state = 'pending'\n folded.payloadRef = undefined\n }\n }\n return\n }\n case 'waiting': {\n if (ev.spec.kind !== 'token') return\n const instance = instanceOf(state, ev.label)\n if (instance) {\n instance.status = 'suspended'\n // The kernel settle that surfaced the suspension marker is NOT a settle of this node —\n // retract it, so fold state matches what the live scheduler recorded (nothing).\n if (instance.settle !== undefined) {\n const settles = state.nodes.get(instance.node)?.settles\n if (settles && settles.at(-1) === instance.settle) settles.pop()\n instance.settle = undefined\n }\n }\n state.suspensions.set(ev.spec.token, {\n token: ev.spec.token,\n node: instance?.node ?? ev.label.split('#')[0] ?? ev.label,\n instance: ev.label,\n onExpire: ev.spec.onExpire,\n ...(ev.spec.expiresAtMs !== undefined ? { expiresAtMs: ev.spec.expiresAtMs } : {}),\n ...(ev.spec.defaultRef !== undefined ? { defaultRef: ev.spec.defaultRef } : {}),\n status: 'pending',\n })\n return\n }\n case 'woken': {\n // The engine wakes suspensions by token-shaped node id `graphwait:<token>`.\n const token = ev.id.startsWith('graphwait:') ? ev.id.slice('graphwait:'.length) : undefined\n const suspension = token === undefined ? undefined : state.suspensions.get(token)\n if (!suspension) return\n const instance = instanceOf(state, suspension.instance)\n if (ev.by === 'expired') {\n suspension.status = 'expired'\n if (instance) {\n instance.status = 'down'\n const settle: GraphNodeSettle = {\n node: suspension.node,\n visit: instance.visit,\n status: 'down',\n reason: 'suspension expired',\n }\n instance.settle = settle\n state.nodes.get(suspension.node)?.settles.push(settle)\n }\n return\n }\n suspension.status = 'woken'\n if (instance) {\n instance.status = 'done'\n const settle: GraphNodeSettle = {\n node: suspension.node,\n visit: instance.visit,\n status: 'done',\n ...(ev.outRef !== undefined ? { outRef: ev.outRef } : {}),\n }\n instance.settle = settle\n state.nodes.get(suspension.node)?.settles.push(settle)\n }\n return\n }\n default:\n return\n }\n}\n\n/** Fold a loaded journal (append order) into scheduler state. */\nexport function foldGraphJournal(\n events: ReadonlyArray<SpawnEvent>,\n compiled: CompiledGraph,\n): GraphFoldState {\n const state = emptyFoldState(compiled)\n for (const ev of events) applyGraphFoldEvent(state, ev, compiled)\n return state\n}\n","/**\n * The four core node kinds (agent-runtime#970) — the ones universal by the rule \"the model cannot\n * decide it with the verbs it has\". Everything else (integrations, notifications, sandbox\n * provisioning, human decisions) is registered by a host against the same `NodeKind` contract.\n *\n * Each `run` returns an `Agent` the kernel spawns under `Scope.spawn`; none of these re-implements\n * pooling, journaling, gating or identity. `agent` and `supervisor` are thin wraps over the\n * kernel's own factories; `script` is the one kind with no kernel primitive behind it; `subgraph`\n * is the scheduler's and is refused here until the scheduler lands (#980).\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { ExecutorConfig } from '../supervise/runtime'\nimport { workerFromBackend } from '../supervise/supervise'\nimport { type SupervisorAgentDeps, supervisorAgent } from '../supervise/supervisor-agent'\nimport type { Agent, AgentSpec, Executor, ExecutorResult, Spend } from '../supervise/types'\nimport type { NodeKind } from './kind'\nimport { formatRegistryHandle, type RegistryHandle } from './registry'\n\n// ── agent ───────────────────────────────────────────────────────────────────────\n\nexport interface AgentKindConfig {\n /** Where this node's profile runs. Omit to inherit the engine's default backend. */\n readonly backend?: ExecutorConfig\n /** This node's completion check. Omit to inherit the graph's terminal check. */\n readonly deliverable?: DeliverableSpec<unknown>\n}\n\n/**\n * One profile, one run: the kernel's leaf, exactly as `supervise()` derives it from `backend`.\n * The model cannot decide this — it is what gets run.\n */\nexport function agentKind(defaults: {\n readonly backend?: ExecutorConfig\n readonly deliverable?: DeliverableSpec<unknown>\n}): NodeKind<AgentKindConfig> {\n return {\n id: 'agent',\n version: 1,\n description: 'One AgentProfile run as a leaf on a backend; the kernel derives the executor.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: agent config`)\n return {\n ...(config.backend !== undefined ? { backend: config.backend as ExecutorConfig } : {}),\n ...(config.deliverable !== undefined\n ? { deliverable: config.deliverable as DeliverableSpec<unknown> }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { backend: { type: 'object' }, deliverable: { type: 'object' } },\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, spawn }) => {\n const backend = config.backend ?? defaults.backend\n if (!backend) {\n throw new ValidationError(\n `agent kind: node ${JSON.stringify(profile.name)} has no backend — set config.backend or the engine default`,\n )\n }\n const make: MakeWorkerAgent = workerFromBackend(\n backend,\n config.deliverable ?? defaults.deliverable,\n )\n return make(profile, spawn)\n },\n }\n}\n\n// ── supervisor ──────────────────────────────────────────────────────────────────\n\nexport interface SupervisorKindConfig {\n /** Per-child budget reserved from the pool on each spawn this supervisor makes. */\n readonly perWorker: SupervisorAgentDeps['perWorker']\n readonly maxLiveWorkers?: number\n}\n\n/**\n * The thing that DECIDES: a nested `supervisorAgent` with the coordination verbs. Its children\n * are its own tree — the graph sees one node in, one `Settled` out. A `subgraph` constrains what\n * it may spawn; without one it is free-form under `profileSecurity` and `allowedModels`.\n */\nexport function supervisorKind(deps: {\n readonly blobs: SupervisorAgentDeps['blobs']\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly router?: SupervisorAgentDeps['router']\n readonly driveHarness?: SupervisorAgentDeps['driveHarness']\n}): NodeKind<SupervisorKindConfig> {\n return {\n id: 'supervisor',\n version: 1,\n description:\n 'A nested supervisor: spawns, observes, steers and awaits its own children with the coordination verbs.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: supervisor config`)\n const perWorker = asRecord(config.perWorker, `${context}: supervisor config.perWorker`)\n return {\n perWorker: perWorker as unknown as SupervisorKindConfig['perWorker'],\n ...(config.maxLiveWorkers !== undefined\n ? { maxLiveWorkers: Number(config.maxLiveWorkers) }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { perWorker: { type: 'object' }, maxLiveWorkers: { type: 'integer' } },\n required: ['perWorker'],\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile }) =>\n supervisorAgent(profile, {\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n perWorker: config.perWorker,\n ...(config.maxLiveWorkers !== undefined ? { maxLiveWorkers: config.maxLiveWorkers } : {}),\n ...(deps.router ? { router: deps.router } : {}),\n ...(deps.driveHarness ? { driveHarness: deps.driveHarness } : {}),\n }),\n }\n}\n\n// ── script ──────────────────────────────────────────────────────────────────────\n\n/** The caller code a `script` node runs. Receives the resolved inputs; returns the output. */\nexport type ScriptBody = (\n inputs: Readonly<Record<string, unknown>>,\n signal: AbortSignal,\n) => Promise<unknown> | unknown\n\nexport interface ScriptKindConfig {\n readonly body: ScriptBody\n /**\n * `pure: true` is the promise that the output is a function of `(config, inputs)` alone: the\n * node is then budget-exempt, its output restorable on replay by content address, and it runs\n * in-process. A pure script that settles with a different `outRef` for the same inputs has\n * lied, and the first replay mismatch is an engine error.\n */\n readonly pure?: boolean\n /** For a metered script: what it spent. Omit on a pure script. A metered script that reports\n * nothing is metered as NOTHING-KNOWN, never as free. */\n readonly spent?: Spend\n}\n\n/** The script kind's handle; it also names the kind in every script node's identity. */\nconst SCRIPT: RegistryHandle = { id: 'script', version: 1 }\n\n/**\n * Caller code as a node. The one kind with no kernel primitive behind it: the kernel has no\n * \"data→data with no execution\" concept (agent-runtime#970 fact-finding), so this is new. It is\n * still a leaf `Agent` carrying an `Executor`, so the journal, the gate and the pool treat it like\n * any other node.\n */\nexport function scriptKind(): NodeKind<ScriptKindConfig> {\n return {\n ...SCRIPT,\n description:\n 'Run caller code over the resolved inputs; pure scripts are exempt and restorable.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: script config`)\n if (typeof config.body !== 'function') {\n throw new ValidationError(`${context}: script config.body must be a function`)\n }\n if (config.pure !== undefined && typeof config.pure !== 'boolean') {\n throw new ValidationError(`${context}: script config.pure must be a boolean`)\n }\n if (config.pure === true && config.spent !== undefined) {\n throw new ValidationError(\n `${context}: a pure script is budget-exempt and cannot report spent`,\n )\n }\n return {\n body: config.body as ScriptBody,\n ...(config.pure !== undefined ? { pure: config.pure } : {}),\n ...(config.spent !== undefined ? { spent: config.spent as Spend } : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { pure: { type: 'boolean' }, spent: { type: 'object' } },\n // `body` is a function and has no JSON form; a host that lifts `script` supplies its own\n // executable reference (ADC: a module in a sandbox) under this same kind id.\n additionalProperties: true,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, inputs }) => scriptAgent(profile, config, inputs, SCRIPT),\n }\n}\n\nfunction scriptAgent(\n profile: AgentProfile,\n config: ScriptKindConfig,\n inputs: Readonly<Record<string, unknown>>,\n kind: RegistryHandle,\n): Agent<unknown, unknown> & { executorSpec: AgentSpec } {\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n // A pure script spends nothing from the pool by construction; the kernel refunds its whole\n // reservation. A metered script with no `spent` is NOT free: it is recorded as unknown.\n ...(config.pure ? { budgetExempt: true } : {}),\n async execute(_task, signal): Promise<ExecutorResult<unknown>> {\n const startedAt = Date.now()\n const out = await config.body(inputs, signal)\n const ms = Date.now() - startedAt\n // Exempt means zero spend on every pool channel, iterations included; only the wall clock is\n // reported, and it is not a pool channel.\n const spent: Spend = config.pure\n ? { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms }\n : (config.spent ?? {\n iterations: 1,\n tokens: { input: 0, output: 0, tokensKnown: false },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n })\n artifact = { outRef: contentAddress(out), out, spent }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) throw new ValidationError('script: resultArtifact() read before execute()')\n return artifact\n },\n }\n // The profile names the node; the kind is the behavioral authority, so it joins the node's\n // identity here. A script claims no harness or model: nothing runs one.\n const spec: AgentSpec = {\n profile,\n harness: null,\n executor,\n execution: { correlation: { nodeKind: formatRegistryHandle(kind) } },\n }\n return {\n name: profile.name ?? 'script',\n // `act` is never the path: Scope reads `executorSpec` and runs the executor itself.\n act: () => Promise.reject(new ValidationError('script: act() is not the execution path')),\n executorSpec: spec,\n }\n}\n\n// ── subgraph ────────────────────────────────────────────────────────────────────\n\n/**\n * A node carrying its own graph: the constraint on what a supervisor may spawn at depth>1. Its\n * executor is a nested engine run; that needs the scheduler (#980), so until then this kind is\n * registered and REFUSES at run time by name rather than being absent — a graph that names it\n * compiles, and the refusal says exactly what is missing.\n */\nexport function subgraphKind(): NodeKind<{ readonly graph: unknown }> {\n return {\n id: 'subgraph',\n version: 1,\n description: 'A node that runs its own graph; constrains a supervisor at depth>1.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: subgraph config`)\n if (config.graph === undefined) {\n throw new ValidationError(`${context}: subgraph config.graph is required`)\n }\n return { graph: config.graph }\n },\n configSchema: {\n type: 'object',\n properties: { graph: { type: 'object' } },\n required: ['graph'],\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ profile }) => {\n throw new ValidationError(\n `subgraph kind: node ${JSON.stringify(profile.name)} cannot run yet — the scheduler that executes a nested graph lands in agent-runtime#980`,\n )\n },\n }\n}\n\nfunction asRecord(value: unknown, context: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context} must be an object`)\n }\n return value as Record<string, unknown>\n}\n","/**\n * The engine scheduler (agent-runtime#980, durable per #974/#976): run a compiled graph by hosting\n * every node instance on one kernel `Scope` — the pool, the journal, the blob store and\n * cancellation are the kernel's, never re-implemented. The scheduler owns only what a graph adds:\n * joins over guarded edges, traversal and visit caps, directive/payload delivery, suspensions,\n * terminals and the finalizer reduce.\n *\n * DURABILITY MODEL — fold, never checkpoint. Every scheduling decision is journaled BEFORE its\n * effect is visible (blob-then-journal where a ref is minted), then applied to in-memory state\n * through the SAME pure reducer (`applyGraphFoldEvent`) a restart replays the journal through.\n * Kill the process at any journal boundary and a restart with the same journal re-enters the exact\n * state: settled nodes restore from `outRef` and are never re-executed; a released-but-unspawned\n * instance re-enters from its pinned `inputRef`; an in-flight instance is in-doubt and re-enters\n * per its kind's `onCrash`.\n *\n * Engine `woken` ordinals live in a reserved high band (`ENGINE_WOKEN_SEQ_BASE`+) so they can\n * never collide with the kernel scope's cursor counter, which the kernel owns and advances\n * concurrently.\n */\nimport { contentAddress } from '../../durable/content-address'\nimport {\n closesCursorSlot,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { addSpend } from '../../runtime/util'\nimport { createBudgetPool } from '../supervise/budget'\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createScope } from '../supervise/scope'\nimport {\n maxSeqOf,\n sumMeasuredSpendFromEvents,\n uncertainSpawnBudgets,\n} from '../supervise/supervisor'\nimport type { Budget, ResultBlobStore, Settled, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { type CompiledEdge, type CompiledGraph, compileGraph } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport {\n applyGraphFoldEvent,\n emptyFoldState,\n type FoldSuspension,\n type GraphFoldState,\n} from './fold'\nimport { narrowEffects } from './kind'\nimport { applyProjection } from './projection'\nimport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\nexport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\n/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter. */\nexport const ENGINE_WOKEN_SEQ_BASE = 10_000_000\n\nconst SUSPEND_MARK = '__graphSuspension'\n\nexport interface SuspensionRequest {\n readonly [SUSPEND_MARK]: true\n readonly onExpire: 'wait' | 'fail' | 'default'\n /** Milliseconds from the suspension's journaling instant; absent with `onExpire: 'wait'`. */\n readonly expiresInMs?: number\n readonly default?: unknown\n}\n\n/** What a kind's executor returns to park its node on a host wake (agent-runtime#976). */\nexport function suspended(\n options: {\n readonly onExpire?: 'wait' | 'fail' | 'default'\n readonly expiresInMs?: number\n readonly default?: unknown\n } = {},\n): SuspensionRequest {\n const onExpire = options.onExpire ?? 'wait'\n if (onExpire !== 'wait' && options.expiresInMs === undefined) {\n throw new ValidationError(`suspended: onExpire '${onExpire}' requires expiresInMs`)\n }\n if (onExpire === 'wait' && options.expiresInMs !== undefined) {\n throw new ValidationError(\"suspended: onExpire 'wait' never expires — remove expiresInMs\")\n }\n if (onExpire === 'default' && options.default === undefined) {\n throw new ValidationError(\"suspended: onExpire 'default' requires a default payload\")\n }\n return {\n [SUSPEND_MARK]: true,\n onExpire,\n ...(options.expiresInMs !== undefined ? { expiresInMs: options.expiresInMs } : {}),\n ...(options.default !== undefined ? { default: options.default } : {}),\n }\n}\n\nfunction isSuspensionRequest(value: unknown): value is SuspensionRequest {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)[SUSPEND_MARK] === true\n )\n}\n\n/** Admission for every value crossing an edge (#971): JSON round-trip, `undefined` stripped, a\n * non-representable value becomes a RECORD of that fact — a degraded record beats a vanished\n * edge. */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n if (text === undefined) return { nonCanonical: `payload of type ${typeof value}` }\n return JSON.parse(text)\n } catch (error) {\n return { nonCanonical: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface GraphRunOptions {\n /** The run's conserved pool. */\n readonly budget: Budget\n /** Default per-instance reservation for nodes that declare no `budget` of their own.\n * Required when any such node exists — the engine invents no split. */\n readonly perNode?: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n /** Resolves `delegates`/`analyzes` directives; required when any edge carries one. */\n readonly prompts?: PromptRegistry\n /** How terminal settles reduce to `out`. Default `bestDelivered`. */\n readonly finalizer?: 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly runId?: string\n /** Continue an existing journaled run. An existing tree without this refuses, like the kernel. */\n readonly resume?: boolean\n /** Hold a fully-suspended run open for live `resume()` calls instead of returning\n * `{ kind: 'suspended' }`. Offline callers leave this off and restart later (#976). */\n readonly waitForWakes?: boolean\n}\n\n/** A live run: await `done`; deliver host wakes through `resume`/`expire` (#976). */\nexport interface GraphRunHandle {\n readonly done: Promise<GraphRunResult>\n resume(token: string, payload: unknown): Promise<void>\n expire(token: string): Promise<void>\n}\n\n/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs\n * no live host wakes. */\nexport async function runEngineGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): Promise<GraphRunResult> {\n return createGraphRun(engine, spec, task, options).done\n}\n\n/**\n * Start (or resume) a graph run and return its handle: await `done` for the result; deliver host\n * wakes through `resume`/`expire` while it runs (#976).\n */\nexport function createGraphRun(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): GraphRunHandle {\n const compiled: CompiledGraph =\n 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n const wakes: Array<{\n token: string\n payload?: unknown\n expire: boolean\n settle: () => void\n fail: (e: unknown) => void\n }> = []\n let notifyWake: (() => void) | undefined\n const handleState = { finished: false }\n const done = runGraphLoop(\n engine,\n compiled,\n task,\n options,\n wakes,\n () => notifyWake?.(),\n (fn) => {\n notifyWake = fn\n },\n ).finally(() => {\n handleState.finished = true\n })\n const queue = (token: string, payload: unknown, expire: boolean): Promise<void> => {\n if (handleState.finished) {\n return Promise.reject(\n new ValidationError(\n `graph resume: run completed; start a new run over the same journal to wake '${token}'`,\n ),\n )\n }\n return new Promise<void>((settle, fail) => {\n wakes.push({ token, payload, expire, settle, fail })\n notifyWake?.()\n })\n }\n return {\n done,\n resume: (token, payload) => queue(token, payload, false),\n expire: (token) => queue(token, undefined, true),\n }\n}\n\n// ── The run loop ─────────────────────────────────────────────────────────────────\n\nasync function runGraphLoop(\n engine: GraphEngine,\n compiled: CompiledGraph,\n task: string,\n options: GraphRunOptions,\n wakes: Array<{\n token: string\n payload?: unknown\n expire: boolean\n settle: () => void\n fail: (e: unknown) => void\n }>,\n _notify: () => void,\n onWakeSignal: (fn: () => void) => void,\n): Promise<GraphRunResult> {\n const context = 'runEngineGraph'\n for (const node of compiled.nodes.values()) {\n const missing = node.kind.effects.filter((name) => !(name in engine.effects))\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: node ${node.id} needs effect(s) ${missing.join(', ')} the host did not provide`,\n )\n }\n if (node.spec.budget === undefined && options.perNode === undefined) {\n throw new ValidationError(\n `${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`,\n )\n }\n }\n for (const edge of compiled.edges) {\n if (edge.spec.directive !== undefined && options.prompts === undefined) {\n throw new ValidationError(\n `${context}: edge ${edge.id} carries a directive but options.prompts is absent`,\n )\n }\n }\n\n const now = options.now ?? Date.now\n const journal = options.journal ?? new InMemorySpawnJournal()\n const blobs = options.blobs ?? new InMemoryResultBlobStore()\n const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`\n\n // ── Begin or resume the journaled tree ─────────────────────────────────────────\n const prior = await journal.loadTree(runId)\n if (prior !== undefined && options.resume !== true) {\n throw new ValidationError(\n `${context}: runId '${runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const resuming = options.resume === true && prior !== undefined && prior.length > 0\n let runEpochMs = now()\n let rootBudget = options.budget\n if (prior === undefined) {\n await journal.beginTree(runId, new Date(runEpochMs).toISOString())\n }\n if (!resuming) {\n // The engine's root marker: the anchor a restart reads the epoch and deadline from, exactly\n // as the kernel supervisor journals its own root. A begun-but-empty journal (killed before\n // its first event) writes it here too.\n await journal.appendEvent(runId, {\n kind: 'spawned',\n id: runId,\n label: 'graph-root',\n budget: options.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(runEpochMs).toISOString(),\n })\n }\n if (resuming) {\n const root = prior.find((ev) => ev.kind === 'spawned' && ev.id === runId)\n if (root?.kind === 'spawned') {\n runEpochMs = Date.parse(root.at)\n rootBudget = root.budget\n }\n }\n\n // ── Pool + scope, resume-aware exactly like the kernel supervisor ──────────────\n const elapsed = () => now() - runEpochMs\n const pool = resuming\n ? createBudgetPool(rootBudget, elapsed, {\n committed: (() => {\n const measured = sumMeasuredSpendFromEvents(prior)\n return addSpend(measured.childWork, measured.driverInference)\n })(),\n uncertainReservations: uncertainSpawnBudgets(prior),\n ...(rootBudget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs }\n : {}),\n })\n : createBudgetPool(rootBudget, elapsed)\n const abort = new AbortController()\n const onOuterAbort = () => abort.abort(options.signal?.reason)\n options.signal?.addEventListener('abort', onOuterAbort, { once: true })\n if (options.signal?.aborted) abort.abort(options.signal.reason)\n const scope = createScope<unknown>({\n parentId: runId,\n root: runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now,\n ...(resuming\n ? {\n resumeFrom: {\n settled: await replaySpawnTree(journal, blobs, runId),\n view: materializeTreeView(prior),\n maxSpawnOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'spawned'),\n maxCursorSeq: maxSeqOf(prior, closesCursorSlot),\n maxWaitOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'waiting'),\n waits: pendingWaits(prior),\n keys: new Map(),\n priorSpend: sumMeasuredSpendFromEvents(prior),\n },\n }\n : {}),\n })\n\n // Every path out of this function — a winner, a refusal, a kill at a journal boundary — tears\n // the scope down; a crashed append must never leak live children.\n try {\n return await runToResult()\n } finally {\n options.signal?.removeEventListener('abort', onOuterAbort)\n abort.abort('run complete')\n }\n\n async function runToResult(): Promise<GraphRunResult> {\n // ── State: ONE reducer builds it, live and on restart ──────────────────────────\n const state: GraphFoldState = emptyFoldState(compiled)\n if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, compiled)\n\n let engineSeq = resuming ? maxEngineSeq(prior) + 1 : 0\n let engineWokenSeq =\n ENGINE_WOKEN_SEQ_BASE +\n (resuming\n ? prior.filter((ev) => ev.kind === 'woken' && ev.seq >= ENGINE_WOKEN_SEQ_BASE).length\n : 0)\n const appendAndApply = async (ev: SpawnEvent): Promise<void> => {\n await journal.appendEvent(runId, ev)\n applyGraphFoldEvent(state, ev, compiled)\n }\n\n const ledger: GraphEdgeTraversal[] = []\n const liveHandles = new Map<string, string>() // scope handle id -> instance label\n const waitingForBudget: string[] = []\n const outCache = new Map<string, unknown>() // outRef -> admitted out, for guard/check evaluation\n let ledgerSeq = resuming ? prior.filter((ev) => ev.kind === 'edge').length : 0\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n const recordLedger = async (\n edge: CompiledEdge,\n traversal: number,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): Promise<void> => {\n const spec = edge.spec\n const entry: GraphEdgeTraversal = {\n edge: edge.id,\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n traversal,\n outcome,\n ...(spec.directive !== undefined\n ? { directive: `${spec.directive.surface}/v${spec.directive.version}` }\n : {}),\n ...(spec.kind === 'data' ? { port: edge.toPort } : {}),\n ...(reason !== undefined ? { reason } : {}),\n }\n ledger.push(entry)\n await journal.appendEvent(runId, {\n kind: 'edge',\n id: `graph:${spec.to.node}`,\n edge: {\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n ...(entry.directive !== undefined ? { directive: entry.directive } : {}),\n ...(entry.port !== undefined ? { port: entry.port } : {}),\n },\n traversal,\n outcome: outcome === 'delivered' ? 'delivered' : outcome,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n\n /** Spawn one released instance from its journaled envelope — the ONE entry path, used for a\n * fresh release, a budget-parked retry, and a restart re-entry alike. */\n const spawnInstance = async (instanceLabel: string): Promise<void> => {\n if (failure) return\n const instance = state.instances.get(instanceLabel)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node || instance.inputRef === undefined) {\n throw new ValidationError(`${context}: instance ${instanceLabel} has no journaled envelope`)\n }\n const envelope = (await blobs.get(instance.inputRef)) as\n | { task: string; inputs: Record<string, unknown> }\n | undefined\n if (envelope === undefined) {\n throw new ValidationError(\n `${context}: envelope ${instance.inputRef} is not in the blob store`,\n )\n }\n const effects = narrowEffects(\n node.kind.effects,\n engine.effects,\n `${context}: node ${node.id}`,\n )\n const agent = node.kind.run({\n config: node.config,\n profile: { name: node.id, ...(node.spec.profile ?? {}) },\n inputs: envelope.inputs,\n effects,\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, envelope.task, { label: instanceLabel, budget })\n if (spawned.ok) {\n liveCount += 1\n liveHandles.set(spawned.handle.id, instanceLabel)\n applyGraphFoldEvent(\n state,\n // The kernel journaled its own `spawned` row inside `scope.spawn`; mirror the two fields\n // the reducer folds so live state matches what a restart will reconstruct.\n {\n kind: 'spawned',\n id: spawned.handle.id,\n label: instanceLabel,\n budget,\n runtime: 'inline',\n seq: 0,\n at: '',\n },\n compiled,\n )\n return\n }\n if (spawned.reason === 'budget-exhausted' || spawned.reason === 'max-live-workers') {\n // Never overcommit: park the entry and retry after the next settle frees capacity (#972).\n waitingForBudget.push(instanceLabel)\n return\n }\n failure = {\n reason: 'driver-failed',\n error: { name: 'SpawnRefused', message: `node ${node.id}: ${spawned.reason}` },\n }\n abort.abort(`spawn refused: ${node.id}`)\n }\n\n /** Release a node: journal the wave (join-state + envelope) then spawn. */\n const release = async (\n nodeId: string,\n satisfiedBy: CompiledEdge[],\n consumedPending: string[],\n ): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n failure = {\n reason: 'cycle-budget-exceeded',\n error: {\n name: 'GraphCycleBudget',\n message: `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`,\n },\n }\n abort.abort(`cycle-budget-exceeded: ${nodeId}`)\n return\n }\n const instanceLabel = `${nodeId}#${visit}`\n // Build the envelope from the wave: data payloads projected and admitted, directives resolved,\n // trace refs lined up — then pinned by content address BEFORE anything spawns.\n const inputs: Record<string, unknown> = {}\n const directives: string[] = []\n const traces: string[] = []\n for (const edge of satisfiedBy) {\n const foldedEdge = state.edges.get(edge.id)\n const spec = edge.spec\n if (spec.kind === 'data' && foldedEdge?.state === 'satisfied') {\n let payload =\n foldedEdge.payloadRef === undefined ? undefined : outCache.get(foldedEdge.payloadRef)\n if (payload === undefined && foldedEdge.payloadRef !== undefined) {\n payload = admitPayload(await blobs.get(foldedEdge.payloadRef))\n }\n let outcome: GraphEdgeTraversal['outcome'] = 'delivered'\n let reason: string | undefined\n if (spec.projection !== undefined) {\n try {\n payload = admitPayload(applyProjection(payload, spec.projection, `edge ${edge.id}`))\n } catch (error) {\n outcome = 'empty'\n reason = error instanceof Error ? error.message : String(error)\n payload = undefined\n }\n }\n if (payload === undefined && outcome === 'delivered') outcome = 'empty'\n await recordLedger(edge, (foldedEdge?.traversals ?? 0) + 1, outcome, reason)\n if (payload !== undefined) inputs[edge.toPort] = payload\n } else {\n if (spec.directive !== undefined && options.prompts !== undefined) {\n directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && foldedEdge?.state === 'satisfied') {\n traces.push(`trace of ${spec.from.node}: ${foldedEdge.payloadRef ?? '(no traceRef)'}`)\n }\n await recordLedger(edge, (foldedEdge?.traversals ?? 0) + 1, 'delivered')\n }\n }\n const nodeTask = [nodeId === compiled.root ? task : '', ...directives, ...traces]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n const envelope = { task: nodeTask.length > 0 ? nodeTask : task, inputs }\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n const at = new Date(now()).toISOString()\n await appendAndApply({\n kind: 'node-inputs-resolved',\n id: instanceLabel,\n node: nodeId,\n instance: instanceLabel,\n inputRef,\n seq: engineSeq++,\n at,\n })\n await appendAndApply({\n kind: 'join-state',\n id: instanceLabel,\n node: nodeId,\n rule: node.join,\n satisfiedBy: satisfiedBy.map((edge) => edge.id),\n consumedPending,\n instance: instanceLabel,\n seq: engineSeq++,\n at,\n })\n await spawnInstance(instanceLabel)\n }\n\n /** Join evaluation per ADC's rules over the folded edge states. */\n const tryRelease = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded || folded.blocked || failure) return\n const gating = node.inbound\n if (gating.length === 0) return\n const states = gating.map((edge) => ({ edge, folded: state.edges.get(edge.id) }))\n const settled = states.filter((entry) => entry.folded && entry.folded.state !== 'pending')\n const satisfied = states.filter((entry) => entry.folded?.state === 'satisfied')\n const failed = states.filter((entry) => entry.folded?.state === 'failed')\n const allSettled = settled.length === gating.length\n let releaseNow = false\n switch (node.join) {\n case 'all':\n releaseNow =\n satisfied.length === gating.length &&\n !states.some(\n (entry) => entry.folded?.state === 'dead' || entry.folded?.state === 'failed',\n )\n break\n case 'any':\n releaseNow = satisfied.length > 0\n if (!releaseNow && allSettled) folded.blocked = true\n break\n case 'any_failed':\n releaseNow = failed.length > 0\n if (!releaseNow && allSettled) folded.blocked = true\n break\n case 'all_done':\n releaseNow = allSettled\n break\n }\n if (!releaseNow) return\n const consuming =\n node.join === 'any'\n ? [satisfied[0] as (typeof states)[number]]\n : node.join === 'any_failed'\n ? [failed[0] as (typeof states)[number]]\n : settled\n // Caps judged on the consuming edges BEFORE anything else happens; a refusal is fold-visible.\n for (const entry of consuming) {\n const cap = entry.edge.spec.maxTraversals\n if (cap !== undefined && (entry.folded?.traversals ?? 0) >= cap) {\n recordLedger(\n entry.edge,\n (entry.folded?.traversals ?? 0) + 1,\n 'unpropagated',\n `traversal-cap-exhausted (max ${cap})`,\n )\n await appendAndApply({\n kind: 'edge-verdict',\n id: `graph:${nodeId}`,\n edge: entry.edge.id,\n fired: false,\n sourceStatus: 'done',\n capped: true,\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n return\n }\n }\n const consumedPending = states\n .filter(\n (entry) =>\n entry.folded?.state === 'pending' &&\n hasLiveInstance(state, liveHandles, entry.edge.spec.from.node),\n )\n .map((entry) => entry.edge.id)\n await release(\n nodeId,\n consuming.map((entry) => entry.edge),\n consumedPending,\n )\n }\n\n /** Judge every outbound edge of a settle: journal the verdict, apply, then try the joins. */\n const propagate = async (instanceLabel: string, settle: GraphNodeSettle): Promise<void> => {\n const node = compiled.nodes.get(settle.node)\n if (!node) return\n const succeeded = settle.status === 'done' && settle.valid !== false\n const sourceSettles = state.nodes.get(settle.node)?.settles.length ?? 0\n for (const edge of node.outbound) {\n const folded = state.edges.get(edge.id)\n if (!folded) continue\n if (folded.judgedSourceSettles >= sourceSettles) {\n // Accounted — by an earlier verdict, or absorbed by the wave that consumed it. This is\n // what makes propagate idempotent, so a restart may re-propagate every settled node.\n continue\n }\n let fired = false\n let inputRef: string | undefined\n if (succeeded) {\n const guardContext = {\n node: settle.node,\n out: settle.out,\n visits: state.nodes.get(settle.node)?.visits ?? 0,\n valid: settle.valid ?? true,\n }\n fired = edge.spec.guard === undefined || evaluateCondition(edge.spec.guard, guardContext)\n if (fired) {\n inputRef =\n edge.spec.kind === 'analyzes'\n ? ((settle as { traceRef?: string }).traceRef ?? undefined)\n : settle.outRef\n }\n }\n await appendAndApply({\n kind: 'edge-verdict',\n id: instanceLabel,\n edge: edge.id,\n fired,\n sourceStatus: settle.status === 'down' ? 'down' : succeeded ? 'done' : 'invalid',\n ...(inputRef !== undefined ? { inputRef } : {}),\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n for (const edge of node.outbound) await tryRelease(edge.spec.to.node)\n }\n\n // ── Suspensions (#976) ─────────────────────────────────────────────────────────\n const mintToken = (instanceLabel: string): string =>\n contentAddress({ runId, instance: instanceLabel, kind: 'graph-suspension' })\n\n const journalSuspension = async (\n instanceLabel: string,\n request: SuspensionRequest,\n ): Promise<void> => {\n const token = mintToken(instanceLabel)\n let defaultRef: string | undefined\n if (request.default !== undefined) {\n const admitted = admitPayload(request.default)\n defaultRef = contentAddress(admitted)\n await blobs.put(defaultRef, admitted)\n }\n await appendAndApply({\n kind: 'waiting',\n id: `graphwait:${token}`,\n label: instanceLabel,\n spec: {\n kind: 'token',\n token,\n onExpire: request.onExpire,\n ...(request.expiresInMs !== undefined\n ? { expiresAtMs: now() + request.expiresInMs }\n : {}),\n ...(defaultRef !== undefined ? { defaultRef } : {}),\n },\n armedAt: now(),\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n\n const wake = async (\n suspension: FoldSuspension,\n by: 'fired' | 'expired',\n outRef?: string,\n ): Promise<void> => {\n await appendAndApply({\n kind: 'woken',\n id: `graphwait:${suspension.token}`,\n by,\n ...(outRef !== undefined ? { outRef } : {}),\n seq: engineWokenSeq++,\n at: new Date(now()).toISOString(),\n })\n const settle = state.instances.get(suspension.instance)?.settle\n if (settle !== undefined) {\n const enriched: GraphNodeSettle = {\n ...settle,\n ...(settle.outRef !== undefined\n ? { out: admitPayload(await blobs.get(settle.outRef)) }\n : {}),\n }\n if (enriched.outRef !== undefined && enriched.out !== undefined)\n outCache.set(enriched.outRef, enriched.out)\n await propagate(suspension.instance, enriched)\n }\n }\n\n /** Expiries are engine-clocked: judged on every loop turn and before parking (#976). */\n const sweepExpiries = async (): Promise<void> => {\n for (const suspension of [...state.suspensions.values()]) {\n if (suspension.status !== 'pending') continue\n if (suspension.expiresAtMs === undefined || now() < suspension.expiresAtMs) continue\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n }\n }\n\n const processWakes = async (): Promise<void> => {\n while (wakes.length > 0) {\n const request = wakes.shift()\n if (!request) break\n try {\n const suspension = state.suspensions.get(request.token)\n if (!suspension) {\n throw new ValidationError(`graph resume: unknown token '${request.token}'`)\n }\n if (suspension.status !== 'pending') {\n throw new ValidationError(`graph resume: token '${request.token}' already woken`)\n }\n if (request.expire) {\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n else await wake(suspension, 'expired')\n } else {\n const admitted = admitPayload(request.payload)\n const outRef = contentAddress(admitted)\n await blobs.put(outRef, admitted)\n outCache.set(outRef, admitted)\n await wake(suspension, 'fired', outRef)\n }\n request.settle()\n } catch (error) {\n request.fail(error)\n }\n }\n }\n\n // ── Settle handling ────────────────────────────────────────────────────────────\n const handleSettle = async (settled: Settled<unknown>): Promise<void> => {\n const instanceLabel = liveHandles.get(settled.handle.id)\n if (instanceLabel === undefined) return\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const instance = state.instances.get(instanceLabel)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node) return\n if (settled.kind === 'done' && isSuspensionRequest(settled.out)) {\n await journalSuspension(instanceLabel, settled.out)\n return\n }\n // Mirror the kernel's own journaled settle through the reducer, then enrich for judging.\n applyGraphFoldEvent(\n state,\n {\n kind: 'settled',\n id: settled.handle.id,\n status: settled.kind === 'done' ? 'done' : 'down',\n ...(settled.kind === 'done' ? { outRef: settled.outRef } : {}),\n ...(settled.kind === 'down' ? { reason: settled.reason } : {}),\n ...(settled.kind === 'done' && settled.trace?.status === 'available'\n ? { trace: settled.trace }\n : {}),\n spent: { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n seq: 0,\n at: '',\n },\n compiled,\n )\n const folded = state.instances.get(instanceLabel)?.settle\n if (!folded) return\n let enriched: GraphNodeSettle = folded\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n if (settled.outRef !== undefined) outCache.set(settled.outRef, admitted)\n let valid: boolean | undefined\n if (node.deliverable !== undefined) {\n try {\n valid = await node.deliverable.check(admitted)\n } catch {\n valid = false\n }\n }\n enriched = { ...folded, out: admitted, ...(valid !== undefined ? { valid } : {}) }\n ;(state.instances.get(instanceLabel) as { settle?: GraphNodeSettle }).settle = enriched\n const settles = state.nodes.get(instance.node)?.settles\n if (settles) settles[settles.length - 1] = enriched\n }\n // Root completion ends the run the moment its check passes (#973).\n if (\n instance.node === compiled.root &&\n enriched.status === 'done' &&\n enriched.valid === true\n ) {\n abort.abort('root delivered')\n return\n }\n await propagate(instanceLabel, enriched)\n }\n\n // ── Entry / restart ────────────────────────────────────────────────────────────\n const enterEntryNode = async (nodeId: string): Promise<void> => {\n const folded = state.nodes.get(nodeId)\n if (!folded) return\n const visit = folded.visits + 1\n const node = compiled.nodes.get(nodeId)\n if (!node) return\n if (visit > node.maxVisits) return\n const instanceLabel = `${nodeId}#${visit}`\n const envelope = { task, inputs: {} as Record<string, unknown> }\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n await appendAndApply({\n kind: 'node-inputs-resolved',\n id: instanceLabel,\n node: nodeId,\n instance: instanceLabel,\n inputRef,\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n await spawnInstance(instanceLabel)\n }\n\n if (!resuming) {\n for (const id of compiled.entries) await enterEntryNode(id)\n } else {\n // Kill-anywhere re-entry: a released instance that never spawned re-enters from its envelope;\n // an in-flight instance at the crash is in-doubt and re-enters per its kind's `onCrash` —\n // both from the pinned `inputRef`, never through re-derivation (#974).\n for (const instance of [...state.instances.values()]) {\n if (instance.status === 'released') await spawnInstance(instance.instance)\n else if (instance.status === 'live') {\n const node = compiled.nodes.get(instance.node)\n const folded = state.nodes.get(instance.node)\n if (!node || !folded) continue\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n failure = {\n reason: 'cycle-budget-exceeded',\n error: {\n name: 'GraphCycleBudget',\n message: `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`,\n },\n }\n break\n }\n const restartLabel = `${instance.node}#${visit}`\n instance.status = 'down' // in-doubt: the journal's reservation stays charged (kernel rule)\n const at = new Date(now()).toISOString()\n await journal.appendEvent(runId, {\n kind: 'node-inputs-resolved',\n id: restartLabel,\n node: instance.node,\n instance: restartLabel,\n inputRef: instance.inputRef as string,\n seq: engineSeq++,\n at,\n })\n applyGraphFoldEvent(\n state,\n {\n kind: 'node-inputs-resolved',\n id: restartLabel,\n node: instance.node,\n instance: restartLabel,\n inputRef: instance.inputRef as string,\n seq: 0,\n at,\n },\n compiled,\n )\n await spawnInstance(restartLabel)\n }\n }\n // A settle whose verdicts never landed (killed between the kernel settle and the engine's\n // propagate) is re-judged now; `judgedSourceSettles` makes this a no-op for judged edges.\n for (const [nodeId, foldedNode] of state.nodes) {\n const latest = foldedNode.settles.at(-1)\n if (latest === undefined) continue\n const instanceLabel = `${nodeId}#${latest.visit}`\n let enriched: GraphNodeSettle = latest\n if (latest.status === 'done' && latest.outRef !== undefined) {\n const out = admitPayload(await blobs.get(latest.outRef))\n if (isSuspensionRequest(out)) {\n // Killed between the kernel settle and the `waiting` event: finish the half-done\n // transition now instead of propagating the marker as data.\n foldedNode.settles.pop()\n const instance = state.instances.get(instanceLabel)\n if (instance) instance.settle = undefined\n await journalSuspension(instanceLabel, out)\n continue\n }\n outCache.set(latest.outRef, out)\n const nodeSpec = compiled.nodes.get(nodeId)\n let valid: boolean | undefined\n if (nodeSpec?.deliverable !== undefined) {\n try {\n valid = await nodeSpec.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n enriched = { ...latest, out, ...(valid !== undefined ? { valid } : {}) }\n }\n await propagate(instanceLabel, enriched)\n }\n // An entry node the crashed process never released enters now — run start is its release.\n for (const id of compiled.entries) {\n if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id)\n }\n // A restart may also land after new settles are already judged: re-try every join once.\n for (const id of compiled.nodes.keys()) await tryRelease(id)\n }\n\n // ── The loop ───────────────────────────────────────────────────────────────────\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0)\n\n let wakeSignal: Promise<void> = Promise.resolve()\n let armWake: () => void = () => {}\n const rearmWakeSignal = () => {\n wakeSignal = new Promise<void>((fire) => {\n armWake = fire\n })\n onWakeSignal(() => armWake())\n }\n rearmWakeSignal()\n\n let inFlightNext: Promise<Settled<unknown> | null> | undefined\n while (!failure) {\n await sweepExpiries()\n if (wakes.length > 0) {\n await processWakes()\n continue\n }\n if (allTerminalsSettled()) break\n if (liveCount === 0) {\n const pendingSuspensions = [...state.suspensions.values()].filter(\n (suspension) => suspension.status === 'pending',\n )\n if (pendingSuspensions.length > 0) {\n const nearest = Math.min(\n ...pendingSuspensions.map(\n (suspension) => suspension.expiresAtMs ?? Number.POSITIVE_INFINITY,\n ),\n )\n if (Number.isFinite(nearest) && now() >= nearest) continue // sweep will transition it\n if (options.waitForWakes) {\n rearmWakeSignal()\n await wakeSignal\n continue\n }\n // Offline (#976): no host will ever answer, so an `onExpire: 'default'` suspension\n // auto-resolves with its default now; `wait` and a future `fail` deadline park the run.\n const defaulting = pendingSuspensions.filter(\n (suspension) => suspension.onExpire === 'default',\n )\n if (defaulting.length > 0) {\n for (const suspension of defaulting)\n await wake(suspension, 'fired', suspension.defaultRef)\n continue\n }\n break // fully parked: a legitimate offline terminal state\n }\n break // stuck or complete: classified below\n }\n inFlightNext ??= scope.next()\n const raced = await Promise.race([\n inFlightNext.then((settle) => ({ settle })),\n wakeSignal.then(() => 'wake' as const),\n ])\n if (raced === 'wake') {\n rearmWakeSignal()\n continue // wakes queue processed on the next turn; inFlightNext stays armed\n }\n inFlightNext = undefined\n if (raced.settle === null) break\n await handleSettle(raced.settle)\n for (const parked of waitingForBudget.splice(0)) await spawnInstance(parked)\n }\n\n abort.abort('graph loop complete')\n while ((await (inFlightNext ?? scope.next())) !== null) inFlightNext = undefined\n\n // ── Result assembly ────────────────────────────────────────────────────────────\n const rehydrate = async (settle: GraphNodeSettle): Promise<GraphNodeSettle> => {\n if (settle.out !== undefined || settle.outRef === undefined) return settle\n const out = outCache.get(settle.outRef) ?? admitPayload(await blobs.get(settle.outRef))\n const node = compiled.nodes.get(settle.node)\n let valid = settle.valid\n if (valid === undefined && node?.deliverable !== undefined && settle.status === 'done') {\n try {\n valid = await node.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n return { ...settle, out, ...(valid !== undefined ? { valid } : {}) }\n }\n const settles = await Promise.all(\n [...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate),\n )\n const terminals = settles.filter((settle) => compiled.nodes.get(settle.node)?.terminal)\n\n const finish = (result: GraphRunResult): GraphRunResult => {\n if (result.kind === 'no-winner' && state.exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...state.exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (failure) {\n return finish({\n kind: 'no-winner',\n reason: failure.reason,\n ...(failure.error ? { error: failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const pendingTokens = [...state.suspensions.values()]\n .filter((suspension) => suspension.status === 'pending')\n .map((suspension) => suspension.token)\n if (pendingTokens.length > 0 && !allTerminalsSettled()) {\n return { kind: 'suspended', tokens: pendingTokens, terminals, settles, ledger }\n }\n if (options.signal?.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const anyDelivered = terminals.some(\n (settle) => settle.status === 'done' && settle.valid !== false,\n )\n const out = anyDelivered\n ? await runFinalizer(\n options.finalizer === undefined || options.finalizer === 'bestDelivered'\n ? bestDelivered\n : options.finalizer === 'collectDelivered'\n ? collectDelivered\n : options.finalizer,\n {\n settled: terminals.map(\n (settle): FinalizerSettled => ({\n id: settle.node,\n status: settle.status,\n valid: settle.status === 'done' && settle.valid !== false,\n ...(settle.outRef !== undefined ? { outRef: settle.outRef } : {}),\n }),\n ),\n blobs,\n tree: scope.view,\n budget: scope.budget,\n },\n )\n : undefined\n if (out !== undefined) return { kind: 'winner', out, terminals, settles, ledger }\n const unreachable = [...compiled.nodes.keys()].filter(\n (id) => (state.nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === compiled.nodes.size\n ? 'budget-exhausted'\n : 'unreachable-terminal'\n : 'all-children-down'\n return finish({ kind: 'no-winner', reason, terminals, settles, ledger, unreachable })\n }\n}\n\n// ── Small helpers ────────────────────────────────────────────────────────────────\n\nfunction hasLiveInstance(\n state: GraphFoldState,\n liveHandles: Map<string, string>,\n node: string,\n): boolean {\n for (const label of liveHandles.values()) {\n if (state.instances.get(label)?.node === node) return true\n }\n return false\n}\n\nfunction maxEngineSeq(events: ReadonlyArray<SpawnEvent>): number {\n let max = -1\n for (const ev of events) {\n if (\n ev.kind === 'node-inputs-resolved' ||\n ev.kind === 'edge-verdict' ||\n ev.kind === 'join-state'\n ) {\n if (ev.seq > max) max = ev.seq\n }\n if (ev.kind === 'waiting' && ev.spec.kind === 'token' && ev.seq > max) max = ev.seq\n }\n return max\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAYA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAIA,MAAM,oBAA8C,IAAI,IACtD,cAAc,QAAQ,OAAO,OAAO,YAAY,OAAO,QAAQ,CACjE;AAiBA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;;AAKrB,SAAgB,mBAAmB,MAAc,SAA0C;CACzF,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,iBACjE,MAAM,IAAI,gBACR,GAAG,QAAQ,+CAA+C,gBAAgB,OAC5E;CAEF,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ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