@tangle-network/agent-runtime 0.166.0 → 0.168.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 (50) hide show
  1. package/dist/{activation-BkO0p4I1.js → activation-CIwer0zU.js} +3 -3
  2. package/dist/{activation-BkO0p4I1.js.map → activation-CIwer0zU.js.map} +1 -1
  3. package/dist/agent.js +2 -2
  4. package/dist/{authoring-Bt17KOML.js → authoring-CUTgAxxE.js} +2 -2
  5. package/dist/{authoring-Bt17KOML.js.map → authoring-CUTgAxxE.js.map} +1 -1
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{candidate-execution-DC0T8l2p.js → candidate-execution-BbMbyhgC.js} +4 -4
  8. package/dist/{candidate-execution-DC0T8l2p.js.map → candidate-execution-BbMbyhgC.js.map} +1 -1
  9. package/dist/durable.js +1 -1
  10. package/dist/graph-ZDMygFIo.js +546 -0
  11. package/dist/graph-ZDMygFIo.js.map +1 -0
  12. package/dist/graph.d.ts +58 -58
  13. package/dist/graph.js +2077 -2
  14. package/dist/graph.js.map +1 -0
  15. package/dist/{improvement-cycle-BAWOyeTA.js → improvement-cycle-BAKN_f4x.js} +4 -4
  16. package/dist/{improvement-cycle-BAWOyeTA.js.map → improvement-cycle-BAKN_f4x.js.map} +1 -1
  17. package/dist/index.js +11 -11
  18. package/dist/intelligence.js +5 -5
  19. package/dist/kernel.js +6 -6
  20. package/dist/{knowledge-Bhhz6lvH.js → knowledge-D-7PXKUV.js} +5 -5
  21. package/dist/{knowledge-Bhhz6lvH.js.map → knowledge-D-7PXKUV.js.map} +1 -1
  22. package/dist/knowledge.js +1 -1
  23. package/dist/{loop-runner-bin-BQnpSn0h.js → loop-runner-bin-DHxQ_VQD.js} +3 -3
  24. package/dist/{loop-runner-bin-BQnpSn0h.js.map → loop-runner-bin-DHxQ_VQD.js.map} +1 -1
  25. package/dist/loop-runner-bin.js +1 -1
  26. package/dist/mcp/bin.js +3 -3
  27. package/dist/mcp/index.js +4 -4
  28. package/dist/{openai-tools-t6spVYKL.js → openai-tools-UyXVO0kd.js} +2 -2
  29. package/dist/{openai-tools-t6spVYKL.js.map → openai-tools-UyXVO0kd.js.map} +1 -1
  30. package/dist/{prepare-BCScSDCv.js → prepare-BAyaNoZu.js} +3 -3
  31. package/dist/prepare-BAyaNoZu.js.map +1 -0
  32. package/dist/{protected-model-port-D-5E3HBe.js → protected-model-port-T2UWrDNQ.js} +2 -2
  33. package/dist/{protected-model-port-D-5E3HBe.js.map → protected-model-port-T2UWrDNQ.js.map} +1 -1
  34. package/dist/{runtime-BJoNta1Y.js → runtime-D5l-enW9.js} +6 -6
  35. package/dist/{runtime-BJoNta1Y.js.map → runtime-D5l-enW9.js.map} +1 -1
  36. package/dist/{structural-rollout-B5E0mWCH.js → structural-rollout-C7nNNhri.js} +2 -2
  37. package/dist/{structural-rollout-B5E0mWCH.js.map → structural-rollout-C7nNNhri.js.map} +1 -1
  38. package/dist/{supervise-CnxqHx1P.js → supervise-rEE46ruH.js} +2 -2
  39. package/dist/{supervise-CnxqHx1P.js.map → supervise-rEE46ruH.js.map} +1 -1
  40. package/dist/{supervisor-C8kgh8mf.js → supervisor-B-mmmiOU.js} +4 -3
  41. package/dist/supervisor-B-mmmiOU.js.map +1 -0
  42. package/dist/testing.js +12 -12
  43. package/dist/{workspace-archive-CHY5HvrF.js → workspace-archive-B0Hqp2eJ.js} +12 -7
  44. package/dist/workspace-archive-B0Hqp2eJ.js.map +1 -0
  45. package/package.json +3 -3
  46. package/dist/graph-E0U0c2YP.js +0 -2668
  47. package/dist/graph-E0U0c2YP.js.map +0 -1
  48. package/dist/prepare-BCScSDCv.js.map +0 -1
  49. package/dist/supervisor-C8kgh8mf.js.map +0 -1
  50. package/dist/workspace-archive-CHY5HvrF.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-E0U0c2YP.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/kinds.ts","../src/runtime/graph/admit.ts","../src/runtime/graph/fold.ts","../src/runtime/graph/join.ts","../src/runtime/graph/ledger.ts","../src/runtime/graph/result.ts","../src/runtime/graph/run-context.ts","../src/runtime/graph/suspension.ts","../src/runtime/graph/scheduler.ts","../src/runtime/graph/preset-run-graph.ts","../src/runtime/supervise/graph.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 /** Force a node out of (or into) the run's entry set. Absent, a node with no inbound edge is an\n * entry, and the declared root always is. A node another node SPAWNS — the `runGraph` preset's\n * workers and analysts — sets `false`: the scheduler must never enter it on its own. */\n readonly entry?: 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`); `0` closes the edge from the start. */\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 // Zero is meaningful and authored in practice: an edge closed from the start, which the\n // scheduler refuses on its first consumption and ledgers `unpropagated`.\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 0) {\n throw new ValidationError(`${who}: maxTraversals must be a non-negative 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\n/** `delegates` is the one MODEL-fired edge kind (agent-runtime#971): its payload is a directive and\n * its target is spawned by the source supervisor through the coordination protocol, not released\n * by the scheduler. `data` and `analyzes` are engine-fired. */\nexport function isEngineFired(edge: CompiledEdge): boolean {\n return edge.spec.kind !== 'delegates'\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 /** Spawned by a supervisor through a `delegates` edge, never entered by the scheduler. */\n readonly modelFired: boolean\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 // A node reached only by `delegates` is spawned by its supervisor, so it is neither an entry nor\n // a scheduler-released node; a node with no ENGINE-fired outbound edge is terminal, because a\n // delegation does not continue the scheduler's flow.\n const engineInbound = (id: string) => (inbound.get(id) ?? []).filter(isEngineFired)\n const engineOutbound = (id: string) => (outbound.get(id) ?? []).filter(isEngineFired)\n const unfed = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (unfed.length === 0 && spec.root === undefined) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (unfed.length === 1\n ? (unfed[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${unfed.length} entry nodes (${unfed.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n // The declared root always starts the run, even when an edge feeds back INTO it — a findings\n // route to the driver, or a cycle's closing edge, never stops the run from beginning there. A\n // node that declares `entry: false` is spawned by another node and never entered here.\n const declaredOut = new Set(\n spec.nodes.filter((node) => node.entry === false).map((node) => node.id),\n )\n const entries = [root, ...unfed.map((node) => node.id).filter((id) => id !== root)].filter(\n (id) => !declaredOut.has(id),\n )\n if (entries.length === 0) {\n throw new ValidationError(`${context}: every entry node declares entry: false — nothing starts`)\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 modelFired = (inbound.get(node.id) ?? []).some((edge) => !isEngineFired(edge))\n const terminal = node.terminal ?? (!modelFired && engineOutbound(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: engineInbound(node.id),\n outbound: outbound.get(node.id) ?? [],\n modelFired,\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,\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 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 * Edge payload admission (agent-runtime#971): every value crossing an edge is JSON round-tripped,\n * `undefined` stripped to absence, and a non-representable value (a cycle, a BigInt, a function)\n * becomes a RECORD of that fact. This is the kernel's existing findings-guard rule, and it is what\n * makes `inputRef` stable and `onCrash: 'restart'` well defined — a degraded record beats a\n * vanished edge.\n */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n // JSON.stringify answers `undefined` for a bare function or symbol — record it, never vanish.\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","/**\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 * Join evaluation: which gating-edge outcomes release a node. Adopted whole from ADC's workflow\n * graph (agent-runtime#968) and kept PURE — the scheduler decides nothing here, so the rule can be\n * read, tested and reasoned about on its own.\n *\n * An edge settles SATISFIED / DEAD / FAILED per its source's LATEST completion. A release consumes\n * the outcomes that produced it; the caller re-arms them and marks any still-pending edge\n * consumed-once, so an OR-diamond's second completer never double-fires.\n */\nimport type { CompiledEdge } from './compile'\nimport type { JoinRule } from './definition'\nimport type { FoldEdge } from './fold'\n\nexport interface GatingEdge {\n readonly edge: CompiledEdge\n readonly folded: FoldEdge | undefined\n}\n\nexport interface JoinDecision {\n /** Whether the node releases now. */\n readonly release: boolean\n /** The edges whose outcomes produced this release — the ones a traversal cap judges. */\n readonly consuming: ReadonlyArray<GatingEdge>\n /** Whether the node can never release again on this wave (recorded like skipped-by-guard). */\n readonly blocked: boolean\n}\n\nconst NOTHING: JoinDecision = { release: false, consuming: [], blocked: false }\n\n/** Decide whether a node's gating edges release it, and which of them the release consumes. */\nexport function decideJoin(rule: JoinRule, gating: ReadonlyArray<GatingEdge>): JoinDecision {\n if (gating.length === 0) return NOTHING\n const settled = gating.filter((entry) => entry.folded && entry.folded.state !== 'pending')\n const satisfied = gating.filter((entry) => entry.folded?.state === 'satisfied')\n const failed = gating.filter((entry) => entry.folded?.state === 'failed')\n const allSettled = settled.length === gating.length\n switch (rule) {\n case 'all': {\n // A dead or failed edge can never satisfy an `all` join on this wave.\n const spoiled = gating.some(\n (entry) => entry.folded?.state === 'dead' || entry.folded?.state === 'failed',\n )\n const release = !spoiled && satisfied.length === gating.length\n return { release, consuming: release ? settled : [], blocked: false }\n }\n case 'any': {\n const first = satisfied[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'any_failed': {\n const first = failed[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'all_done':\n return { release: allSettled, consuming: allSettled ? settled : [], blocked: false }\n default:\n return NOTHING\n }\n}\n","/**\n * The edge ledger: what the runtime actually DELIVERED across each edge. It is observability, not\n * a fold input (agent-runtime#974) — `edge-verdict` carries the scheduler's decision, and this\n * carries the delivery, so a change to what an optimizer wants to see never changes resume\n * semantics. Its ordinals live in their own namespace, outside the kernel's cursor.\n */\n\nimport type { SpawnJournal } from '../supervise/types'\nimport type { CompiledEdge } from './compile'\nimport type { GraphEdgeTraversal } from './scheduler-types'\n\nexport interface EdgeLedger {\n readonly entries: ReadonlyArray<GraphEdgeTraversal>\n record(\n edge: CompiledEdge,\n traversal: number,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): Promise<void>\n}\n\n/** Open a ledger for one run; its ordinals continue past whatever a prior process recorded. */\nexport function createEdgeLedger(args: {\n readonly journal: SpawnJournal\n readonly runId: string\n readonly now: () => number\n readonly startSeq: number\n}): EdgeLedger {\n const entries: GraphEdgeTraversal[] = []\n let seq = args.startSeq\n return {\n entries,\n async record(edge, traversal, outcome, reason) {\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 entries.push(entry)\n await args.journal.appendEvent(args.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,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: seq++,\n at: new Date(args.now()).toISOString(),\n })\n },\n }\n}\n","/**\n * Turning a finished run into its result: rehydrate each settle's output, reduce the terminals\n * through the kernel's finalizer seam, and name the honest cause when nothing delivered\n * (agent-runtime#973). Separate from the loop so \"what happened\" is readable without reading\n * \"what ran\".\n */\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { ResultBlobStore, Scope } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport type { CompiledGraph } from './compile'\nimport type { GraphFoldState } from './fold'\nimport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\nexport type FinalizerChoice = 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n\nfunction resolveFinalizer(choice: FinalizerChoice | undefined): SupervisorFinalizer {\n if (choice === undefined || choice === 'bestDelivered') return bestDelivered\n if (choice === 'collectDelivered') return collectDelivered\n return choice\n}\n\n/** Every node settlement with its output rehydrated and its completion check applied. */\nexport async function materializeSettles(\n compiled: CompiledGraph,\n state: GraphFoldState,\n blobs: ResultBlobStore,\n outCache: ReadonlyMap<string, unknown>,\n): Promise<GraphNodeSettle[]> {\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 return Promise.all(\n [...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate),\n )\n}\n\n/** Turn a finished run into its result: rehydrate, reduce the terminals, classify a no-winner. */\nexport async function assembleGraphResult(args: {\n readonly compiled: CompiledGraph\n readonly state: GraphFoldState\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly outCache: ReadonlyMap<string, unknown>\n readonly ledger: ReadonlyArray<GraphEdgeTraversal>\n readonly finalizer?: FinalizerChoice\n readonly failure?: {\n readonly reason: GraphRunReason\n readonly error?: { name: string; message: string }\n }\n readonly aborted: boolean\n}): Promise<GraphRunResult> {\n const settles = await materializeSettles(args.compiled, args.state, args.blobs, args.outCache)\n const terminals = settles.filter((settle) => args.compiled.nodes.get(settle.node)?.terminal)\n const ledger = args.ledger\n\n // A capped edge that left the run winnerless is a NAMED failure, not a quiet no-winner (#973).\n const finish = (result: GraphRunResult): GraphRunResult => {\n if (result.kind === 'no-winner' && args.state.exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...args.state.exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (args.failure) {\n return finish({\n kind: 'no-winner',\n reason: args.failure.reason,\n ...(args.failure.error ? { error: args.failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const allTerminalsSettled = args.compiled.terminals.every(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) > 0,\n )\n const pendingTokens = [...args.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 (args.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const delivered = terminals.filter((settle) => settle.status === 'done' && settle.valid !== false)\n const out =\n delivered.length === 0\n ? undefined\n : await runFinalizer(resolveFinalizer(args.finalizer), {\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: args.blobs,\n tree: args.scope.view,\n budget: args.scope.budget,\n })\n if (out !== undefined) return { kind: 'winner', out, terminals, settles, ledger }\n\n const unreachable = [...args.compiled.nodes.keys()].filter(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = args.compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === args.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 * Opening a graph run: begin or resume the journaled tree, rebuild the pool and the kernel `Scope`\n * on the SAME recipe the kernel supervisor uses for its own resume, and fold the prior journal\n * into scheduler state. Extracted so the restart contract is one readable unit rather than a\n * preamble inside the loop.\n */\nimport {\n closesCursorSlot,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { createBudgetPool } from '../supervise/budget'\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, Scope, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { addSpend } from '../util'\nimport type { CompiledGraph } from './compile'\nimport { applyGraphFoldEvent, emptyFoldState, type GraphFoldState } from './fold'\n\n/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter, so the two\n * counters can advance independently without ever colliding. */\nexport const ENGINE_WOKEN_SEQ_BASE = 10_000_000\n\nexport interface GraphRunContext {\n readonly runId: string\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly abort: AbortController\n readonly state: GraphFoldState\n readonly resuming: boolean\n /** Journal events present before this process started; empty on a fresh run. */\n readonly prior: ReadonlyArray<SpawnEvent>\n /** Next engine fold-event ordinal, and next engine `woken` ordinal. */\n readonly engineSeq: number\n readonly engineWokenSeq: number\n /** Ledger ordinals already used by a prior process. */\n readonly ledgerSeq: number\n}\n\n/** Begin or resume a run's journaled tree, pool, scope and folded state. */\nexport async function openGraphRun(args: {\n readonly compiled: CompiledGraph\n readonly runId: string\n readonly budget: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly now: () => number\n readonly resume?: boolean\n readonly signal?: AbortSignal\n readonly onAbort: (listener: () => void) => void\n}): Promise<GraphRunContext> {\n const journal = args.journal ?? new InMemorySpawnJournal()\n const blobs = args.blobs ?? new InMemoryResultBlobStore()\n const loaded = await journal.loadTree(args.runId)\n if (loaded !== undefined && args.resume !== true) {\n throw new ValidationError(\n `runEngineGraph: runId '${args.runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const prior = loaded ?? []\n const resuming = args.resume === true && prior.length > 0\n let runEpochMs = args.now()\n let rootBudget = args.budget\n if (loaded === undefined) {\n await journal.beginTree(args.runId, new Date(runEpochMs).toISOString())\n }\n if (resuming) {\n const root = prior.find((ev) => ev.kind === 'spawned' && ev.id === args.runId)\n if (root?.kind === 'spawned') {\n runEpochMs = Date.parse(root.at)\n rootBudget = root.budget\n }\n } else {\n // The engine's root anchor: what a restart reads its epoch and deadline from, exactly as the\n // kernel supervisor journals its own root. A begun-but-empty journal writes it here too.\n await journal.appendEvent(args.runId, {\n kind: 'spawned',\n id: args.runId,\n label: 'graph-root',\n budget: args.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(runEpochMs).toISOString(),\n })\n }\n\n const elapsed = () => args.now() - runEpochMs\n const measured = resuming ? sumMeasuredSpendFromEvents([...prior]) : undefined\n const pool = createBudgetPool(\n rootBudget,\n elapsed,\n measured === undefined\n ? undefined\n : {\n committed: addSpend(measured.childWork, measured.driverInference),\n uncertainReservations: uncertainSpawnBudgets([...prior]),\n ...(rootBudget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs }\n : {}),\n },\n )\n const abort = new AbortController()\n if (args.signal !== undefined) {\n const forward = () => abort.abort(args.signal?.reason)\n args.signal.addEventListener('abort', forward, { once: true })\n args.onAbort(() => args.signal?.removeEventListener('abort', forward))\n if (args.signal.aborted) abort.abort(args.signal.reason)\n }\n const scope = createScope<unknown>({\n parentId: args.runId,\n root: args.runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now: args.now,\n ...(resuming\n ? {\n resumeFrom: {\n settled: await replaySpawnTree(journal, blobs, args.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 const state = emptyFoldState(args.compiled)\n if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, args.compiled)\n\n return {\n runId: args.runId,\n journal,\n blobs,\n scope,\n abort,\n state,\n resuming,\n prior,\n engineSeq: resuming ? maxEngineSeq(prior) + 1 : 0,\n 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 ledgerSeq: prior.filter((ev) => ev.kind === 'edge').length,\n }\n}\n\nfunction maxEngineSeq(events: ReadonlyArray<SpawnEvent>): number {\n let max = -1\n for (const ev of events) {\n const engineEvent =\n ev.kind === 'node-inputs-resolved' ||\n ev.kind === 'edge-verdict' ||\n ev.kind === 'join-state' ||\n (ev.kind === 'waiting' && ev.spec.kind === 'token')\n if (engineEvent && ev.seq > max) max = ev.seq\n }\n return max\n}\n","/**\n * Suspensions (agent-runtime#976): a node parks on a host wake as the kernel's `waiting`/`woken`\n * pair. The engine owns the transition table; a host owns only how the wake arrives.\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\n\nconst SUSPEND_MARK = '__graphSuspension'\n\n/** What a kind's executor returns to park its node until a host wakes it. */\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/** Build a suspension request. `wait` never expires; `fail` settles the node down at its deadline;\n * `default` resolves with the given payload. */\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\n/** Whether a node's output is a park request rather than its result. */\nexport function 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/** Content-addressed over the run identity, so a restart recomputes it and needs no token table. */\nexport function mintSuspensionToken(runId: string, instance: string): string {\n return contentAddress({ runId, instance, kind: 'graph-suspension' })\n}\n\n/** The journal id one suspension's `waiting`/`woken` pair shares. */\nexport function suspensionNodeId(token: string): string {\n return `graphwait:${token}`\n}\n\n/** The token inside a suspension node id, or `undefined` for any other id. */\nexport function tokenFromSuspensionNodeId(id: string): string | undefined {\n return id.startsWith('graphwait:') ? id.slice('graphwait:'.length) : undefined\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; the scheduler owns only what a graph adds — releasing nodes over\n * guarded edges, delivering payloads and directives, the two cycle caps, and suspensions.\n *\n * DURABILITY — fold, never checkpoint. Every decision is journaled BEFORE its effect is visible\n * (blob-then-journal where a ref is minted), then applied to live state through the SAME reducer\n * (`applyGraphFoldEvent`) a restart replays the journal through. Kill the process at any journal\n * boundary and a restart re-enters the exact state: settled nodes restore from `outRef` and never\n * re-execute; a released-but-unspawned instance re-enters from its pinned `inputRef`; an in-flight\n * instance is in-doubt and re-enters per its kind's `onCrash`.\n *\n * The parts this file does NOT own, so it stays a loop and not a god object: payload admission\n * (`admit.ts`), the edge ledger (`ledger.ts`), the join rule (`join.ts`), suspension vocabulary\n * (`suspension.ts`), the journal/pool/scope bootstrap (`run-context.ts`), and result assembly\n * (`result.ts`).\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport type { Budget, ResultBlobStore, Settled, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport { type CompiledGraph, compileGraph, isEngineFired } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport { applyGraphFoldEvent, type FoldSuspension } from './fold'\nimport { decideJoin, type GatingEdge } from './join'\nimport { narrowEffects } from './kind'\nimport { createEdgeLedger } from './ledger'\nimport { applyProjection } from './projection'\nimport { assembleGraphResult, type FinalizerChoice } from './result'\nimport { openGraphRun } from './run-context'\nimport type { GraphNodeSettle, GraphRunReason, GraphRunResult } from './scheduler-types'\nimport {\n isSuspensionRequest,\n mintSuspensionToken,\n type SuspensionRequest,\n suspensionNodeId,\n} from './suspension'\n\nexport { admitPayload } from './admit'\nexport { ENGINE_WOKEN_SEQ_BASE } from './run-context'\nexport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\nexport { type SuspensionRequest, suspended } from './suspension'\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?: FinalizerChoice\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\ninterface QueuedWake {\n readonly token: string\n readonly payload?: unknown\n readonly expire: boolean\n readonly settle: () => void\n readonly fail: (error: unknown) => void\n}\n\n/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs no\n * 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 = asCompiled(engine, spec)\n const wakes: QueuedWake[] = []\n let signalWake: () => void = () => {}\n let finished = false\n const done = runGraphLoop(engine, compiled, task, options, wakes, (fn) => {\n signalWake = fn\n }).finally(() => {\n finished = true\n })\n const queue = (token: string, payload: unknown, expire: boolean): Promise<void> => {\n if (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 signalWake()\n })\n }\n return {\n done,\n resume: (token, payload) => queue(token, payload, false),\n expire: (token) => queue(token, undefined, true),\n }\n}\n\nfunction asCompiled(engine: GraphEngine, spec: EngineGraphSpec | CompiledGraph): CompiledGraph {\n return 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n}\n\n/** Everything a run must be able to satisfy before it spends anything. */\nfunction assertRunnable(\n engine: GraphEngine,\n compiled: CompiledGraph,\n options: GraphRunOptions,\n): void {\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 // Only an ENGINE-fired edge's directive is the scheduler's to resolve; a `delegates` directive\n // is resolved by the supervisor that spawns the target (#971).\n if (isEngineFired(edge) && 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\nasync function runGraphLoop(\n engine: GraphEngine,\n compiled: CompiledGraph,\n task: string,\n options: GraphRunOptions,\n wakes: QueuedWake[],\n onWakeSignal: (fn: () => void) => void,\n): Promise<GraphRunResult> {\n assertRunnable(engine, compiled, options)\n const now = options.now ?? Date.now\n const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`\n let detachOuterAbort: () => void = () => {}\n const context = await openGraphRun({\n compiled,\n runId,\n budget: options.budget,\n ...(options.journal !== undefined ? { journal: options.journal } : {}),\n ...(options.blobs !== undefined ? { blobs: options.blobs } : {}),\n now,\n ...(options.resume !== undefined ? { resume: options.resume } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n onAbort: (detach) => {\n detachOuterAbort = detach\n },\n })\n const { abort, blobs, journal, scope, state } = context\n const ledger = createEdgeLedger({ journal, runId, now, startSeq: context.ledgerSeq })\n let engineSeq = context.engineSeq\n let wokenSeq = context.engineWokenSeq\n\n const liveHandles = new Map<string, string>() // kernel node id -> engine instance label\n const waitingForBudget: string[] = []\n const outCache = new Map<string, unknown>()\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n /** Journal one engine event, then apply it through the reducer a restart will replay. */\n const emit = async (ev: SpawnEvent): Promise<void> => {\n await journal.appendEvent(runId, ev)\n applyGraphFoldEvent(state, ev, compiled)\n }\n const stamp = () => new Date(now()).toISOString()\n\n const fail = (reason: GraphRunReason, name: string, message: string): void => {\n failure = { reason, error: { name, message } }\n abort.abort(`${reason}: ${message}`)\n }\n\n // ── Spawning ───────────────────────────────────────────────────────────────────\n\n /** The ONE entry path: spawn a released instance from its journaled envelope. Used by a fresh\n * release, a budget-parked retry, and a restart re-entry alike. */\n const spawnInstance = async (label: string): Promise<void> => {\n if (failure) return\n const instance = state.instances.get(label)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node || instance.inputRef === undefined) {\n throw new ValidationError(`runEngineGraph: instance ${label} 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 `runEngineGraph: envelope ${instance.inputRef} is not in the blob store`,\n )\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: narrowEffects(node.kind.effects, engine.effects, `runEngineGraph: node ${node.id}`),\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, envelope.task, { label, budget })\n if (spawned.ok) {\n liveCount += 1\n liveHandles.set(spawned.handle.id, label)\n // The kernel journaled its own `spawned` row inside `scope.spawn`; mirror the two fields the\n // reducer folds, so live state matches what a restart reconstructs.\n applyGraphFoldEvent(\n state,\n {\n kind: 'spawned',\n id: spawned.handle.id,\n label,\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 waitingForBudget.push(label) // never overcommit: retry after the next settle frees capacity\n return\n }\n fail('driver-failed', 'SpawnRefused', `node ${node.id}: ${spawned.reason}`)\n }\n\n /** Pin an instance's envelope (inputs + task) by content address; answers the instance label. */\n const openInstance = async (\n nodeId: string,\n visit: number,\n envelope: { task: string; inputs: Record<string, unknown> },\n ): Promise<string> => {\n const label = `${nodeId}#${visit}`\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: nodeId,\n instance: label,\n inputRef,\n seq: engineSeq++,\n at: stamp(),\n })\n return label\n }\n\n const enterEntryNode = async (nodeId: string): 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) return\n await spawnInstance(await openInstance(nodeId, visit, { task, inputs: {} }))\n }\n\n // ── Releasing ──────────────────────────────────────────────────────────────────\n\n /** Build the released instance's envelope from its wave: data payloads projected and admitted,\n * directives resolved, trace refs lined up — every consumption ledgered as it is taken. */\n const consumeWave = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n ): Promise<{ task: string; inputs: Record<string, unknown> }> => {\n const inputs: Record<string, unknown> = {}\n const directives: string[] = []\n const traces: string[] = []\n for (const { edge, folded } of consuming) {\n const spec = edge.spec\n const traversal = (folded?.traversals ?? 0) + 1\n if (spec.kind === 'data' && folded?.state === 'satisfied') {\n let payload =\n folded.payloadRef === undefined\n ? undefined\n : (outCache.get(folded.payloadRef) ?? admitPayload(await blobs.get(folded.payloadRef)))\n let outcome: 'delivered' | 'empty' = '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 = 'empty'\n await ledger.record(edge, traversal, outcome, reason)\n if (payload !== undefined) inputs[edge.toPort] = payload\n continue\n }\n if (spec.directive !== undefined && options.prompts !== undefined) {\n directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && folded?.state === 'satisfied') {\n traces.push(`trace of ${spec.from.node}: ${folded.payloadRef ?? '(no traceRef)'}`)\n }\n await ledger.record(edge, traversal, 'delivered')\n }\n const composed = [nodeId === compiled.root ? task : '', ...directives, ...traces]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n return { task: composed.length > 0 ? composed : task, inputs }\n }\n\n const release = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n consumedPending: ReadonlyArray<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 fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n const envelope = await consumeWave(nodeId, consuming)\n const label = await openInstance(nodeId, visit, envelope)\n await emit({\n kind: 'join-state',\n id: label,\n node: nodeId,\n rule: node.join,\n satisfiedBy: consuming.map(({ edge }) => edge.id),\n consumedPending: [...consumedPending],\n instance: label,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n\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: GatingEdge[] = node.inbound.map((edge) => ({\n edge,\n folded: state.edges.get(edge.id),\n }))\n const decision = decideJoin(node.join, gating)\n if (decision.blocked) folded.blocked = true\n if (!decision.release) return\n // Caps are judged on the consuming edges BEFORE anything else happens, and the refusal is\n // journaled so a restart sees the same exhaustion.\n for (const entry of decision.consuming) {\n const cap = entry.edge.spec.maxTraversals\n if (cap !== undefined && (entry.folded?.traversals ?? 0) >= cap) {\n await ledger.record(\n entry.edge,\n (entry.folded?.traversals ?? 0) + 1,\n 'unpropagated',\n `traversal-cap-exhausted (max ${cap})`,\n )\n await emit({\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: stamp(),\n })\n return\n }\n }\n const consumedPending = gating\n .filter(\n (entry) => entry.folded?.state === 'pending' && hasLiveInstance(entry.edge.spec.from.node),\n )\n .map((entry) => entry.edge.id)\n await release(nodeId, decision.consuming, consumedPending)\n }\n\n const hasLiveInstance = (nodeId: string): boolean => {\n for (const label of liveHandles.values()) {\n if (state.instances.get(label)?.node === nodeId) return true\n }\n return false\n }\n\n // ── Judging ────────────────────────────────────────────────────────────────────\n\n /** Journal a verdict for every unaccounted outbound edge of a settle, then try the joins. */\n const propagate = async (label: 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 // A `delegates` target is spawned by its supervisor inside the kernel's authorized path,\n // with the pin and the directive applied there — the scheduler judges nothing (#971).\n if (!isEngineFired(edge)) continue\n const folded = state.edges.get(edge.id)\n if (!folded || 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 fired =\n edge.spec.guard === undefined ||\n evaluateCondition(edge.spec.guard, {\n node: settle.node,\n out: settle.out,\n visits: state.nodes.get(settle.node)?.visits ?? 0,\n valid: settle.valid ?? true,\n })\n if (fired) {\n inputRef =\n edge.spec.kind === 'analyzes'\n ? (settle as { traceRef?: string }).traceRef\n : settle.outRef\n }\n }\n await emit({\n kind: 'edge-verdict',\n id: label,\n edge: edge.id,\n fired,\n sourceStatus: settle.status === 'down' ? 'down' : succeeded ? 'done' : 'invalid',\n ...(inputRef !== undefined ? { inputRef } : {}),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n for (const edge of node.outbound) {\n if (isEngineFired(edge)) await tryRelease(edge.spec.to.node)\n }\n }\n\n // ── Suspensions ────────────────────────────────────────────────────────────────\n\n const park = async (label: string, request: SuspensionRequest): Promise<void> => {\n const token = mintSuspensionToken(runId, label)\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 emit({\n kind: 'waiting',\n id: suspensionNodeId(token),\n label,\n spec: {\n kind: 'token',\n token,\n onExpire: request.onExpire,\n ...(request.expiresInMs !== undefined ? { expiresAtMs: now() + request.expiresInMs } : {}),\n ...(defaultRef !== undefined ? { defaultRef } : {}),\n },\n armedAt: now(),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n\n const wake = async (\n suspension: FoldSuspension,\n by: 'fired' | 'expired',\n outRef?: string,\n ): Promise<void> => {\n await emit({\n kind: 'woken',\n id: suspensionNodeId(suspension.token),\n by,\n ...(outRef !== undefined ? { outRef } : {}),\n seq: wokenSeq++,\n at: stamp(),\n })\n const settle = state.instances.get(suspension.instance)?.settle\n if (settle === undefined) return\n const out =\n settle.outRef === undefined ? undefined : admitPayload(await blobs.get(settle.outRef))\n if (settle.outRef !== undefined && out !== undefined) outCache.set(settle.outRef, out)\n await propagate(suspension.instance, out === undefined ? settle : { ...settle, out })\n }\n\n /** Expiries are engine-clocked, so an offline run transitions them without a host sweep (#976). */\n const expireDue = async (): Promise<boolean> => {\n let transitioned = false\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 else continue\n transitioned = true\n }\n return transitioned\n }\n\n const drainWakes = async (): Promise<void> => {\n while (wakes.length > 0) {\n const request = wakes.shift()\n if (!request) return\n try {\n const suspension = state.suspensions.get(request.token)\n if (!suspension) throw new ValidationError(`graph resume: unknown token '${request.token}'`)\n if (suspension.status !== 'pending') {\n throw new ValidationError(`graph resume: token '${request.token}' already woken`)\n }\n if (request.expire) {\n await wake(\n suspension,\n suspension.onExpire === 'default' ? 'fired' : 'expired',\n suspension.onExpire === 'default' ? suspension.defaultRef : undefined,\n )\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 // ── Settling ───────────────────────────────────────────────────────────────────\n\n const handleSettle = async (settled: Settled<unknown>): Promise<void> => {\n const label = liveHandles.get(settled.handle.id)\n if (label === undefined) return\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const instance = state.instances.get(label)\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 park(label, settled.out)\n return\n }\n // Mirror the kernel's own journaled settle through the reducer, then enrich it 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(label)?.settle\n if (!folded) return\n let enriched = folded\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n if (settled.outRef !== undefined) outCache.set(settled.outRef, admitted)\n enriched = { ...folded, out: admitted, ...(await checkDeliverable(node, admitted)) }\n const settles = state.nodes.get(instance.node)?.settles\n if (settles) settles[settles.length - 1] = enriched\n ;(state.instances.get(label) as { settle?: GraphNodeSettle }).settle = enriched\n }\n // Root completion ends the run the moment its check passes (#973).\n if (instance.node === compiled.root && enriched.status === 'done' && enriched.valid === true) {\n abort.abort('root delivered')\n return\n }\n await propagate(label, enriched)\n }\n\n const checkDeliverable = async (\n node: CompiledGraph['nodes'] extends ReadonlyMap<string, infer N> ? N : never,\n out: unknown,\n ): Promise<{ valid?: boolean }> => {\n if (node.deliverable === undefined) return {}\n try {\n return { valid: await node.deliverable.check(out) }\n } catch {\n return { valid: false }\n }\n }\n\n // ── Entry / restart ────────────────────────────────────────────────────────────\n\n if (!context.resuming) {\n for (const id of compiled.entries) await enterEntryNode(id)\n } else {\n await reenterAfterCrash()\n }\n\n /** Kill-anywhere re-entry: finish every half-done transition the crashed process left, from the\n * pinned envelopes and journaled settles only — never by re-deriving anything (#974). */\n async function reenterAfterCrash(): Promise<void> {\n for (const instance of [...state.instances.values()]) {\n if (instance.status === 'released') {\n await spawnInstance(instance.instance)\n continue\n }\n if (instance.status !== 'live') continue\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 fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n // In-doubt: the journal keeps its reservation charged (the kernel's rule), and the restart\n // re-enters from the SAME pinned envelope.\n instance.status = 'down'\n const label = `${instance.node}#${visit}`\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: instance.node,\n instance: label,\n inputRef: instance.inputRef as string,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n for (const [nodeId, folded] of state.nodes) {\n const latest = folded.settles.at(-1)\n if (latest === undefined) continue\n const label = `${nodeId}#${latest.visit}`\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 transition\n // instead of propagating the park marker as data.\n folded.settles.pop()\n const instance = state.instances.get(label)\n if (instance) instance.settle = undefined\n await park(label, out)\n continue\n }\n outCache.set(latest.outRef, out)\n const node = compiled.nodes.get(nodeId)\n await propagate(label, {\n ...latest,\n out,\n ...(node === undefined ? {} : await checkDeliverable(node, out)),\n })\n continue\n }\n await propagate(label, latest)\n }\n for (const id of compiled.entries) {\n if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id)\n }\n for (const id of compiled.nodes.keys()) await tryRelease(id)\n }\n\n // ── The loop ───────────────────────────────────────────────────────────────────\n\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0)\n\n let wakeSignal = Promise.resolve()\n const rearmWakeSignal = () => {\n wakeSignal = new Promise<void>((fire) => {\n onWakeSignal(fire)\n })\n }\n rearmWakeSignal()\n\n let pendingNext: Promise<Settled<unknown> | null> | undefined\n while (!failure) {\n if (await expireDue()) continue\n if (wakes.length > 0) {\n await drainWakes()\n continue\n }\n if (allTerminalsSettled()) break\n if (liveCount === 0) {\n const parked = [...state.suspensions.values()].filter(\n (suspension) => suspension.status === 'pending',\n )\n if (parked.length === 0) break // stuck or complete: `assembleGraphResult` classifies it\n if (options.waitForWakes) {\n rearmWakeSignal()\n await wakeSignal\n continue\n }\n // Offline (#976): no host will answer, so a `default` suspension resolves now; `wait` and a\n // future `fail` deadline park the run as a resumable artifact.\n const defaulting = parked.filter((suspension) => suspension.onExpire === 'default')\n if (defaulting.length === 0) break\n for (const suspension of defaulting) await wake(suspension, 'fired', suspension.defaultRef)\n continue\n }\n pendingNext ??= scope.next()\n const raced = await Promise.race([\n pendingNext.then((settle) => ({ settle })),\n wakeSignal.then(() => 'wake' as const),\n ])\n if (raced === 'wake') {\n rearmWakeSignal()\n continue // the queued wakes run on the next turn; `pendingNext` stays armed\n }\n pendingNext = undefined\n if (raced.settle === null) break\n await handleSettle(raced.settle)\n for (const label of waitingForBudget.splice(0)) await spawnInstance(label)\n }\n\n detachOuterAbort()\n abort.abort('graph loop complete')\n while ((await (pendingNext ?? scope.next())) !== null) pendingNext = undefined\n\n return assembleGraphResult({\n compiled,\n state,\n blobs,\n scope,\n outCache,\n ledger: ledger.entries,\n ...(options.finalizer !== undefined ? { finalizer: options.finalizer } : {}),\n ...(failure !== undefined ? { failure } : {}),\n aborted: options.signal?.aborted ?? false,\n })\n}\n","/**\n * The `runGraph` preset (agent-runtime#982, #975): today's `AgentGraph` compiled into an engine\n * graph and run by the engine. `runGraph` keeps its signature and becomes this call, so the six\n * consumers measured in #967 change nothing.\n *\n * WHAT THE ENGINE GRAPH LOOKS LIKE. One `supervisor` root carrying the whole graph, one pinned\n * `agent` node per worker, and the `delegates`/`analyzes` edges as authored. A `delegates` edge is\n * MODEL-fired (#971): its target is spawned by the supervisor through the coordination protocol,\n * with the node pin and the directive applied inside the kernel's authorized path. So the engine\n * schedules exactly one node — the supervisor — and the worker nodes are the declarative record of\n * what it may spawn. That record is what makes a `runGraph` graph a first-class engine graph:\n * compiled, type-checked, inspectable, and composable with `data` edges and `script` nodes.\n *\n * WHY THE ROOT NODE RUNS `superviseAgentGraph`. The engine's `supervisor` kind IS `supervisorAgent`\n * (#970), and the graph authority — pinning, the edge ledger, per-edge caps, continuity — already\n * lives in that one function. Executing it as the root node's body preserves every one of #967's\n * load-bearing properties by construction rather than by re-implementation.\n */\n\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { AgentGraph, GraphResult, RunGraphOptions } from '../supervise/graph'\nimport { kernelPromptRegistry } from '../supervise/prompt-registry'\nimport type { Agent, AgentSpec, Executor, ExecutorResult, Spend } from '../supervise/types'\nimport type { ToolLoopChat } from '../tool-loop'\nimport { compileGraph } from './compile'\nimport type { EngineGraphEdge, EngineGraphNode, EngineGraphSpec } from './definition'\nimport { createGraphEngine, type GraphEngine } from './engine'\nimport type { NodeKind } from './kind'\nimport { agentKind } from './kinds'\nimport { runEngineGraph } from './scheduler'\nimport type { GraphRunResult } from './scheduler-types'\n\n/** The preset's root kind: one node whose body is the graph's supervise run. */\nexport const RUN_GRAPH_KIND = 'run-graph.supervisor'\n\n/** The graph supervise run, injected rather than imported: the preset describes the graph, and\n * `runGraph` supplies the body, so this module never imports its caller at runtime. */\nexport type RunGraphBody = (\n graph: AgentGraph,\n options: RunGraphOptions,\n brain?: ToolLoopChat,\n) => Promise<GraphResult>\n\n/** Where the run body's raw failure is kept. A node's output crosses the edge-admission boundary\n * (JSON round-trip), which would reduce an `Error` to a plain object and a typed\n * `GraphEdgeCapError` to an untyped one. The error therefore travels beside the output, by\n * reference, and the preset rethrows the ORIGINAL object. */\nexport interface RunGraphCapture {\n error?: unknown\n}\n\n/** What the root node carries: the authored graph, the caller's options, and the run body. */\nexport interface RunGraphNodeConfig {\n readonly graph: AgentGraph\n readonly options: RunGraphOptions\n readonly run: RunGraphBody\n readonly capture: RunGraphCapture\n readonly brain?: ToolLoopChat\n}\n\n/** The run's outcome as the root node's output: never a throw, so a typed failure (an exhausted\n * delegates cap) reaches the caller as the exact error object rather than a settle reason. */\nexport type RunGraphNodeOut =\n | { readonly ok: true; readonly result: GraphResult }\n /** The message only; the raw error rides in {@link RunGraphCapture}. */\n | { readonly ok: false; readonly error: string }\n\nfunction spendOf(out: RunGraphNodeOut): Spend {\n const measured = out.ok ? out.result.result.spentTotal : undefined\n return measured ?? { iterations: 1, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 }\n}\n\n/**\n * The node kind behind the preset. Its executor runs the graph and reports the run's own measured\n * spend, so the engine pool debits what the graph actually used, never a second copy of it.\n */\nexport function runGraphKind(): NodeKind<RunGraphNodeConfig> {\n return {\n id: RUN_GRAPH_KIND,\n version: 1,\n description: 'One AgentGraph supervise run as an engine node (the runGraph preset).',\n validateConfig: (raw, context) => {\n if (typeof raw !== 'object' || raw === null) {\n throw new ValidationError(`${context}: config must carry { graph, options }`)\n }\n const config = raw as Partial<RunGraphNodeConfig>\n if (\n config.graph === undefined ||\n config.options === undefined ||\n config.run === undefined ||\n config.capture === undefined\n ) {\n throw new ValidationError(`${context}: config must carry { graph, options, run, capture }`)\n }\n return config as RunGraphNodeConfig\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: ({ config, profile }) => {\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n async execute(): Promise<ExecutorResult<unknown>> {\n const out: RunGraphNodeOut = await config\n .run(config.graph, config.options, config.brain)\n .then(\n (result) => ({ ok: true, result }) as const,\n (error: unknown) => {\n config.capture.error = error\n return { ok: false, error: String(error) } as const\n },\n )\n artifact = { outRef: contentAddress({ runGraph: out.ok }), out, spent: spendOf(out) }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact: () => {\n if (!artifact) {\n throw new ValidationError(`${RUN_GRAPH_KIND}: resultArtifact() read before execute()`)\n }\n return artifact\n },\n }\n return {\n name: profile.name ?? 'graph',\n act: () =>\n Promise.reject(new ValidationError(`${RUN_GRAPH_KIND}: act() is not the execution path`)),\n executorSpec: { profile, harness: null, executor } as AgentSpec,\n } as Agent<unknown, unknown> & { executorSpec: AgentSpec }\n },\n }\n}\n\n/** An engine with the preset kind registered beside the core `agent` kind the workers use. */\nexport function runGraphEngine(): GraphEngine {\n // Each kind fixes its own `Config`, so the heterogeneous set widens here — the registry stores\n // `NodeKind<unknown>` and every kind validates its own config on the way in.\n const kinds = [agentKind({}), runGraphKind()] as unknown as ReadonlyArray<NodeKind>\n return createGraphEngine({ coreKinds: kinds })\n}\n\n/**\n * Compile an `AgentGraph` into the engine graph that represents it: the supervisor root, one\n * pinned `agent` node per worker, and every authored edge. Pure — nothing runs, so a caller can\n * inspect, diff, or extend the result before handing it to the engine.\n */\nexport function graphFromRunGraph(\n graph: AgentGraph,\n options: RunGraphOptions,\n run: RunGraphBody,\n capture: RunGraphCapture = {},\n brain?: ToolLoopChat,\n): EngineGraphSpec {\n const root = graph.nodes[0]\n if (root === undefined) throw new ValidationError('graphFromRunGraph: a graph needs a root node')\n const nodes: EngineGraphNode[] = graph.nodes.map((node, index) =>\n index === 0\n ? {\n id: node.id,\n kind: `${RUN_GRAPH_KIND}/v1`,\n config: { graph, options, run, capture, ...(brain !== undefined ? { brain } : {}) },\n profile: node.profile,\n budget: graph.budget,\n terminal: true,\n // The engine-level check is that the run produced its graph result; whether that result\n // found a winner is the graph's own business, carried inside it.\n deliverable: {\n check: (out: unknown) => (out as RunGraphNodeOut | undefined)?.ok === true,\n },\n }\n : {\n id: node.id,\n kind: 'agent/v1',\n profile: node.profile,\n // Spawned by the supervisor through its delegates edges: never entered, never awaited,\n // and never a terminal of the scheduler's run.\n entry: false,\n terminal: false,\n budget: options.perWorker ?? graph.budget,\n },\n )\n const edges: EngineGraphEdge[] = graph.edges.flatMap((edge): EngineGraphEdge[] =>\n edge.kind === 'delegates'\n ? [\n {\n kind: 'delegates' as const,\n from: { node: edge.from },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n },\n ]\n : // One engine edge per analysed source: the engine's edges are 1:1, the authored form fans in.\n edge.over.map((source) => ({\n kind: 'analyzes' as const,\n from: { node: source, port: 'trace' },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n })),\n )\n return { nodes, edges, root: root.id, deliverable: graph.deliverable }\n}\n\n/**\n * Run an `AgentGraph` through the engine: compile it with {@link graphFromRunGraph}, schedule it,\n * and answer the caller in `runGraph`'s own vocabulary. A typed failure the graph threw — an\n * exhausted delegates cap — is rethrown as the exact error object it was, never flattened into a\n * settle reason.\n */\nexport function runGraphThroughEngine(\n graph: AgentGraph,\n options: RunGraphOptions,\n run: RunGraphBody,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const engine = runGraphEngine()\n const capture: RunGraphCapture = {}\n // Compiling here, synchronously, is deliberate: a structural refusal reaches the caller as a\n // throw rather than a rejection, which is the contract `runGraph` has always had.\n const spec = graphFromRunGraph(graph, options, run, capture, brain)\n const root = spec.root as string\n // The engine's own tree is a sibling of the graph's: the graph keeps `options.runId` for its\n // journal, so every consumer reading that tree (discovery-lab's provenance classifier) is\n // unaffected by the preset.\n const engineRunId = `${options.runId ?? contentAddress({ graph: root }).slice(0, 18)}:engine`\n const compiled = compileGraph(engine, spec, 'runGraph')\n return runEngineGraph(engine, compiled, graphRootTask(graph), {\n budget: graph.budget,\n perNode: graph.budget,\n ...(options.journal !== undefined ? { journal: options.journal } : {}),\n ...(options.blobs !== undefined ? { blobs: options.blobs } : {}),\n // The same default `runGraph` itself applies, so an authored directive always resolves.\n prompts: options.registry ?? kernelPromptRegistry(),\n runId: engineRunId,\n }).then((finished) => mapEngineResult(finished, root, capture))\n}\n\nfunction mapEngineResult(run: GraphRunResult, root: string, capture: RunGraphCapture): GraphResult {\n if (capture.error !== undefined) throw capture.error\n const settle = run.settles.find((entry) => entry.node === root)\n const out = settle?.out as RunGraphNodeOut | undefined\n if (out === undefined) {\n throw new ValidationError(\n `runGraph: the engine returned no settlement for root node '${root}' (${run.kind}${\n run.kind === 'no-winner' ? `/${run.reason}` : ''\n })`,\n )\n }\n if (!out.ok) throw new ValidationError(`runGraph: ${out.error}`)\n return out.result\n}\n\n/** The root's task line, as `runGraph` composes it today. */\nfunction graphRootTask(graph: AgentGraph): string {\n const root = graph.nodes[0]\n return root === undefined ? 'run the graph' : `run graph from '${root.id}'`\n}\n","/**\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 { runGraphThroughEngine } from '../graph/preset-run-graph'\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 // The preset compiles this graph into an engine graph and runs it there (agent-runtime#982). The\n // signature, the options and the result are unchanged: a caller sees no difference, including\n // the timing of a refusal — the authoring contract is asserted here, synchronously, first.\n assertRunGraphAuthoring(graph, runtimeOptions, brain)\n return runGraphThroughEngine(graph, runtimeOptions, superviseAgentGraph, 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 assertRunGraphAuthoring(graph, runtimeOptions, brain)\n return runGraphThroughEngine(graph, runtimeOptions, superviseAgentGraph, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const { root } = validated\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // 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 return validated\n}\n\nexport function superviseAgentGraph(\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 } = assertRunGraphAuthoring(\n graph,\n opts,\n brain,\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":";;;;;;;;;;;;;;;;;;;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,KAAK,MAAM,GAAG,GAAG;EAClC,MAAM,OAAO,KAAK,QAAQ,GAAG;EAC7B,MAAM,OAAO,SAAS,KAAK,OAAO,KAAK,MAAM,GAAG,IAAI;EACpD,IAAI,KAAK,SAAS,GAAG;GACnB,IAAI,CAAC,aAAa,KAAK,IAAI,GACzB,MAAM,IAAI,gBACR,GAAG,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