@tangle-network/agent-runtime 0.164.0 → 0.165.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 (68) hide show
  1. package/dist/{activation-CneAm4jL.js → activation-DmUIq51m.js} +3 -3
  2. package/dist/{activation-CneAm4jL.js.map → activation-DmUIq51m.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{authoring-CZM22nUG.js → authoring-Cm122Duf.js} +2 -2
  6. package/dist/{authoring-CZM22nUG.js.map → authoring-Cm122Duf.js.map} +1 -1
  7. package/dist/candidate-execution/index.js +4 -4
  8. package/dist/{candidate-execution-DNLk6h0A.js → candidate-execution-DC0T8l2p.js} +4 -4
  9. package/dist/{candidate-execution-DNLk6h0A.js.map → candidate-execution-DC0T8l2p.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/durable.d.ts +2 -2
  12. package/dist/durable.js +1 -1
  13. package/dist/{environment-provider-BXFFK_rZ.d.ts → environment-provider-DWjbGH8W.d.ts} +2 -2
  14. package/dist/environment-provider.d.ts +1 -1
  15. package/dist/{graph-DzE4SwfP.js → graph-DGri_zJm.js} +3 -3
  16. package/dist/{graph-DzE4SwfP.js.map → graph-DGri_zJm.js.map} +1 -1
  17. package/dist/graph.d.ts +155 -53
  18. package/dist/graph.js +946 -330
  19. package/dist/graph.js.map +1 -1
  20. package/dist/{improvement-cycle-a_L8FFql.js → improvement-cycle-BOd5DFeG.js} +4 -4
  21. package/dist/{improvement-cycle-a_L8FFql.js.map → improvement-cycle-BOd5DFeG.js.map} +1 -1
  22. package/dist/{index-BP11HXYi.d.ts → index-BGQtpQuJ.d.ts} +5 -5
  23. package/dist/{index-C2X-OVPZ.d.ts → index-BgptUCKl.d.ts} +4 -4
  24. package/dist/{index-OFOvnNc2.d.ts → index-CFMB9ux3.d.ts} +2 -2
  25. package/dist/index.d.ts +7 -7
  26. package/dist/index.js +11 -11
  27. package/dist/intelligence.d.ts +4 -4
  28. package/dist/intelligence.js +5 -5
  29. package/dist/kernel.d.ts +5 -5
  30. package/dist/kernel.js +7 -7
  31. package/dist/{knowledge-Ccdghy81.js → knowledge-7_IfyD9R.js} +5 -5
  32. package/dist/{knowledge-Ccdghy81.js.map → knowledge-7_IfyD9R.js.map} +1 -1
  33. package/dist/knowledge.d.ts +1 -1
  34. package/dist/knowledge.js +1 -1
  35. package/dist/{loop-runner-bin-2NITRIFc.d.ts → loop-runner-bin-C2NXQK7J.d.ts} +3 -3
  36. package/dist/{loop-runner-bin-DM-AnPC-.js → loop-runner-bin-Dx-5GZQK.js} +3 -3
  37. package/dist/{loop-runner-bin-DM-AnPC-.js.map → loop-runner-bin-Dx-5GZQK.js.map} +1 -1
  38. package/dist/loop-runner-bin.d.ts +1 -1
  39. package/dist/loop-runner-bin.js +1 -1
  40. package/dist/mcp/bin.js +3 -3
  41. package/dist/mcp/index.d.ts +3 -3
  42. package/dist/mcp/index.js +4 -4
  43. package/dist/{openai-tools-CIo9tB75.js → openai-tools-CDS7eSww.js} +2 -2
  44. package/dist/{openai-tools-CIo9tB75.js.map → openai-tools-CDS7eSww.js.map} +1 -1
  45. package/dist/{prepare-D7Fb75XR.js → prepare-BCScSDCv.js} +2 -2
  46. package/dist/{prepare-D7Fb75XR.js.map → prepare-BCScSDCv.js.map} +1 -1
  47. package/dist/primeintellect/index.d.ts +1 -1
  48. package/dist/{protected-model-port-RZkxRZhp.js → protected-model-port-D-5E3HBe.js} +2 -2
  49. package/dist/{protected-model-port-RZkxRZhp.js.map → protected-model-port-D-5E3HBe.js.map} +1 -1
  50. package/dist/{redact-D4vlt6p4.d.ts → redact-DkObldQP.d.ts} +3 -3
  51. package/dist/{runtime-D44YrQ4t.d.ts → runtime-B0HZbuEv.d.ts} +3 -3
  52. package/dist/{runtime-BDHsMgCK.js → runtime-DESENUe1.js} +7 -7
  53. package/dist/{runtime-BDHsMgCK.js.map → runtime-DESENUe1.js.map} +1 -1
  54. package/dist/{spawn-journal-oewq1g2h.js → spawn-journal-Tgvp5VS5.js} +8 -2
  55. package/dist/{spawn-journal-oewq1g2h.js.map → spawn-journal-Tgvp5VS5.js.map} +1 -1
  56. package/dist/{stream-agent-turn-Dx2YrEWW.d.ts → stream-agent-turn-DxQ3GOuR.d.ts} +2 -2
  57. package/dist/{structural-rollout-CBK2LHni.js → structural-rollout-DZGDg0yX.js} +3 -3
  58. package/dist/{structural-rollout-CBK2LHni.js.map → structural-rollout-DZGDg0yX.js.map} +1 -1
  59. package/dist/{supervise-CzllE0vn.js → supervise-Da20R0PO.js} +3 -3
  60. package/dist/{supervise-CzllE0vn.js.map → supervise-Da20R0PO.js.map} +1 -1
  61. package/dist/{supervisor-D5K8ihKQ.js → supervisor-DpIKMlPJ.js} +9 -5
  62. package/dist/{supervisor-D5K8ihKQ.js.map → supervisor-DpIKMlPJ.js.map} +1 -1
  63. package/dist/testing.d.ts +2 -2
  64. package/dist/testing.js +12 -12
  65. package/dist/{types-C2l1jaos.d.ts → types-DjVO-p7R.d.ts} +58 -3
  66. package/dist/{workspace-archive-DK0mDjSB.js → workspace-archive-CHY5HvrF.js} +2 -2
  67. package/dist/{workspace-archive-DK0mDjSB.js.map → workspace-archive-CHY5HvrF.js.map} +1 -1
  68. package/package.json +1 -1
package/dist/graph.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"graph.js","names":[],"sources":["../src/runtime/graph/condition.ts","../src/runtime/graph/projection.ts","../src/runtime/graph/registry.ts","../src/runtime/graph/definition.ts","../src/runtime/graph/compile.ts","../src/runtime/graph/kind.ts","../src/runtime/graph/engine.ts","../src/runtime/graph/kinds.ts","../src/runtime/graph/scheduler.ts"],"sourcesContent":["/**\n * The ONE predicate tree: every guard in a graph — an edge `guard`, a filter projection's\n * predicate — is this shape, evaluated by this evaluator, so `contains`, ordering and equality can\n * never mean two different things on two surfaces (adopted from ADC's `workflow-conditions`,\n * agent-runtime#968). A declarative tree keeps an untrusted predicate incapable of code execution;\n * the size and depth bounds keep a predicate authored once from burning CPU on every settle.\n *\n * No zod: the kernel's grain is a hand-written validator that throws `ValidationError` by name.\n */\nimport { ValidationError } from '../../errors'\n\n/** The leaf comparison operators; `exists`/`truthy` are unary, the rest compare against `value`. */\nexport const CONDITION_OPS = [\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'in',\n 'contains',\n 'exists',\n 'truthy',\n] as const\nexport type ConditionOp = (typeof CONDITION_OPS)[number]\n\n/** Operators that compare against `value`; `exists`/`truthy` are unary and must omit it. */\nconst OPS_NEEDING_VALUE: ReadonlySet<ConditionOp> = new Set(\n CONDITION_OPS.filter((op) => op !== 'exists' && op !== 'truthy'),\n)\n\nexport interface ConditionLeaf {\n /** Dotted path with `[N]` indexing into the guard context, e.g. `out.findings[0].severity`. */\n readonly path: string\n readonly op: ConditionOp\n readonly value?: unknown\n}\n\nexport type Condition =\n | ConditionLeaf\n | { readonly all: ReadonlyArray<Condition> }\n | { readonly any: ReadonlyArray<Condition> }\n | { readonly not: Condition }\n\nexport const MAX_CONDITION_NODES = 40\nexport const MAX_CONDITION_DEPTH = 6\nconst MAX_PATH_LENGTH = 256\nconst MAX_PATH_SEGMENTS = 16\nconst PATH_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$-]*$/u\n\ntype PathStep = string | number\n\n/** Parse `a.b[0].c` into steps; refuse anything outside the bounded grammar. */\nexport function parseConditionPath(path: string, context: string): ReadonlyArray<PathStep> {\n if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH_LENGTH) {\n throw new ValidationError(\n `${context}: path must be a non-empty string of at most ${MAX_PATH_LENGTH} chars`,\n )\n }\n const steps: PathStep[] = []\n for (const part of path.split('.')) {\n const open = part.indexOf('[')\n const head = open === -1 ? part : part.slice(0, open)\n if (head.length > 0) {\n if (!PATH_SEGMENT.test(head)) {\n throw new ValidationError(\n `${context}: path segment ${JSON.stringify(head)} is not addressable`,\n )\n }\n steps.push(head)\n } else if (open !== 0 || steps.length === 0) {\n throw new ValidationError(`${context}: path ${JSON.stringify(path)} has an empty segment`)\n }\n let rest = open === -1 ? '' : part.slice(open)\n while (rest.length > 0) {\n const match = /^\\[(\\d{1,6})\\]/u.exec(rest)\n if (!match) {\n throw new ValidationError(`${context}: path index in ${JSON.stringify(part)} must be [N]`)\n }\n steps.push(Number(match[1]))\n rest = rest.slice(match[0].length)\n }\n if (steps.length > MAX_PATH_SEGMENTS) {\n throw new ValidationError(`${context}: path exceeds ${MAX_PATH_SEGMENTS} segments`)\n }\n }\n if (steps.length === 0) throw new ValidationError(`${context}: path resolves no segment`)\n return steps\n}\n\n/** Walk a parsed path; any miss resolves `undefined`, never a throw — absence is an answer. */\nexport function resolveConditionPath(context: unknown, steps: ReadonlyArray<PathStep>): unknown {\n let current: unknown = context\n for (const step of steps) {\n if (current === null || current === undefined) return undefined\n if (typeof step === 'number') {\n if (!Array.isArray(current)) return undefined\n current = current[step]\n } else {\n if (typeof current !== 'object' || Array.isArray(current)) return undefined\n current = (current as Record<string, unknown>)[step]\n }\n }\n return current\n}\n\nfunction isLeaf(condition: Condition): condition is ConditionLeaf {\n return typeof (condition as ConditionLeaf).path === 'string'\n}\n\n/** Validate shape, bounds, and per-leaf path/operator rules; returns the input for chaining. */\nexport function validateCondition(raw: unknown, context: string): Condition {\n let nodes = 0\n const walk = (value: unknown, depth: number): Condition => {\n nodes += 1\n if (nodes > MAX_CONDITION_NODES) {\n throw new ValidationError(`${context}: condition exceeds ${MAX_CONDITION_NODES} nodes`)\n }\n if (depth > MAX_CONDITION_DEPTH) {\n throw new ValidationError(`${context}: condition exceeds depth ${MAX_CONDITION_DEPTH}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: a condition must be an object`)\n }\n const record = value as Record<string, unknown>\n const combinators = ['all', 'any', 'not'].filter((key) => record[key] !== undefined)\n if (combinators.length > 1) {\n throw new ValidationError(\n `${context}: a condition carries ONE of all/any/not, got ${combinators.join('+')}`,\n )\n }\n if (record.all !== undefined || record.any !== undefined) {\n const key = record.all !== undefined ? 'all' : 'any'\n const branch = record[key]\n if (!Array.isArray(branch) || branch.length === 0) {\n throw new ValidationError(`${context}: ${key} must be a non-empty array`)\n }\n for (const child of branch) walk(child, depth + 1)\n return value as Condition\n }\n if (record.not !== undefined) {\n walk(record.not, depth + 1)\n return value as Condition\n }\n const op = record.op\n if (typeof record.path !== 'string' || typeof op !== 'string') {\n throw new ValidationError(`${context}: a leaf needs { path, op }`)\n }\n if (!(CONDITION_OPS as ReadonlyArray<string>).includes(op)) {\n throw new ValidationError(\n `${context}: unknown op ${JSON.stringify(op)}; known: ${CONDITION_OPS.join(', ')}`,\n )\n }\n parseConditionPath(record.path, context)\n const needsValue = OPS_NEEDING_VALUE.has(op as ConditionOp)\n if (needsValue && !('value' in record)) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} requires a value`)\n }\n if (!needsValue && 'value' in record) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} is unary — remove value`)\n }\n if (op === 'in' && !Array.isArray(record.value)) {\n throw new ValidationError(`${context}: op \"in\" takes an array value`)\n }\n return value as Condition\n }\n return walk(raw, 1)\n}\n\nfunction canonicalEquals(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n\nfunction ordering(op: 'gt' | 'gte' | 'lt' | 'lte', left: unknown, right: unknown): boolean {\n // Numbers order with numbers and strings with strings; a mixed or non-orderable pair is false,\n // never a coercion.\n if (typeof left === 'number' && typeof right === 'number') {\n if (Number.isNaN(left) || Number.isNaN(right)) return false\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n if (typeof left === 'string' && typeof right === 'string') {\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n return false\n}\n\n/** Walk a validated condition over a context to a boolean. Never throws on data shape. */\nexport function evaluateCondition(condition: Condition, context: unknown): boolean {\n if (isLeaf(condition)) {\n const resolved = resolveConditionPath(context, parseConditionPath(condition.path, 'evaluate'))\n switch (condition.op) {\n case 'exists':\n return resolved !== undefined && resolved !== null\n case 'truthy':\n return Boolean(resolved)\n case 'eq':\n return canonicalEquals(resolved, condition.value)\n case 'neq':\n return !canonicalEquals(resolved, condition.value)\n case 'in':\n return Array.isArray(condition.value)\n ? condition.value.some((candidate) => canonicalEquals(resolved, candidate))\n : false\n case 'contains':\n if (Array.isArray(resolved)) {\n return resolved.some((element) => canonicalEquals(element, condition.value))\n }\n return typeof resolved === 'string' && typeof condition.value === 'string'\n ? resolved.includes(condition.value)\n : false\n default:\n return ordering(condition.op, resolved, condition.value)\n }\n }\n if ('all' in condition) return condition.all.every((child) => evaluateCondition(child, context))\n if ('any' in condition) return condition.any.some((child) => evaluateCondition(child, context))\n return !evaluateCondition(condition.not, context)\n}\n","/**\n * The ONE pure projection a `data` edge may carry (agent-runtime#971): the bounded,\n * schema-preserving subset of ADC's collection helpers. Anything richer is a `script` NODE, so it\n * is journaled (`inputRef` → `outRef`), typed, and visible. Exactly one operator per projection.\n */\nimport { ValidationError } from '../../errors'\nimport {\n type Condition,\n evaluateCondition,\n parseConditionPath,\n resolveConditionPath,\n validateCondition,\n} from './condition'\n\nexport type Projection =\n | { readonly path: string }\n | { readonly pick: ReadonlyArray<string> }\n | { readonly map: string }\n | { readonly filter: Condition }\n | { readonly first: true }\n | { readonly last: true }\n | { readonly count: true }\n\nconst PROJECTION_KEYS = ['path', 'pick', 'map', 'filter', 'first', 'last', 'count'] as const\n\n/** Validate a projection: exactly one known operator, its argument well-formed. */\nexport function validateProjection(raw: unknown, context: string): Projection {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new ValidationError(`${context}: a projection must be an object`)\n }\n const record = raw as Record<string, unknown>\n const keys = PROJECTION_KEYS.filter((key) => record[key] !== undefined)\n const unknown = Object.keys(record).filter(\n (key) => !(PROJECTION_KEYS as ReadonlyArray<string>).includes(key),\n )\n if (unknown.length > 0) {\n throw new ValidationError(\n `${context}: unknown projection key(s) ${unknown.join(', ')}; known: ${PROJECTION_KEYS.join(', ')}`,\n )\n }\n if (keys.length !== 1) {\n throw new ValidationError(\n `${context}: a projection carries exactly ONE of ${PROJECTION_KEYS.join('/')}`,\n )\n }\n const key = keys[0]\n if (key === 'path' || key === 'map') parseConditionPath(record[key] as string, context)\n if (key === 'pick') {\n const fields = record.pick\n if (\n !Array.isArray(fields) ||\n fields.length === 0 ||\n fields.some((f) => typeof f !== 'string')\n ) {\n throw new ValidationError(`${context}: pick must be a non-empty array of field names`)\n }\n }\n if (key === 'filter') validateCondition(record.filter, context)\n if ((key === 'first' || key === 'last' || key === 'count') && record[key] !== true) {\n throw new ValidationError(`${context}: ${key} must be literally true`)\n }\n return raw as Projection\n}\n\n/**\n * Apply a validated projection to an admitted payload. Collection operators over a non-array\n * refuse by name — a shape the author did not expect is a graph defect, not an empty result.\n */\nexport function applyProjection(value: unknown, projection: Projection, context: string): unknown {\n if ('path' in projection) {\n return resolveConditionPath(value, parseConditionPath(projection.path, context))\n }\n if ('pick' in projection) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: pick needs an object payload`)\n }\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const field of projection.pick) if (field in record) out[field] = record[field]\n return out\n }\n const collection = value\n if (!Array.isArray(collection)) {\n throw new ValidationError(`${context}: this projection needs an array payload`)\n }\n if ('map' in projection) {\n const steps = parseConditionPath(projection.map, context)\n return collection.map((element) => resolveConditionPath(element, steps))\n }\n if ('filter' in projection) {\n return collection.filter((element) => evaluateCondition(projection.filter, element))\n }\n if ('first' in projection) return collection[0]\n if ('last' in projection) return collection[collection.length - 1]\n return collection.length\n}\n","/**\n * `Registry<T>` — the ONE name→thing shape for the graph engine.\n *\n * The kernel grew fourteen of these (agent-runtime#978) that differ in three properties:\n * whether names can be listed, what a miss does, and whether the table is global. This one\n * fixes all three — enumerable, a miss is refused BY NAME listing what is registered, and every\n * registry is per-instance — and it is lifted from `AgentEnvironmentProviderRegistry`, the\n * richest and best-tested of the fourteen, not invented.\n *\n * Entries are addressed by a versioned handle, `<id>/v<n>`, the same way the prompt registry\n * addresses directives. A graph names a kind by handle; a host registers exact versions; a\n * missing version is refused, never served by a newer one.\n */\n\nimport { ValidationError } from '../../errors'\n\n/** A versioned name: what a graph writes and what a host registers. */\nexport interface RegistryHandle {\n readonly id: string\n readonly version: number\n}\n\n/** `<id>/v<n>` — the only spelling a handle has on the wire, in a journal, or in an error. */\nexport function formatRegistryHandle(handle: RegistryHandle): string {\n return `${handle.id}/v${handle.version}`\n}\n\n/** Parse the wire spelling back. Refuses anything that is not exactly `<id>/v<n>`. */\nexport function parseRegistryHandle(text: string, context: string): RegistryHandle {\n const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)\\/v(\\d+)$/u.exec(text)\n if (!match) {\n throw new ValidationError(\n `${context}: ${JSON.stringify(text)} is not a registry handle; expected \"<id>/v<n>\"`,\n )\n }\n const version = Number(match[2])\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new ValidationError(`${context}: handle version must be a positive integer`)\n }\n return { id: match[1] as string, version }\n}\n\n/** Anything a registry holds carries its own handle, so the table cannot drift from the entry. */\nexport interface Registered extends RegistryHandle {}\n\nexport interface Registry<T extends Registered> {\n /** Add one entry. A second entry under the same handle is refused unless `replace` is set —\n * silently shadowing a registered kind is how a key no caller could produce once survived. */\n register(entry: T, options?: { readonly replace?: boolean }): void\n has(handle: RegistryHandle): boolean\n get(handle: RegistryHandle): T | undefined\n /** The entry, or a refusal that names the handle AND lists every registered handle — a miss\n * must be diagnosable from its message alone. */\n require(handle: RegistryHandle, context?: string): T\n /** Every registered handle, sorted, as wire spellings. The thing the fourteen predecessors\n * mostly could not do and four callers needed. */\n names(): string[]\n /** Every entry, in `names()` order. */\n entries(): T[]\n}\n\n/**\n * Create a registry. Per-instance by construction: two engines in one process may hold\n * different kind sets, a test is hermetic, and a run can print its own table. There is\n * deliberately no module-level singleton — `builtinShapes` was the one mutable global in the\n * kernel and it had zero tests.\n */\nexport function createRegistry<T extends Registered>(\n label: string,\n seed: Iterable<T> = [],\n): Registry<T> {\n const table = new Map<string, T>()\n const registry: Registry<T> = {\n register(entry, options = {}): void {\n if (typeof entry.id !== 'string' || entry.id.length === 0) {\n throw new ValidationError(`${label}: an entry must carry a non-empty id`)\n }\n if (!Number.isSafeInteger(entry.version) || entry.version < 1) {\n throw new ValidationError(\n `${label}: ${JSON.stringify(entry.id)} must carry a positive integer version`,\n )\n }\n const key = formatRegistryHandle(entry)\n if (!options.replace && table.has(key)) {\n throw new ValidationError(`${label}: ${JSON.stringify(key)} is already registered`)\n }\n table.set(key, entry)\n },\n has(handle): boolean {\n return table.has(formatRegistryHandle(handle))\n },\n get(handle): T | undefined {\n return table.get(formatRegistryHandle(handle))\n },\n require(handle, context = label): T {\n const key = formatRegistryHandle(handle)\n const entry = table.get(key)\n if (entry === undefined) {\n const known = registry.names()\n const suffix =\n known.length > 0 ? `; registered: ${known.join(', ')}` : '; nothing is registered'\n throw new ValidationError(`${context}: ${JSON.stringify(key)} is not registered${suffix}`)\n }\n return entry\n },\n names(): string[] {\n return Array.from(table.keys()).sort()\n },\n entries(): T[] {\n return registry.names().map((key) => table.get(key) as T)\n },\n }\n for (const entry of seed) registry.register(entry)\n return registry\n}\n","/**\n * The authored form of an engine graph (agent-runtime#971, #973, #968): typed-port nodes over\n * three edge kinds, each guardable by the one predicate tree; `data` edges may carry one pure\n * projection. ADC's `${steps.<id>.field}` strings are an AUTHORING surface that compiles down to\n * these port references — this is the runtime form, checked before any spend.\n */\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { PromptHandle } from '../supervise/prompt-registry'\nimport type { Budget } from '../supervise/types'\nimport { type Condition, validateCondition } from './condition'\nimport type { NodeFlags, PortSpec } from './kind'\nimport { type Projection, validateProjection } from './projection'\nimport { parseRegistryHandle, type RegistryHandle } from './registry'\n\n/** Which gating-edge outcomes release a node (adopted from ADC, agent-runtime#968). */\nexport const JOIN_RULES = ['all', 'any', 'any_failed', 'all_done'] as const\nexport type JoinRule = (typeof JOIN_RULES)[number]\n\n/** ADC-compatible visit backstop: nothing may be ENTERED more than this many times. */\nexport const DEFAULT_MAX_NODE_VISITS = 25\n/** The hard ceiling an author's `maxVisits`/`maxNodeVisits` override may reach. */\nexport const MAX_MAX_NODE_VISITS = 100\n\nexport type GraphEdgeKind = 'delegates' | 'analyzes' | 'data'\n\nexport interface EngineGraphNode {\n readonly id: string\n /** `<id>/v<n>` into the engine's kind registry. */\n readonly kind: string\n /** This node's config, validated by its kind's `validateConfig` at compile. */\n readonly config?: unknown\n /** Per-node flags — properties of the node, never of its kind (agent-runtime#970). */\n readonly flags?: NodeFlags\n /** Node-level port declarations, merged OVER the kind's. A kind whose surface depends on its\n * config (a script) declares ports here; a typed kind's declared ports stay authoritative. */\n readonly ports?: {\n readonly inputs?: ReadonlyArray<PortSpec>\n readonly outputs?: ReadonlyArray<PortSpec>\n }\n /** Which inbound gating-edge outcomes release this node. Default `all`. */\n readonly join?: JoinRule\n /** Entered more than this many times fails the run `cycle-budget-exceeded`. */\n readonly maxVisits?: number\n /** This node's completion check; a terminal without one (or a kind/graph default) refuses. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Force-mark a terminal. Absent, a node with no outbound gating edge is terminal. */\n readonly terminal?: boolean\n /** Profile fields merged over the engine-authored `{ name: id }` for this node's spawns. */\n readonly profile?: Readonly<Partial<AgentProfile>>\n /** Per-instance reservation for this node's spawns; falls back to the run's `perNode`. */\n readonly budget?: Budget\n}\n\nexport interface EngineGraphEdge {\n /** Stable id for the ledger; defaults to `<from>-><to>#<ordinal>`. */\n readonly id?: string\n readonly kind: GraphEdgeKind\n readonly from: { readonly node: string; readonly port?: string }\n readonly to: { readonly node: string; readonly port?: string }\n /** Evaluated over the source's settle context; absent = satisfied by completion. */\n readonly guard?: Condition\n /** `data` edges only: ONE pure reshape of the admitted payload. */\n readonly projection?: Projection\n /** Refuses the traversal past this many firings (ledgered `unpropagated`). */\n readonly maxTraversals?: number\n /** `delegates`/`analyzes`: the versioned directive appended to the target's task. */\n readonly directive?: PromptHandle\n}\n\nexport interface EngineGraphSpec {\n readonly nodes: ReadonlyArray<EngineGraphNode>\n readonly edges: ReadonlyArray<EngineGraphEdge>\n /** Root node for the graph-level completion check. Defaults to the single entry node. */\n readonly root?: string\n /** Becomes the ROOT node's completion check when the root declares none (#973). */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly maxNodeVisits?: number\n}\n\nexport interface ParsedGraphNode extends EngineGraphNode {\n readonly kindHandle: RegistryHandle\n readonly join: JoinRule\n readonly maxVisits: number\n}\n\n/** Structural validation only — everything a registry is not needed for. */\nexport function validateEngineGraphSpec(spec: EngineGraphSpec, context = 'compileGraph'): void {\n if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) {\n throw new ValidationError(`${context}: a graph needs at least one node`)\n }\n const ids = new Set<string>()\n for (const node of spec.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError(`${context}: every node needs a non-empty id`)\n }\n if (ids.has(node.id))\n throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`)\n ids.add(node.id)\n parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`)\n if (node.join !== undefined && !(JOIN_RULES as ReadonlyArray<string>).includes(node.join)) {\n throw new ValidationError(\n `${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(', ')}`,\n )\n }\n if (node.maxVisits !== undefined) {\n if (\n !Number.isSafeInteger(node.maxVisits) ||\n node.maxVisits < 1 ||\n node.maxVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: node ${node.id} maxVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n }\n if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`)\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}]`\n if (edge.kind !== 'delegates' && edge.kind !== 'analyzes' && edge.kind !== 'data') {\n throw new ValidationError(`${who}: kind must be delegates | analyzes | data`)\n }\n for (const end of ['from', 'to'] as const) {\n const ref = edge[end]\n if (\n typeof ref !== 'object' ||\n ref === null ||\n typeof ref.node !== 'string' ||\n !ids.has(ref.node)\n ) {\n throw new ValidationError(`${who}: ${end}.node must name a node in this graph`)\n }\n }\n if (edge.guard !== undefined) validateCondition(edge.guard, `${who} guard`)\n if (edge.projection !== undefined) {\n if (edge.kind !== 'data') {\n throw new ValidationError(`${who}: only a data edge carries a projection`)\n }\n validateProjection(edge.projection, `${who} projection`)\n }\n if (edge.maxTraversals !== undefined) {\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 1) {\n throw new ValidationError(`${who}: maxTraversals must be a positive integer`)\n }\n }\n if (edge.kind === 'data' && edge.directive !== undefined) {\n throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`)\n }\n }\n if (spec.root !== undefined && !ids.has(spec.root)) {\n throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`)\n }\n if (spec.maxNodeVisits !== undefined) {\n if (\n !Number.isSafeInteger(spec.maxNodeVisits) ||\n spec.maxNodeVisits < 1 ||\n spec.maxNodeVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: maxNodeVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n}\n","/**\n * Compile an authored graph against an engine's kind registry into the schedulable form. Every\n * refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`\n * binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no\n * completion check (agent-runtime#971, #973).\n */\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport {\n DEFAULT_MAX_NODE_VISITS,\n type EngineGraphEdge,\n type EngineGraphSpec,\n type JoinRule,\n validateEngineGraphSpec,\n} from './definition'\nimport type { GraphEngine } from './engine'\nimport type { JsonSchema, NodeKind, PortSpec } from './kind'\nimport { formatRegistryHandle, parseRegistryHandle } from './registry'\n\n/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */\nexport const IMPLICIT_OUTPUT_PORTS = ['out', 'trace'] as const\n\nexport interface CompiledEdge {\n readonly id: string\n readonly spec: EngineGraphEdge\n readonly fromPort: string\n readonly toPort: string\n}\n\nexport interface CompiledNode {\n readonly id: string\n readonly kind: NodeKind\n readonly config: unknown\n readonly join: JoinRule\n readonly maxVisits: number\n readonly oracle: boolean\n readonly pure: boolean\n readonly terminal: boolean\n /** The check this node must pass to count DELIVERED; resolved per #973. */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly inbound: ReadonlyArray<CompiledEdge>\n readonly outbound: ReadonlyArray<CompiledEdge>\n readonly spec: EngineGraphSpec['nodes'][number]\n}\n\nexport interface CompiledGraph {\n readonly nodes: ReadonlyMap<string, CompiledNode>\n readonly edges: ReadonlyArray<CompiledEdge>\n readonly entries: ReadonlyArray<string>\n readonly terminals: ReadonlyArray<string>\n readonly root: string\n readonly maxNodeVisits: number\n}\n\ntype NodePorts = {\n readonly inputs: ReadonlyArray<PortSpec>\n readonly outputs: ReadonlyArray<PortSpec>\n}\n\n/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */\nfunction nodePorts(kind: NodeKind, node: EngineGraphSpec['nodes'][number]): NodePorts {\n const merge = (\n declared: ReadonlyArray<PortSpec>,\n own: ReadonlyArray<PortSpec> | undefined,\n ): ReadonlyArray<PortSpec> => {\n if (own === undefined || own.length === 0) return declared\n const names = new Set(own.map((port) => port.name))\n return [...own, ...declared.filter((port) => !names.has(port.name))]\n }\n return {\n inputs: merge(kind.inputs, node.ports?.inputs),\n outputs: merge(kind.outputs, node.ports?.outputs),\n }\n}\n\nfunction outputPort(ports: NodePorts, port: string): PortSpec | undefined {\n if ((IMPLICIT_OUTPUT_PORTS as ReadonlyArray<string>).includes(port)) {\n return { name: port, schema: {} }\n }\n return ports.outputs.find((candidate) => candidate.name === port)\n}\n\nfunction inputPort(ports: NodePorts, port: string): PortSpec | undefined {\n return ports.inputs.find((candidate) => candidate.name === port)\n}\n\n/**\n * Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no\n * `type` accept anything; object targets require their `required` properties to be present and\n * accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,\n * not a full JSON Schema validator.\n */\nexport function schemaAccepts(source: JsonSchema, target: JsonSchema, depth = 0): boolean {\n if (depth > 6) return true\n const sourceType = source.type\n const targetType = target.type\n if (targetType === undefined || sourceType === undefined) return true\n const targets = Array.isArray(targetType) ? targetType : [targetType]\n const sources = Array.isArray(sourceType) ? sourceType : [sourceType]\n const overlap = sources.filter(\n (candidate) =>\n targets.includes(candidate === 'integer' ? 'number' : candidate) ||\n targets.includes(candidate),\n )\n if (overlap.length === 0) return false\n if (targets.includes('object') && sources.includes('object')) {\n const required = Array.isArray(target.required) ? (target.required as string[]) : []\n const sourceProps = source.properties as Record<string, JsonSchema> | undefined\n const targetProps = target.properties as Record<string, JsonSchema> | undefined\n if (sourceProps !== undefined) {\n for (const name of required) {\n const sourceProp = sourceProps[name]\n if (sourceProp === undefined) return false\n const targetProp = targetProps?.[name]\n if (targetProp !== undefined && !schemaAccepts(sourceProp, targetProp, depth + 1)) {\n return false\n }\n }\n }\n }\n if (targets.includes('array') && sources.includes('array')) {\n const sourceItems = source.items as JsonSchema | undefined\n const targetItems = target.items as JsonSchema | undefined\n if (sourceItems !== undefined && targetItems !== undefined) {\n return schemaAccepts(sourceItems, targetItems, depth + 1)\n }\n }\n return true\n}\n\n/**\n * Lower an authored graph against an engine's kind registry into the schedulable form, refusing\n * every structural defect before any spend.\n */\nexport function compileGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec,\n context = 'compileGraph',\n): CompiledGraph {\n validateEngineGraphSpec(spec, context)\n const kinds = new Map<string, NodeKind>()\n const configs = new Map<string, unknown>()\n for (const node of spec.nodes) {\n const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`)\n const kind = engine.kinds.require(handle, `${context}: node ${node.id}`)\n kinds.set(node.id, kind)\n configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`))\n if (node.flags?.pure && kind.id !== 'script') {\n throw new ValidationError(\n `${context}: node ${node.id} sets pure, which only a script node may claim`,\n )\n }\n }\n\n const compiledEdges: CompiledEdge[] = []\n const inbound = new Map<string, CompiledEdge[]>()\n const outbound = new Map<string, CompiledEdge[]>()\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`\n const fromKind = kinds.get(edge.from.node)\n const toKind = kinds.get(edge.to.node)\n if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`)\n const toNode = spec.nodes.find((node) => node.id === edge.to.node)\n if (edge.kind !== 'analyzes' && toNode?.flags?.oracle) {\n // An edge to a grader leaks the rubric: an oracle is bound only by `analyzes`.\n throw new ValidationError(\n `${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`,\n )\n }\n const fromPort = edge.from.port ?? (edge.kind === 'analyzes' ? 'trace' : 'out')\n if (edge.kind === 'analyzes' && fromPort !== 'trace') {\n throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`)\n }\n const fromNode = spec.nodes.find((node) => node.id === edge.from.node)\n const fromPorts = nodePorts(fromKind, fromNode as EngineGraphSpec['nodes'][number])\n const toPorts = nodePorts(toKind, toNode as EngineGraphSpec['nodes'][number])\n const sourcePort = outputPort(fromPorts, fromPort)\n if (!sourcePort) {\n const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)]\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(', ')}`,\n )\n }\n let toPort = edge.to.port ?? ''\n if (edge.kind === 'data') {\n if (toPort === '') {\n if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? ''\n else {\n throw new ValidationError(\n `${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`,\n )\n }\n }\n const targetPort = inputPort(toPorts, toPort)\n if (!targetPort) {\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(', ') || '(none)'}`,\n )\n }\n // A projection reshapes the payload, so the source schema no longer describes it; the\n // projected shape is checked at admission, not statically.\n if (edge.projection === undefined && !schemaAccepts(sourcePort.schema, targetPort.schema)) {\n throw new ValidationError(\n `${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? 'any')}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? 'any')})`,\n )\n }\n }\n const compiled: CompiledEdge = {\n id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,\n spec: edge,\n fromPort,\n toPort: toPort === '' ? 'out' : toPort,\n }\n compiledEdges.push(compiled)\n outbound.set(edge.from.node, [...(outbound.get(edge.from.node) ?? []), compiled])\n inbound.set(edge.to.node, [...(inbound.get(edge.to.node) ?? []), compiled])\n }\n const dupes = new Set<string>()\n for (const edge of compiledEdges) {\n if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`)\n dupes.add(edge.id)\n }\n\n const entries = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (entries.length === 0) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (entries.length === 1\n ? (entries[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${entries.length} entry nodes (${entries.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n\n const nodes = new Map<string, CompiledNode>()\n const terminals: string[] = []\n for (const node of spec.nodes) {\n const kind = kinds.get(node.id)\n if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`)\n const terminal = node.terminal ?? (outbound.get(node.id) ?? []).length === 0\n const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : undefined)\n if (terminal) terminals.push(node.id)\n nodes.set(node.id, {\n id: node.id,\n kind,\n config: configs.get(node.id),\n join: node.join ?? 'all',\n maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n oracle: node.flags?.oracle ?? false,\n pure: node.flags?.pure ?? false,\n terminal,\n ...(deliverable === undefined ? {} : { deliverable }),\n inbound: inbound.get(node.id) ?? [],\n outbound: outbound.get(node.id) ?? [],\n spec: node,\n })\n }\n const unchecked = terminals.filter((id) => nodes.get(id)?.deliverable === undefined)\n if (unchecked.length === terminals.length) {\n // Termination is mandatory per terminal (#973): a graph none of whose terminals declares a\n // completion check (own, or the graph's on the root) can never prove it is done.\n throw new ValidationError(\n `${context}: no terminal declares a completion check (terminals: ${terminals.join(', ')}); give a node a deliverable or set spec.deliverable`,\n )\n }\n return {\n nodes,\n edges: compiledEdges,\n entries: entries.map((node) => node.id),\n terminals,\n root,\n maxNodeVisits: spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n }\n}\n","/**\n * `NodeKind` — what a consumer registers to add a node kind to the graph engine without forking\n * it (agent-runtime#969, #970).\n *\n * The engine owns the graph: scheduling over typed data edges, guards, joins, cycles, the\n * conserved pool, the journal. It does NOT own execution — `run` returns an `Agent`, the\n * kernel's spawn contract (`Scope.spawn` takes an `Agent { name, act }`; a leaf `Agent` carries its\n * `Executor` as `executorSpec: AgentSpec`, and a supervisor `Agent` is `supervisorAgent(...)`). So\n * every node rides `supervise()`'s machinery unchanged: the pool's reserve/reconcile, the\n * content-addressed journal, the completion gate, `Settled`, trace evidence. An engine that\n * re-implemented any of those would be a second kernel.\n *\n * Every kernel-owned extension contract is a TS interface plus a hand-written validator that\n * throws `ValidationError` by name (the kernel has no zod), and this one follows suit. JSON Schema\n * is the PORTABLE form of a config/port shape — a `Record<string, unknown>`, as `McpToolDescriptor`\n * and `DeliveryBinding` already spell it — so a kind's declaration can be published in a manifest\n * and lifted by a host on another stack.\n *\n * The bar this file is measured against: the scheduler's source names no kind that is not\n * universal. A kind the engine ships (`agent`, `supervisor`, `subgraph`, `script`) is universal by\n * the rule \"the model cannot decide it with the verbs it has\"; everything else — integrations,\n * notifications, sandbox provisioning, human decisions — is registered by a host.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport type { Agent } from '../supervise/types'\nimport type { Registered, RegistryHandle } from './registry'\n\n/** A JSON Schema document as the kernel already spells it: an opaque record, validated by the\n * consumer's own validator, published verbatim. */\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\n/**\n * One declared port on a node. Ports are how a `data` edge binds one node's output to another's\n * input with a type the compiler can check structurally before any spend. A node has two implicit\n * output ports beside its declared ones: `out` (its result) and `trace` (its `WorkerTraceEvidence`\n * by `traceRef`); only an `analyzes` edge may bind `trace`.\n */\nexport interface PortSpec {\n readonly name: string\n readonly schema: JsonSchema\n readonly description?: string\n}\n\n/**\n * What a kind declares it needs from the host. The engine never imports a host capability; it\n * knows only that a kind SAID it needs something under this name and the host PROVIDED something\n * under it. The context a kind receives is narrowed to exactly its declaration — an undeclared\n * effect is `undefined`, never a service locator.\n */\nexport type EffectName = string\n\nexport type EffectContext<Effects extends ReadonlyArray<EffectName>> = Readonly<{\n [K in Effects[number]]: unknown\n}>\n\n/**\n * What happens to a node that was IN FLIGHT when the process died. A settled node is never a\n * per-kind choice — it restores from its content-addressed `outRef` on replay. `'restart'` re-runs\n * from the journaled `inputRef`; `'resume'` is legal only for a kind whose executor can re-attach\n * to the live process (the bridge backend's session re-attachment is the existing instance).\n */\nexport type OnCrash = 'restart' | 'resume'\n\n/**\n * Whether a kind's spend enters the conserved pool. `'metered'`: the executor reports `Spend` and\n * settling without one is an ENGINE ERROR — never \"free\". `'exempt'`: the whole reservation is\n * refunded on settle, keeping the node out of Σk by construction (the kernel's `budgetExempt`).\n */\nexport type BudgetMode = 'metered' | 'exempt'\n\n/** The validated declaration every kind provides. `Config` is the per-node config shape;\n * `Effects` is the tuple of host capabilities it declares, so the context `run` receives is typed\n * to exactly that tuple. */\nexport interface NodeKind<\n Config = unknown,\n Effects extends ReadonlyArray<EffectName> = ReadonlyArray<EffectName>,\n> extends Registered {\n /** Kind id, e.g. `agent`, `integration.invoke`. With `version`, forms the handle `<id>/v<n>`. */\n readonly id: string\n readonly version: number\n readonly description: string\n /** Validate and narrow one node's config. Throw `ValidationError` to refuse; the compiler\n * surfaces the message with the node id prefixed. */\n readonly validateConfig: (raw: unknown, context: string) => Config\n /** The portable form of `validateConfig`'s accepted shape, for manifests and hosts. */\n readonly configSchema: JsonSchema\n /** Declared input ports; a `data` edge may bind only these. Empty for a source node. */\n readonly inputs: ReadonlyArray<PortSpec>\n /** Declared output ports beside the implicit `out` and `trace`. */\n readonly outputs: ReadonlyArray<PortSpec>\n /** Host capabilities this kind reaches for, by name. The context is narrowed to exactly these. */\n readonly effects: Effects\n readonly onCrash: OnCrash\n readonly budget: BudgetMode\n /**\n * Build the agent for one node instance. The kernel spawns it under `Scope.spawn`, so it is\n * authorized, classified, journaled, pooled and gated like any child — the kind owns only what\n * the agent DOES. `profile` is the node's pinned profile (an `agent`/`supervisor` kind runs it;\n * a `script` kind may ignore it); `inputs` are the resolved, content-addressed port values;\n * `effects` is the narrowed host context; `spawn` is the kernel's per-spawn context when the\n * kind needs it (a supervisor kind threads it into `nodeContext`).\n */\n readonly run: (args: {\n readonly config: Config\n readonly profile: AgentProfile\n readonly inputs: Readonly<Record<string, unknown>>\n readonly effects: EffectContext<Effects>\n readonly spawn?: WorkerSpawnContext\n }) => Agent<unknown, unknown>\n}\n\n/** Per-node flags a graph author sets; they are node properties, not kinds (agent-runtime#970). */\nexport interface NodeFlags {\n /** An oracle — a judge, grader, auditor, trace analyst — may be bound only by an `analyzes`\n * edge. The compiler refuses a `delegates` or `data` edge INTO an oracle: an edge to a grader\n * leaks the rubric. */\n readonly oracle?: boolean\n /** `script` only: pure over `(config, inputs)` ⇒ budget exempt, output restorable on replay,\n * runs in-process. A pure script that settles with a different `outRef` for the same inputs\n * has lied, and the first replay mismatch is an engine error. */\n readonly pure?: boolean\n}\n\n/** Validate a kind declaration at registration — so a malformed kind is refused by name once,\n * not at the first node that uses it. */\nexport function validateNodeKind(kind: NodeKind, context = 'registerNodeKind'): NodeKind {\n const who = `${context}: kind ${JSON.stringify(`${kind.id}/v${kind.version}`)}`\n if (typeof kind.id !== 'string' || kind.id.length === 0) {\n throw new ValidationError(`${context}: a kind must carry a non-empty id`)\n }\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(kind.id)) {\n throw new ValidationError(`${who}: id may contain only letters, digits, \".\", \"_\" and \"-\"`)\n }\n if (!Number.isSafeInteger(kind.version) || kind.version < 1) {\n throw new ValidationError(`${who}: version must be a positive integer`)\n }\n if (typeof kind.description !== 'string' || kind.description.trim().length === 0) {\n throw new ValidationError(`${who}: description is required`)\n }\n if (typeof kind.validateConfig !== 'function') {\n throw new ValidationError(`${who}: validateConfig must be a function`)\n }\n if (!isRecord(kind.configSchema)) {\n throw new ValidationError(`${who}: configSchema must be a JSON Schema object`)\n }\n for (const [field, ports] of [\n ['inputs', kind.inputs],\n ['outputs', kind.outputs],\n ] as const) {\n if (!Array.isArray(ports)) throw new ValidationError(`${who}: ${field} must be an array`)\n const seen = new Set<string>()\n for (const port of ports) {\n if (!port || typeof port.name !== 'string' || port.name.length === 0) {\n throw new ValidationError(`${who}: every ${field} port needs a non-empty name`)\n }\n if (field === 'outputs' && (port.name === 'out' || port.name === 'trace')) {\n throw new ValidationError(\n `${who}: output port ${JSON.stringify(port.name)} is implicit on every node and cannot be declared`,\n )\n }\n if (seen.has(port.name)) {\n throw new ValidationError(`${who}: duplicate ${field} port ${JSON.stringify(port.name)}`)\n }\n seen.add(port.name)\n if (!isRecord(port.schema)) {\n throw new ValidationError(\n `${who}: ${field} port ${JSON.stringify(port.name)} needs a JSON Schema`,\n )\n }\n }\n }\n if (\n !Array.isArray(kind.effects) ||\n kind.effects.some((e) => typeof e !== 'string' || e.length === 0)\n ) {\n throw new ValidationError(`${who}: effects must be an array of non-empty names`)\n }\n if (new Set(kind.effects).size !== kind.effects.length) {\n throw new ValidationError(`${who}: effects must not repeat a name`)\n }\n if (kind.onCrash !== 'restart' && kind.onCrash !== 'resume') {\n throw new ValidationError(`${who}: onCrash must be \"restart\" or \"resume\"`)\n }\n if (kind.budget !== 'metered' && kind.budget !== 'exempt') {\n throw new ValidationError(`${who}: budget must be \"metered\" or \"exempt\"`)\n }\n if (typeof kind.run !== 'function') {\n throw new ValidationError(`${who}: run must be a function`)\n }\n return kind\n}\n\n/** The handle a graph writes to name this kind. */\nexport function kindHandle(kind: Pick<NodeKind, 'id' | 'version'>): RegistryHandle {\n return { id: kind.id, version: kind.version }\n}\n\n/**\n * Narrow a host's effect table to exactly what one kind declared. Anything the kind did not\n * declare is absent — `undefined` on read — so a kind cannot reach past its declaration, and the\n * engine can list a graph's required effects before spending a token.\n */\nexport function narrowEffects<Effects extends ReadonlyArray<EffectName>>(\n declared: Effects,\n provided: Readonly<Record<string, unknown>>,\n context: string,\n): EffectContext<Effects> {\n const out: Record<string, unknown> = {}\n const missing: string[] = []\n for (const name of declared) {\n if (!(name in provided)) {\n missing.push(name)\n continue\n }\n out[name] = provided[name]\n }\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: host provides no effect for ${missing.map((m) => JSON.stringify(m)).join(', ')}; provided: ${\n Object.keys(provided).sort().join(', ') || 'none'\n }`,\n )\n }\n return Object.freeze(out) as EffectContext<Effects>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * `createGraphEngine` — one engine instance: its kind registry (core kinds pre-registered, host\n * kinds added by the caller), its effect table, and nothing global.\n *\n * The scheduler (#980), journal fold (#981) and the `runGraph` preset (#982) attach here; this\n * file is the part that must exist first so a host can register kinds and a compiler can ask\n * \"which effects does this graph need\" before a token is spent.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { EffectName, NodeKind } from './kind'\nimport { validateNodeKind } from './kind'\nimport { createRegistry, type Registry } from './registry'\n\nexport interface GraphEngineOptions {\n /** Kinds to register beside the core set. A host adds its own here; nothing is global. */\n readonly kinds?: ReadonlyArray<NodeKind>\n /** The host's effect table, by name. A kind receives only the effects it declared. */\n readonly effects?: Readonly<Record<EffectName, unknown>>\n /** The core set. Injected so a test can substitute, and so the engine never imports a\n * backend-specific factory at module load. */\n readonly coreKinds: ReadonlyArray<NodeKind>\n}\n\nexport interface GraphEngine {\n readonly kinds: Registry<NodeKind>\n readonly effects: Readonly<Record<EffectName, unknown>>\n /** Every effect name any registered kind declares — what a host must provide for this engine's\n * whole kind set to be runnable. Listed, never discovered mid-run. */\n requiredEffects(): string[]\n /** The declared effects no host value covers. Empty means every registered kind is runnable. */\n missingEffects(): string[]\n}\n\n/**\n * Build one engine: a kind registry seeded with the core kinds plus the host's, and the host's\n * effect values. Every kind is validated by name at construction, so a malformed host kind fails\n * here, never at its first node.\n */\nexport function createGraphEngine(options: GraphEngineOptions): GraphEngine {\n const kinds = createRegistry<NodeKind>('graph kinds')\n for (const kind of options.coreKinds) kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n for (const kind of options.kinds ?? [])\n kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n const effects = Object.freeze({ ...(options.effects ?? {}) })\n if (Object.keys(effects).some((name) => name.length === 0)) {\n throw new ValidationError('createGraphEngine: an effect name must be non-empty')\n }\n const engine: GraphEngine = {\n kinds,\n effects,\n requiredEffects(): string[] {\n const names = new Set<string>()\n for (const kind of kinds.entries()) for (const name of kind.effects) names.add(name)\n return Array.from(names).sort()\n },\n missingEffects(): string[] {\n return engine.requiredEffects().filter((name) => !(name in effects))\n },\n }\n return engine\n}\n","/**\n * The four core node kinds (agent-runtime#970) — the ones universal by the rule \"the model cannot\n * decide it with the verbs it has\". Everything else (integrations, notifications, sandbox\n * provisioning, human decisions) is registered by a host against the same `NodeKind` contract.\n *\n * Each `run` returns an `Agent` the kernel spawns under `Scope.spawn`; none of these re-implements\n * pooling, journaling, gating or identity. `agent` and `supervisor` are thin wraps over the\n * kernel's own factories; `script` is the one kind with no kernel primitive behind it; `subgraph`\n * is the scheduler's and is refused here until the scheduler lands (#980).\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { ExecutorConfig } from '../supervise/runtime'\nimport { workerFromBackend } from '../supervise/supervise'\nimport { type SupervisorAgentDeps, supervisorAgent } from '../supervise/supervisor-agent'\nimport type { Agent, AgentSpec, Executor, ExecutorResult, Spend } from '../supervise/types'\nimport type { NodeKind } from './kind'\nimport { formatRegistryHandle, type RegistryHandle } from './registry'\n\n// ── agent ───────────────────────────────────────────────────────────────────────\n\nexport interface AgentKindConfig {\n /** Where this node's profile runs. Omit to inherit the engine's default backend. */\n readonly backend?: ExecutorConfig\n /** This node's completion check. Omit to inherit the graph's terminal check. */\n readonly deliverable?: DeliverableSpec<unknown>\n}\n\n/**\n * One profile, one run: the kernel's leaf, exactly as `supervise()` derives it from `backend`.\n * The model cannot decide this — it is what gets run.\n */\nexport function agentKind(defaults: {\n readonly backend?: ExecutorConfig\n readonly deliverable?: DeliverableSpec<unknown>\n}): NodeKind<AgentKindConfig> {\n return {\n id: 'agent',\n version: 1,\n description: 'One AgentProfile run as a leaf on a backend; the kernel derives the executor.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: agent config`)\n return {\n ...(config.backend !== undefined ? { backend: config.backend as ExecutorConfig } : {}),\n ...(config.deliverable !== undefined\n ? { deliverable: config.deliverable as DeliverableSpec<unknown> }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { backend: { type: 'object' }, deliverable: { type: 'object' } },\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, spawn }) => {\n const backend = config.backend ?? defaults.backend\n if (!backend) {\n throw new ValidationError(\n `agent kind: node ${JSON.stringify(profile.name)} has no backend — set config.backend or the engine default`,\n )\n }\n const make: MakeWorkerAgent = workerFromBackend(\n backend,\n config.deliverable ?? defaults.deliverable,\n )\n return make(profile, spawn)\n },\n }\n}\n\n// ── supervisor ──────────────────────────────────────────────────────────────────\n\nexport interface SupervisorKindConfig {\n /** Per-child budget reserved from the pool on each spawn this supervisor makes. */\n readonly perWorker: SupervisorAgentDeps['perWorker']\n readonly maxLiveWorkers?: number\n}\n\n/**\n * The thing that DECIDES: a nested `supervisorAgent` with the coordination verbs. Its children\n * are its own tree — the graph sees one node in, one `Settled` out. A `subgraph` constrains what\n * it may spawn; without one it is free-form under `profileSecurity` and `allowedModels`.\n */\nexport function supervisorKind(deps: {\n readonly blobs: SupervisorAgentDeps['blobs']\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly router?: SupervisorAgentDeps['router']\n readonly driveHarness?: SupervisorAgentDeps['driveHarness']\n}): NodeKind<SupervisorKindConfig> {\n return {\n id: 'supervisor',\n version: 1,\n description:\n 'A nested supervisor: spawns, observes, steers and awaits its own children with the coordination verbs.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: supervisor config`)\n const perWorker = asRecord(config.perWorker, `${context}: supervisor config.perWorker`)\n return {\n perWorker: perWorker as unknown as SupervisorKindConfig['perWorker'],\n ...(config.maxLiveWorkers !== undefined\n ? { maxLiveWorkers: Number(config.maxLiveWorkers) }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { perWorker: { type: 'object' }, maxLiveWorkers: { type: 'integer' } },\n required: ['perWorker'],\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile }) =>\n supervisorAgent(profile, {\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n perWorker: config.perWorker,\n ...(config.maxLiveWorkers !== undefined ? { maxLiveWorkers: config.maxLiveWorkers } : {}),\n ...(deps.router ? { router: deps.router } : {}),\n ...(deps.driveHarness ? { driveHarness: deps.driveHarness } : {}),\n }),\n }\n}\n\n// ── script ──────────────────────────────────────────────────────────────────────\n\n/** The caller code a `script` node runs. Receives the resolved inputs; returns the output. */\nexport type ScriptBody = (\n inputs: Readonly<Record<string, unknown>>,\n signal: AbortSignal,\n) => Promise<unknown> | unknown\n\nexport interface ScriptKindConfig {\n readonly body: ScriptBody\n /**\n * `pure: true` is the promise that the output is a function of `(config, inputs)` alone: the\n * node is then budget-exempt, its output restorable on replay by content address, and it runs\n * in-process. A pure script that settles with a different `outRef` for the same inputs has\n * lied, and the first replay mismatch is an engine error.\n */\n readonly pure?: boolean\n /** For a metered script: what it spent. Omit on a pure script. A metered script that reports\n * nothing is metered as NOTHING-KNOWN, never as free. */\n readonly spent?: Spend\n}\n\n/** The script kind's handle; it also names the kind in every script node's identity. */\nconst SCRIPT: RegistryHandle = { id: 'script', version: 1 }\n\n/**\n * Caller code as a node. The one kind with no kernel primitive behind it: the kernel has no\n * \"data→data with no execution\" concept (agent-runtime#970 fact-finding), so this is new. It is\n * still a leaf `Agent` carrying an `Executor`, so the journal, the gate and the pool treat it like\n * any other node.\n */\nexport function scriptKind(): NodeKind<ScriptKindConfig> {\n return {\n ...SCRIPT,\n description:\n 'Run caller code over the resolved inputs; pure scripts are exempt and restorable.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: script config`)\n if (typeof config.body !== 'function') {\n throw new ValidationError(`${context}: script config.body must be a function`)\n }\n if (config.pure !== undefined && typeof config.pure !== 'boolean') {\n throw new ValidationError(`${context}: script config.pure must be a boolean`)\n }\n if (config.pure === true && config.spent !== undefined) {\n throw new ValidationError(\n `${context}: a pure script is budget-exempt and cannot report spent`,\n )\n }\n return {\n body: config.body as ScriptBody,\n ...(config.pure !== undefined ? { pure: config.pure } : {}),\n ...(config.spent !== undefined ? { spent: config.spent as Spend } : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { pure: { type: 'boolean' }, spent: { type: 'object' } },\n // `body` is a function and has no JSON form; a host that lifts `script` supplies its own\n // executable reference (ADC: a module in a sandbox) under this same kind id.\n additionalProperties: true,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, inputs }) => scriptAgent(profile, config, inputs, SCRIPT),\n }\n}\n\nfunction scriptAgent(\n profile: AgentProfile,\n config: ScriptKindConfig,\n inputs: Readonly<Record<string, unknown>>,\n kind: RegistryHandle,\n): Agent<unknown, unknown> & { executorSpec: AgentSpec } {\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n // A pure script spends nothing from the pool by construction; the kernel refunds its whole\n // reservation. A metered script with no `spent` is NOT free: it is recorded as unknown.\n ...(config.pure ? { budgetExempt: true } : {}),\n async execute(_task, signal): Promise<ExecutorResult<unknown>> {\n const startedAt = Date.now()\n const out = await config.body(inputs, signal)\n const ms = Date.now() - startedAt\n // Exempt means zero spend on every pool channel, iterations included; only the wall clock is\n // reported, and it is not a pool channel.\n const spent: Spend = config.pure\n ? { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms }\n : (config.spent ?? {\n iterations: 1,\n tokens: { input: 0, output: 0, tokensKnown: false },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n })\n artifact = { outRef: contentAddress(out), out, spent }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) throw new ValidationError('script: resultArtifact() read before execute()')\n return artifact\n },\n }\n // The profile names the node; the kind is the behavioral authority, so it joins the node's\n // identity here. A script claims no harness or model: nothing runs one.\n const spec: AgentSpec = {\n profile,\n harness: null,\n executor,\n execution: { correlation: { nodeKind: formatRegistryHandle(kind) } },\n }\n return {\n name: profile.name ?? 'script',\n // `act` is never the path: Scope reads `executorSpec` and runs the executor itself.\n act: () => Promise.reject(new ValidationError('script: act() is not the execution path')),\n executorSpec: spec,\n }\n}\n\n// ── subgraph ────────────────────────────────────────────────────────────────────\n\n/**\n * A node carrying its own graph: the constraint on what a supervisor may spawn at depth>1. Its\n * executor is a nested engine run; that needs the scheduler (#980), so until then this kind is\n * registered and REFUSES at run time by name rather than being absent — a graph that names it\n * compiles, and the refusal says exactly what is missing.\n */\nexport function subgraphKind(): NodeKind<{ readonly graph: unknown }> {\n return {\n id: 'subgraph',\n version: 1,\n description: 'A node that runs its own graph; constrains a supervisor at depth>1.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: subgraph config`)\n if (config.graph === undefined) {\n throw new ValidationError(`${context}: subgraph config.graph is required`)\n }\n return { graph: config.graph }\n },\n configSchema: {\n type: 'object',\n properties: { graph: { type: 'object' } },\n required: ['graph'],\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ profile }) => {\n throw new ValidationError(\n `subgraph kind: node ${JSON.stringify(profile.name)} cannot run yet — the scheduler that executes a nested graph lands in agent-runtime#980`,\n )\n },\n }\n}\n\nfunction asRecord(value: unknown, context: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context} must be an object`)\n }\n return value as Record<string, unknown>\n}\n","/**\n * The engine scheduler (agent-runtime#980): run a compiled graph by hosting every node instance on\n * one kernel `Scope` — the pool, the journal, the blob store and cancellation are the kernel's,\n * never re-implemented. The scheduler owns only what a graph adds: joins over guarded edges,\n * traversal and visit caps, directive/payload delivery, terminals and the finalizer reduce.\n *\n * Edge semantics are adopted from ADC's workflow graph (agent-runtime#968): an edge settles\n * SATISFIED / DEAD / FAILED per its source's LATEST completion; join rules `all | any | any_failed\n * | all_done` decide release; a release CONSUMES the outcomes that produced it (settled edges\n * re-arm; a pending edge at release is consumed-once, so an OR-diamond's second completer never\n * double-fires). Per-edge `maxTraversals` refuses the consumption and ledgers `unpropagated`; a\n * node entered past `maxVisits` fails the run `cycle-budget-exceeded` (#973).\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { createBudgetPool } from '../supervise/budget'\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createScope } from '../supervise/scope'\nimport type { Budget, ResultBlobStore, Settled, SpawnJournal } from '../supervise/types'\nimport { type CompiledEdge, type CompiledGraph, compileGraph } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport { narrowEffects } from './kind'\nimport { applyProjection } from './projection'\n\nexport type GraphRunReason =\n | 'all-children-down'\n | 'budget-exhausted'\n | 'aborted'\n | 'driver-failed'\n | 'cycle-budget-exceeded'\n | 'unreachable-terminal'\n\n/** One node settlement as the graph result reports it. */\nexport interface GraphNodeSettle {\n readonly node: string\n readonly visit: number\n readonly status: 'done' | 'down'\n /** The node's completion check verdict; `undefined` when the node declares no check. */\n readonly valid?: boolean\n readonly out?: unknown\n readonly outRef?: string\n readonly reason?: string\n}\n\n/** One ledgered edge firing (or refusal) — the run's observable data flow. */\nexport interface GraphEdgeTraversal {\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'data'\n readonly from: string\n readonly to: string\n readonly traversal: number\n readonly outcome: 'delivered' | 'empty' | 'unpropagated'\n readonly directive?: string\n readonly port?: string\n readonly reason?: string\n}\n\nexport type GraphRunResult =\n | {\n readonly kind: 'winner'\n readonly out: unknown\n readonly terminals: ReadonlyArray<GraphNodeSettle>\n readonly settles: ReadonlyArray<GraphNodeSettle>\n readonly ledger: ReadonlyArray<GraphEdgeTraversal>\n }\n | {\n readonly kind: 'no-winner'\n readonly reason: GraphRunReason\n readonly error?: { readonly name: string; readonly message: string }\n readonly terminals: ReadonlyArray<GraphNodeSettle>\n readonly settles: ReadonlyArray<GraphNodeSettle>\n readonly ledger: ReadonlyArray<GraphEdgeTraversal>\n /** Nodes provably stuck when the run ended: every upstream settled, no release possible. */\n readonly unreachable: ReadonlyArray<string>\n }\n\nexport interface GraphRunOptions {\n /** The run's conserved pool. */\n readonly budget: Budget\n /** Default per-instance reservation for nodes that declare no `budget` of their own.\n * Required when any such node exists — the engine invents no split. */\n readonly perNode?: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n /** Resolves `delegates`/`analyzes` directives; required when any edge carries one. */\n readonly prompts?: PromptRegistry\n /** How terminal settles reduce to `out`. Default `bestDelivered`. */\n readonly finalizer?: 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly runId?: string\n}\n\n/** Admission for every value crossing an edge (#971): JSON round-trip, `undefined` stripped, a\n * non-representable value becomes a RECORD of that fact — a degraded record beats a vanished\n * edge. */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n // JSON.stringify returns undefined for bare functions/symbols — record, 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\ntype EdgeState = 'pending' | 'satisfied' | 'dead' | 'failed'\n\ninterface EdgeRuntime {\n readonly edge: CompiledEdge\n state: EdgeState\n /** Set when this edge was pending at a release it fed into: its in-flight completion belongs to\n * the wave that already fired, so it re-arms without releasing again. */\n consumedOnce: boolean\n traversals: number\n /** The admitted payload of the source completion this state reflects. */\n payload?: unknown\n}\n\ninterface NodeRuntime {\n visits: number\n live: number\n settles: GraphNodeSettle[]\n /** Latest admitted value per input port, from consumed `data` edges. */\n inputs: Map<string, unknown>\n /** Directive texts consumed by the next entry, in consumption order. */\n directives: string[]\n /** Trace refs delivered by consumed `analyzes` edges. */\n traces: Array<{ readonly node: string; readonly traceRef?: string }>\n blocked: boolean\n}\n\n/**\n * Run a graph: host every node instance on one kernel `Scope`, resolve joins over guarded edges,\n * enforce the traversal and visit caps, and reduce the terminal settlements through the finalizer.\n */\nexport async function runEngineGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): Promise<GraphRunResult> {\n const compiled: CompiledGraph =\n 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n const context = 'runEngineGraph'\n for (const node of compiled.nodes.values()) {\n const missing = node.kind.effects.filter((name) => !(name in engine.effects))\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: node ${node.id} needs effect(s) ${missing.join(', ')} the host did not provide`,\n )\n }\n if (node.spec.budget === undefined && options.perNode === undefined) {\n throw new ValidationError(\n `${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`,\n )\n }\n }\n for (const edge of compiled.edges) {\n if (edge.spec.directive !== undefined && options.prompts === undefined) {\n throw new ValidationError(\n `${context}: edge ${edge.id} carries a directive but options.prompts is absent`,\n )\n }\n }\n\n const now = options.now ?? Date.now\n const started = now()\n const runId = options.runId ?? `graph:${contentAddress({ task, at: started }).slice(0, 18)}`\n const pool = createBudgetPool(options.budget, () => now() - started)\n const journal = options.journal ?? new InMemorySpawnJournal()\n const blobs = options.blobs ?? new InMemoryResultBlobStore()\n await journal.beginTree(runId, new Date(started).toISOString())\n const abort = new AbortController()\n const onOuterAbort = () => abort.abort(options.signal?.reason)\n options.signal?.addEventListener('abort', onOuterAbort, { once: true })\n if (options.signal?.aborted) abort.abort(options.signal.reason)\n const scope = createScope<unknown>({\n parentId: runId,\n root: runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now,\n })\n\n const nodes = new Map<string, NodeRuntime>()\n for (const id of compiled.nodes.keys()) {\n nodes.set(id, {\n visits: 0,\n live: 0,\n settles: [],\n inputs: new Map(),\n directives: [],\n traces: [],\n blocked: false,\n })\n }\n const edges = new Map<string, EdgeRuntime>()\n for (const edge of compiled.edges) {\n edges.set(edge.id, {\n edge,\n state: 'pending',\n consumedOnce: false,\n traversals: 0,\n payload: undefined,\n })\n }\n const ledger: GraphEdgeTraversal[] = []\n const exhaustedEdges = new Set<string>()\n const settles: GraphNodeSettle[] = []\n const liveHandles = new Map<string, string>() // scope handle id -> node id\n const waitingForBudget: string[] = []\n let ledgerSeq = 0\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n const record = (\n runtime: EdgeRuntime,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): void => {\n runtime.traversals += 1\n const spec = runtime.edge.spec\n const entry: GraphEdgeTraversal = {\n edge: runtime.edge.id,\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n traversal: runtime.traversals,\n outcome,\n ...(spec.directive !== undefined\n ? { directive: `${spec.directive.surface}/v${spec.directive.version}` }\n : {}),\n ...(spec.kind === 'data' ? { port: runtime.edge.toPort } : {}),\n ...(reason !== undefined ? { reason } : {}),\n }\n ledger.push(entry)\n void journal.appendEvent(runId, {\n kind: 'edge',\n id: `graph:${spec.to.node}`,\n edge: {\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n ...(entry.directive !== undefined ? { directive: entry.directive } : {}),\n ...(entry.port !== undefined ? { port: entry.port } : {}),\n },\n traversal: entry.traversal,\n outcome: outcome === 'delivered' ? 'delivered' : outcome,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n\n /** Enter a node: count the visit, build its Agent from consumed inputs, spawn on the Scope. */\n const enter = (id: string): void => {\n if (failure) return\n const node = compiled.nodes.get(id)\n const runtime = nodes.get(id)\n if (!node || !runtime) throw new ValidationError(`${context}: unknown node ${id}`)\n runtime.visits += 1\n if (runtime.visits > node.maxVisits) {\n failure = {\n reason: 'cycle-budget-exceeded',\n error: {\n name: 'GraphCycleBudget',\n message: `node ${id} entered ${runtime.visits} times; maxVisits ${node.maxVisits}`,\n },\n }\n abort.abort(`cycle-budget-exceeded: ${id}`)\n return\n }\n const inputs: Record<string, unknown> = {}\n for (const [port, value] of runtime.inputs) inputs[port] = value\n const directives = runtime.directives.splice(0)\n const traces = runtime.traces.splice(0)\n const nodeTask = [\n id === compiled.root ? task : '',\n ...directives,\n ...traces.map((trace) => `trace of ${trace.node}: ${trace.traceRef ?? '(no traceRef)'}`),\n ]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n const effects = narrowEffects(node.kind.effects, engine.effects, `${context}: node ${id}`)\n const agent = node.kind.run({\n config: node.config,\n profile: { name: id, ...(node.spec.profile ?? {}) },\n inputs,\n effects,\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, nodeTask.length > 0 ? nodeTask : task, { label: id, budget })\n if (spawned.ok) {\n liveCount += 1\n runtime.live += 1\n liveHandles.set(spawned.handle.id, id)\n return\n }\n if (spawned.reason === 'budget-exhausted' || spawned.reason === 'max-live-workers') {\n // Never overcommit: park the entry and retry after the next settle frees capacity (#972).\n // The consumed directives/traces are restored so the retry enters with the same wave.\n waitingForBudget.push(id)\n runtime.visits -= 1\n runtime.directives.unshift(...directives)\n runtime.traces.unshift(...traces)\n return\n }\n failure = {\n reason: 'driver-failed',\n error: { name: 'SpawnRefused', message: `node ${id}: ${spawned.reason}` },\n }\n abort.abort(`spawn refused: ${id}`)\n }\n\n /** Join evaluation per ADC's rules; returns whether the node released. */\n const tryRelease = (id: string): boolean => {\n const node = compiled.nodes.get(id)\n const runtime = nodes.get(id)\n if (!node || !runtime || runtime.blocked || failure) return false\n const gating = node.inbound.map((edge) => edges.get(edge.id)) as EdgeRuntime[]\n if (gating.length === 0) return false\n const settled = gating.filter((edge) => edge.state !== 'pending')\n const satisfied = gating.filter((edge) => edge.state === 'satisfied')\n const failed = gating.filter((edge) => edge.state === 'failed')\n const allSettled = settled.length === gating.length\n let release = false\n switch (node.join) {\n case 'all':\n if (gating.some((edge) => edge.state === 'dead' || edge.state === 'failed')) {\n // A dead or failed edge can never satisfy an `all` join again this wave; the node is\n // blocked until (and unless) a later source completion re-judges that edge.\n release = false\n } else release = satisfied.length === gating.length\n break\n case 'any':\n release = satisfied.length > 0\n if (!release && allSettled) runtime.blocked = true\n break\n case 'any_failed':\n release = failed.length > 0\n if (!release && allSettled) runtime.blocked = true\n break\n case 'all_done':\n release = allSettled\n break\n }\n if (!release) return false\n // Consume the wave: check caps on the edges whose outcome produced the release, deliver their\n // payloads, then re-arm every settled edge; a still-pending edge is consumed-once.\n const consuming =\n node.join === 'any'\n ? [satisfied[0] as EdgeRuntime]\n : node.join === 'any_failed'\n ? [failed[0] as EdgeRuntime]\n : settled\n for (const runtimeEdge of consuming) {\n const cap = runtimeEdge.edge.spec.maxTraversals\n if (cap !== undefined && runtimeEdge.traversals >= cap) {\n record(runtimeEdge, 'unpropagated', `traversal-cap-exhausted (max ${cap})`)\n // Undo the count: a refusal is ledgered but does not consume a traversal slot.\n runtimeEdge.traversals -= 1\n exhaustedEdges.add(runtimeEdge.edge.id)\n runtime.blocked = node.join === 'any' || node.join === 'any_failed' ? runtime.blocked : true\n return false\n }\n }\n for (const runtimeEdge of consuming) {\n const spec = runtimeEdge.edge.spec\n if (runtimeEdge.state === 'satisfied' && spec.kind === 'data') {\n let payload = runtimeEdge.payload\n let outcome: GraphEdgeTraversal['outcome'] = 'delivered'\n let reason: string | undefined\n if (spec.projection !== undefined) {\n try {\n payload = admitPayload(\n applyProjection(payload, spec.projection, `edge ${runtimeEdge.edge.id}`),\n )\n } catch (error) {\n outcome = 'empty'\n reason = error instanceof Error ? error.message : String(error)\n payload = undefined\n }\n }\n if (payload === undefined && outcome === 'delivered') outcome = 'empty'\n record(runtimeEdge, outcome, reason)\n if (payload !== undefined) runtime.inputs.set(runtimeEdge.edge.toPort, payload)\n } else if (\n runtimeEdge.state === 'satisfied' ||\n node.join === 'any_failed' ||\n node.join === 'all_done'\n ) {\n if (spec.directive !== undefined && options.prompts !== undefined) {\n runtime.directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && runtimeEdge.state === 'satisfied') {\n const trace = runtimeEdge.payload as { traceRef?: string } | undefined\n runtime.traces.push({\n node: spec.from.node,\n ...(trace?.traceRef !== undefined ? { traceRef: trace.traceRef } : {}),\n })\n }\n record(runtimeEdge, 'delivered')\n }\n }\n for (const runtimeEdge of gating) {\n if (runtimeEdge.state !== 'pending') {\n runtimeEdge.state = 'pending'\n runtimeEdge.payload = undefined\n } else if ((nodes.get(runtimeEdge.edge.spec.from.node)?.live ?? 0) > 0) {\n // Only an IN-FLIGHT completion belongs to the wave that just fired (the OR-diamond's\n // second completer). An idle source has nothing in flight; its next completion is new.\n runtimeEdge.consumedOnce = true\n }\n }\n enter(id)\n return true\n }\n\n /** Settle every outbound edge of a completed source per its LATEST completion, then try joins. */\n const propagate = (id: string, settle: GraphNodeSettle): void => {\n const node = compiled.nodes.get(id)\n if (!node) return\n const succeeded = settle.status === 'done' && settle.valid !== false\n for (const edge of node.outbound) {\n const runtime = edges.get(edge.id)\n if (!runtime) continue\n if (runtime.consumedOnce && runtime.state === 'pending') {\n // This completion belongs to a wave that already fired; absorb it and re-arm.\n runtime.consumedOnce = false\n continue\n }\n if (!succeeded) {\n runtime.state = 'failed'\n runtime.payload = undefined\n } else {\n const guardContext = {\n node: id,\n out: settle.out,\n visits: nodes.get(id)?.visits ?? 0,\n valid: settle.valid ?? true,\n }\n const pass =\n edge.spec.guard === undefined || evaluateCondition(edge.spec.guard, guardContext)\n runtime.state = pass ? 'satisfied' : 'dead'\n runtime.payload = pass\n ? edge.spec.kind === 'analyzes'\n ? { traceRef: (settle as { traceRef?: string }).traceRef }\n : settle.out\n : undefined\n }\n }\n for (const edge of node.outbound) tryRelease(edge.spec.to.node)\n }\n\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (nodes.get(id)?.settles.length ?? 0) > 0)\n\n // ── The run ────────────────────────────────────────────────────────────────────\n for (const id of compiled.entries) enter(id)\n\n while (!failure && liveCount > 0) {\n const settled: Settled<unknown> | null = await scope.next()\n if (settled === null) break\n const nodeId = liveHandles.get(settled.handle.id)\n if (nodeId === undefined) continue\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const node = compiled.nodes.get(nodeId)\n const runtime = nodes.get(nodeId)\n if (!node || !runtime) continue\n runtime.live -= 1\n let entry: GraphNodeSettle\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n let valid: boolean | undefined\n if (node.deliverable !== undefined) {\n try {\n valid = await node.deliverable.check(admitted)\n } catch (error) {\n valid = false\n }\n }\n entry = {\n node: nodeId,\n visit: runtime.visits,\n status: 'done',\n ...(valid !== undefined ? { valid } : {}),\n out: admitted,\n outRef: settled.outRef,\n }\n if (settled.trace?.status === 'available') {\n ;(entry as { traceRef?: string }).traceRef = settled.trace.traceRef\n }\n } else if (settled.kind === 'down') {\n entry = { node: nodeId, visit: runtime.visits, status: 'down', reason: settled.reason }\n } else {\n continue\n }\n runtime.settles.push(entry)\n settles.push(entry)\n // Root completion ends the run the moment its check passes (#973).\n if (nodeId === compiled.root && entry.status === 'done' && entry.valid === true) {\n abort.abort('root delivered')\n break\n }\n propagate(nodeId, entry)\n if (allTerminalsSettled()) break\n // Capacity freed: retry parked entries in arrival order.\n for (const parked of waitingForBudget.splice(0)) enter(parked)\n if (liveCount === 0 && !failure) {\n // Nothing live and nothing released: the graph is stuck; the loop exit will classify it.\n break\n }\n }\n\n options.signal?.removeEventListener('abort', onOuterAbort)\n abort.abort('run complete')\n // Drain whatever teardown produced so the scope owns no live child when we return.\n while ((await scope.next()) !== null) {\n /* drained */\n }\n\n const finalize = async (): Promise<unknown | undefined> => {\n const rows: FinalizerSettled[] = compiled.terminals.flatMap((id) =>\n (nodes.get(id)?.settles ?? []).map((settle) => ({\n id: settle.node,\n status: settle.status,\n // A terminal with no check delivers on `done` — the check's absence was accepted at\n // compile because ANOTHER terminal carries one (#973).\n valid: settle.status === 'done' && settle.valid !== false,\n ...(settle.outRef !== undefined ? { outRef: settle.outRef } : {}),\n })),\n )\n const finalizer =\n options.finalizer === undefined || options.finalizer === 'bestDelivered'\n ? bestDelivered\n : options.finalizer === 'collectDelivered'\n ? collectDelivered\n : options.finalizer\n return runFinalizer(finalizer, { settled: rows, blobs, tree: scope.view, budget: scope.budget })\n }\n\n const terminals = compiled.terminals.flatMap((id) => nodes.get(id)?.settles ?? [])\n const finish = (result: GraphRunResult): GraphRunResult => {\n // A capped edge that left the run winnerless is a NAMED failure, not a quiet no-winner (#973).\n if (result.kind === 'no-winner' && exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (failure) {\n return finish({\n kind: 'no-winner',\n reason: failure.reason,\n ...(failure.error ? { error: failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n if (options.signal?.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const anyDelivered = compiled.terminals.some((id) =>\n (nodes.get(id)?.settles ?? []).some(\n (settle) => settle.status === 'done' && settle.valid !== false,\n ),\n )\n const out = anyDelivered ? await finalize() : undefined\n if (out !== undefined) {\n return { kind: 'winner', out, terminals, settles, ledger }\n }\n // No delivered terminal. Name the honest cause: an unreachable terminal beats a generic down.\n const unreachable = [...compiled.nodes.keys()].filter(\n (id) => (nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === compiled.nodes.size\n ? 'budget-exhausted'\n : 'unreachable-terminal'\n : 'all-children-down'\n return finish({ kind: 'no-winner', reason, terminals, settles, ledger, unreachable })\n}\n"],"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,QAAQ,iBAAiB,KAAK,UAAU,IAAI,EAAE,oBACnD;GAEF,MAAM,KAAK,IAAI;EACjB,OAAO,IAAI,SAAS,KAAK,MAAM,WAAW,GACxC,MAAM,IAAI,gBAAgB,GAAG,QAAQ,SAAS,KAAK,UAAU,IAAI,EAAE,sBAAsB;EAE3F,IAAI,OAAO,SAAS,KAAK,KAAK,KAAK,MAAM,IAAI;E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CAAC,QAC5C,QAAQ,MAAM,IAAI,EAAE,CAAC,EAAE,QAAQ,UAAU,OAAO,CACnD;CAMA,OAAO,OAAO;EAAE,MAAM;EAAa,QALJ,SAAS,UAAU,MAAM,OAAO,YAAY,SAAS,EAAE,CAAC,IACnF,YAAY,WAAW,SAAS,MAAM,OACpC,qBACA,yBACF;EACuC;EAAW;EAAS;EAAQ;CAAY,CAAC;AACtF"}
1
+ {"version":3,"file":"graph.js","names":[],"sources":["../src/runtime/graph/condition.ts","../src/runtime/graph/projection.ts","../src/runtime/graph/registry.ts","../src/runtime/graph/definition.ts","../src/runtime/graph/compile.ts","../src/runtime/graph/kind.ts","../src/runtime/graph/engine.ts","../src/runtime/graph/fold.ts","../src/runtime/graph/kinds.ts","../src/runtime/graph/scheduler.ts"],"sourcesContent":["/**\n * The ONE predicate tree: every guard in a graph — an edge `guard`, a filter projection's\n * predicate — is this shape, evaluated by this evaluator, so `contains`, ordering and equality can\n * never mean two different things on two surfaces (adopted from ADC's `workflow-conditions`,\n * agent-runtime#968). A declarative tree keeps an untrusted predicate incapable of code execution;\n * the size and depth bounds keep a predicate authored once from burning CPU on every settle.\n *\n * No zod: the kernel's grain is a hand-written validator that throws `ValidationError` by name.\n */\nimport { ValidationError } from '../../errors'\n\n/** The leaf comparison operators; `exists`/`truthy` are unary, the rest compare against `value`. */\nexport const CONDITION_OPS = [\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'in',\n 'contains',\n 'exists',\n 'truthy',\n] as const\nexport type ConditionOp = (typeof CONDITION_OPS)[number]\n\n/** Operators that compare against `value`; `exists`/`truthy` are unary and must omit it. */\nconst OPS_NEEDING_VALUE: ReadonlySet<ConditionOp> = new Set(\n CONDITION_OPS.filter((op) => op !== 'exists' && op !== 'truthy'),\n)\n\nexport interface ConditionLeaf {\n /** Dotted path with `[N]` indexing into the guard context, e.g. `out.findings[0].severity`. */\n readonly path: string\n readonly op: ConditionOp\n readonly value?: unknown\n}\n\nexport type Condition =\n | ConditionLeaf\n | { readonly all: ReadonlyArray<Condition> }\n | { readonly any: ReadonlyArray<Condition> }\n | { readonly not: Condition }\n\nexport const MAX_CONDITION_NODES = 40\nexport const MAX_CONDITION_DEPTH = 6\nconst MAX_PATH_LENGTH = 256\nconst MAX_PATH_SEGMENTS = 16\nconst PATH_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$-]*$/u\n\ntype PathStep = string | number\n\n/** Parse `a.b[0].c` into steps; refuse anything outside the bounded grammar. */\nexport function parseConditionPath(path: string, context: string): ReadonlyArray<PathStep> {\n if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH_LENGTH) {\n throw new ValidationError(\n `${context}: path must be a non-empty string of at most ${MAX_PATH_LENGTH} chars`,\n )\n }\n const steps: PathStep[] = []\n for (const part of path.split('.')) {\n const open = part.indexOf('[')\n const head = open === -1 ? part : part.slice(0, open)\n if (head.length > 0) {\n if (!PATH_SEGMENT.test(head)) {\n throw new ValidationError(\n `${context}: path segment ${JSON.stringify(head)} is not addressable`,\n )\n }\n steps.push(head)\n } else if (open !== 0 || steps.length === 0) {\n throw new ValidationError(`${context}: path ${JSON.stringify(path)} has an empty segment`)\n }\n let rest = open === -1 ? '' : part.slice(open)\n while (rest.length > 0) {\n const match = /^\\[(\\d{1,6})\\]/u.exec(rest)\n if (!match) {\n throw new ValidationError(`${context}: path index in ${JSON.stringify(part)} must be [N]`)\n }\n steps.push(Number(match[1]))\n rest = rest.slice(match[0].length)\n }\n if (steps.length > MAX_PATH_SEGMENTS) {\n throw new ValidationError(`${context}: path exceeds ${MAX_PATH_SEGMENTS} segments`)\n }\n }\n if (steps.length === 0) throw new ValidationError(`${context}: path resolves no segment`)\n return steps\n}\n\n/** Walk a parsed path; any miss resolves `undefined`, never a throw — absence is an answer. */\nexport function resolveConditionPath(context: unknown, steps: ReadonlyArray<PathStep>): unknown {\n let current: unknown = context\n for (const step of steps) {\n if (current === null || current === undefined) return undefined\n if (typeof step === 'number') {\n if (!Array.isArray(current)) return undefined\n current = current[step]\n } else {\n if (typeof current !== 'object' || Array.isArray(current)) return undefined\n current = (current as Record<string, unknown>)[step]\n }\n }\n return current\n}\n\nfunction isLeaf(condition: Condition): condition is ConditionLeaf {\n return typeof (condition as ConditionLeaf).path === 'string'\n}\n\n/** Validate shape, bounds, and per-leaf path/operator rules; returns the input for chaining. */\nexport function validateCondition(raw: unknown, context: string): Condition {\n let nodes = 0\n const walk = (value: unknown, depth: number): Condition => {\n nodes += 1\n if (nodes > MAX_CONDITION_NODES) {\n throw new ValidationError(`${context}: condition exceeds ${MAX_CONDITION_NODES} nodes`)\n }\n if (depth > MAX_CONDITION_DEPTH) {\n throw new ValidationError(`${context}: condition exceeds depth ${MAX_CONDITION_DEPTH}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: a condition must be an object`)\n }\n const record = value as Record<string, unknown>\n const combinators = ['all', 'any', 'not'].filter((key) => record[key] !== undefined)\n if (combinators.length > 1) {\n throw new ValidationError(\n `${context}: a condition carries ONE of all/any/not, got ${combinators.join('+')}`,\n )\n }\n if (record.all !== undefined || record.any !== undefined) {\n const key = record.all !== undefined ? 'all' : 'any'\n const branch = record[key]\n if (!Array.isArray(branch) || branch.length === 0) {\n throw new ValidationError(`${context}: ${key} must be a non-empty array`)\n }\n for (const child of branch) walk(child, depth + 1)\n return value as Condition\n }\n if (record.not !== undefined) {\n walk(record.not, depth + 1)\n return value as Condition\n }\n const op = record.op\n if (typeof record.path !== 'string' || typeof op !== 'string') {\n throw new ValidationError(`${context}: a leaf needs { path, op }`)\n }\n if (!(CONDITION_OPS as ReadonlyArray<string>).includes(op)) {\n throw new ValidationError(\n `${context}: unknown op ${JSON.stringify(op)}; known: ${CONDITION_OPS.join(', ')}`,\n )\n }\n parseConditionPath(record.path, context)\n const needsValue = OPS_NEEDING_VALUE.has(op as ConditionOp)\n if (needsValue && !('value' in record)) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} requires a value`)\n }\n if (!needsValue && 'value' in record) {\n throw new ValidationError(`${context}: op ${JSON.stringify(op)} is unary — remove value`)\n }\n if (op === 'in' && !Array.isArray(record.value)) {\n throw new ValidationError(`${context}: op \"in\" takes an array value`)\n }\n return value as Condition\n }\n return walk(raw, 1)\n}\n\nfunction canonicalEquals(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n\nfunction ordering(op: 'gt' | 'gte' | 'lt' | 'lte', left: unknown, right: unknown): boolean {\n // Numbers order with numbers and strings with strings; a mixed or non-orderable pair is false,\n // never a coercion.\n if (typeof left === 'number' && typeof right === 'number') {\n if (Number.isNaN(left) || Number.isNaN(right)) return false\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n if (typeof left === 'string' && typeof right === 'string') {\n if (op === 'gt') return left > right\n if (op === 'gte') return left >= right\n if (op === 'lt') return left < right\n return left <= right\n }\n return false\n}\n\n/** Walk a validated condition over a context to a boolean. Never throws on data shape. */\nexport function evaluateCondition(condition: Condition, context: unknown): boolean {\n if (isLeaf(condition)) {\n const resolved = resolveConditionPath(context, parseConditionPath(condition.path, 'evaluate'))\n switch (condition.op) {\n case 'exists':\n return resolved !== undefined && resolved !== null\n case 'truthy':\n return Boolean(resolved)\n case 'eq':\n return canonicalEquals(resolved, condition.value)\n case 'neq':\n return !canonicalEquals(resolved, condition.value)\n case 'in':\n return Array.isArray(condition.value)\n ? condition.value.some((candidate) => canonicalEquals(resolved, candidate))\n : false\n case 'contains':\n if (Array.isArray(resolved)) {\n return resolved.some((element) => canonicalEquals(element, condition.value))\n }\n return typeof resolved === 'string' && typeof condition.value === 'string'\n ? resolved.includes(condition.value)\n : false\n default:\n return ordering(condition.op, resolved, condition.value)\n }\n }\n if ('all' in condition) return condition.all.every((child) => evaluateCondition(child, context))\n if ('any' in condition) return condition.any.some((child) => evaluateCondition(child, context))\n return !evaluateCondition(condition.not, context)\n}\n","/**\n * The ONE pure projection a `data` edge may carry (agent-runtime#971): the bounded,\n * schema-preserving subset of ADC's collection helpers. Anything richer is a `script` NODE, so it\n * is journaled (`inputRef` → `outRef`), typed, and visible. Exactly one operator per projection.\n */\nimport { ValidationError } from '../../errors'\nimport {\n type Condition,\n evaluateCondition,\n parseConditionPath,\n resolveConditionPath,\n validateCondition,\n} from './condition'\n\nexport type Projection =\n | { readonly path: string }\n | { readonly pick: ReadonlyArray<string> }\n | { readonly map: string }\n | { readonly filter: Condition }\n | { readonly first: true }\n | { readonly last: true }\n | { readonly count: true }\n\nconst PROJECTION_KEYS = ['path', 'pick', 'map', 'filter', 'first', 'last', 'count'] as const\n\n/** Validate a projection: exactly one known operator, its argument well-formed. */\nexport function validateProjection(raw: unknown, context: string): Projection {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new ValidationError(`${context}: a projection must be an object`)\n }\n const record = raw as Record<string, unknown>\n const keys = PROJECTION_KEYS.filter((key) => record[key] !== undefined)\n const unknown = Object.keys(record).filter(\n (key) => !(PROJECTION_KEYS as ReadonlyArray<string>).includes(key),\n )\n if (unknown.length > 0) {\n throw new ValidationError(\n `${context}: unknown projection key(s) ${unknown.join(', ')}; known: ${PROJECTION_KEYS.join(', ')}`,\n )\n }\n if (keys.length !== 1) {\n throw new ValidationError(\n `${context}: a projection carries exactly ONE of ${PROJECTION_KEYS.join('/')}`,\n )\n }\n const key = keys[0]\n if (key === 'path' || key === 'map') parseConditionPath(record[key] as string, context)\n if (key === 'pick') {\n const fields = record.pick\n if (\n !Array.isArray(fields) ||\n fields.length === 0 ||\n fields.some((f) => typeof f !== 'string')\n ) {\n throw new ValidationError(`${context}: pick must be a non-empty array of field names`)\n }\n }\n if (key === 'filter') validateCondition(record.filter, context)\n if ((key === 'first' || key === 'last' || key === 'count') && record[key] !== true) {\n throw new ValidationError(`${context}: ${key} must be literally true`)\n }\n return raw as Projection\n}\n\n/**\n * Apply a validated projection to an admitted payload. Collection operators over a non-array\n * refuse by name — a shape the author did not expect is a graph defect, not an empty result.\n */\nexport function applyProjection(value: unknown, projection: Projection, context: string): unknown {\n if ('path' in projection) {\n return resolveConditionPath(value, parseConditionPath(projection.path, context))\n }\n if ('pick' in projection) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context}: pick needs an object payload`)\n }\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const field of projection.pick) if (field in record) out[field] = record[field]\n return out\n }\n const collection = value\n if (!Array.isArray(collection)) {\n throw new ValidationError(`${context}: this projection needs an array payload`)\n }\n if ('map' in projection) {\n const steps = parseConditionPath(projection.map, context)\n return collection.map((element) => resolveConditionPath(element, steps))\n }\n if ('filter' in projection) {\n return collection.filter((element) => evaluateCondition(projection.filter, element))\n }\n if ('first' in projection) return collection[0]\n if ('last' in projection) return collection[collection.length - 1]\n return collection.length\n}\n","/**\n * `Registry<T>` — the ONE name→thing shape for the graph engine.\n *\n * The kernel grew fourteen of these (agent-runtime#978) that differ in three properties:\n * whether names can be listed, what a miss does, and whether the table is global. This one\n * fixes all three — enumerable, a miss is refused BY NAME listing what is registered, and every\n * registry is per-instance — and it is lifted from `AgentEnvironmentProviderRegistry`, the\n * richest and best-tested of the fourteen, not invented.\n *\n * Entries are addressed by a versioned handle, `<id>/v<n>`, the same way the prompt registry\n * addresses directives. A graph names a kind by handle; a host registers exact versions; a\n * missing version is refused, never served by a newer one.\n */\n\nimport { ValidationError } from '../../errors'\n\n/** A versioned name: what a graph writes and what a host registers. */\nexport interface RegistryHandle {\n readonly id: string\n readonly version: number\n}\n\n/** `<id>/v<n>` — the only spelling a handle has on the wire, in a journal, or in an error. */\nexport function formatRegistryHandle(handle: RegistryHandle): string {\n return `${handle.id}/v${handle.version}`\n}\n\n/** Parse the wire spelling back. Refuses anything that is not exactly `<id>/v<n>`. */\nexport function parseRegistryHandle(text: string, context: string): RegistryHandle {\n const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)\\/v(\\d+)$/u.exec(text)\n if (!match) {\n throw new ValidationError(\n `${context}: ${JSON.stringify(text)} is not a registry handle; expected \"<id>/v<n>\"`,\n )\n }\n const version = Number(match[2])\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new ValidationError(`${context}: handle version must be a positive integer`)\n }\n return { id: match[1] as string, version }\n}\n\n/** Anything a registry holds carries its own handle, so the table cannot drift from the entry. */\nexport interface Registered extends RegistryHandle {}\n\nexport interface Registry<T extends Registered> {\n /** Add one entry. A second entry under the same handle is refused unless `replace` is set —\n * silently shadowing a registered kind is how a key no caller could produce once survived. */\n register(entry: T, options?: { readonly replace?: boolean }): void\n has(handle: RegistryHandle): boolean\n get(handle: RegistryHandle): T | undefined\n /** The entry, or a refusal that names the handle AND lists every registered handle — a miss\n * must be diagnosable from its message alone. */\n require(handle: RegistryHandle, context?: string): T\n /** Every registered handle, sorted, as wire spellings. The thing the fourteen predecessors\n * mostly could not do and four callers needed. */\n names(): string[]\n /** Every entry, in `names()` order. */\n entries(): T[]\n}\n\n/**\n * Create a registry. Per-instance by construction: two engines in one process may hold\n * different kind sets, a test is hermetic, and a run can print its own table. There is\n * deliberately no module-level singleton — `builtinShapes` was the one mutable global in the\n * kernel and it had zero tests.\n */\nexport function createRegistry<T extends Registered>(\n label: string,\n seed: Iterable<T> = [],\n): Registry<T> {\n const table = new Map<string, T>()\n const registry: Registry<T> = {\n register(entry, options = {}): void {\n if (typeof entry.id !== 'string' || entry.id.length === 0) {\n throw new ValidationError(`${label}: an entry must carry a non-empty id`)\n }\n if (!Number.isSafeInteger(entry.version) || entry.version < 1) {\n throw new ValidationError(\n `${label}: ${JSON.stringify(entry.id)} must carry a positive integer version`,\n )\n }\n const key = formatRegistryHandle(entry)\n if (!options.replace && table.has(key)) {\n throw new ValidationError(`${label}: ${JSON.stringify(key)} is already registered`)\n }\n table.set(key, entry)\n },\n has(handle): boolean {\n return table.has(formatRegistryHandle(handle))\n },\n get(handle): T | undefined {\n return table.get(formatRegistryHandle(handle))\n },\n require(handle, context = label): T {\n const key = formatRegistryHandle(handle)\n const entry = table.get(key)\n if (entry === undefined) {\n const known = registry.names()\n const suffix =\n known.length > 0 ? `; registered: ${known.join(', ')}` : '; nothing is registered'\n throw new ValidationError(`${context}: ${JSON.stringify(key)} is not registered${suffix}`)\n }\n return entry\n },\n names(): string[] {\n return Array.from(table.keys()).sort()\n },\n entries(): T[] {\n return registry.names().map((key) => table.get(key) as T)\n },\n }\n for (const entry of seed) registry.register(entry)\n return registry\n}\n","/**\n * The authored form of an engine graph (agent-runtime#971, #973, #968): typed-port nodes over\n * three edge kinds, each guardable by the one predicate tree; `data` edges may carry one pure\n * projection. ADC's `${steps.<id>.field}` strings are an AUTHORING surface that compiles down to\n * these port references — this is the runtime form, checked before any spend.\n */\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { PromptHandle } from '../supervise/prompt-registry'\nimport type { Budget } from '../supervise/types'\nimport { type Condition, validateCondition } from './condition'\nimport type { NodeFlags, PortSpec } from './kind'\nimport { type Projection, validateProjection } from './projection'\nimport { parseRegistryHandle, type RegistryHandle } from './registry'\n\n/** Which gating-edge outcomes release a node (adopted from ADC, agent-runtime#968). */\nexport const JOIN_RULES = ['all', 'any', 'any_failed', 'all_done'] as const\nexport type JoinRule = (typeof JOIN_RULES)[number]\n\n/** ADC-compatible visit backstop: nothing may be ENTERED more than this many times. */\nexport const DEFAULT_MAX_NODE_VISITS = 25\n/** The hard ceiling an author's `maxVisits`/`maxNodeVisits` override may reach. */\nexport const MAX_MAX_NODE_VISITS = 100\n\nexport type GraphEdgeKind = 'delegates' | 'analyzes' | 'data'\n\nexport interface EngineGraphNode {\n readonly id: string\n /** `<id>/v<n>` into the engine's kind registry. */\n readonly kind: string\n /** This node's config, validated by its kind's `validateConfig` at compile. */\n readonly config?: unknown\n /** Per-node flags — properties of the node, never of its kind (agent-runtime#970). */\n readonly flags?: NodeFlags\n /** Node-level port declarations, merged OVER the kind's. A kind whose surface depends on its\n * config (a script) declares ports here; a typed kind's declared ports stay authoritative. */\n readonly ports?: {\n readonly inputs?: ReadonlyArray<PortSpec>\n readonly outputs?: ReadonlyArray<PortSpec>\n }\n /** Which inbound gating-edge outcomes release this node. Default `all`. */\n readonly join?: JoinRule\n /** Entered more than this many times fails the run `cycle-budget-exceeded`. */\n readonly maxVisits?: number\n /** This node's completion check; a terminal without one (or a kind/graph default) refuses. */\n readonly deliverable?: DeliverableSpec<unknown>\n /** Force-mark a terminal. Absent, a node with no outbound gating edge is terminal. */\n readonly terminal?: boolean\n /** Profile fields merged over the engine-authored `{ name: id }` for this node's spawns. */\n readonly profile?: Readonly<Partial<AgentProfile>>\n /** Per-instance reservation for this node's spawns; falls back to the run's `perNode`. */\n readonly budget?: Budget\n}\n\nexport interface EngineGraphEdge {\n /** Stable id for the ledger; defaults to `<from>-><to>#<ordinal>`. */\n readonly id?: string\n readonly kind: GraphEdgeKind\n readonly from: { readonly node: string; readonly port?: string }\n readonly to: { readonly node: string; readonly port?: string }\n /** Evaluated over the source's settle context; absent = satisfied by completion. */\n readonly guard?: Condition\n /** `data` edges only: ONE pure reshape of the admitted payload. */\n readonly projection?: Projection\n /** Refuses the traversal past this many firings (ledgered `unpropagated`). */\n readonly maxTraversals?: number\n /** `delegates`/`analyzes`: the versioned directive appended to the target's task. */\n readonly directive?: PromptHandle\n}\n\nexport interface EngineGraphSpec {\n readonly nodes: ReadonlyArray<EngineGraphNode>\n readonly edges: ReadonlyArray<EngineGraphEdge>\n /** Root node for the graph-level completion check. Defaults to the single entry node. */\n readonly root?: string\n /** Becomes the ROOT node's completion check when the root declares none (#973). */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly maxNodeVisits?: number\n}\n\nexport interface ParsedGraphNode extends EngineGraphNode {\n readonly kindHandle: RegistryHandle\n readonly join: JoinRule\n readonly maxVisits: number\n}\n\n/** Structural validation only — everything a registry is not needed for. */\nexport function validateEngineGraphSpec(spec: EngineGraphSpec, context = 'compileGraph'): void {\n if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) {\n throw new ValidationError(`${context}: a graph needs at least one node`)\n }\n const ids = new Set<string>()\n for (const node of spec.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError(`${context}: every node needs a non-empty id`)\n }\n if (ids.has(node.id))\n throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`)\n ids.add(node.id)\n parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`)\n if (node.join !== undefined && !(JOIN_RULES as ReadonlyArray<string>).includes(node.join)) {\n throw new ValidationError(\n `${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(', ')}`,\n )\n }\n if (node.maxVisits !== undefined) {\n if (\n !Number.isSafeInteger(node.maxVisits) ||\n node.maxVisits < 1 ||\n node.maxVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: node ${node.id} maxVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n }\n if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`)\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}]`\n if (edge.kind !== 'delegates' && edge.kind !== 'analyzes' && edge.kind !== 'data') {\n throw new ValidationError(`${who}: kind must be delegates | analyzes | data`)\n }\n for (const end of ['from', 'to'] as const) {\n const ref = edge[end]\n if (\n typeof ref !== 'object' ||\n ref === null ||\n typeof ref.node !== 'string' ||\n !ids.has(ref.node)\n ) {\n throw new ValidationError(`${who}: ${end}.node must name a node in this graph`)\n }\n }\n if (edge.guard !== undefined) validateCondition(edge.guard, `${who} guard`)\n if (edge.projection !== undefined) {\n if (edge.kind !== 'data') {\n throw new ValidationError(`${who}: only a data edge carries a projection`)\n }\n validateProjection(edge.projection, `${who} projection`)\n }\n if (edge.maxTraversals !== undefined) {\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 1) {\n throw new ValidationError(`${who}: maxTraversals must be a positive integer`)\n }\n }\n if (edge.kind === 'data' && edge.directive !== undefined) {\n throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`)\n }\n }\n if (spec.root !== undefined && !ids.has(spec.root)) {\n throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`)\n }\n if (spec.maxNodeVisits !== undefined) {\n if (\n !Number.isSafeInteger(spec.maxNodeVisits) ||\n spec.maxNodeVisits < 1 ||\n spec.maxNodeVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: maxNodeVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n}\n","/**\n * Compile an authored graph against an engine's kind registry into the schedulable form. Every\n * refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`\n * binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no\n * completion check (agent-runtime#971, #973).\n */\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport {\n DEFAULT_MAX_NODE_VISITS,\n type EngineGraphEdge,\n type EngineGraphSpec,\n type JoinRule,\n validateEngineGraphSpec,\n} from './definition'\nimport type { GraphEngine } from './engine'\nimport type { JsonSchema, NodeKind, PortSpec } from './kind'\nimport { formatRegistryHandle, parseRegistryHandle } from './registry'\n\n/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */\nexport const IMPLICIT_OUTPUT_PORTS = ['out', 'trace'] as const\n\nexport interface CompiledEdge {\n readonly id: string\n readonly spec: EngineGraphEdge\n readonly fromPort: string\n readonly toPort: string\n}\n\nexport interface CompiledNode {\n readonly id: string\n readonly kind: NodeKind\n readonly config: unknown\n readonly join: JoinRule\n readonly maxVisits: number\n readonly oracle: boolean\n readonly pure: boolean\n readonly terminal: boolean\n /** The check this node must pass to count DELIVERED; resolved per #973. */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly inbound: ReadonlyArray<CompiledEdge>\n readonly outbound: ReadonlyArray<CompiledEdge>\n readonly spec: EngineGraphSpec['nodes'][number]\n}\n\nexport interface CompiledGraph {\n readonly nodes: ReadonlyMap<string, CompiledNode>\n readonly edges: ReadonlyArray<CompiledEdge>\n readonly entries: ReadonlyArray<string>\n readonly terminals: ReadonlyArray<string>\n readonly root: string\n readonly maxNodeVisits: number\n}\n\ntype NodePorts = {\n readonly inputs: ReadonlyArray<PortSpec>\n readonly outputs: ReadonlyArray<PortSpec>\n}\n\n/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */\nfunction nodePorts(kind: NodeKind, node: EngineGraphSpec['nodes'][number]): NodePorts {\n const merge = (\n declared: ReadonlyArray<PortSpec>,\n own: ReadonlyArray<PortSpec> | undefined,\n ): ReadonlyArray<PortSpec> => {\n if (own === undefined || own.length === 0) return declared\n const names = new Set(own.map((port) => port.name))\n return [...own, ...declared.filter((port) => !names.has(port.name))]\n }\n return {\n inputs: merge(kind.inputs, node.ports?.inputs),\n outputs: merge(kind.outputs, node.ports?.outputs),\n }\n}\n\nfunction outputPort(ports: NodePorts, port: string): PortSpec | undefined {\n if ((IMPLICIT_OUTPUT_PORTS as ReadonlyArray<string>).includes(port)) {\n return { name: port, schema: {} }\n }\n return ports.outputs.find((candidate) => candidate.name === port)\n}\n\nfunction inputPort(ports: NodePorts, port: string): PortSpec | undefined {\n return ports.inputs.find((candidate) => candidate.name === port)\n}\n\n/**\n * Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no\n * `type` accept anything; object targets require their `required` properties to be present and\n * accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,\n * not a full JSON Schema validator.\n */\nexport function schemaAccepts(source: JsonSchema, target: JsonSchema, depth = 0): boolean {\n if (depth > 6) return true\n const sourceType = source.type\n const targetType = target.type\n if (targetType === undefined || sourceType === undefined) return true\n const targets = Array.isArray(targetType) ? targetType : [targetType]\n const sources = Array.isArray(sourceType) ? sourceType : [sourceType]\n const overlap = sources.filter(\n (candidate) =>\n targets.includes(candidate === 'integer' ? 'number' : candidate) ||\n targets.includes(candidate),\n )\n if (overlap.length === 0) return false\n if (targets.includes('object') && sources.includes('object')) {\n const required = Array.isArray(target.required) ? (target.required as string[]) : []\n const sourceProps = source.properties as Record<string, JsonSchema> | undefined\n const targetProps = target.properties as Record<string, JsonSchema> | undefined\n if (sourceProps !== undefined) {\n for (const name of required) {\n const sourceProp = sourceProps[name]\n if (sourceProp === undefined) return false\n const targetProp = targetProps?.[name]\n if (targetProp !== undefined && !schemaAccepts(sourceProp, targetProp, depth + 1)) {\n return false\n }\n }\n }\n }\n if (targets.includes('array') && sources.includes('array')) {\n const sourceItems = source.items as JsonSchema | undefined\n const targetItems = target.items as JsonSchema | undefined\n if (sourceItems !== undefined && targetItems !== undefined) {\n return schemaAccepts(sourceItems, targetItems, depth + 1)\n }\n }\n return true\n}\n\n/**\n * Lower an authored graph against an engine's kind registry into the schedulable form, refusing\n * every structural defect before any spend.\n */\nexport function compileGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec,\n context = 'compileGraph',\n): CompiledGraph {\n validateEngineGraphSpec(spec, context)\n const kinds = new Map<string, NodeKind>()\n const configs = new Map<string, unknown>()\n for (const node of spec.nodes) {\n const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`)\n const kind = engine.kinds.require(handle, `${context}: node ${node.id}`)\n kinds.set(node.id, kind)\n configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`))\n if (node.flags?.pure && kind.id !== 'script') {\n throw new ValidationError(\n `${context}: node ${node.id} sets pure, which only a script node may claim`,\n )\n }\n }\n\n const compiledEdges: CompiledEdge[] = []\n const inbound = new Map<string, CompiledEdge[]>()\n const outbound = new Map<string, CompiledEdge[]>()\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`\n const fromKind = kinds.get(edge.from.node)\n const toKind = kinds.get(edge.to.node)\n if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`)\n const toNode = spec.nodes.find((node) => node.id === edge.to.node)\n if (edge.kind !== 'analyzes' && toNode?.flags?.oracle) {\n // An edge to a grader leaks the rubric: an oracle is bound only by `analyzes`.\n throw new ValidationError(\n `${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`,\n )\n }\n const fromPort = edge.from.port ?? (edge.kind === 'analyzes' ? 'trace' : 'out')\n if (edge.kind === 'analyzes' && fromPort !== 'trace') {\n throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`)\n }\n const fromNode = spec.nodes.find((node) => node.id === edge.from.node)\n const fromPorts = nodePorts(fromKind, fromNode as EngineGraphSpec['nodes'][number])\n const toPorts = nodePorts(toKind, toNode as EngineGraphSpec['nodes'][number])\n const sourcePort = outputPort(fromPorts, fromPort)\n if (!sourcePort) {\n const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)]\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(', ')}`,\n )\n }\n let toPort = edge.to.port ?? ''\n if (edge.kind === 'data') {\n if (toPort === '') {\n if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? ''\n else {\n throw new ValidationError(\n `${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`,\n )\n }\n }\n const targetPort = inputPort(toPorts, toPort)\n if (!targetPort) {\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(', ') || '(none)'}`,\n )\n }\n // A projection reshapes the payload, so the source schema no longer describes it; the\n // projected shape is checked at admission, not statically.\n if (edge.projection === undefined && !schemaAccepts(sourcePort.schema, targetPort.schema)) {\n throw new ValidationError(\n `${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? 'any')}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? 'any')})`,\n )\n }\n }\n const compiled: CompiledEdge = {\n id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,\n spec: edge,\n fromPort,\n toPort: toPort === '' ? 'out' : toPort,\n }\n compiledEdges.push(compiled)\n outbound.set(edge.from.node, [...(outbound.get(edge.from.node) ?? []), compiled])\n inbound.set(edge.to.node, [...(inbound.get(edge.to.node) ?? []), compiled])\n }\n const dupes = new Set<string>()\n for (const edge of compiledEdges) {\n if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`)\n dupes.add(edge.id)\n }\n\n const entries = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (entries.length === 0) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (entries.length === 1\n ? (entries[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${entries.length} entry nodes (${entries.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n\n const nodes = new Map<string, CompiledNode>()\n const terminals: string[] = []\n for (const node of spec.nodes) {\n const kind = kinds.get(node.id)\n if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`)\n const terminal = node.terminal ?? (outbound.get(node.id) ?? []).length === 0\n const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : undefined)\n if (terminal) terminals.push(node.id)\n nodes.set(node.id, {\n id: node.id,\n kind,\n config: configs.get(node.id),\n join: node.join ?? 'all',\n maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n oracle: node.flags?.oracle ?? false,\n pure: node.flags?.pure ?? false,\n terminal,\n ...(deliverable === undefined ? {} : { deliverable }),\n inbound: inbound.get(node.id) ?? [],\n outbound: outbound.get(node.id) ?? [],\n spec: node,\n })\n }\n const unchecked = terminals.filter((id) => nodes.get(id)?.deliverable === undefined)\n if (unchecked.length === terminals.length) {\n // Termination is mandatory per terminal (#973): a graph none of whose terminals declares a\n // completion check (own, or the graph's on the root) can never prove it is done.\n throw new ValidationError(\n `${context}: no terminal declares a completion check (terminals: ${terminals.join(', ')}); give a node a deliverable or set spec.deliverable`,\n )\n }\n return {\n nodes,\n edges: compiledEdges,\n entries: entries.map((node) => node.id),\n terminals,\n root,\n maxNodeVisits: spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n }\n}\n","/**\n * `NodeKind` — what a consumer registers to add a node kind to the graph engine without forking\n * it (agent-runtime#969, #970).\n *\n * The engine owns the graph: scheduling over typed data edges, guards, joins, cycles, the\n * conserved pool, the journal. It does NOT own execution — `run` returns an `Agent`, the\n * kernel's spawn contract (`Scope.spawn` takes an `Agent { name, act }`; a leaf `Agent` carries its\n * `Executor` as `executorSpec: AgentSpec`, and a supervisor `Agent` is `supervisorAgent(...)`). So\n * every node rides `supervise()`'s machinery unchanged: the pool's reserve/reconcile, the\n * content-addressed journal, the completion gate, `Settled`, trace evidence. An engine that\n * re-implemented any of those would be a second kernel.\n *\n * Every kernel-owned extension contract is a TS interface plus a hand-written validator that\n * throws `ValidationError` by name (the kernel has no zod), and this one follows suit. JSON Schema\n * is the PORTABLE form of a config/port shape — a `Record<string, unknown>`, as `McpToolDescriptor`\n * and `DeliveryBinding` already spell it — so a kind's declaration can be published in a manifest\n * and lifted by a host on another stack.\n *\n * The bar this file is measured against: the scheduler's source names no kind that is not\n * universal. A kind the engine ships (`agent`, `supervisor`, `subgraph`, `script`) is universal by\n * the rule \"the model cannot decide it with the verbs it has\"; everything else — integrations,\n * notifications, sandbox provisioning, human decisions — is registered by a host.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport type { Agent } from '../supervise/types'\nimport type { Registered, RegistryHandle } from './registry'\n\n/** A JSON Schema document as the kernel already spells it: an opaque record, validated by the\n * consumer's own validator, published verbatim. */\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\n/**\n * One declared port on a node. Ports are how a `data` edge binds one node's output to another's\n * input with a type the compiler can check structurally before any spend. A node has two implicit\n * output ports beside its declared ones: `out` (its result) and `trace` (its `WorkerTraceEvidence`\n * by `traceRef`); only an `analyzes` edge may bind `trace`.\n */\nexport interface PortSpec {\n readonly name: string\n readonly schema: JsonSchema\n readonly description?: string\n}\n\n/**\n * What a kind declares it needs from the host. The engine never imports a host capability; it\n * knows only that a kind SAID it needs something under this name and the host PROVIDED something\n * under it. The context a kind receives is narrowed to exactly its declaration — an undeclared\n * effect is `undefined`, never a service locator.\n */\nexport type EffectName = string\n\nexport type EffectContext<Effects extends ReadonlyArray<EffectName>> = Readonly<{\n [K in Effects[number]]: unknown\n}>\n\n/**\n * What happens to a node that was IN FLIGHT when the process died. A settled node is never a\n * per-kind choice — it restores from its content-addressed `outRef` on replay. `'restart'` re-runs\n * from the journaled `inputRef`; `'resume'` is legal only for a kind whose executor can re-attach\n * to the live process (the bridge backend's session re-attachment is the existing instance).\n */\nexport type OnCrash = 'restart' | 'resume'\n\n/**\n * Whether a kind's spend enters the conserved pool. `'metered'`: the executor reports `Spend` and\n * settling without one is an ENGINE ERROR — never \"free\". `'exempt'`: the whole reservation is\n * refunded on settle, keeping the node out of Σk by construction (the kernel's `budgetExempt`).\n */\nexport type BudgetMode = 'metered' | 'exempt'\n\n/** The validated declaration every kind provides. `Config` is the per-node config shape;\n * `Effects` is the tuple of host capabilities it declares, so the context `run` receives is typed\n * to exactly that tuple. */\nexport interface NodeKind<\n Config = unknown,\n Effects extends ReadonlyArray<EffectName> = ReadonlyArray<EffectName>,\n> extends Registered {\n /** Kind id, e.g. `agent`, `integration.invoke`. With `version`, forms the handle `<id>/v<n>`. */\n readonly id: string\n readonly version: number\n readonly description: string\n /** Validate and narrow one node's config. Throw `ValidationError` to refuse; the compiler\n * surfaces the message with the node id prefixed. */\n readonly validateConfig: (raw: unknown, context: string) => Config\n /** The portable form of `validateConfig`'s accepted shape, for manifests and hosts. */\n readonly configSchema: JsonSchema\n /** Declared input ports; a `data` edge may bind only these. Empty for a source node. */\n readonly inputs: ReadonlyArray<PortSpec>\n /** Declared output ports beside the implicit `out` and `trace`. */\n readonly outputs: ReadonlyArray<PortSpec>\n /** Host capabilities this kind reaches for, by name. The context is narrowed to exactly these. */\n readonly effects: Effects\n readonly onCrash: OnCrash\n readonly budget: BudgetMode\n /**\n * Build the agent for one node instance. The kernel spawns it under `Scope.spawn`, so it is\n * authorized, classified, journaled, pooled and gated like any child — the kind owns only what\n * the agent DOES. `profile` is the node's pinned profile (an `agent`/`supervisor` kind runs it;\n * a `script` kind may ignore it); `inputs` are the resolved, content-addressed port values;\n * `effects` is the narrowed host context; `spawn` is the kernel's per-spawn context when the\n * kind needs it (a supervisor kind threads it into `nodeContext`).\n */\n readonly run: (args: {\n readonly config: Config\n readonly profile: AgentProfile\n readonly inputs: Readonly<Record<string, unknown>>\n readonly effects: EffectContext<Effects>\n readonly spawn?: WorkerSpawnContext\n }) => Agent<unknown, unknown>\n}\n\n/** Per-node flags a graph author sets; they are node properties, not kinds (agent-runtime#970). */\nexport interface NodeFlags {\n /** An oracle — a judge, grader, auditor, trace analyst — may be bound only by an `analyzes`\n * edge. The compiler refuses a `delegates` or `data` edge INTO an oracle: an edge to a grader\n * leaks the rubric. */\n readonly oracle?: boolean\n /** `script` only: pure over `(config, inputs)` ⇒ budget exempt, output restorable on replay,\n * runs in-process. A pure script that settles with a different `outRef` for the same inputs\n * has lied, and the first replay mismatch is an engine error. */\n readonly pure?: boolean\n}\n\n/** Validate a kind declaration at registration — so a malformed kind is refused by name once,\n * not at the first node that uses it. */\nexport function validateNodeKind(kind: NodeKind, context = 'registerNodeKind'): NodeKind {\n const who = `${context}: kind ${JSON.stringify(`${kind.id}/v${kind.version}`)}`\n if (typeof kind.id !== 'string' || kind.id.length === 0) {\n throw new ValidationError(`${context}: a kind must carry a non-empty id`)\n }\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(kind.id)) {\n throw new ValidationError(`${who}: id may contain only letters, digits, \".\", \"_\" and \"-\"`)\n }\n if (!Number.isSafeInteger(kind.version) || kind.version < 1) {\n throw new ValidationError(`${who}: version must be a positive integer`)\n }\n if (typeof kind.description !== 'string' || kind.description.trim().length === 0) {\n throw new ValidationError(`${who}: description is required`)\n }\n if (typeof kind.validateConfig !== 'function') {\n throw new ValidationError(`${who}: validateConfig must be a function`)\n }\n if (!isRecord(kind.configSchema)) {\n throw new ValidationError(`${who}: configSchema must be a JSON Schema object`)\n }\n for (const [field, ports] of [\n ['inputs', kind.inputs],\n ['outputs', kind.outputs],\n ] as const) {\n if (!Array.isArray(ports)) throw new ValidationError(`${who}: ${field} must be an array`)\n const seen = new Set<string>()\n for (const port of ports) {\n if (!port || typeof port.name !== 'string' || port.name.length === 0) {\n throw new ValidationError(`${who}: every ${field} port needs a non-empty name`)\n }\n if (field === 'outputs' && (port.name === 'out' || port.name === 'trace')) {\n throw new ValidationError(\n `${who}: output port ${JSON.stringify(port.name)} is implicit on every node and cannot be declared`,\n )\n }\n if (seen.has(port.name)) {\n throw new ValidationError(`${who}: duplicate ${field} port ${JSON.stringify(port.name)}`)\n }\n seen.add(port.name)\n if (!isRecord(port.schema)) {\n throw new ValidationError(\n `${who}: ${field} port ${JSON.stringify(port.name)} needs a JSON Schema`,\n )\n }\n }\n }\n if (\n !Array.isArray(kind.effects) ||\n kind.effects.some((e) => typeof e !== 'string' || e.length === 0)\n ) {\n throw new ValidationError(`${who}: effects must be an array of non-empty names`)\n }\n if (new Set(kind.effects).size !== kind.effects.length) {\n throw new ValidationError(`${who}: effects must not repeat a name`)\n }\n if (kind.onCrash !== 'restart' && kind.onCrash !== 'resume') {\n throw new ValidationError(`${who}: onCrash must be \"restart\" or \"resume\"`)\n }\n if (kind.budget !== 'metered' && kind.budget !== 'exempt') {\n throw new ValidationError(`${who}: budget must be \"metered\" or \"exempt\"`)\n }\n if (typeof kind.run !== 'function') {\n throw new ValidationError(`${who}: run must be a function`)\n }\n return kind\n}\n\n/** The handle a graph writes to name this kind. */\nexport function kindHandle(kind: Pick<NodeKind, 'id' | 'version'>): RegistryHandle {\n return { id: kind.id, version: kind.version }\n}\n\n/**\n * Narrow a host's effect table to exactly what one kind declared. Anything the kind did not\n * declare is absent — `undefined` on read — so a kind cannot reach past its declaration, and the\n * engine can list a graph's required effects before spending a token.\n */\nexport function narrowEffects<Effects extends ReadonlyArray<EffectName>>(\n declared: Effects,\n provided: Readonly<Record<string, unknown>>,\n context: string,\n): EffectContext<Effects> {\n const out: Record<string, unknown> = {}\n const missing: string[] = []\n for (const name of declared) {\n if (!(name in provided)) {\n missing.push(name)\n continue\n }\n out[name] = provided[name]\n }\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: host provides no effect for ${missing.map((m) => JSON.stringify(m)).join(', ')}; provided: ${\n Object.keys(provided).sort().join(', ') || 'none'\n }`,\n )\n }\n return Object.freeze(out) as EffectContext<Effects>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * `createGraphEngine` — one engine instance: its kind registry (core kinds pre-registered, host\n * kinds added by the caller), its effect table, and nothing global.\n *\n * The scheduler (#980), journal fold (#981) and the `runGraph` preset (#982) attach here; this\n * file is the part that must exist first so a host can register kinds and a compiler can ask\n * \"which effects does this graph need\" before a token is spent.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { EffectName, NodeKind } from './kind'\nimport { validateNodeKind } from './kind'\nimport { createRegistry, type Registry } from './registry'\n\nexport interface GraphEngineOptions {\n /** Kinds to register beside the core set. A host adds its own here; nothing is global. */\n readonly kinds?: ReadonlyArray<NodeKind>\n /** The host's effect table, by name. A kind receives only the effects it declared. */\n readonly effects?: Readonly<Record<EffectName, unknown>>\n /** The core set. Injected so a test can substitute, and so the engine never imports a\n * backend-specific factory at module load. */\n readonly coreKinds: ReadonlyArray<NodeKind>\n}\n\nexport interface GraphEngine {\n readonly kinds: Registry<NodeKind>\n readonly effects: Readonly<Record<EffectName, unknown>>\n /** Every effect name any registered kind declares — what a host must provide for this engine's\n * whole kind set to be runnable. Listed, never discovered mid-run. */\n requiredEffects(): string[]\n /** The declared effects no host value covers. Empty means every registered kind is runnable. */\n missingEffects(): string[]\n}\n\n/**\n * Build one engine: a kind registry seeded with the core kinds plus the host's, and the host's\n * effect values. Every kind is validated by name at construction, so a malformed host kind fails\n * here, never at its first node.\n */\nexport function createGraphEngine(options: GraphEngineOptions): GraphEngine {\n const kinds = createRegistry<NodeKind>('graph kinds')\n for (const kind of options.coreKinds) kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n for (const kind of options.kinds ?? [])\n kinds.register(validateNodeKind(kind, 'createGraphEngine'))\n const effects = Object.freeze({ ...(options.effects ?? {}) })\n if (Object.keys(effects).some((name) => name.length === 0)) {\n throw new ValidationError('createGraphEngine: an effect name must be non-empty')\n }\n const engine: GraphEngine = {\n kinds,\n effects,\n requiredEffects(): string[] {\n const names = new Set<string>()\n for (const kind of kinds.entries()) for (const name of kind.effects) names.add(name)\n return Array.from(names).sort()\n },\n missingEffects(): string[] {\n return engine.requiredEffects().filter((name) => !(name in effects))\n },\n }\n return engine\n}\n","/**\n * The fold (agent-runtime#974): scheduler state is a pure function of the journal, reconstructed\n * by replaying events through the SAME reducer the live scheduler feeds — fold, never checkpoint.\n * Kernel events (`spawned`, `settled`, `waiting`, `woken`) carry what the kernel owns; the engine's\n * events (`node-inputs-resolved`, `edge-verdict`, `join-state`) carry what the scheduler decided,\n * each journaled BEFORE its effect was visible. `edge` stays observability and is skipped here\n * exactly as the kernel's own replay skips it.\n *\n * Events are consumed in APPEND order (the journal file's line order), not by `seq`: kernel and\n * engine events carry independent ordinal counters, and append order is the one total order both\n * share.\n */\nimport { ValidationError } from '../../errors'\nimport type { SpawnEvent } from '../supervise/types'\nimport type { CompiledGraph } from './compile'\nimport type { GraphNodeSettle } from './scheduler-types'\n\nexport type FoldEdgeState = 'pending' | 'satisfied' | 'dead' | 'failed'\n\nexport interface FoldEdge {\n state: FoldEdgeState\n /** Set by a `join-state` whose wave this edge was pending inside; cleared when the in-flight\n * completion it refers to settles (absorbed, never re-released). */\n consumedOnce: boolean\n /** Delivered consumptions — what the per-edge cap counts. */\n traversals: number\n /** How many of the source's settles this edge has accounted for — by a journaled verdict or by\n * an absorption. The idempotence key: a kill between a settle and its verdicts re-judges ONLY\n * the unaccounted edges on restart, never a judged or absorbed one twice. */\n judgedSourceSettles: number\n /** The admitted source payload this state reflects (the source settle's outRef). */\n payloadRef?: string\n capped: boolean\n}\n\nexport type FoldInstanceStatus = 'released' | 'live' | 'done' | 'down' | 'suspended'\n\nexport interface FoldInstance {\n readonly node: string\n readonly instance: string\n readonly visit: number\n inputRef?: string\n status: FoldInstanceStatus\n settle?: GraphNodeSettle\n}\n\nexport interface FoldSuspension {\n readonly token: string\n readonly node: string\n readonly instance: string\n readonly onExpire: 'wait' | 'fail' | 'default'\n readonly expiresAtMs?: number\n readonly defaultRef?: string\n status: 'pending' | 'woken' | 'expired'\n}\n\nexport interface FoldNode {\n visits: number\n blocked: boolean\n settles: GraphNodeSettle[]\n}\n\nexport interface GraphFoldState {\n readonly nodes: Map<string, FoldNode>\n readonly edges: Map<string, FoldEdge>\n /** Every node instance the journal knows, keyed by `<node>#<visit>`. */\n readonly instances: Map<string, FoldInstance>\n /** Kernel node id → engine instance label, from `spawned`. */\n readonly spawnedIds: Map<string, string>\n readonly suspensions: Map<string, FoldSuspension>\n readonly exhaustedEdges: Set<string>\n}\n\n/** The reducer's zero: every node unvisited, every edge pending, nothing suspended. */\nexport function emptyFoldState(compiled: CompiledGraph): GraphFoldState {\n const nodes = new Map<string, FoldNode>()\n for (const id of compiled.nodes.keys()) nodes.set(id, { visits: 0, blocked: false, settles: [] })\n const edges = new Map<string, FoldEdge>()\n for (const edge of compiled.edges) {\n edges.set(edge.id, {\n state: 'pending',\n consumedOnce: false,\n traversals: 0,\n judgedSourceSettles: 0,\n capped: false,\n })\n }\n return {\n nodes,\n edges,\n instances: new Map(),\n spawnedIds: new Map(),\n suspensions: new Map(),\n exhaustedEdges: new Set(),\n }\n}\n\nfunction instanceOf(state: GraphFoldState, label: string): FoldInstance | undefined {\n return state.instances.get(label)\n}\n\n/**\n * Apply ONE journal event. The live scheduler calls this right after each append; the restart path\n * calls it over the loaded journal. Unknown kernel events are ignored — the engine folds only what\n * it understands, exactly as the kernel's replay skips the engine's events.\n */\nexport function applyGraphFoldEvent(\n state: GraphFoldState,\n ev: SpawnEvent,\n compiled: CompiledGraph,\n): void {\n switch (ev.kind) {\n case 'node-inputs-resolved': {\n const visit = Number(ev.instance.split('#').at(-1))\n if (!Number.isSafeInteger(visit)) {\n throw new ValidationError(`graph fold: instance ${ev.instance} carries no visit ordinal`)\n }\n state.instances.set(ev.instance, {\n node: ev.node,\n instance: ev.instance,\n visit,\n inputRef: ev.inputRef,\n status: 'released',\n })\n const node = state.nodes.get(ev.node)\n if (node) node.visits = Math.max(node.visits, visit)\n return\n }\n case 'spawned': {\n const instance = instanceOf(state, ev.label)\n if (instance) {\n instance.status = 'live'\n state.spawnedIds.set(ev.id, ev.label)\n }\n return\n }\n case 'settled': {\n const label = state.spawnedIds.get(ev.id)\n const instance = label === undefined ? undefined : instanceOf(state, label)\n if (!instance) return\n instance.status = ev.status\n const settle: GraphNodeSettle = {\n node: instance.node,\n visit: instance.visit,\n status: ev.status,\n ...(ev.outRef !== undefined ? { outRef: ev.outRef } : {}),\n ...(ev.reason !== undefined ? { reason: ev.reason } : {}),\n }\n if (ev.trace?.status === 'available') {\n ;(settle as { traceRef?: string }).traceRef = ev.trace.traceRef\n }\n instance.settle = settle\n state.nodes.get(instance.node)?.settles.push(settle)\n // The settle of an in-flight completion a wave already consumed re-arms its edges silently —\n // and counts as ACCOUNTED, so a restart never re-judges an absorbed completion.\n const node = compiled.nodes.get(instance.node)\n for (const edge of node?.outbound ?? []) {\n const folded = state.edges.get(edge.id)\n if (folded?.consumedOnce && folded.state === 'pending') {\n folded.consumedOnce = false\n folded.judgedSourceSettles += 1\n }\n }\n return\n }\n case 'edge-verdict': {\n const folded = state.edges.get(ev.edge)\n if (!folded) return\n if (ev.capped) {\n folded.capped = true\n state.exhaustedEdges.add(ev.edge)\n const target = compiled.edges.find((edge) => edge.id === ev.edge)?.spec.to.node\n const compiledTarget = target === undefined ? undefined : compiled.nodes.get(target)\n if (\n compiledTarget &&\n (compiledTarget.join === 'all' || compiledTarget.join === 'all_done')\n ) {\n const node = state.nodes.get(target as string)\n if (node) node.blocked = true\n }\n return\n }\n folded.judgedSourceSettles += 1\n if (!ev.fired) {\n folded.state = ev.sourceStatus === 'done' ? 'dead' : 'failed'\n folded.payloadRef = undefined\n return\n }\n folded.state = 'satisfied'\n folded.payloadRef = ev.inputRef\n return\n }\n case 'join-state': {\n // A release consumes its wave: delivered consumptions count a traversal and re-arm; every\n // gating edge still pending is consumed-once.\n for (const edgeId of ev.satisfiedBy) {\n const folded = state.edges.get(edgeId)\n if (!folded) continue\n folded.traversals += 1\n folded.state = 'pending'\n folded.payloadRef = undefined\n }\n const target = compiled.nodes.get(ev.node)\n for (const edge of target?.inbound ?? []) {\n const folded = state.edges.get(edge.id)\n if (!folded) continue\n if (ev.consumedPending.includes(edge.id)) folded.consumedOnce = true\n else if (folded.state !== 'pending' && !ev.satisfiedBy.includes(edge.id)) {\n // Settled but not part of the wave (an `any` join's losers): re-arm without a traversal.\n folded.state = 'pending'\n folded.payloadRef = undefined\n }\n }\n return\n }\n case 'waiting': {\n if (ev.spec.kind !== 'token') return\n const instance = instanceOf(state, ev.label)\n if (instance) {\n instance.status = 'suspended'\n // The kernel settle that surfaced the suspension marker is NOT a settle of this node —\n // retract it, so fold state matches what the live scheduler recorded (nothing).\n if (instance.settle !== undefined) {\n const settles = state.nodes.get(instance.node)?.settles\n if (settles && settles.at(-1) === instance.settle) settles.pop()\n instance.settle = undefined\n }\n }\n state.suspensions.set(ev.spec.token, {\n token: ev.spec.token,\n node: instance?.node ?? ev.label.split('#')[0] ?? ev.label,\n instance: ev.label,\n onExpire: ev.spec.onExpire,\n ...(ev.spec.expiresAtMs !== undefined ? { expiresAtMs: ev.spec.expiresAtMs } : {}),\n ...(ev.spec.defaultRef !== undefined ? { defaultRef: ev.spec.defaultRef } : {}),\n status: 'pending',\n })\n return\n }\n case 'woken': {\n // The engine wakes suspensions by token-shaped node id `graphwait:<token>`.\n const token = ev.id.startsWith('graphwait:') ? ev.id.slice('graphwait:'.length) : undefined\n const suspension = token === undefined ? undefined : state.suspensions.get(token)\n if (!suspension) return\n const instance = instanceOf(state, suspension.instance)\n if (ev.by === 'expired') {\n suspension.status = 'expired'\n if (instance) {\n instance.status = 'down'\n const settle: GraphNodeSettle = {\n node: suspension.node,\n visit: instance.visit,\n status: 'down',\n reason: 'suspension expired',\n }\n instance.settle = settle\n state.nodes.get(suspension.node)?.settles.push(settle)\n }\n return\n }\n suspension.status = 'woken'\n if (instance) {\n instance.status = 'done'\n const settle: GraphNodeSettle = {\n node: suspension.node,\n visit: instance.visit,\n status: 'done',\n ...(ev.outRef !== undefined ? { outRef: ev.outRef } : {}),\n }\n instance.settle = settle\n state.nodes.get(suspension.node)?.settles.push(settle)\n }\n return\n }\n default:\n return\n }\n}\n\n/** Fold a loaded journal (append order) into scheduler state. */\nexport function foldGraphJournal(\n events: ReadonlyArray<SpawnEvent>,\n compiled: CompiledGraph,\n): GraphFoldState {\n const state = emptyFoldState(compiled)\n for (const ev of events) applyGraphFoldEvent(state, ev, compiled)\n return state\n}\n","/**\n * The four core node kinds (agent-runtime#970) — the ones universal by the rule \"the model cannot\n * decide it with the verbs it has\". Everything else (integrations, notifications, sandbox\n * provisioning, human decisions) is registered by a host against the same `NodeKind` contract.\n *\n * Each `run` returns an `Agent` the kernel spawns under `Scope.spawn`; none of these re-implements\n * pooling, journaling, gating or identity. `agent` and `supervisor` are thin wraps over the\n * kernel's own factories; `script` is the one kind with no kernel primitive behind it; `subgraph`\n * is the scheduler's and is refused here until the scheduler lands (#980).\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport type { ExecutorConfig } from '../supervise/runtime'\nimport { workerFromBackend } from '../supervise/supervise'\nimport { type SupervisorAgentDeps, supervisorAgent } from '../supervise/supervisor-agent'\nimport type { Agent, AgentSpec, Executor, ExecutorResult, Spend } from '../supervise/types'\nimport type { NodeKind } from './kind'\nimport { formatRegistryHandle, type RegistryHandle } from './registry'\n\n// ── agent ───────────────────────────────────────────────────────────────────────\n\nexport interface AgentKindConfig {\n /** Where this node's profile runs. Omit to inherit the engine's default backend. */\n readonly backend?: ExecutorConfig\n /** This node's completion check. Omit to inherit the graph's terminal check. */\n readonly deliverable?: DeliverableSpec<unknown>\n}\n\n/**\n * One profile, one run: the kernel's leaf, exactly as `supervise()` derives it from `backend`.\n * The model cannot decide this — it is what gets run.\n */\nexport function agentKind(defaults: {\n readonly backend?: ExecutorConfig\n readonly deliverable?: DeliverableSpec<unknown>\n}): NodeKind<AgentKindConfig> {\n return {\n id: 'agent',\n version: 1,\n description: 'One AgentProfile run as a leaf on a backend; the kernel derives the executor.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: agent config`)\n return {\n ...(config.backend !== undefined ? { backend: config.backend as ExecutorConfig } : {}),\n ...(config.deliverable !== undefined\n ? { deliverable: config.deliverable as DeliverableSpec<unknown> }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { backend: { type: 'object' }, deliverable: { type: 'object' } },\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, spawn }) => {\n const backend = config.backend ?? defaults.backend\n if (!backend) {\n throw new ValidationError(\n `agent kind: node ${JSON.stringify(profile.name)} has no backend — set config.backend or the engine default`,\n )\n }\n const make: MakeWorkerAgent = workerFromBackend(\n backend,\n config.deliverable ?? defaults.deliverable,\n )\n return make(profile, spawn)\n },\n }\n}\n\n// ── supervisor ──────────────────────────────────────────────────────────────────\n\nexport interface SupervisorKindConfig {\n /** Per-child budget reserved from the pool on each spawn this supervisor makes. */\n readonly perWorker: SupervisorAgentDeps['perWorker']\n readonly maxLiveWorkers?: number\n}\n\n/**\n * The thing that DECIDES: a nested `supervisorAgent` with the coordination verbs. Its children\n * are its own tree — the graph sees one node in, one `Settled` out. A `subgraph` constrains what\n * it may spawn; without one it is free-form under `profileSecurity` and `allowedModels`.\n */\nexport function supervisorKind(deps: {\n readonly blobs: SupervisorAgentDeps['blobs']\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly router?: SupervisorAgentDeps['router']\n readonly driveHarness?: SupervisorAgentDeps['driveHarness']\n}): NodeKind<SupervisorKindConfig> {\n return {\n id: 'supervisor',\n version: 1,\n description:\n 'A nested supervisor: spawns, observes, steers and awaits its own children with the coordination verbs.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: supervisor config`)\n const perWorker = asRecord(config.perWorker, `${context}: supervisor config.perWorker`)\n return {\n perWorker: perWorker as unknown as SupervisorKindConfig['perWorker'],\n ...(config.maxLiveWorkers !== undefined\n ? { maxLiveWorkers: Number(config.maxLiveWorkers) }\n : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { perWorker: { type: 'object' }, maxLiveWorkers: { type: 'integer' } },\n required: ['perWorker'],\n additionalProperties: false,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile }) =>\n supervisorAgent(profile, {\n blobs: deps.blobs,\n makeWorkerAgent: deps.makeWorkerAgent,\n perWorker: config.perWorker,\n ...(config.maxLiveWorkers !== undefined ? { maxLiveWorkers: config.maxLiveWorkers } : {}),\n ...(deps.router ? { router: deps.router } : {}),\n ...(deps.driveHarness ? { driveHarness: deps.driveHarness } : {}),\n }),\n }\n}\n\n// ── script ──────────────────────────────────────────────────────────────────────\n\n/** The caller code a `script` node runs. Receives the resolved inputs; returns the output. */\nexport type ScriptBody = (\n inputs: Readonly<Record<string, unknown>>,\n signal: AbortSignal,\n) => Promise<unknown> | unknown\n\nexport interface ScriptKindConfig {\n readonly body: ScriptBody\n /**\n * `pure: true` is the promise that the output is a function of `(config, inputs)` alone: the\n * node is then budget-exempt, its output restorable on replay by content address, and it runs\n * in-process. A pure script that settles with a different `outRef` for the same inputs has\n * lied, and the first replay mismatch is an engine error.\n */\n readonly pure?: boolean\n /** For a metered script: what it spent. Omit on a pure script. A metered script that reports\n * nothing is metered as NOTHING-KNOWN, never as free. */\n readonly spent?: Spend\n}\n\n/** The script kind's handle; it also names the kind in every script node's identity. */\nconst SCRIPT: RegistryHandle = { id: 'script', version: 1 }\n\n/**\n * Caller code as a node. The one kind with no kernel primitive behind it: the kernel has no\n * \"data→data with no execution\" concept (agent-runtime#970 fact-finding), so this is new. It is\n * still a leaf `Agent` carrying an `Executor`, so the journal, the gate and the pool treat it like\n * any other node.\n */\nexport function scriptKind(): NodeKind<ScriptKindConfig> {\n return {\n ...SCRIPT,\n description:\n 'Run caller code over the resolved inputs; pure scripts are exempt and restorable.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: script config`)\n if (typeof config.body !== 'function') {\n throw new ValidationError(`${context}: script config.body must be a function`)\n }\n if (config.pure !== undefined && typeof config.pure !== 'boolean') {\n throw new ValidationError(`${context}: script config.pure must be a boolean`)\n }\n if (config.pure === true && config.spent !== undefined) {\n throw new ValidationError(\n `${context}: a pure script is budget-exempt and cannot report spent`,\n )\n }\n return {\n body: config.body as ScriptBody,\n ...(config.pure !== undefined ? { pure: config.pure } : {}),\n ...(config.spent !== undefined ? { spent: config.spent as Spend } : {}),\n }\n },\n configSchema: {\n type: 'object',\n properties: { pure: { type: 'boolean' }, spent: { type: 'object' } },\n // `body` is a function and has no JSON form; a host that lifts `script` supplies its own\n // executable reference (ADC: a module in a sandbox) under this same kind id.\n additionalProperties: true,\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, inputs }) => scriptAgent(profile, config, inputs, SCRIPT),\n }\n}\n\nfunction scriptAgent(\n profile: AgentProfile,\n config: ScriptKindConfig,\n inputs: Readonly<Record<string, unknown>>,\n kind: RegistryHandle,\n): Agent<unknown, unknown> & { executorSpec: AgentSpec } {\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n // A pure script spends nothing from the pool by construction; the kernel refunds its whole\n // reservation. A metered script with no `spent` is NOT free: it is recorded as unknown.\n ...(config.pure ? { budgetExempt: true } : {}),\n async execute(_task, signal): Promise<ExecutorResult<unknown>> {\n const startedAt = Date.now()\n const out = await config.body(inputs, signal)\n const ms = Date.now() - startedAt\n // Exempt means zero spend on every pool channel, iterations included; only the wall clock is\n // reported, and it is not a pool channel.\n const spent: Spend = config.pure\n ? { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms }\n : (config.spent ?? {\n iterations: 1,\n tokens: { input: 0, output: 0, tokensKnown: false },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n })\n artifact = { outRef: contentAddress(out), out, spent }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) throw new ValidationError('script: resultArtifact() read before execute()')\n return artifact\n },\n }\n // The profile names the node; the kind is the behavioral authority, so it joins the node's\n // identity here. A script claims no harness or model: nothing runs one.\n const spec: AgentSpec = {\n profile,\n harness: null,\n executor,\n execution: { correlation: { nodeKind: formatRegistryHandle(kind) } },\n }\n return {\n name: profile.name ?? 'script',\n // `act` is never the path: Scope reads `executorSpec` and runs the executor itself.\n act: () => Promise.reject(new ValidationError('script: act() is not the execution path')),\n executorSpec: spec,\n }\n}\n\n// ── subgraph ────────────────────────────────────────────────────────────────────\n\n/**\n * A node carrying its own graph: the constraint on what a supervisor may spawn at depth>1. Its\n * executor is a nested engine run; that needs the scheduler (#980), so until then this kind is\n * registered and REFUSES at run time by name rather than being absent — a graph that names it\n * compiles, and the refusal says exactly what is missing.\n */\nexport function subgraphKind(): NodeKind<{ readonly graph: unknown }> {\n return {\n id: 'subgraph',\n version: 1,\n description: 'A node that runs its own graph; constrains a supervisor at depth>1.',\n validateConfig: (raw, context) => {\n const config = asRecord(raw, `${context}: subgraph config`)\n if (config.graph === undefined) {\n throw new ValidationError(`${context}: subgraph config.graph is required`)\n }\n return { graph: config.graph }\n },\n configSchema: {\n type: 'object',\n properties: { graph: { type: 'object' } },\n required: ['graph'],\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ profile }) => {\n throw new ValidationError(\n `subgraph kind: node ${JSON.stringify(profile.name)} cannot run yet — the scheduler that executes a nested graph lands in agent-runtime#980`,\n )\n },\n }\n}\n\nfunction asRecord(value: unknown, context: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError(`${context} must be an object`)\n }\n return value as Record<string, unknown>\n}\n","/**\n * The engine scheduler (agent-runtime#980, durable per #974/#976): run a compiled graph by hosting\n * every node instance on one kernel `Scope` — the pool, the journal, the blob store and\n * cancellation are the kernel's, never re-implemented. The scheduler owns only what a graph adds:\n * joins over guarded edges, traversal and visit caps, directive/payload delivery, suspensions,\n * terminals and the finalizer reduce.\n *\n * DURABILITY MODEL — fold, never checkpoint. Every scheduling decision is journaled BEFORE its\n * effect is visible (blob-then-journal where a ref is minted), then applied to in-memory state\n * through the SAME pure reducer (`applyGraphFoldEvent`) a restart replays the journal through.\n * Kill the process at any journal boundary and a restart with the same journal re-enters the exact\n * state: settled nodes restore from `outRef` and are never re-executed; a released-but-unspawned\n * instance re-enters from its pinned `inputRef`; an in-flight instance is in-doubt and re-enters\n * per its kind's `onCrash`.\n *\n * Engine `woken` ordinals live in a reserved high band (`ENGINE_WOKEN_SEQ_BASE`+) so they can\n * never collide with the kernel scope's cursor counter, which the kernel owns and advances\n * concurrently.\n */\nimport { contentAddress } from '../../durable/content-address'\nimport {\n closesCursorSlot,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { addSpend } from '../../runtime/util'\nimport { createBudgetPool } from '../supervise/budget'\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createScope } from '../supervise/scope'\nimport {\n maxSeqOf,\n sumMeasuredSpendFromEvents,\n uncertainSpawnBudgets,\n} from '../supervise/supervisor'\nimport type { Budget, ResultBlobStore, Settled, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { type CompiledEdge, type CompiledGraph, compileGraph } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport {\n applyGraphFoldEvent,\n emptyFoldState,\n type FoldSuspension,\n type GraphFoldState,\n} from './fold'\nimport { narrowEffects } from './kind'\nimport { applyProjection } from './projection'\nimport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\nexport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\n/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter. */\nexport const ENGINE_WOKEN_SEQ_BASE = 10_000_000\n\nconst SUSPEND_MARK = '__graphSuspension'\n\nexport interface SuspensionRequest {\n readonly [SUSPEND_MARK]: true\n readonly onExpire: 'wait' | 'fail' | 'default'\n /** Milliseconds from the suspension's journaling instant; absent with `onExpire: 'wait'`. */\n readonly expiresInMs?: number\n readonly default?: unknown\n}\n\n/** What a kind's executor returns to park its node on a host wake (agent-runtime#976). */\nexport function suspended(\n options: {\n readonly onExpire?: 'wait' | 'fail' | 'default'\n readonly expiresInMs?: number\n readonly default?: unknown\n } = {},\n): SuspensionRequest {\n const onExpire = options.onExpire ?? 'wait'\n if (onExpire !== 'wait' && options.expiresInMs === undefined) {\n throw new ValidationError(`suspended: onExpire '${onExpire}' requires expiresInMs`)\n }\n if (onExpire === 'wait' && options.expiresInMs !== undefined) {\n throw new ValidationError(\"suspended: onExpire 'wait' never expires — remove expiresInMs\")\n }\n if (onExpire === 'default' && options.default === undefined) {\n throw new ValidationError(\"suspended: onExpire 'default' requires a default payload\")\n }\n return {\n [SUSPEND_MARK]: true,\n onExpire,\n ...(options.expiresInMs !== undefined ? { expiresInMs: options.expiresInMs } : {}),\n ...(options.default !== undefined ? { default: options.default } : {}),\n }\n}\n\nfunction isSuspensionRequest(value: unknown): value is SuspensionRequest {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)[SUSPEND_MARK] === true\n )\n}\n\n/** Admission for every value crossing an edge (#971): JSON round-trip, `undefined` stripped, a\n * non-representable value becomes a RECORD of that fact — a degraded record beats a vanished\n * edge. */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n if (text === undefined) return { nonCanonical: `payload of type ${typeof value}` }\n return JSON.parse(text)\n } catch (error) {\n return { nonCanonical: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface GraphRunOptions {\n /** The run's conserved pool. */\n readonly budget: Budget\n /** Default per-instance reservation for nodes that declare no `budget` of their own.\n * Required when any such node exists — the engine invents no split. */\n readonly perNode?: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n /** Resolves `delegates`/`analyzes` directives; required when any edge carries one. */\n readonly prompts?: PromptRegistry\n /** How terminal settles reduce to `out`. Default `bestDelivered`. */\n readonly finalizer?: 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly runId?: string\n /** Continue an existing journaled run. An existing tree without this refuses, like the kernel. */\n readonly resume?: boolean\n /** Hold a fully-suspended run open for live `resume()` calls instead of returning\n * `{ kind: 'suspended' }`. Offline callers leave this off and restart later (#976). */\n readonly waitForWakes?: boolean\n}\n\n/** A live run: await `done`; deliver host wakes through `resume`/`expire` (#976). */\nexport interface GraphRunHandle {\n readonly done: Promise<GraphRunResult>\n resume(token: string, payload: unknown): Promise<void>\n expire(token: string): Promise<void>\n}\n\n/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs\n * no live host wakes. */\nexport async function runEngineGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): Promise<GraphRunResult> {\n return createGraphRun(engine, spec, task, options).done\n}\n\n/**\n * Start (or resume) a graph run and return its handle: await `done` for the result; deliver host\n * wakes through `resume`/`expire` while it runs (#976).\n */\nexport function createGraphRun(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): GraphRunHandle {\n const compiled: CompiledGraph =\n 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n const wakes: Array<{\n token: string\n payload?: unknown\n expire: boolean\n settle: () => void\n fail: (e: unknown) => void\n }> = []\n let notifyWake: (() => void) | undefined\n const handleState = { finished: false }\n const done = runGraphLoop(\n engine,\n compiled,\n task,\n options,\n wakes,\n () => notifyWake?.(),\n (fn) => {\n notifyWake = fn\n },\n ).finally(() => {\n handleState.finished = true\n })\n const queue = (token: string, payload: unknown, expire: boolean): Promise<void> => {\n if (handleState.finished) {\n return Promise.reject(\n new ValidationError(\n `graph resume: run completed; start a new run over the same journal to wake '${token}'`,\n ),\n )\n }\n return new Promise<void>((settle, fail) => {\n wakes.push({ token, payload, expire, settle, fail })\n notifyWake?.()\n })\n }\n return {\n done,\n resume: (token, payload) => queue(token, payload, false),\n expire: (token) => queue(token, undefined, true),\n }\n}\n\n// ── The run loop ─────────────────────────────────────────────────────────────────\n\nasync function runGraphLoop(\n engine: GraphEngine,\n compiled: CompiledGraph,\n task: string,\n options: GraphRunOptions,\n wakes: Array<{\n token: string\n payload?: unknown\n expire: boolean\n settle: () => void\n fail: (e: unknown) => void\n }>,\n _notify: () => void,\n onWakeSignal: (fn: () => void) => void,\n): Promise<GraphRunResult> {\n const context = 'runEngineGraph'\n for (const node of compiled.nodes.values()) {\n const missing = node.kind.effects.filter((name) => !(name in engine.effects))\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: node ${node.id} needs effect(s) ${missing.join(', ')} the host did not provide`,\n )\n }\n if (node.spec.budget === undefined && options.perNode === undefined) {\n throw new ValidationError(\n `${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`,\n )\n }\n }\n for (const edge of compiled.edges) {\n if (edge.spec.directive !== undefined && options.prompts === undefined) {\n throw new ValidationError(\n `${context}: edge ${edge.id} carries a directive but options.prompts is absent`,\n )\n }\n }\n\n const now = options.now ?? Date.now\n const journal = options.journal ?? new InMemorySpawnJournal()\n const blobs = options.blobs ?? new InMemoryResultBlobStore()\n const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`\n\n // ── Begin or resume the journaled tree ─────────────────────────────────────────\n const prior = await journal.loadTree(runId)\n if (prior !== undefined && options.resume !== true) {\n throw new ValidationError(\n `${context}: runId '${runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const resuming = options.resume === true && prior !== undefined && prior.length > 0\n let runEpochMs = now()\n let rootBudget = options.budget\n if (prior === undefined) {\n await journal.beginTree(runId, new Date(runEpochMs).toISOString())\n }\n if (!resuming) {\n // The engine's root marker: the anchor a restart reads the epoch and deadline from, exactly\n // as the kernel supervisor journals its own root. A begun-but-empty journal (killed before\n // its first event) writes it here too.\n await journal.appendEvent(runId, {\n kind: 'spawned',\n id: runId,\n label: 'graph-root',\n budget: options.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(runEpochMs).toISOString(),\n })\n }\n if (resuming) {\n const root = prior.find((ev) => ev.kind === 'spawned' && ev.id === runId)\n if (root?.kind === 'spawned') {\n runEpochMs = Date.parse(root.at)\n rootBudget = root.budget\n }\n }\n\n // ── Pool + scope, resume-aware exactly like the kernel supervisor ──────────────\n const elapsed = () => now() - runEpochMs\n const pool = resuming\n ? createBudgetPool(rootBudget, elapsed, {\n committed: (() => {\n const measured = sumMeasuredSpendFromEvents(prior)\n return addSpend(measured.childWork, measured.driverInference)\n })(),\n uncertainReservations: uncertainSpawnBudgets(prior),\n ...(rootBudget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs }\n : {}),\n })\n : createBudgetPool(rootBudget, elapsed)\n const abort = new AbortController()\n const onOuterAbort = () => abort.abort(options.signal?.reason)\n options.signal?.addEventListener('abort', onOuterAbort, { once: true })\n if (options.signal?.aborted) abort.abort(options.signal.reason)\n const scope = createScope<unknown>({\n parentId: runId,\n root: runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now,\n ...(resuming\n ? {\n resumeFrom: {\n settled: await replaySpawnTree(journal, blobs, runId),\n view: materializeTreeView(prior),\n maxSpawnOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'spawned'),\n maxCursorSeq: maxSeqOf(prior, closesCursorSlot),\n maxWaitOrdinal: maxSeqOf(prior, (ev) => ev.kind === 'waiting'),\n waits: pendingWaits(prior),\n keys: new Map(),\n priorSpend: sumMeasuredSpendFromEvents(prior),\n },\n }\n : {}),\n })\n\n // Every path out of this function — a winner, a refusal, a kill at a journal boundary — tears\n // the scope down; a crashed append must never leak live children.\n try {\n return await runToResult()\n } finally {\n options.signal?.removeEventListener('abort', onOuterAbort)\n abort.abort('run complete')\n }\n\n async function runToResult(): Promise<GraphRunResult> {\n // ── State: ONE reducer builds it, live and on restart ──────────────────────────\n const state: GraphFoldState = emptyFoldState(compiled)\n if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, compiled)\n\n let engineSeq = resuming ? maxEngineSeq(prior) + 1 : 0\n let engineWokenSeq =\n ENGINE_WOKEN_SEQ_BASE +\n (resuming\n ? prior.filter((ev) => ev.kind === 'woken' && ev.seq >= ENGINE_WOKEN_SEQ_BASE).length\n : 0)\n const appendAndApply = async (ev: SpawnEvent): Promise<void> => {\n await journal.appendEvent(runId, ev)\n applyGraphFoldEvent(state, ev, compiled)\n }\n\n const ledger: GraphEdgeTraversal[] = []\n const liveHandles = new Map<string, string>() // scope handle id -> instance label\n const waitingForBudget: string[] = []\n const outCache = new Map<string, unknown>() // outRef -> admitted out, for guard/check evaluation\n let ledgerSeq = resuming ? prior.filter((ev) => ev.kind === 'edge').length : 0\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n const recordLedger = async (\n edge: CompiledEdge,\n traversal: number,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): Promise<void> => {\n const spec = edge.spec\n const entry: GraphEdgeTraversal = {\n edge: edge.id,\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n traversal,\n outcome,\n ...(spec.directive !== undefined\n ? { directive: `${spec.directive.surface}/v${spec.directive.version}` }\n : {}),\n ...(spec.kind === 'data' ? { port: edge.toPort } : {}),\n ...(reason !== undefined ? { reason } : {}),\n }\n ledger.push(entry)\n await journal.appendEvent(runId, {\n kind: 'edge',\n id: `graph:${spec.to.node}`,\n edge: {\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n ...(entry.directive !== undefined ? { directive: entry.directive } : {}),\n ...(entry.port !== undefined ? { port: entry.port } : {}),\n },\n traversal,\n outcome: outcome === 'delivered' ? 'delivered' : outcome,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n\n /** Spawn one released instance from its journaled envelope — the ONE entry path, used for a\n * fresh release, a budget-parked retry, and a restart re-entry alike. */\n const spawnInstance = async (instanceLabel: string): Promise<void> => {\n if (failure) return\n const instance = state.instances.get(instanceLabel)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node || instance.inputRef === undefined) {\n throw new ValidationError(`${context}: instance ${instanceLabel} has no journaled envelope`)\n }\n const envelope = (await blobs.get(instance.inputRef)) as\n | { task: string; inputs: Record<string, unknown> }\n | undefined\n if (envelope === undefined) {\n throw new ValidationError(\n `${context}: envelope ${instance.inputRef} is not in the blob store`,\n )\n }\n const effects = narrowEffects(\n node.kind.effects,\n engine.effects,\n `${context}: node ${node.id}`,\n )\n const agent = node.kind.run({\n config: node.config,\n profile: { name: node.id, ...(node.spec.profile ?? {}) },\n inputs: envelope.inputs,\n effects,\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, envelope.task, { label: instanceLabel, budget })\n if (spawned.ok) {\n liveCount += 1\n liveHandles.set(spawned.handle.id, instanceLabel)\n applyGraphFoldEvent(\n state,\n // The kernel journaled its own `spawned` row inside `scope.spawn`; mirror the two fields\n // the reducer folds so live state matches what a restart will reconstruct.\n {\n kind: 'spawned',\n id: spawned.handle.id,\n label: instanceLabel,\n budget,\n runtime: 'inline',\n seq: 0,\n at: '',\n },\n compiled,\n )\n return\n }\n if (spawned.reason === 'budget-exhausted' || spawned.reason === 'max-live-workers') {\n // Never overcommit: park the entry and retry after the next settle frees capacity (#972).\n waitingForBudget.push(instanceLabel)\n return\n }\n failure = {\n reason: 'driver-failed',\n error: { name: 'SpawnRefused', message: `node ${node.id}: ${spawned.reason}` },\n }\n abort.abort(`spawn refused: ${node.id}`)\n }\n\n /** Release a node: journal the wave (join-state + envelope) then spawn. */\n const release = async (\n nodeId: string,\n satisfiedBy: CompiledEdge[],\n consumedPending: string[],\n ): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n failure = {\n reason: 'cycle-budget-exceeded',\n error: {\n name: 'GraphCycleBudget',\n message: `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`,\n },\n }\n abort.abort(`cycle-budget-exceeded: ${nodeId}`)\n return\n }\n const instanceLabel = `${nodeId}#${visit}`\n // Build the envelope from the wave: data payloads projected and admitted, directives resolved,\n // trace refs lined up — then pinned by content address BEFORE anything spawns.\n const inputs: Record<string, unknown> = {}\n const directives: string[] = []\n const traces: string[] = []\n for (const edge of satisfiedBy) {\n const foldedEdge = state.edges.get(edge.id)\n const spec = edge.spec\n if (spec.kind === 'data' && foldedEdge?.state === 'satisfied') {\n let payload =\n foldedEdge.payloadRef === undefined ? undefined : outCache.get(foldedEdge.payloadRef)\n if (payload === undefined && foldedEdge.payloadRef !== undefined) {\n payload = admitPayload(await blobs.get(foldedEdge.payloadRef))\n }\n let outcome: GraphEdgeTraversal['outcome'] = 'delivered'\n let reason: string | undefined\n if (spec.projection !== undefined) {\n try {\n payload = admitPayload(applyProjection(payload, spec.projection, `edge ${edge.id}`))\n } catch (error) {\n outcome = 'empty'\n reason = error instanceof Error ? error.message : String(error)\n payload = undefined\n }\n }\n if (payload === undefined && outcome === 'delivered') outcome = 'empty'\n await recordLedger(edge, (foldedEdge?.traversals ?? 0) + 1, outcome, reason)\n if (payload !== undefined) inputs[edge.toPort] = payload\n } else {\n if (spec.directive !== undefined && options.prompts !== undefined) {\n directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && foldedEdge?.state === 'satisfied') {\n traces.push(`trace of ${spec.from.node}: ${foldedEdge.payloadRef ?? '(no traceRef)'}`)\n }\n await recordLedger(edge, (foldedEdge?.traversals ?? 0) + 1, 'delivered')\n }\n }\n const nodeTask = [nodeId === compiled.root ? task : '', ...directives, ...traces]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n const envelope = { task: nodeTask.length > 0 ? nodeTask : task, inputs }\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n const at = new Date(now()).toISOString()\n await appendAndApply({\n kind: 'node-inputs-resolved',\n id: instanceLabel,\n node: nodeId,\n instance: instanceLabel,\n inputRef,\n seq: engineSeq++,\n at,\n })\n await appendAndApply({\n kind: 'join-state',\n id: instanceLabel,\n node: nodeId,\n rule: node.join,\n satisfiedBy: satisfiedBy.map((edge) => edge.id),\n consumedPending,\n instance: instanceLabel,\n seq: engineSeq++,\n at,\n })\n await spawnInstance(instanceLabel)\n }\n\n /** Join evaluation per ADC's rules over the folded edge states. */\n const tryRelease = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded || folded.blocked || failure) return\n const gating = node.inbound\n if (gating.length === 0) return\n const states = gating.map((edge) => ({ edge, folded: state.edges.get(edge.id) }))\n const settled = states.filter((entry) => entry.folded && entry.folded.state !== 'pending')\n const satisfied = states.filter((entry) => entry.folded?.state === 'satisfied')\n const failed = states.filter((entry) => entry.folded?.state === 'failed')\n const allSettled = settled.length === gating.length\n let releaseNow = false\n switch (node.join) {\n case 'all':\n releaseNow =\n satisfied.length === gating.length &&\n !states.some(\n (entry) => entry.folded?.state === 'dead' || entry.folded?.state === 'failed',\n )\n break\n case 'any':\n releaseNow = satisfied.length > 0\n if (!releaseNow && allSettled) folded.blocked = true\n break\n case 'any_failed':\n releaseNow = failed.length > 0\n if (!releaseNow && allSettled) folded.blocked = true\n break\n case 'all_done':\n releaseNow = allSettled\n break\n }\n if (!releaseNow) return\n const consuming =\n node.join === 'any'\n ? [satisfied[0] as (typeof states)[number]]\n : node.join === 'any_failed'\n ? [failed[0] as (typeof states)[number]]\n : settled\n // Caps judged on the consuming edges BEFORE anything else happens; a refusal is fold-visible.\n for (const entry of consuming) {\n const cap = entry.edge.spec.maxTraversals\n if (cap !== undefined && (entry.folded?.traversals ?? 0) >= cap) {\n recordLedger(\n entry.edge,\n (entry.folded?.traversals ?? 0) + 1,\n 'unpropagated',\n `traversal-cap-exhausted (max ${cap})`,\n )\n await appendAndApply({\n kind: 'edge-verdict',\n id: `graph:${nodeId}`,\n edge: entry.edge.id,\n fired: false,\n sourceStatus: 'done',\n capped: true,\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n return\n }\n }\n const consumedPending = states\n .filter(\n (entry) =>\n entry.folded?.state === 'pending' &&\n hasLiveInstance(state, liveHandles, entry.edge.spec.from.node),\n )\n .map((entry) => entry.edge.id)\n await release(\n nodeId,\n consuming.map((entry) => entry.edge),\n consumedPending,\n )\n }\n\n /** Judge every outbound edge of a settle: journal the verdict, apply, then try the joins. */\n const propagate = async (instanceLabel: string, settle: GraphNodeSettle): Promise<void> => {\n const node = compiled.nodes.get(settle.node)\n if (!node) return\n const succeeded = settle.status === 'done' && settle.valid !== false\n const sourceSettles = state.nodes.get(settle.node)?.settles.length ?? 0\n for (const edge of node.outbound) {\n const folded = state.edges.get(edge.id)\n if (!folded) continue\n if (folded.judgedSourceSettles >= sourceSettles) {\n // Accounted — by an earlier verdict, or absorbed by the wave that consumed it. This is\n // what makes propagate idempotent, so a restart may re-propagate every settled node.\n continue\n }\n let fired = false\n let inputRef: string | undefined\n if (succeeded) {\n const guardContext = {\n node: settle.node,\n out: settle.out,\n visits: state.nodes.get(settle.node)?.visits ?? 0,\n valid: settle.valid ?? true,\n }\n fired = edge.spec.guard === undefined || evaluateCondition(edge.spec.guard, guardContext)\n if (fired) {\n inputRef =\n edge.spec.kind === 'analyzes'\n ? ((settle as { traceRef?: string }).traceRef ?? undefined)\n : settle.outRef\n }\n }\n await appendAndApply({\n kind: 'edge-verdict',\n id: instanceLabel,\n edge: edge.id,\n fired,\n sourceStatus: settle.status === 'down' ? 'down' : succeeded ? 'done' : 'invalid',\n ...(inputRef !== undefined ? { inputRef } : {}),\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n for (const edge of node.outbound) await tryRelease(edge.spec.to.node)\n }\n\n // ── Suspensions (#976) ─────────────────────────────────────────────────────────\n const mintToken = (instanceLabel: string): string =>\n contentAddress({ runId, instance: instanceLabel, kind: 'graph-suspension' })\n\n const journalSuspension = async (\n instanceLabel: string,\n request: SuspensionRequest,\n ): Promise<void> => {\n const token = mintToken(instanceLabel)\n let defaultRef: string | undefined\n if (request.default !== undefined) {\n const admitted = admitPayload(request.default)\n defaultRef = contentAddress(admitted)\n await blobs.put(defaultRef, admitted)\n }\n await appendAndApply({\n kind: 'waiting',\n id: `graphwait:${token}`,\n label: instanceLabel,\n spec: {\n kind: 'token',\n token,\n onExpire: request.onExpire,\n ...(request.expiresInMs !== undefined\n ? { expiresAtMs: now() + request.expiresInMs }\n : {}),\n ...(defaultRef !== undefined ? { defaultRef } : {}),\n },\n armedAt: now(),\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n }\n\n const wake = async (\n suspension: FoldSuspension,\n by: 'fired' | 'expired',\n outRef?: string,\n ): Promise<void> => {\n await appendAndApply({\n kind: 'woken',\n id: `graphwait:${suspension.token}`,\n by,\n ...(outRef !== undefined ? { outRef } : {}),\n seq: engineWokenSeq++,\n at: new Date(now()).toISOString(),\n })\n const settle = state.instances.get(suspension.instance)?.settle\n if (settle !== undefined) {\n const enriched: GraphNodeSettle = {\n ...settle,\n ...(settle.outRef !== undefined\n ? { out: admitPayload(await blobs.get(settle.outRef)) }\n : {}),\n }\n if (enriched.outRef !== undefined && enriched.out !== undefined)\n outCache.set(enriched.outRef, enriched.out)\n await propagate(suspension.instance, enriched)\n }\n }\n\n /** Expiries are engine-clocked: judged on every loop turn and before parking (#976). */\n const sweepExpiries = async (): Promise<void> => {\n for (const suspension of [...state.suspensions.values()]) {\n if (suspension.status !== 'pending') continue\n if (suspension.expiresAtMs === undefined || now() < suspension.expiresAtMs) continue\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n }\n }\n\n const processWakes = async (): Promise<void> => {\n while (wakes.length > 0) {\n const request = wakes.shift()\n if (!request) break\n try {\n const suspension = state.suspensions.get(request.token)\n if (!suspension) {\n throw new ValidationError(`graph resume: unknown token '${request.token}'`)\n }\n if (suspension.status !== 'pending') {\n throw new ValidationError(`graph resume: token '${request.token}' already woken`)\n }\n if (request.expire) {\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n else await wake(suspension, 'expired')\n } else {\n const admitted = admitPayload(request.payload)\n const outRef = contentAddress(admitted)\n await blobs.put(outRef, admitted)\n outCache.set(outRef, admitted)\n await wake(suspension, 'fired', outRef)\n }\n request.settle()\n } catch (error) {\n request.fail(error)\n }\n }\n }\n\n // ── Settle handling ────────────────────────────────────────────────────────────\n const handleSettle = async (settled: Settled<unknown>): Promise<void> => {\n const instanceLabel = liveHandles.get(settled.handle.id)\n if (instanceLabel === undefined) return\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const instance = state.instances.get(instanceLabel)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node) return\n if (settled.kind === 'done' && isSuspensionRequest(settled.out)) {\n await journalSuspension(instanceLabel, settled.out)\n return\n }\n // Mirror the kernel's own journaled settle through the reducer, then enrich for judging.\n applyGraphFoldEvent(\n state,\n {\n kind: 'settled',\n id: settled.handle.id,\n status: settled.kind === 'done' ? 'done' : 'down',\n ...(settled.kind === 'done' ? { outRef: settled.outRef } : {}),\n ...(settled.kind === 'down' ? { reason: settled.reason } : {}),\n ...(settled.kind === 'done' && settled.trace?.status === 'available'\n ? { trace: settled.trace }\n : {}),\n spent: { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n seq: 0,\n at: '',\n },\n compiled,\n )\n const folded = state.instances.get(instanceLabel)?.settle\n if (!folded) return\n let enriched: GraphNodeSettle = folded\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n if (settled.outRef !== undefined) outCache.set(settled.outRef, admitted)\n let valid: boolean | undefined\n if (node.deliverable !== undefined) {\n try {\n valid = await node.deliverable.check(admitted)\n } catch {\n valid = false\n }\n }\n enriched = { ...folded, out: admitted, ...(valid !== undefined ? { valid } : {}) }\n ;(state.instances.get(instanceLabel) as { settle?: GraphNodeSettle }).settle = enriched\n const settles = state.nodes.get(instance.node)?.settles\n if (settles) settles[settles.length - 1] = enriched\n }\n // Root completion ends the run the moment its check passes (#973).\n if (\n instance.node === compiled.root &&\n enriched.status === 'done' &&\n enriched.valid === true\n ) {\n abort.abort('root delivered')\n return\n }\n await propagate(instanceLabel, enriched)\n }\n\n // ── Entry / restart ────────────────────────────────────────────────────────────\n const enterEntryNode = async (nodeId: string): Promise<void> => {\n const folded = state.nodes.get(nodeId)\n if (!folded) return\n const visit = folded.visits + 1\n const node = compiled.nodes.get(nodeId)\n if (!node) return\n if (visit > node.maxVisits) return\n const instanceLabel = `${nodeId}#${visit}`\n const envelope = { task, inputs: {} as Record<string, unknown> }\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n await appendAndApply({\n kind: 'node-inputs-resolved',\n id: instanceLabel,\n node: nodeId,\n instance: instanceLabel,\n inputRef,\n seq: engineSeq++,\n at: new Date(now()).toISOString(),\n })\n await spawnInstance(instanceLabel)\n }\n\n if (!resuming) {\n for (const id of compiled.entries) await enterEntryNode(id)\n } else {\n // Kill-anywhere re-entry: a released instance that never spawned re-enters from its envelope;\n // an in-flight instance at the crash is in-doubt and re-enters per its kind's `onCrash` —\n // both from the pinned `inputRef`, never through re-derivation (#974).\n for (const instance of [...state.instances.values()]) {\n if (instance.status === 'released') await spawnInstance(instance.instance)\n else if (instance.status === 'live') {\n const node = compiled.nodes.get(instance.node)\n const folded = state.nodes.get(instance.node)\n if (!node || !folded) continue\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n failure = {\n reason: 'cycle-budget-exceeded',\n error: {\n name: 'GraphCycleBudget',\n message: `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`,\n },\n }\n break\n }\n const restartLabel = `${instance.node}#${visit}`\n instance.status = 'down' // in-doubt: the journal's reservation stays charged (kernel rule)\n const at = new Date(now()).toISOString()\n await journal.appendEvent(runId, {\n kind: 'node-inputs-resolved',\n id: restartLabel,\n node: instance.node,\n instance: restartLabel,\n inputRef: instance.inputRef as string,\n seq: engineSeq++,\n at,\n })\n applyGraphFoldEvent(\n state,\n {\n kind: 'node-inputs-resolved',\n id: restartLabel,\n node: instance.node,\n instance: restartLabel,\n inputRef: instance.inputRef as string,\n seq: 0,\n at,\n },\n compiled,\n )\n await spawnInstance(restartLabel)\n }\n }\n // A settle whose verdicts never landed (killed between the kernel settle and the engine's\n // propagate) is re-judged now; `judgedSourceSettles` makes this a no-op for judged edges.\n for (const [nodeId, foldedNode] of state.nodes) {\n const latest = foldedNode.settles.at(-1)\n if (latest === undefined) continue\n const instanceLabel = `${nodeId}#${latest.visit}`\n let enriched: GraphNodeSettle = latest\n if (latest.status === 'done' && latest.outRef !== undefined) {\n const out = admitPayload(await blobs.get(latest.outRef))\n if (isSuspensionRequest(out)) {\n // Killed between the kernel settle and the `waiting` event: finish the half-done\n // transition now instead of propagating the marker as data.\n foldedNode.settles.pop()\n const instance = state.instances.get(instanceLabel)\n if (instance) instance.settle = undefined\n await journalSuspension(instanceLabel, out)\n continue\n }\n outCache.set(latest.outRef, out)\n const nodeSpec = compiled.nodes.get(nodeId)\n let valid: boolean | undefined\n if (nodeSpec?.deliverable !== undefined) {\n try {\n valid = await nodeSpec.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n enriched = { ...latest, out, ...(valid !== undefined ? { valid } : {}) }\n }\n await propagate(instanceLabel, enriched)\n }\n // An entry node the crashed process never released enters now — run start is its release.\n for (const id of compiled.entries) {\n if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id)\n }\n // A restart may also land after new settles are already judged: re-try every join once.\n for (const id of compiled.nodes.keys()) await tryRelease(id)\n }\n\n // ── The loop ───────────────────────────────────────────────────────────────────\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0)\n\n let wakeSignal: Promise<void> = Promise.resolve()\n let armWake: () => void = () => {}\n const rearmWakeSignal = () => {\n wakeSignal = new Promise<void>((fire) => {\n armWake = fire\n })\n onWakeSignal(() => armWake())\n }\n rearmWakeSignal()\n\n let inFlightNext: Promise<Settled<unknown> | null> | undefined\n while (!failure) {\n await sweepExpiries()\n if (wakes.length > 0) {\n await processWakes()\n continue\n }\n if (allTerminalsSettled()) break\n if (liveCount === 0) {\n const pendingSuspensions = [...state.suspensions.values()].filter(\n (suspension) => suspension.status === 'pending',\n )\n if (pendingSuspensions.length > 0) {\n const nearest = Math.min(\n ...pendingSuspensions.map(\n (suspension) => suspension.expiresAtMs ?? Number.POSITIVE_INFINITY,\n ),\n )\n if (Number.isFinite(nearest) && now() >= nearest) continue // sweep will transition it\n if (options.waitForWakes) {\n rearmWakeSignal()\n await wakeSignal\n continue\n }\n // Offline (#976): no host will ever answer, so an `onExpire: 'default'` suspension\n // auto-resolves with its default now; `wait` and a future `fail` deadline park the run.\n const defaulting = pendingSuspensions.filter(\n (suspension) => suspension.onExpire === 'default',\n )\n if (defaulting.length > 0) {\n for (const suspension of defaulting)\n await wake(suspension, 'fired', suspension.defaultRef)\n continue\n }\n break // fully parked: a legitimate offline terminal state\n }\n break // stuck or complete: classified below\n }\n inFlightNext ??= scope.next()\n const raced = await Promise.race([\n inFlightNext.then((settle) => ({ settle })),\n wakeSignal.then(() => 'wake' as const),\n ])\n if (raced === 'wake') {\n rearmWakeSignal()\n continue // wakes queue processed on the next turn; inFlightNext stays armed\n }\n inFlightNext = undefined\n if (raced.settle === null) break\n await handleSettle(raced.settle)\n for (const parked of waitingForBudget.splice(0)) await spawnInstance(parked)\n }\n\n abort.abort('graph loop complete')\n while ((await (inFlightNext ?? scope.next())) !== null) inFlightNext = undefined\n\n // ── Result assembly ────────────────────────────────────────────────────────────\n const rehydrate = async (settle: GraphNodeSettle): Promise<GraphNodeSettle> => {\n if (settle.out !== undefined || settle.outRef === undefined) return settle\n const out = outCache.get(settle.outRef) ?? admitPayload(await blobs.get(settle.outRef))\n const node = compiled.nodes.get(settle.node)\n let valid = settle.valid\n if (valid === undefined && node?.deliverable !== undefined && settle.status === 'done') {\n try {\n valid = await node.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n return { ...settle, out, ...(valid !== undefined ? { valid } : {}) }\n }\n const settles = await Promise.all(\n [...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate),\n )\n const terminals = settles.filter((settle) => compiled.nodes.get(settle.node)?.terminal)\n\n const finish = (result: GraphRunResult): GraphRunResult => {\n if (result.kind === 'no-winner' && state.exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...state.exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (failure) {\n return finish({\n kind: 'no-winner',\n reason: failure.reason,\n ...(failure.error ? { error: failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const pendingTokens = [...state.suspensions.values()]\n .filter((suspension) => suspension.status === 'pending')\n .map((suspension) => suspension.token)\n if (pendingTokens.length > 0 && !allTerminalsSettled()) {\n return { kind: 'suspended', tokens: pendingTokens, terminals, settles, ledger }\n }\n if (options.signal?.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const anyDelivered = terminals.some(\n (settle) => settle.status === 'done' && settle.valid !== false,\n )\n const out = anyDelivered\n ? await runFinalizer(\n options.finalizer === undefined || options.finalizer === 'bestDelivered'\n ? bestDelivered\n : options.finalizer === 'collectDelivered'\n ? collectDelivered\n : options.finalizer,\n {\n settled: terminals.map(\n (settle): FinalizerSettled => ({\n id: settle.node,\n status: settle.status,\n valid: settle.status === 'done' && settle.valid !== false,\n ...(settle.outRef !== undefined ? { outRef: settle.outRef } : {}),\n }),\n ),\n blobs,\n tree: scope.view,\n budget: scope.budget,\n },\n )\n : undefined\n if (out !== undefined) return { kind: 'winner', out, terminals, settles, ledger }\n const unreachable = [...compiled.nodes.keys()].filter(\n (id) => (state.nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === compiled.nodes.size\n ? 'budget-exhausted'\n : 'unreachable-terminal'\n : 'all-children-down'\n return finish({ kind: 'no-winner', reason, terminals, settles, ledger, unreachable })\n }\n}\n\n// ── Small helpers ────────────────────────────────────────────────────────────────\n\nfunction hasLiveInstance(\n state: GraphFoldState,\n liveHandles: Map<string, string>,\n node: string,\n): boolean {\n for (const label of liveHandles.values()) {\n if (state.instances.get(label)?.node === node) return true\n }\n return false\n}\n\nfunction maxEngineSeq(events: ReadonlyArray<SpawnEvent>): number {\n let max = -1\n for (const ev of events) {\n if (\n ev.kind === 'node-inputs-resolved' ||\n ev.kind === 'edge-verdict' ||\n ev.kind === 'join-state'\n ) {\n if (ev.seq > max) max = ev.seq\n }\n if (ev.kind === 'waiting' && ev.spec.kind === 'token' && ev.seq > max) max = ev.seq\n }\n return max\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAYA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAIA,MAAM,oBAA8C,IAAI,IACtD,cAAc,QAAQ,OAAO,OAAO,YAAY,OAAO,QAAQ,CACjE;AAiBA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;;AAKrB,SAAgB,mBAAmB,MAAc,SAA0C;CACzF,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,iBACjE,MAAM,IAAI,gBACR,GAAG,QAAQ,+CAA+C,gBAAgB,OAC5E;CAEF,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,KA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