@tangle-network/agent-runtime 0.167.0 → 0.168.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graph.d.ts +24 -5
- package/dist/graph.js +5 -1
- package/dist/graph.js.map +1 -1
- package/dist/testing.js +8 -8
- package/package.json +1 -1
package/dist/graph.d.ts
CHANGED
|
@@ -163,6 +163,17 @@ interface NodeKind<Config = unknown, Effects extends ReadonlyArray<EffectName> =
|
|
|
163
163
|
readonly host?: GraphHost;
|
|
164
164
|
}) => Agent<unknown, unknown>;
|
|
165
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* A kind of ANY config shape — what a registry holds and what every engine signature accepts.
|
|
168
|
+
*
|
|
169
|
+
* `NodeKind<Config>` puts `Config` in a parameter position (`run({ config })`), so it is
|
|
170
|
+
* contravariant: an array of differently-configured kinds is not assignable to
|
|
171
|
+
* `ReadonlyArray<NodeKind<unknown>>`, and every caller composing a heterogeneous kind set would
|
|
172
|
+
* need a cast. That cost belongs here, once, not at each consumer: a registry is heterogeneous by
|
|
173
|
+
* definition, and each kind validates its own config at its own boundary through
|
|
174
|
+
* `validateConfig`, which is where the type is actually enforced.
|
|
175
|
+
*/
|
|
176
|
+
type AnyNodeKind = NodeKind<any, ReadonlyArray<EffectName>>;
|
|
166
177
|
/** Per-node flags a graph author sets; they are node properties, not kinds (agent-runtime#970). */
|
|
167
178
|
interface NodeFlags {
|
|
168
179
|
/** An oracle — a judge, grader, auditor, trace analyst — may be bound only by an `analyzes`
|
|
@@ -176,7 +187,7 @@ interface NodeFlags {
|
|
|
176
187
|
}
|
|
177
188
|
/** Validate a kind declaration at registration — so a malformed kind is refused by name once,
|
|
178
189
|
* not at the first node that uses it. */
|
|
179
|
-
declare function validateNodeKind(kind:
|
|
190
|
+
declare function validateNodeKind(kind: AnyNodeKind, context?: string): AnyNodeKind;
|
|
180
191
|
/** The handle a graph writes to name this kind. */
|
|
181
192
|
declare function kindHandle(kind: Pick<NodeKind, 'id' | 'version'>): RegistryHandle;
|
|
182
193
|
/**
|
|
@@ -284,15 +295,15 @@ interface EngineGraphSpec {
|
|
|
284
295
|
//#region src/runtime/graph/engine.d.ts
|
|
285
296
|
interface GraphEngineOptions {
|
|
286
297
|
/** Kinds to register beside the core set. A host adds its own here; nothing is global. */
|
|
287
|
-
readonly kinds?: ReadonlyArray<
|
|
298
|
+
readonly kinds?: ReadonlyArray<AnyNodeKind>;
|
|
288
299
|
/** The host's effect table, by name. A kind receives only the effects it declared. */
|
|
289
300
|
readonly effects?: Readonly<Record<EffectName, unknown>>;
|
|
290
301
|
/** The core set. Injected so a test can substitute, and so the engine never imports a
|
|
291
302
|
* backend-specific factory at module load. */
|
|
292
|
-
readonly coreKinds: ReadonlyArray<
|
|
303
|
+
readonly coreKinds: ReadonlyArray<AnyNodeKind>;
|
|
293
304
|
}
|
|
294
305
|
interface GraphEngine {
|
|
295
|
-
readonly kinds: Registry<
|
|
306
|
+
readonly kinds: Registry<AnyNodeKind>;
|
|
296
307
|
readonly effects: Readonly<Record<EffectName, unknown>>;
|
|
297
308
|
/** Every effect name any registered kind declares — what a host must provide for this engine's
|
|
298
309
|
* whole kind set to be runnable. Listed, never discovered mid-run. */
|
|
@@ -363,6 +374,10 @@ type GraphRunReason = 'all-children-down' | 'budget-exhausted' | 'aborted' | 'dr
|
|
|
363
374
|
interface GraphNodeSettle {
|
|
364
375
|
readonly node: string;
|
|
365
376
|
readonly visit: number;
|
|
377
|
+
/** Run-wide settle ordinal. `GraphRunResult.settles` is sorted by it, so the array reads in the
|
|
378
|
+
* order the run actually settled — not grouped by node, which is what a reader assumes and
|
|
379
|
+
* what the first consumer of this API tripped on. */
|
|
380
|
+
readonly seq: number;
|
|
366
381
|
readonly status: 'done' | 'down';
|
|
367
382
|
/** The node's completion check verdict; `undefined` when the node declares no check. */
|
|
368
383
|
readonly valid?: boolean;
|
|
@@ -451,6 +466,10 @@ interface FoldNode {
|
|
|
451
466
|
settles: GraphNodeSettle[];
|
|
452
467
|
}
|
|
453
468
|
interface GraphFoldState {
|
|
469
|
+
/** Next settle ordinal; the fold is the only writer, so replay reproduces the same order. */
|
|
470
|
+
settleSeq: {
|
|
471
|
+
value: number;
|
|
472
|
+
};
|
|
454
473
|
readonly nodes: Map<string, FoldNode>;
|
|
455
474
|
readonly edges: Map<string, FoldEdge>;
|
|
456
475
|
/** Every node instance the journal knows, keyed by `<node>#<visit>`. */
|
|
@@ -710,5 +729,5 @@ declare function runEngineGraph(engine: GraphEngine, spec: EngineGraphSpec | Com
|
|
|
710
729
|
*/
|
|
711
730
|
declare function createGraphRun(engine: GraphEngine, spec: EngineGraphSpec | CompiledGraph, task: string, options: GraphRunOptions): GraphRunHandle;
|
|
712
731
|
//#endregion
|
|
713
|
-
export { type AgentKindConfig, type BudgetMode, CONDITION_OPS, type CompiledEdge, type CompiledGraph, type CompiledNode, type Condition, type ConditionLeaf, type ConditionOp, DEFAULT_MAX_NODE_VISITS, ENGINE_WOKEN_SEQ_BASE, type EdgeLedger, type EffectContext, type EffectName, type EngineGraphEdge, type EngineGraphNode, type EngineGraphSpec, type FinalizerChoice, type FoldEdge, type FoldEdgeState, type FoldInstance, type FoldInstanceStatus, type FoldNode, type FoldSuspension, type GatingEdge, type GraphEdgeKind, type GraphEdgeTraversal, type GraphEngine, type GraphEngineOptions, type GraphFoldState, type GraphHost, type GraphNodeSettle, type GraphRunContext, type GraphRunHandle, type GraphRunOptions, type GraphRunReason, type GraphRunResult, JOIN_RULES, type JoinDecision, type JoinRule, type JsonSchema, MAX_MAX_NODE_VISITS, type NodeFlags, type NodeKind, type OnCrash, type PortSpec, type Projection, RUN_GRAPH_ROOT_KIND, type Registered, type Registry, type RegistryHandle, type ScriptBody, type ScriptKindConfig, type SubgraphKindConfig, type SupervisorKindConfig, type SuspensionRequest, admitPayload, agentKind, applyGraphFoldEvent, applyProjection, assembleGraphResult, compileGraph, createEdgeLedger, createGraphEngine, createGraphRun, createRegistry, decideJoin, emptyFoldState, evaluateCondition, foldGraphJournal, formatRegistryHandle, graphFromRunGraph, isEngineFired, isSuspensionRequest, kindHandle, materializeSettles, mintSuspensionToken, narrowEffects, openGraphRun, parseRegistryHandle, runEngineGraph, schemaAccepts, scriptKind, subgraphKind, supervisorKind, suspended, suspensionNodeId, tokenFromSuspensionNodeId, validateCondition, validateNodeKind, validateProjection };
|
|
732
|
+
export { type AgentKindConfig, type AnyNodeKind, type BudgetMode, CONDITION_OPS, type CompiledEdge, type CompiledGraph, type CompiledNode, type Condition, type ConditionLeaf, type ConditionOp, DEFAULT_MAX_NODE_VISITS, ENGINE_WOKEN_SEQ_BASE, type EdgeLedger, type EffectContext, type EffectName, type EngineGraphEdge, type EngineGraphNode, type EngineGraphSpec, type FinalizerChoice, type FoldEdge, type FoldEdgeState, type FoldInstance, type FoldInstanceStatus, type FoldNode, type FoldSuspension, type GatingEdge, type GraphEdgeKind, type GraphEdgeTraversal, type GraphEngine, type GraphEngineOptions, type GraphFoldState, type GraphHost, type GraphNodeSettle, type GraphRunContext, type GraphRunHandle, type GraphRunOptions, type GraphRunReason, type GraphRunResult, JOIN_RULES, type JoinDecision, type JoinRule, type JsonSchema, MAX_MAX_NODE_VISITS, type NodeFlags, type NodeKind, type OnCrash, type PortSpec, type Projection, RUN_GRAPH_ROOT_KIND, type Registered, type Registry, type RegistryHandle, type ScriptBody, type ScriptKindConfig, type SubgraphKindConfig, type SupervisorKindConfig, type SuspensionRequest, admitPayload, agentKind, applyGraphFoldEvent, applyProjection, assembleGraphResult, compileGraph, createEdgeLedger, createGraphEngine, createGraphRun, createRegistry, decideJoin, emptyFoldState, evaluateCondition, foldGraphJournal, formatRegistryHandle, graphFromRunGraph, isEngineFired, isSuspensionRequest, kindHandle, materializeSettles, mintSuspensionToken, narrowEffects, openGraphRun, parseRegistryHandle, runEngineGraph, schemaAccepts, scriptKind, subgraphKind, supervisorKind, suspended, suspensionNodeId, tokenFromSuspensionNodeId, validateCondition, validateNodeKind, validateProjection };
|
|
714
733
|
//# sourceMappingURL=graph.d.ts.map
|
package/dist/graph.js
CHANGED
|
@@ -632,6 +632,7 @@ function emptyFoldState(compiled) {
|
|
|
632
632
|
capped: false
|
|
633
633
|
});
|
|
634
634
|
return {
|
|
635
|
+
settleSeq: { value: 0 },
|
|
635
636
|
nodes,
|
|
636
637
|
edges,
|
|
637
638
|
instances: /* @__PURE__ */ new Map(),
|
|
@@ -681,6 +682,7 @@ function applyGraphFoldEvent(state, ev, compiled) {
|
|
|
681
682
|
node: instance.node,
|
|
682
683
|
visit: instance.visit,
|
|
683
684
|
status: ev.status,
|
|
685
|
+
seq: state.settleSeq.value++,
|
|
684
686
|
...ev.outRef !== void 0 ? { outRef: ev.outRef } : {},
|
|
685
687
|
...ev.reason !== void 0 ? { reason: ev.reason } : {}
|
|
686
688
|
};
|
|
@@ -776,6 +778,7 @@ function applyGraphFoldEvent(state, ev, compiled) {
|
|
|
776
778
|
node: suspension.node,
|
|
777
779
|
visit: instance.visit,
|
|
778
780
|
status: "down",
|
|
781
|
+
seq: state.settleSeq.value++,
|
|
779
782
|
reason: "suspension expired"
|
|
780
783
|
};
|
|
781
784
|
instance.settle = settle;
|
|
@@ -790,6 +793,7 @@ function applyGraphFoldEvent(state, ev, compiled) {
|
|
|
790
793
|
node: suspension.node,
|
|
791
794
|
visit: instance.visit,
|
|
792
795
|
status: "done",
|
|
796
|
+
seq: state.settleSeq.value++,
|
|
793
797
|
...ev.outRef !== void 0 ? { outRef: ev.outRef } : {}
|
|
794
798
|
};
|
|
795
799
|
instance.settle = settle;
|
|
@@ -1282,7 +1286,7 @@ async function materializeSettles(compiled, state, blobs, outCache) {
|
|
|
1282
1286
|
...valid !== void 0 ? { valid } : {}
|
|
1283
1287
|
};
|
|
1284
1288
|
};
|
|
1285
|
-
return Promise.all([...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate));
|
|
1289
|
+
return Promise.all([...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).sort((a, b) => a.seq - b.seq).map(rehydrate));
|
|
1286
1290
|
}
|
|
1287
1291
|
/** Turn a finished run into its result: rehydrate, reduce the terminals, classify a no-winner. */
|
|
1288
1292
|
async function assembleGraphResult(args) {
|
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/fold.ts","../src/runtime/graph/join.ts","../src/runtime/graph/kinds.ts","../src/runtime/graph/ledger.ts","../src/runtime/graph/preset-run-graph.ts","../src/runtime/graph/admit.ts","../src/runtime/graph/result.ts","../src/runtime/graph/run-context.ts","../src/runtime/graph/suspension.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 /** Force a node out of (or into) the run's entry set. Absent, a node with no inbound edge is an\n * entry, and the declared root always is. A node another node SPAWNS — the `runGraph` preset's\n * workers and analysts — sets `false`: the scheduler must never enter it on its own. */\n readonly entry?: boolean\n /** Profile fields merged over the engine-authored `{ name: id }` for this node's spawns. */\n readonly profile?: Readonly<Partial<AgentProfile>>\n /** Per-instance reservation for this node's spawns; falls back to the run's `perNode`. */\n readonly budget?: Budget\n}\n\nexport interface EngineGraphEdge {\n /** Stable id for the ledger; defaults to `<from>-><to>#<ordinal>`. */\n readonly id?: string\n readonly kind: GraphEdgeKind\n readonly from: { readonly node: string; readonly port?: string }\n readonly to: { readonly node: string; readonly port?: string }\n /** Evaluated over the source's settle context; absent = satisfied by completion. */\n readonly guard?: Condition\n /** `data` edges only: ONE pure reshape of the admitted payload. */\n readonly projection?: Projection\n /** Refuses the traversal past this many firings (ledgered `unpropagated`); `0` closes the edge from the start. */\n readonly maxTraversals?: number\n /** `delegates`/`analyzes`: the versioned directive appended to the target's task. */\n readonly directive?: PromptHandle\n}\n\nexport interface EngineGraphSpec {\n readonly nodes: ReadonlyArray<EngineGraphNode>\n readonly edges: ReadonlyArray<EngineGraphEdge>\n /** Root node for the graph-level completion check. Defaults to the single entry node. */\n readonly root?: string\n /** Becomes the ROOT node's completion check when the root declares none (#973). */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly maxNodeVisits?: number\n}\n\nexport interface ParsedGraphNode extends EngineGraphNode {\n readonly kindHandle: RegistryHandle\n readonly join: JoinRule\n readonly maxVisits: number\n}\n\n/** Structural validation only — everything a registry is not needed for. */\nexport function validateEngineGraphSpec(spec: EngineGraphSpec, context = 'compileGraph'): void {\n if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) {\n throw new ValidationError(`${context}: a graph needs at least one node`)\n }\n const ids = new Set<string>()\n for (const node of spec.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError(`${context}: every node needs a non-empty id`)\n }\n if (ids.has(node.id))\n throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`)\n ids.add(node.id)\n parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`)\n if (node.join !== undefined && !(JOIN_RULES as ReadonlyArray<string>).includes(node.join)) {\n throw new ValidationError(\n `${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(', ')}`,\n )\n }\n if (node.maxVisits !== undefined) {\n if (\n !Number.isSafeInteger(node.maxVisits) ||\n node.maxVisits < 1 ||\n node.maxVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: node ${node.id} maxVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n }\n if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`)\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}]`\n if (edge.kind !== 'delegates' && edge.kind !== 'analyzes' && edge.kind !== 'data') {\n throw new ValidationError(`${who}: kind must be delegates | analyzes | data`)\n }\n for (const end of ['from', 'to'] as const) {\n const ref = edge[end]\n if (\n typeof ref !== 'object' ||\n ref === null ||\n typeof ref.node !== 'string' ||\n !ids.has(ref.node)\n ) {\n throw new ValidationError(`${who}: ${end}.node must name a node in this graph`)\n }\n }\n if (edge.guard !== undefined) validateCondition(edge.guard, `${who} guard`)\n if (edge.projection !== undefined) {\n if (edge.kind !== 'data') {\n throw new ValidationError(`${who}: only a data edge carries a projection`)\n }\n validateProjection(edge.projection, `${who} projection`)\n }\n if (edge.maxTraversals !== undefined) {\n // Zero is meaningful and authored in practice: an edge closed from the start, which the\n // scheduler refuses on its first consumption and ledgers `unpropagated`.\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 0) {\n throw new ValidationError(`${who}: maxTraversals must be a non-negative integer`)\n }\n }\n if (edge.kind === 'data' && edge.directive !== undefined) {\n throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`)\n }\n }\n if (spec.root !== undefined && !ids.has(spec.root)) {\n throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`)\n }\n if (spec.maxNodeVisits !== undefined) {\n if (\n !Number.isSafeInteger(spec.maxNodeVisits) ||\n spec.maxNodeVisits < 1 ||\n spec.maxNodeVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: maxNodeVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n}\n","/**\n * Compile an authored graph against an engine's kind registry into the schedulable form. Every\n * refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`\n * binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no\n * completion check (agent-runtime#971, #973).\n */\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport {\n DEFAULT_MAX_NODE_VISITS,\n type EngineGraphEdge,\n type EngineGraphSpec,\n type JoinRule,\n validateEngineGraphSpec,\n} from './definition'\nimport type { GraphEngine } from './engine'\nimport type { JsonSchema, NodeKind, PortSpec } from './kind'\nimport { formatRegistryHandle, parseRegistryHandle } from './registry'\n\n/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */\nexport const IMPLICIT_OUTPUT_PORTS = ['out', 'trace'] as const\n\nexport interface CompiledEdge {\n readonly id: string\n readonly spec: EngineGraphEdge\n readonly fromPort: string\n readonly toPort: string\n}\n\n/** `delegates` is the one MODEL-fired edge kind (agent-runtime#971): its payload is a directive and\n * its target is spawned by the source supervisor through the coordination protocol, not released\n * by the scheduler. `data` and `analyzes` are engine-fired. */\nexport function isEngineFired(edge: CompiledEdge): boolean {\n return edge.spec.kind !== 'delegates'\n}\n\nexport interface CompiledNode {\n readonly id: string\n readonly kind: NodeKind\n readonly config: unknown\n readonly join: JoinRule\n readonly maxVisits: number\n readonly oracle: boolean\n readonly pure: boolean\n readonly terminal: boolean\n /** The check this node must pass to count DELIVERED; resolved per #973. */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly inbound: ReadonlyArray<CompiledEdge>\n readonly outbound: ReadonlyArray<CompiledEdge>\n /** Spawned by a supervisor through a `delegates` edge, never entered by the scheduler. */\n readonly modelFired: boolean\n readonly spec: EngineGraphSpec['nodes'][number]\n}\n\nexport interface CompiledGraph {\n readonly nodes: ReadonlyMap<string, CompiledNode>\n readonly edges: ReadonlyArray<CompiledEdge>\n readonly entries: ReadonlyArray<string>\n readonly terminals: ReadonlyArray<string>\n readonly root: string\n readonly maxNodeVisits: number\n}\n\ntype NodePorts = {\n readonly inputs: ReadonlyArray<PortSpec>\n readonly outputs: ReadonlyArray<PortSpec>\n}\n\n/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */\nfunction nodePorts(kind: NodeKind, node: EngineGraphSpec['nodes'][number]): NodePorts {\n const merge = (\n declared: ReadonlyArray<PortSpec>,\n own: ReadonlyArray<PortSpec> | undefined,\n ): ReadonlyArray<PortSpec> => {\n if (own === undefined || own.length === 0) return declared\n const names = new Set(own.map((port) => port.name))\n return [...own, ...declared.filter((port) => !names.has(port.name))]\n }\n return {\n inputs: merge(kind.inputs, node.ports?.inputs),\n outputs: merge(kind.outputs, node.ports?.outputs),\n }\n}\n\nfunction outputPort(ports: NodePorts, port: string): PortSpec | undefined {\n if ((IMPLICIT_OUTPUT_PORTS as ReadonlyArray<string>).includes(port)) {\n return { name: port, schema: {} }\n }\n return ports.outputs.find((candidate) => candidate.name === port)\n}\n\nfunction inputPort(ports: NodePorts, port: string): PortSpec | undefined {\n return ports.inputs.find((candidate) => candidate.name === port)\n}\n\n/**\n * Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no\n * `type` accept anything; object targets require their `required` properties to be present and\n * accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,\n * not a full JSON Schema validator.\n */\nexport function schemaAccepts(source: JsonSchema, target: JsonSchema, depth = 0): boolean {\n if (depth > 6) return true\n const sourceType = source.type\n const targetType = target.type\n if (targetType === undefined || sourceType === undefined) return true\n const targets = Array.isArray(targetType) ? targetType : [targetType]\n const sources = Array.isArray(sourceType) ? sourceType : [sourceType]\n const overlap = sources.filter(\n (candidate) =>\n targets.includes(candidate === 'integer' ? 'number' : candidate) ||\n targets.includes(candidate),\n )\n if (overlap.length === 0) return false\n if (targets.includes('object') && sources.includes('object')) {\n const required = Array.isArray(target.required) ? (target.required as string[]) : []\n const sourceProps = source.properties as Record<string, JsonSchema> | undefined\n const targetProps = target.properties as Record<string, JsonSchema> | undefined\n if (sourceProps !== undefined) {\n for (const name of required) {\n const sourceProp = sourceProps[name]\n if (sourceProp === undefined) return false\n const targetProp = targetProps?.[name]\n if (targetProp !== undefined && !schemaAccepts(sourceProp, targetProp, depth + 1)) {\n return false\n }\n }\n }\n }\n if (targets.includes('array') && sources.includes('array')) {\n const sourceItems = source.items as JsonSchema | undefined\n const targetItems = target.items as JsonSchema | undefined\n if (sourceItems !== undefined && targetItems !== undefined) {\n return schemaAccepts(sourceItems, targetItems, depth + 1)\n }\n }\n return true\n}\n\n/**\n * Lower an authored graph against an engine's kind registry into the schedulable form, refusing\n * every structural defect before any spend.\n */\nexport function compileGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec,\n context = 'compileGraph',\n): CompiledGraph {\n validateEngineGraphSpec(spec, context)\n const kinds = new Map<string, NodeKind>()\n const configs = new Map<string, unknown>()\n for (const node of spec.nodes) {\n const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`)\n const kind = engine.kinds.require(handle, `${context}: node ${node.id}`)\n kinds.set(node.id, kind)\n configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`))\n if (node.flags?.pure && kind.id !== 'script') {\n throw new ValidationError(\n `${context}: node ${node.id} sets pure, which only a script node may claim`,\n )\n }\n }\n\n const compiledEdges: CompiledEdge[] = []\n const inbound = new Map<string, CompiledEdge[]>()\n const outbound = new Map<string, CompiledEdge[]>()\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`\n const fromKind = kinds.get(edge.from.node)\n const toKind = kinds.get(edge.to.node)\n if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`)\n const toNode = spec.nodes.find((node) => node.id === edge.to.node)\n if (edge.kind !== 'analyzes' && toNode?.flags?.oracle) {\n // An edge to a grader leaks the rubric: an oracle is bound only by `analyzes`.\n throw new ValidationError(\n `${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`,\n )\n }\n const fromPort = edge.from.port ?? (edge.kind === 'analyzes' ? 'trace' : 'out')\n if (edge.kind === 'analyzes' && fromPort !== 'trace') {\n throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`)\n }\n const fromNode = spec.nodes.find((node) => node.id === edge.from.node)\n const fromPorts = nodePorts(fromKind, fromNode as EngineGraphSpec['nodes'][number])\n const toPorts = nodePorts(toKind, toNode as EngineGraphSpec['nodes'][number])\n const sourcePort = outputPort(fromPorts, fromPort)\n if (!sourcePort) {\n const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)]\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(', ')}`,\n )\n }\n let toPort = edge.to.port ?? ''\n if (edge.kind === 'data') {\n if (toPort === '') {\n if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? ''\n else {\n throw new ValidationError(\n `${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`,\n )\n }\n }\n const targetPort = inputPort(toPorts, toPort)\n if (!targetPort) {\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(', ') || '(none)'}`,\n )\n }\n // A projection reshapes the payload, so the source schema no longer describes it; the\n // projected shape is checked at admission, not statically.\n if (edge.projection === undefined && !schemaAccepts(sourcePort.schema, targetPort.schema)) {\n throw new ValidationError(\n `${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? 'any')}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? 'any')})`,\n )\n }\n }\n const compiled: CompiledEdge = {\n id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,\n spec: edge,\n fromPort,\n toPort: toPort === '' ? 'out' : toPort,\n }\n compiledEdges.push(compiled)\n outbound.set(edge.from.node, [...(outbound.get(edge.from.node) ?? []), compiled])\n inbound.set(edge.to.node, [...(inbound.get(edge.to.node) ?? []), compiled])\n }\n const dupes = new Set<string>()\n for (const edge of compiledEdges) {\n if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`)\n dupes.add(edge.id)\n }\n\n // A node reached only by `delegates` is spawned by its supervisor, so it is neither an entry nor\n // a scheduler-released node; a node with no ENGINE-fired outbound edge is terminal, because a\n // delegation does not continue the scheduler's flow.\n const engineInbound = (id: string) => (inbound.get(id) ?? []).filter(isEngineFired)\n const engineOutbound = (id: string) => (outbound.get(id) ?? []).filter(isEngineFired)\n const unfed = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (unfed.length === 0 && spec.root === undefined) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (unfed.length === 1\n ? (unfed[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${unfed.length} entry nodes (${unfed.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n // The declared root always starts the run, even when an edge feeds back INTO it — a findings\n // route to the driver, or a cycle's closing edge, never stops the run from beginning there. A\n // node that declares `entry: false` is spawned by another node and never entered here.\n const declaredOut = new Set(\n spec.nodes.filter((node) => node.entry === false).map((node) => node.id),\n )\n const entries = [root, ...unfed.map((node) => node.id).filter((id) => id !== root)].filter(\n (id) => !declaredOut.has(id),\n )\n if (entries.length === 0) {\n throw new ValidationError(`${context}: every entry node declares entry: false — nothing starts`)\n }\n\n const nodes = new Map<string, CompiledNode>()\n const terminals: string[] = []\n for (const node of spec.nodes) {\n const kind = kinds.get(node.id)\n if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`)\n const modelFired = (inbound.get(node.id) ?? []).some((edge) => !isEngineFired(edge))\n const terminal = node.terminal ?? (!modelFired && engineOutbound(node.id).length === 0)\n const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : undefined)\n if (terminal) terminals.push(node.id)\n nodes.set(node.id, {\n id: node.id,\n kind,\n config: configs.get(node.id),\n join: node.join ?? 'all',\n maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n oracle: node.flags?.oracle ?? false,\n pure: node.flags?.pure ?? false,\n terminal,\n ...(deliverable === undefined ? {} : { deliverable }),\n inbound: engineInbound(node.id),\n outbound: outbound.get(node.id) ?? [],\n modelFired,\n spec: node,\n })\n }\n const unchecked = terminals.filter((id) => nodes.get(id)?.deliverable === undefined)\n if (unchecked.length === terminals.length) {\n // Termination is mandatory per terminal (#973): a graph none of whose terminals declares a\n // completion check (own, or the graph's on the root) can never prove it is done.\n throw new ValidationError(\n `${context}: no terminal declares a completion check (terminals: ${terminals.join(', ')}); give a node a deliverable or set spec.deliverable`,\n )\n }\n return {\n nodes,\n edges: compiledEdges,\n entries,\n terminals,\n root,\n maxNodeVisits: spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n }\n}\n","/**\n * `NodeKind` — what a consumer registers to add a node kind to the graph engine without forking\n * it (agent-runtime#969, #970).\n *\n * The engine owns the graph: scheduling over typed data edges, guards, joins, cycles, the\n * conserved pool, the journal. It does NOT own execution — `run` returns an `Agent`, the\n * kernel's spawn contract (`Scope.spawn` takes an `Agent { name, act }`; a leaf `Agent` carries its\n * `Executor` as `executorSpec: AgentSpec`, and a supervisor `Agent` is `supervisorAgent(...)`). So\n * every node rides `supervise()`'s machinery unchanged: the pool's reserve/reconcile, the\n * content-addressed journal, the completion gate, `Settled`, trace evidence. An engine that\n * re-implemented any of those would be a second kernel.\n *\n * Every kernel-owned extension contract is a TS interface plus a hand-written validator that\n * throws `ValidationError` by name (the kernel has no zod), and this one follows suit. JSON Schema\n * is the PORTABLE form of a config/port shape — a `Record<string, unknown>`, as `McpToolDescriptor`\n * and `DeliveryBinding` already spell it — so a kind's declaration can be published in a manifest\n * and lifted by a host on another stack.\n *\n * The bar this file is measured against: the scheduler's source names no kind that is not\n * universal. A kind the engine ships (`agent`, `supervisor`, `subgraph`, `script`) is universal by\n * the rule \"the model cannot decide it with the verbs it has\"; everything else — integrations,\n * notifications, sandbox provisioning, human decisions — is registered by a host.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport type { Agent } from '../supervise/types'\nimport type { Registered, RegistryHandle } from './registry'\n\n/** A JSON Schema document as the kernel already spells it: an opaque record, validated by the\n * consumer's own validator, published verbatim. */\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\n/**\n * One declared port on a node. Ports are how a `data` edge binds one node's output to another's\n * input with a type the compiler can check structurally before any spend. A node has two implicit\n * output ports beside its declared ones: `out` (its result) and `trace` (its `WorkerTraceEvidence`\n * by `traceRef`); only an `analyzes` edge may bind `trace`.\n */\nexport interface PortSpec {\n readonly name: string\n readonly schema: JsonSchema\n readonly description?: string\n}\n\n/**\n * What a kind declares it needs from the host. The engine never imports a host capability; it\n * knows only that a kind SAID it needs something under this name and the host PROVIDED something\n * under it. The context a kind receives is narrowed to exactly its declaration — an undeclared\n * effect is `undefined`, never a service locator.\n */\n/** What a nesting kind needs from its host: run one graph, on the host's own kinds and effects.\n * Declared here (not imported from the scheduler) so the contract module stays dependency-free. */\nexport interface GraphHost {\n runNested(\n graph: unknown,\n task: string,\n options: {\n readonly budget: unknown\n readonly perNode?: unknown\n readonly runId: string\n readonly signal?: AbortSignal\n },\n ): Promise<{ readonly kind: string; readonly out?: unknown }>\n}\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 /** The engine hosting this node, for a kind that runs a graph of its own (`subgraph`). The\n * scheduler supplies it; a kind that does not nest ignores it. */\n readonly host?: GraphHost\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 * Join evaluation: which gating-edge outcomes release a node. Adopted whole from ADC's workflow\n * graph (agent-runtime#968) and kept PURE — the scheduler decides nothing here, so the rule can be\n * read, tested and reasoned about on its own.\n *\n * An edge settles SATISFIED / DEAD / FAILED per its source's LATEST completion. A release consumes\n * the outcomes that produced it; the caller re-arms them and marks any still-pending edge\n * consumed-once, so an OR-diamond's second completer never double-fires.\n */\nimport type { CompiledEdge } from './compile'\nimport type { JoinRule } from './definition'\nimport type { FoldEdge } from './fold'\n\nexport interface GatingEdge {\n readonly edge: CompiledEdge\n readonly folded: FoldEdge | undefined\n}\n\nexport interface JoinDecision {\n /** Whether the node releases now. */\n readonly release: boolean\n /** The edges whose outcomes produced this release — the ones a traversal cap judges. */\n readonly consuming: ReadonlyArray<GatingEdge>\n /** Whether the node can never release again on this wave (recorded like skipped-by-guard). */\n readonly blocked: boolean\n}\n\nconst NOTHING: JoinDecision = { release: false, consuming: [], blocked: false }\n\n/** Decide whether a node's gating edges release it, and which of them the release consumes. */\nexport function decideJoin(rule: JoinRule, gating: ReadonlyArray<GatingEdge>): JoinDecision {\n if (gating.length === 0) return NOTHING\n const settled = gating.filter((entry) => entry.folded && entry.folded.state !== 'pending')\n const satisfied = gating.filter((entry) => entry.folded?.state === 'satisfied')\n const failed = gating.filter((entry) => entry.folded?.state === 'failed')\n const allSettled = settled.length === gating.length\n switch (rule) {\n case 'all': {\n // A dead or failed edge can never satisfy an `all` join on this wave.\n const spoiled = gating.some(\n (entry) => entry.folded?.state === 'dead' || entry.folded?.state === 'failed',\n )\n const release = !spoiled && satisfied.length === gating.length\n return { release, consuming: release ? settled : [], blocked: false }\n }\n case 'any': {\n const first = satisfied[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'any_failed': {\n const first = failed[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'all_done':\n return { release: allSettled, consuming: allSettled ? settled : [], blocked: false }\n default:\n return NOTHING\n }\n}\n","/**\n * The 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 */\n/** Config for a nesting node: the inner graph, and the pool the inner run is given. */\nexport interface SubgraphKindConfig {\n readonly graph: unknown\n /** The inner run's conserved pool. Its spend is the inner pool's, never re-charged here. */\n readonly budget?: unknown\n readonly perNode?: unknown\n}\n\n/** A node carrying its own graph: it runs as a full engine run on the host's kinds and effects. */\nexport function subgraphKind(): NodeKind<SubgraphKindConfig> {\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 {\n graph: config.graph,\n ...(config.budget === undefined ? {} : { budget: config.budget }),\n ...(config.perNode === undefined ? {} : { perNode: config.perNode }),\n }\n },\n configSchema: {\n type: 'object',\n properties: { graph: { type: 'object' } },\n required: ['graph'],\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, host }) => {\n const name = profile.name ?? 'subgraph'\n if (!host) {\n throw new ValidationError(\n `subgraph kind: node ${JSON.stringify(name)} needs its hosting engine; run it through the scheduler, which supplies one`,\n )\n }\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n async execute(_task, signal): Promise<ExecutorResult<unknown>> {\n // The inner run is a FULL engine run on the host's kinds and effects: its own scope,\n // pool and journal tree, nested under this node's id so the two never collide.\n const inner = await host.runNested(config.graph, name, {\n budget: config.budget ?? { maxIterations: 1, maxTokens: 0 },\n ...(config.perNode === undefined ? {} : { perNode: config.perNode }),\n runId: `${name}:subgraph`,\n signal,\n })\n const out = { kind: inner.kind, out: inner.out }\n artifact = {\n outRef: contentAddress(out),\n out,\n // The inner run debits the pool it was given; this node reports the wall clock only.\n spent: { iterations: 1, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact: () => {\n if (!artifact)\n throw new ValidationError(`subgraph: resultArtifact() read before execute()`)\n return artifact\n },\n }\n return {\n name,\n act: () => Promise.reject(new ValidationError('subgraph: act() is not the execution path')),\n executorSpec: { profile, harness: null, executor } as AgentSpec,\n } as Agent<unknown, unknown> & { executorSpec: AgentSpec }\n },\n }\n}\n\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 edge ledger: what the runtime actually DELIVERED across each edge. It is observability, not\n * a fold input (agent-runtime#974) — `edge-verdict` carries the scheduler's decision, and this\n * carries the delivery, so a change to what an optimizer wants to see never changes resume\n * semantics. Its ordinals live in their own namespace, outside the kernel's cursor.\n */\n\nimport type { SpawnJournal } from '../supervise/types'\nimport type { CompiledEdge } from './compile'\nimport type { GraphEdgeTraversal } from './scheduler-types'\n\nexport interface EdgeLedger {\n readonly entries: ReadonlyArray<GraphEdgeTraversal>\n record(\n edge: CompiledEdge,\n traversal: number,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): Promise<void>\n}\n\n/** Open a ledger for one run; its ordinals continue past whatever a prior process recorded. */\nexport function createEdgeLedger(args: {\n readonly journal: SpawnJournal\n readonly runId: string\n readonly now: () => number\n readonly startSeq: number\n}): EdgeLedger {\n const entries: GraphEdgeTraversal[] = []\n let seq = args.startSeq\n return {\n entries,\n async record(edge, traversal, outcome, reason) {\n const spec = edge.spec\n const entry: GraphEdgeTraversal = {\n edge: edge.id,\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n traversal,\n outcome,\n ...(spec.directive !== undefined\n ? { directive: `${spec.directive.surface}/v${spec.directive.version}` }\n : {}),\n ...(spec.kind === 'data' ? { port: edge.toPort } : {}),\n ...(reason !== undefined ? { reason } : {}),\n }\n entries.push(entry)\n await args.journal.appendEvent(args.runId, {\n kind: 'edge',\n id: `graph:${spec.to.node}`,\n edge: {\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n ...(entry.directive !== undefined ? { directive: entry.directive } : {}),\n ...(entry.port !== undefined ? { port: entry.port } : {}),\n },\n traversal,\n outcome,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: seq++,\n at: new Date(args.now()).toISOString(),\n })\n },\n }\n}\n","/**\n * `runGraph` as an engine graph (agent-runtime#982, #975) — a COMPILER, not a second runtime.\n *\n * `graphFromRunGraph` lowers today's `AgentGraph` into the engine's vocabulary: one supervisor\n * root carrying the graph, one pinned `agent` node per worker, the authored `delegates`/`analyzes`\n * edges. That gives a `runGraph` consumer a first-class engine graph it can inspect, diff, and use\n * as the starting point for authoring one natively — the migration path #975 asked for.\n *\n * WHAT THIS DELIBERATELY DOES NOT DO: run it. `runGraph` executes through `superviseAgentGraph`,\n * exactly as it always has. An earlier version of this module wrapped that call in a one-node\n * engine run, which read as \"runGraph runs on the engine\" while changing nothing about execution\n * and costing a second journal tree, a second budget pool and a second `Scope`. A wrapper that\n * moves no behaviour is a second source of truth, so it is gone: the graph a consumer runs and the\n * graph they can inspect are produced from the same `AgentGraph`, and only one of them executes.\n *\n * The engine EXECUTES a graph a consumer authors directly (`runEngineGraph`), where nodes are\n * scheduled over `data` edges, guards decide traversal, and the fold makes it restartable.\n */\nimport { ValidationError } from '../../errors'\nimport type { AgentGraph, RunGraphOptions } from '../supervise/graph'\nimport type { EngineGraphEdge, EngineGraphNode, EngineGraphSpec } from './definition'\n\n/** The kind id the root node carries: a supervisor holding the whole `AgentGraph`. */\nexport const RUN_GRAPH_ROOT_KIND = 'supervisor/v1'\n\n/**\n * Compile an `AgentGraph` into the engine graph that describes it. Pure: nothing runs, nothing is\n * registered, no executor is built. A `delegates` edge is MODEL-fired (#971) — its target is\n * spawned by the supervisor through the coordination protocol — so every worker node is marked\n * `entry: false`, which is exactly what the engine's scheduler would honour if this graph were\n * handed to it.\n */\nexport function graphFromRunGraph(graph: AgentGraph, options: RunGraphOptions): EngineGraphSpec {\n const root = graph.nodes[0]\n if (root === undefined) throw new ValidationError('graphFromRunGraph: a graph needs a root node')\n const nodes: EngineGraphNode[] = graph.nodes.map((node, index) =>\n index === 0\n ? {\n id: node.id,\n kind: RUN_GRAPH_ROOT_KIND,\n config: {\n perWorker: options.perWorker ?? graph.budget,\n ...(options.maxLiveWorkers === undefined\n ? {}\n : { maxLiveWorkers: options.maxLiveWorkers }),\n },\n profile: node.profile,\n budget: graph.budget,\n terminal: true,\n deliverable: graph.deliverable,\n }\n : {\n id: node.id,\n kind: 'agent/v1',\n profile: node.profile,\n entry: false,\n terminal: false,\n budget: options.perWorker ?? graph.budget,\n },\n )\n const edges: EngineGraphEdge[] = graph.edges.flatMap((edge): EngineGraphEdge[] =>\n edge.kind === 'delegates'\n ? [\n {\n kind: 'delegates',\n from: { node: edge.from },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n },\n ]\n : // One engine edge per analysed source: engine edges are 1:1, the authored form fans in.\n edge.over.map((source) => ({\n kind: 'analyzes' as const,\n from: { node: source, port: 'trace' },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n })),\n )\n return { nodes, edges, root: root.id, deliverable: graph.deliverable }\n}\n","/**\n * Edge payload admission (agent-runtime#971): every value crossing an edge is JSON round-tripped,\n * `undefined` stripped to absence, and a non-representable value (a cycle, a BigInt, a function)\n * becomes a RECORD of that fact. This is the kernel's existing findings-guard rule, and it is what\n * makes `inputRef` stable and `onCrash: 'restart'` well defined — a degraded record beats a\n * vanished edge.\n */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n // JSON.stringify answers `undefined` for a bare function or symbol — record it, never vanish.\n if (text === undefined) return { nonCanonical: `payload of type ${typeof value}` }\n return JSON.parse(text)\n } catch (error) {\n return { nonCanonical: error instanceof Error ? error.message : String(error) }\n }\n}\n","/**\n * Turning a finished run into its result: rehydrate each settle's output, reduce the terminals\n * through the kernel's finalizer seam, and name the honest cause when nothing delivered\n * (agent-runtime#973). Separate from the loop so \"what happened\" is readable without reading\n * \"what ran\".\n */\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { ResultBlobStore, Scope } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport type { CompiledGraph } from './compile'\nimport type { GraphFoldState } from './fold'\nimport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\nexport type FinalizerChoice = 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n\nfunction resolveFinalizer(choice: FinalizerChoice | undefined): SupervisorFinalizer {\n if (choice === undefined || choice === 'bestDelivered') return bestDelivered\n if (choice === 'collectDelivered') return collectDelivered\n return choice\n}\n\n/** Every node settlement with its output rehydrated and its completion check applied. */\nexport async function materializeSettles(\n compiled: CompiledGraph,\n state: GraphFoldState,\n blobs: ResultBlobStore,\n outCache: ReadonlyMap<string, unknown>,\n): Promise<GraphNodeSettle[]> {\n const rehydrate = async (settle: GraphNodeSettle): Promise<GraphNodeSettle> => {\n if (settle.out !== undefined || settle.outRef === undefined) return settle\n const out = outCache.get(settle.outRef) ?? admitPayload(await blobs.get(settle.outRef))\n const node = compiled.nodes.get(settle.node)\n let valid = settle.valid\n if (valid === undefined && node?.deliverable !== undefined && settle.status === 'done') {\n try {\n valid = await node.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n return { ...settle, out, ...(valid !== undefined ? { valid } : {}) }\n }\n return Promise.all(\n [...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate),\n )\n}\n\n/** Turn a finished run into its result: rehydrate, reduce the terminals, classify a no-winner. */\nexport async function assembleGraphResult(args: {\n readonly compiled: CompiledGraph\n readonly state: GraphFoldState\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly outCache: ReadonlyMap<string, unknown>\n readonly ledger: ReadonlyArray<GraphEdgeTraversal>\n readonly finalizer?: FinalizerChoice\n readonly failure?: {\n readonly reason: GraphRunReason\n readonly error?: { name: string; message: string }\n }\n readonly aborted: boolean\n}): Promise<GraphRunResult> {\n const settles = await materializeSettles(args.compiled, args.state, args.blobs, args.outCache)\n const terminals = settles.filter((settle) => args.compiled.nodes.get(settle.node)?.terminal)\n const ledger = args.ledger\n\n // A capped edge that left the run winnerless is a NAMED failure, not a quiet no-winner (#973).\n const finish = (result: GraphRunResult): GraphRunResult => {\n if (result.kind === 'no-winner' && args.state.exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...args.state.exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (args.failure) {\n return finish({\n kind: 'no-winner',\n reason: args.failure.reason,\n ...(args.failure.error ? { error: args.failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const allTerminalsSettled = args.compiled.terminals.every(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) > 0,\n )\n const pendingTokens = [...args.state.suspensions.values()]\n .filter((suspension) => suspension.status === 'pending')\n .map((suspension) => suspension.token)\n if (pendingTokens.length > 0 && !allTerminalsSettled) {\n return { kind: 'suspended', tokens: pendingTokens, terminals, settles, ledger }\n }\n if (args.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const delivered = terminals.filter((settle) => settle.status === 'done' && settle.valid !== false)\n const out =\n delivered.length === 0\n ? undefined\n : await runFinalizer(resolveFinalizer(args.finalizer), {\n settled: terminals.map(\n (settle): FinalizerSettled => ({\n id: settle.node,\n status: settle.status,\n valid: settle.status === 'done' && settle.valid !== false,\n ...(settle.outRef !== undefined ? { outRef: settle.outRef } : {}),\n }),\n ),\n blobs: args.blobs,\n tree: args.scope.view,\n budget: args.scope.budget,\n })\n if (out !== undefined) return { kind: 'winner', out, terminals, settles, ledger }\n\n const unreachable = [...args.compiled.nodes.keys()].filter(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = args.compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === args.compiled.nodes.size\n ? 'budget-exhausted'\n : 'unreachable-terminal'\n : 'all-children-down'\n return finish({ kind: 'no-winner', reason, terminals, settles, ledger, unreachable })\n}\n","/**\n * Opening a graph run: begin or resume the journaled tree, rebuild the pool and the kernel `Scope`\n * on the SAME recipe the kernel supervisor uses for its own resume, and fold the prior journal\n * into scheduler state. Extracted so the restart contract is one readable unit rather than a\n * preamble inside the loop.\n */\nimport {\n closesCursorSlot,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { createBudgetPool } from '../supervise/budget'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createScope } from '../supervise/scope'\nimport {\n maxSeqOf,\n sumMeasuredSpendFromEvents,\n uncertainSpawnBudgets,\n} from '../supervise/supervisor'\nimport type { Budget, ResultBlobStore, Scope, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { addSpend } from '../util'\nimport type { CompiledGraph } from './compile'\nimport { applyGraphFoldEvent, emptyFoldState, type GraphFoldState } from './fold'\n\n/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter, so the two\n * counters can advance independently without ever colliding. */\nexport const ENGINE_WOKEN_SEQ_BASE = 10_000_000\n\nexport interface GraphRunContext {\n readonly runId: string\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly abort: AbortController\n readonly state: GraphFoldState\n readonly resuming: boolean\n /** Journal events present before this process started; empty on a fresh run. */\n readonly prior: ReadonlyArray<SpawnEvent>\n /** Next engine fold-event ordinal, and next engine `woken` ordinal. */\n readonly engineSeq: number\n readonly engineWokenSeq: number\n /** Ledger ordinals already used by a prior process. */\n readonly ledgerSeq: number\n}\n\n/** Begin or resume a run's journaled tree, pool, scope and folded state. */\nexport async function openGraphRun(args: {\n readonly compiled: CompiledGraph\n readonly runId: string\n readonly budget: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly now: () => number\n readonly resume?: boolean\n readonly signal?: AbortSignal\n readonly onAbort: (listener: () => void) => void\n}): Promise<GraphRunContext> {\n const journal = args.journal ?? new InMemorySpawnJournal()\n const blobs = args.blobs ?? new InMemoryResultBlobStore()\n const loaded = await journal.loadTree(args.runId)\n if (loaded !== undefined && args.resume !== true) {\n throw new ValidationError(\n `runEngineGraph: runId '${args.runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const prior = loaded ?? []\n const resuming = args.resume === true && prior.length > 0\n let runEpochMs = args.now()\n let rootBudget = args.budget\n if (loaded === undefined) {\n await journal.beginTree(args.runId, new Date(runEpochMs).toISOString())\n }\n if (resuming) {\n const root = prior.find((ev) => ev.kind === 'spawned' && ev.id === args.runId)\n if (root?.kind === 'spawned') {\n runEpochMs = Date.parse(root.at)\n rootBudget = root.budget\n }\n } else {\n // The engine's root anchor: what a restart reads its epoch and deadline from, exactly as the\n // kernel supervisor journals its own root. A begun-but-empty journal writes it here too.\n await journal.appendEvent(args.runId, {\n kind: 'spawned',\n id: args.runId,\n label: 'graph-root',\n budget: args.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(runEpochMs).toISOString(),\n })\n }\n\n const elapsed = () => args.now() - runEpochMs\n const measured = resuming ? sumMeasuredSpendFromEvents([...prior]) : undefined\n const pool = createBudgetPool(\n rootBudget,\n elapsed,\n measured === undefined\n ? undefined\n : {\n committed: addSpend(measured.childWork, measured.driverInference),\n uncertainReservations: uncertainSpawnBudgets([...prior]),\n ...(rootBudget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs }\n : {}),\n },\n )\n const abort = new AbortController()\n if (args.signal !== undefined) {\n const forward = () => abort.abort(args.signal?.reason)\n args.signal.addEventListener('abort', forward, { once: true })\n args.onAbort(() => args.signal?.removeEventListener('abort', forward))\n if (args.signal.aborted) abort.abort(args.signal.reason)\n }\n const scope = createScope<unknown>({\n parentId: args.runId,\n root: args.runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now: args.now,\n ...(resuming\n ? {\n resumeFrom: {\n settled: await replaySpawnTree(journal, blobs, args.runId),\n view: materializeTreeView([...prior]),\n maxSpawnOrdinal: maxSeqOf([...prior], (ev) => ev.kind === 'spawned'),\n maxCursorSeq: maxSeqOf([...prior], closesCursorSlot),\n maxWaitOrdinal: maxSeqOf([...prior], (ev) => ev.kind === 'waiting'),\n waits: pendingWaits([...prior]),\n keys: new Map(),\n priorSpend: sumMeasuredSpendFromEvents([...prior]),\n },\n }\n : {}),\n })\n\n const state = emptyFoldState(args.compiled)\n if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, args.compiled)\n\n return {\n runId: args.runId,\n journal,\n blobs,\n scope,\n abort,\n state,\n resuming,\n prior,\n engineSeq: resuming ? maxEngineSeq(prior) + 1 : 0,\n engineWokenSeq:\n ENGINE_WOKEN_SEQ_BASE +\n (resuming\n ? prior.filter((ev) => ev.kind === 'woken' && ev.seq >= ENGINE_WOKEN_SEQ_BASE).length\n : 0),\n ledgerSeq: prior.filter((ev) => ev.kind === 'edge').length,\n }\n}\n\nfunction maxEngineSeq(events: ReadonlyArray<SpawnEvent>): number {\n let max = -1\n for (const ev of events) {\n const engineEvent =\n ev.kind === 'node-inputs-resolved' ||\n ev.kind === 'edge-verdict' ||\n ev.kind === 'join-state' ||\n (ev.kind === 'waiting' && ev.spec.kind === 'token')\n if (engineEvent && ev.seq > max) max = ev.seq\n }\n return max\n}\n","/**\n * Suspensions (agent-runtime#976): a node parks on a host wake as the kernel's `waiting`/`woken`\n * pair. The engine owns the transition table; a host owns only how the wake arrives.\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\n\nconst SUSPEND_MARK = '__graphSuspension'\n\n/** What a kind's executor returns to park its node until a host wakes it. */\nexport interface SuspensionRequest {\n readonly [SUSPEND_MARK]: true\n readonly onExpire: 'wait' | 'fail' | 'default'\n /** Milliseconds from the suspension's journaling instant; absent with `onExpire: 'wait'`. */\n readonly expiresInMs?: number\n readonly default?: unknown\n}\n\n/** Build a suspension request. `wait` never expires; `fail` settles the node down at its deadline;\n * `default` resolves with the given payload. */\nexport function suspended(\n options: {\n readonly onExpire?: 'wait' | 'fail' | 'default'\n readonly expiresInMs?: number\n readonly default?: unknown\n } = {},\n): SuspensionRequest {\n const onExpire = options.onExpire ?? 'wait'\n if (onExpire !== 'wait' && options.expiresInMs === undefined) {\n throw new ValidationError(`suspended: onExpire '${onExpire}' requires expiresInMs`)\n }\n if (onExpire === 'wait' && options.expiresInMs !== undefined) {\n throw new ValidationError(\"suspended: onExpire 'wait' never expires — remove expiresInMs\")\n }\n if (onExpire === 'default' && options.default === undefined) {\n throw new ValidationError(\"suspended: onExpire 'default' requires a default payload\")\n }\n return {\n [SUSPEND_MARK]: true,\n onExpire,\n ...(options.expiresInMs !== undefined ? { expiresInMs: options.expiresInMs } : {}),\n ...(options.default !== undefined ? { default: options.default } : {}),\n }\n}\n\n/** Whether a node's output is a park request rather than its result. */\nexport function isSuspensionRequest(value: unknown): value is SuspensionRequest {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)[SUSPEND_MARK] === true\n )\n}\n\n/** Content-addressed over the run identity, so a restart recomputes it and needs no token table. */\nexport function mintSuspensionToken(runId: string, instance: string): string {\n return contentAddress({ runId, instance, kind: 'graph-suspension' })\n}\n\n/** The journal id one suspension's `waiting`/`woken` pair shares. */\nexport function suspensionNodeId(token: string): string {\n return `graphwait:${token}`\n}\n\n/** The token inside a suspension node id, or `undefined` for any other id. */\nexport function tokenFromSuspensionNodeId(id: string): string | undefined {\n return id.startsWith('graphwait:') ? id.slice('graphwait:'.length) : undefined\n}\n","/**\n * The engine scheduler (agent-runtime#980, durable per #974/#976): run a compiled graph by hosting\n * every node instance on one kernel `Scope`. The pool, the journal, the blob store and\n * cancellation are the kernel's; the scheduler owns only what a graph adds — releasing nodes over\n * guarded edges, delivering payloads and directives, the two cycle caps, and suspensions.\n *\n * DURABILITY — fold, never checkpoint. Every decision is journaled BEFORE its effect is visible\n * (blob-then-journal where a ref is minted), then applied to live state through the SAME reducer\n * (`applyGraphFoldEvent`) a restart replays the journal through. Kill the process at any journal\n * boundary and a restart re-enters the exact state: settled nodes restore from `outRef` and never\n * re-execute; a released-but-unspawned instance re-enters from its pinned `inputRef`; an in-flight\n * instance is in-doubt and re-enters per its kind's `onCrash`.\n *\n * The parts this file does NOT own, so it stays a loop and not a god object: payload admission\n * (`admit.ts`), the edge ledger (`ledger.ts`), the join rule (`join.ts`), suspension vocabulary\n * (`suspension.ts`), the journal/pool/scope bootstrap (`run-context.ts`), and result assembly\n * (`result.ts`).\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport type { Budget, ResultBlobStore, Settled, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport { type CompiledGraph, compileGraph, isEngineFired } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport { applyGraphFoldEvent, type FoldSuspension } from './fold'\nimport { decideJoin, type GatingEdge } from './join'\nimport { narrowEffects } from './kind'\nimport { createEdgeLedger } from './ledger'\nimport { applyProjection } from './projection'\nimport { assembleGraphResult, type FinalizerChoice } from './result'\nimport { openGraphRun } from './run-context'\nimport type { GraphNodeSettle, GraphRunReason, GraphRunResult } from './scheduler-types'\nimport {\n isSuspensionRequest,\n mintSuspensionToken,\n type SuspensionRequest,\n suspensionNodeId,\n} from './suspension'\n\nexport { admitPayload } from './admit'\nexport { ENGINE_WOKEN_SEQ_BASE } from './run-context'\nexport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\nexport { type SuspensionRequest, suspended } from './suspension'\n\nexport interface GraphRunOptions {\n /** The run's conserved pool. */\n readonly budget: Budget\n /** Default per-instance reservation for nodes that declare no `budget` of their own.\n * Required when any such node exists — the engine invents no split. */\n readonly perNode?: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n /** Resolves `delegates`/`analyzes` directives; required when any edge carries one. */\n readonly prompts?: PromptRegistry\n /** How terminal settles reduce to `out`. Default `bestDelivered`. */\n readonly finalizer?: FinalizerChoice\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly runId?: string\n /** Continue an existing journaled run. An existing tree without this refuses, like the kernel. */\n readonly resume?: boolean\n /** Hold a fully-suspended run open for live `resume()` calls instead of returning\n * `{ kind: 'suspended' }`. Offline callers leave this off and restart later (#976). */\n readonly waitForWakes?: boolean\n}\n\n/** A live run: await `done`; deliver host wakes through `resume`/`expire` (#976). */\nexport interface GraphRunHandle {\n readonly done: Promise<GraphRunResult>\n resume(token: string, payload: unknown): Promise<void>\n expire(token: string): Promise<void>\n}\n\ninterface QueuedWake {\n readonly token: string\n readonly payload?: unknown\n readonly expire: boolean\n readonly settle: () => void\n readonly fail: (error: unknown) => void\n}\n\n/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs no\n * live host wakes. */\nexport async function runEngineGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): Promise<GraphRunResult> {\n return createGraphRun(engine, spec, task, options).done\n}\n\n/**\n * Start (or resume) a graph run and return its handle: await `done` for the result; deliver host\n * wakes through `resume`/`expire` while it runs (#976).\n */\nexport function createGraphRun(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): GraphRunHandle {\n const compiled = asCompiled(engine, spec)\n const wakes: QueuedWake[] = []\n let signalWake: () => void = () => {}\n let finished = false\n const done = runGraphLoop(engine, compiled, task, options, wakes, (fn) => {\n signalWake = fn\n }).finally(() => {\n finished = true\n })\n const queue = (token: string, payload: unknown, expire: boolean): Promise<void> => {\n if (finished) {\n return Promise.reject(\n new ValidationError(\n `graph resume: run completed; start a new run over the same journal to wake '${token}'`,\n ),\n )\n }\n return new Promise<void>((settle, fail) => {\n wakes.push({ token, payload, expire, settle, fail })\n signalWake()\n })\n }\n return {\n done,\n resume: (token, payload) => queue(token, payload, false),\n expire: (token) => queue(token, undefined, true),\n }\n}\n\nfunction asCompiled(engine: GraphEngine, spec: EngineGraphSpec | CompiledGraph): CompiledGraph {\n return 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n}\n\n/** Everything a run must be able to satisfy before it spends anything. */\nfunction assertRunnable(\n engine: GraphEngine,\n compiled: CompiledGraph,\n options: GraphRunOptions,\n): void {\n const context = 'runEngineGraph'\n for (const node of compiled.nodes.values()) {\n const missing = node.kind.effects.filter((name) => !(name in engine.effects))\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: node ${node.id} needs effect(s) ${missing.join(', ')} the host did not provide`,\n )\n }\n if (node.spec.budget === undefined && options.perNode === undefined) {\n throw new ValidationError(\n `${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`,\n )\n }\n }\n for (const edge of compiled.edges) {\n // Only an ENGINE-fired edge's directive is the scheduler's to resolve; a `delegates` directive\n // is resolved by the supervisor that spawns the target (#971).\n if (isEngineFired(edge) && edge.spec.directive !== undefined && options.prompts === undefined) {\n throw new ValidationError(\n `${context}: edge ${edge.id} carries a directive but options.prompts is absent`,\n )\n }\n }\n}\n\nasync function runGraphLoop(\n engine: GraphEngine,\n compiled: CompiledGraph,\n task: string,\n options: GraphRunOptions,\n wakes: QueuedWake[],\n onWakeSignal: (fn: () => void) => void,\n): Promise<GraphRunResult> {\n assertRunnable(engine, compiled, options)\n const now = options.now ?? Date.now\n const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`\n let detachOuterAbort: () => void = () => {}\n const context = await openGraphRun({\n compiled,\n runId,\n budget: options.budget,\n ...(options.journal !== undefined ? { journal: options.journal } : {}),\n ...(options.blobs !== undefined ? { blobs: options.blobs } : {}),\n now,\n ...(options.resume !== undefined ? { resume: options.resume } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n onAbort: (detach) => {\n detachOuterAbort = detach\n },\n })\n const { abort, blobs, journal, scope, state } = context\n const ledger = createEdgeLedger({ journal, runId, now, startSeq: context.ledgerSeq })\n let engineSeq = context.engineSeq\n let wokenSeq = context.engineWokenSeq\n\n const liveHandles = new Map<string, string>() // kernel node id -> engine instance label\n const waitingForBudget: string[] = []\n const outCache = new Map<string, unknown>()\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n /** Journal one engine event, then apply it through the reducer a restart will replay. */\n const emit = async (ev: SpawnEvent): Promise<void> => {\n await journal.appendEvent(runId, ev)\n applyGraphFoldEvent(state, ev, compiled)\n }\n const stamp = () => new Date(now()).toISOString()\n\n const fail = (reason: GraphRunReason, name: string, message: string): void => {\n failure = { reason, error: { name, message } }\n abort.abort(`${reason}: ${message}`)\n }\n\n // ── Spawning ───────────────────────────────────────────────────────────────────\n\n /** The ONE entry path: spawn a released instance from its journaled envelope. Used by a fresh\n * release, a budget-parked retry, and a restart re-entry alike. */\n const spawnInstance = async (label: string): Promise<void> => {\n if (failure) return\n const instance = state.instances.get(label)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node || instance.inputRef === undefined) {\n throw new ValidationError(`runEngineGraph: instance ${label} has no journaled envelope`)\n }\n const envelope = (await blobs.get(instance.inputRef)) as\n | { task: string; inputs: Record<string, unknown> }\n | undefined\n if (envelope === undefined) {\n throw new ValidationError(\n `runEngineGraph: envelope ${instance.inputRef} is not in the blob store`,\n )\n }\n const agent = node.kind.run({\n config: node.config,\n profile: { name: node.id, ...(node.spec.profile ?? {}) },\n inputs: envelope.inputs,\n effects: narrowEffects(node.kind.effects, engine.effects, `runEngineGraph: node ${node.id}`),\n // A nesting kind (`subgraph`) runs its inner graph on THIS engine — same kinds, same\n // effects — with its own scope, pool and journal tree under a derived run id.\n host: {\n runNested: (inner, task, opts) =>\n runEngineGraph(engine, inner as EngineGraphSpec, task, {\n budget: opts.budget as Budget,\n ...(opts.perNode === undefined ? {} : { perNode: opts.perNode as Budget }),\n journal,\n blobs,\n ...(options.prompts === undefined ? {} : { prompts: options.prompts }),\n runId: `${runId}:${opts.runId}`,\n ...(opts.signal === undefined ? {} : { signal: opts.signal }),\n now,\n }).then((result) => ({\n kind: result.kind,\n ...(result.kind === 'winner' ? { out: result.out } : {}),\n })),\n },\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, envelope.task, { label, budget })\n if (spawned.ok) {\n liveCount += 1\n liveHandles.set(spawned.handle.id, label)\n // The kernel journaled its own `spawned` row inside `scope.spawn`; mirror the two fields the\n // reducer folds, so live state matches what a restart reconstructs.\n applyGraphFoldEvent(\n state,\n {\n kind: 'spawned',\n id: spawned.handle.id,\n label,\n budget,\n runtime: 'inline',\n seq: 0,\n at: '',\n },\n compiled,\n )\n return\n }\n if (spawned.reason === 'budget-exhausted' || spawned.reason === 'max-live-workers') {\n waitingForBudget.push(label) // never overcommit: retry after the next settle frees capacity\n return\n }\n fail('driver-failed', 'SpawnRefused', `node ${node.id}: ${spawned.reason}`)\n }\n\n /** Pin an instance's envelope (inputs + task) by content address; answers the instance label. */\n const openInstance = async (\n nodeId: string,\n visit: number,\n envelope: { task: string; inputs: Record<string, unknown> },\n ): Promise<string> => {\n const label = `${nodeId}#${visit}`\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: nodeId,\n instance: label,\n inputRef,\n seq: engineSeq++,\n at: stamp(),\n })\n return label\n }\n\n const enterEntryNode = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) return\n await spawnInstance(await openInstance(nodeId, visit, { task, inputs: {} }))\n }\n\n // ── Releasing ──────────────────────────────────────────────────────────────────\n\n /** Build the released instance's envelope from its wave: data payloads projected and admitted,\n * directives resolved, trace refs lined up — every consumption ledgered as it is taken. */\n const consumeWave = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n ): Promise<{ task: string; inputs: Record<string, unknown> }> => {\n const inputs: Record<string, unknown> = {}\n const directives: string[] = []\n const traces: string[] = []\n for (const { edge, folded } of consuming) {\n const spec = edge.spec\n const traversal = (folded?.traversals ?? 0) + 1\n if (spec.kind === 'data' && folded?.state === 'satisfied') {\n let payload =\n folded.payloadRef === undefined\n ? undefined\n : (outCache.get(folded.payloadRef) ?? admitPayload(await blobs.get(folded.payloadRef)))\n let outcome: 'delivered' | 'empty' = 'delivered'\n let reason: string | undefined\n if (spec.projection !== undefined) {\n try {\n payload = admitPayload(applyProjection(payload, spec.projection, `edge ${edge.id}`))\n } catch (error) {\n outcome = 'empty'\n reason = error instanceof Error ? error.message : String(error)\n payload = undefined\n }\n }\n if (payload === undefined) outcome = 'empty'\n await ledger.record(edge, traversal, outcome, reason)\n if (payload !== undefined) inputs[edge.toPort] = payload\n continue\n }\n if (spec.directive !== undefined && options.prompts !== undefined) {\n directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && folded?.state === 'satisfied') {\n traces.push(`trace of ${spec.from.node}: ${folded.payloadRef ?? '(no traceRef)'}`)\n }\n await ledger.record(edge, traversal, 'delivered')\n }\n const composed = [nodeId === compiled.root ? task : '', ...directives, ...traces]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n return { task: composed.length > 0 ? composed : task, inputs }\n }\n\n const release = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n consumedPending: ReadonlyArray<string>,\n ): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n const envelope = await consumeWave(nodeId, consuming)\n const label = await openInstance(nodeId, visit, envelope)\n await emit({\n kind: 'join-state',\n id: label,\n node: nodeId,\n rule: node.join,\n satisfiedBy: consuming.map(({ edge }) => edge.id),\n consumedPending: [...consumedPending],\n instance: label,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n\n const tryRelease = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded || folded.blocked || failure) return\n const gating: GatingEdge[] = node.inbound.map((edge) => ({\n edge,\n folded: state.edges.get(edge.id),\n }))\n const decision = decideJoin(node.join, gating)\n if (decision.blocked) folded.blocked = true\n if (!decision.release) return\n // Caps are judged on the consuming edges BEFORE anything else happens, and the refusal is\n // journaled so a restart sees the same exhaustion.\n for (const entry of decision.consuming) {\n const cap = entry.edge.spec.maxTraversals\n if (cap !== undefined && (entry.folded?.traversals ?? 0) >= cap) {\n await ledger.record(\n entry.edge,\n (entry.folded?.traversals ?? 0) + 1,\n 'unpropagated',\n `traversal-cap-exhausted (max ${cap})`,\n )\n await emit({\n kind: 'edge-verdict',\n id: `graph:${nodeId}`,\n edge: entry.edge.id,\n fired: false,\n sourceStatus: 'done',\n capped: true,\n seq: engineSeq++,\n at: stamp(),\n })\n return\n }\n }\n const consumedPending = gating\n .filter(\n (entry) => entry.folded?.state === 'pending' && hasLiveInstance(entry.edge.spec.from.node),\n )\n .map((entry) => entry.edge.id)\n await release(nodeId, decision.consuming, consumedPending)\n }\n\n const hasLiveInstance = (nodeId: string): boolean => {\n for (const label of liveHandles.values()) {\n if (state.instances.get(label)?.node === nodeId) return true\n }\n return false\n }\n\n // ── Judging ────────────────────────────────────────────────────────────────────\n\n /** Journal a verdict for every unaccounted outbound edge of a settle, then try the joins. */\n const propagate = async (label: string, settle: GraphNodeSettle): Promise<void> => {\n const node = compiled.nodes.get(settle.node)\n if (!node) return\n const succeeded = settle.status === 'done' && settle.valid !== false\n const sourceSettles = state.nodes.get(settle.node)?.settles.length ?? 0\n for (const edge of node.outbound) {\n // A `delegates` target is spawned by its supervisor inside the kernel's authorized path,\n // with the pin and the directive applied there — the scheduler judges nothing (#971).\n if (!isEngineFired(edge)) continue\n const folded = state.edges.get(edge.id)\n if (!folded || folded.judgedSourceSettles >= sourceSettles) {\n // Accounted — by an earlier verdict, or absorbed by the wave that consumed it. This is\n // what makes propagate idempotent, so a restart may re-propagate every settled node.\n continue\n }\n let fired = false\n let inputRef: string | undefined\n if (succeeded) {\n fired =\n edge.spec.guard === undefined ||\n evaluateCondition(edge.spec.guard, {\n node: settle.node,\n out: settle.out,\n visits: state.nodes.get(settle.node)?.visits ?? 0,\n valid: settle.valid ?? true,\n })\n if (fired) {\n inputRef =\n edge.spec.kind === 'analyzes'\n ? (settle as { traceRef?: string }).traceRef\n : settle.outRef\n }\n }\n await emit({\n kind: 'edge-verdict',\n id: label,\n edge: edge.id,\n fired,\n sourceStatus: settle.status === 'down' ? 'down' : succeeded ? 'done' : 'invalid',\n ...(inputRef !== undefined ? { inputRef } : {}),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n for (const edge of node.outbound) {\n if (isEngineFired(edge)) await tryRelease(edge.spec.to.node)\n }\n }\n\n // ── Suspensions ────────────────────────────────────────────────────────────────\n\n const park = async (label: string, request: SuspensionRequest): Promise<void> => {\n const token = mintSuspensionToken(runId, label)\n let defaultRef: string | undefined\n if (request.default !== undefined) {\n const admitted = admitPayload(request.default)\n defaultRef = contentAddress(admitted)\n await blobs.put(defaultRef, admitted)\n }\n await emit({\n kind: 'waiting',\n id: suspensionNodeId(token),\n label,\n spec: {\n kind: 'token',\n token,\n onExpire: request.onExpire,\n ...(request.expiresInMs !== undefined ? { expiresAtMs: now() + request.expiresInMs } : {}),\n ...(defaultRef !== undefined ? { defaultRef } : {}),\n },\n armedAt: now(),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n\n const wake = async (\n suspension: FoldSuspension,\n by: 'fired' | 'expired',\n outRef?: string,\n ): Promise<void> => {\n await emit({\n kind: 'woken',\n id: suspensionNodeId(suspension.token),\n by,\n ...(outRef !== undefined ? { outRef } : {}),\n seq: wokenSeq++,\n at: stamp(),\n })\n const settle = state.instances.get(suspension.instance)?.settle\n if (settle === undefined) return\n const out =\n settle.outRef === undefined ? undefined : admitPayload(await blobs.get(settle.outRef))\n if (settle.outRef !== undefined && out !== undefined) outCache.set(settle.outRef, out)\n await propagate(suspension.instance, out === undefined ? settle : { ...settle, out })\n }\n\n /** Expiries are engine-clocked, so an offline run transitions them without a host sweep (#976). */\n const expireDue = async (): Promise<boolean> => {\n let transitioned = false\n for (const suspension of [...state.suspensions.values()]) {\n if (suspension.status !== 'pending') continue\n if (suspension.expiresAtMs === undefined || now() < suspension.expiresAtMs) continue\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n else continue\n transitioned = true\n }\n return transitioned\n }\n\n const drainWakes = async (): Promise<void> => {\n while (wakes.length > 0) {\n const request = wakes.shift()\n if (!request) return\n try {\n const suspension = state.suspensions.get(request.token)\n if (!suspension) throw new ValidationError(`graph resume: unknown token '${request.token}'`)\n if (suspension.status !== 'pending') {\n throw new ValidationError(`graph resume: token '${request.token}' already woken`)\n }\n if (request.expire) {\n await wake(\n suspension,\n suspension.onExpire === 'default' ? 'fired' : 'expired',\n suspension.onExpire === 'default' ? suspension.defaultRef : undefined,\n )\n } else {\n const admitted = admitPayload(request.payload)\n const outRef = contentAddress(admitted)\n await blobs.put(outRef, admitted)\n outCache.set(outRef, admitted)\n await wake(suspension, 'fired', outRef)\n }\n request.settle()\n } catch (error) {\n request.fail(error)\n }\n }\n }\n\n // ── Settling ───────────────────────────────────────────────────────────────────\n\n const handleSettle = async (settled: Settled<unknown>): Promise<void> => {\n const label = liveHandles.get(settled.handle.id)\n if (label === undefined) return\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const instance = state.instances.get(label)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node) return\n if (settled.kind === 'done' && isSuspensionRequest(settled.out)) {\n await park(label, settled.out)\n return\n }\n // Mirror the kernel's own journaled settle through the reducer, then enrich it for judging.\n applyGraphFoldEvent(\n state,\n {\n kind: 'settled',\n id: settled.handle.id,\n status: settled.kind === 'done' ? 'done' : 'down',\n ...(settled.kind === 'done' ? { outRef: settled.outRef } : {}),\n ...(settled.kind === 'down' ? { reason: settled.reason } : {}),\n ...(settled.kind === 'done' && settled.trace?.status === 'available'\n ? { trace: settled.trace }\n : {}),\n spent: { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n seq: 0,\n at: '',\n },\n compiled,\n )\n const folded = state.instances.get(label)?.settle\n if (!folded) return\n let enriched = folded\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n if (settled.outRef !== undefined) outCache.set(settled.outRef, admitted)\n enriched = { ...folded, out: admitted, ...(await checkDeliverable(node, admitted)) }\n const settles = state.nodes.get(instance.node)?.settles\n if (settles) settles[settles.length - 1] = enriched\n ;(state.instances.get(label) as { settle?: GraphNodeSettle }).settle = enriched\n }\n // Root completion ends the run the moment its check passes (#973).\n if (instance.node === compiled.root && enriched.status === 'done' && enriched.valid === true) {\n abort.abort('root delivered')\n return\n }\n await propagate(label, enriched)\n }\n\n const checkDeliverable = async (\n node: CompiledGraph['nodes'] extends ReadonlyMap<string, infer N> ? N : never,\n out: unknown,\n ): Promise<{ valid?: boolean }> => {\n if (node.deliverable === undefined) return {}\n try {\n return { valid: await node.deliverable.check(out) }\n } catch {\n return { valid: false }\n }\n }\n\n // ── Entry / restart ────────────────────────────────────────────────────────────\n\n if (!context.resuming) {\n for (const id of compiled.entries) await enterEntryNode(id)\n } else {\n await reenterAfterCrash()\n }\n\n /** Kill-anywhere re-entry: finish every half-done transition the crashed process left, from the\n * pinned envelopes and journaled settles only — never by re-deriving anything (#974). */\n async function reenterAfterCrash(): Promise<void> {\n for (const instance of [...state.instances.values()]) {\n if (instance.status === 'released') {\n await spawnInstance(instance.instance)\n continue\n }\n if (instance.status !== 'live') continue\n const node = compiled.nodes.get(instance.node)\n const folded = state.nodes.get(instance.node)\n if (!node || !folded) continue\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n // In-doubt: the journal keeps its reservation charged (the kernel's rule), and the restart\n // re-enters from the SAME pinned envelope.\n instance.status = 'down'\n const label = `${instance.node}#${visit}`\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: instance.node,\n instance: label,\n inputRef: instance.inputRef as string,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n for (const [nodeId, folded] of state.nodes) {\n const latest = folded.settles.at(-1)\n if (latest === undefined) continue\n const label = `${nodeId}#${latest.visit}`\n if (latest.status === 'done' && latest.outRef !== undefined) {\n const out = admitPayload(await blobs.get(latest.outRef))\n if (isSuspensionRequest(out)) {\n // Killed between the kernel settle and the `waiting` event: finish the transition\n // instead of propagating the park marker as data.\n folded.settles.pop()\n const instance = state.instances.get(label)\n if (instance) instance.settle = undefined\n await park(label, out)\n continue\n }\n outCache.set(latest.outRef, out)\n const node = compiled.nodes.get(nodeId)\n await propagate(label, {\n ...latest,\n out,\n ...(node === undefined ? {} : await checkDeliverable(node, out)),\n })\n continue\n }\n await propagate(label, latest)\n }\n for (const id of compiled.entries) {\n if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id)\n }\n for (const id of compiled.nodes.keys()) await tryRelease(id)\n }\n\n // ── The loop ───────────────────────────────────────────────────────────────────\n\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0)\n\n let wakeSignal = Promise.resolve()\n const rearmWakeSignal = () => {\n wakeSignal = new Promise<void>((fire) => {\n onWakeSignal(fire)\n })\n }\n rearmWakeSignal()\n\n let pendingNext: Promise<Settled<unknown> | null> | undefined\n while (!failure) {\n if (await expireDue()) continue\n if (wakes.length > 0) {\n await drainWakes()\n continue\n }\n if (allTerminalsSettled()) break\n if (liveCount === 0) {\n const parked = [...state.suspensions.values()].filter(\n (suspension) => suspension.status === 'pending',\n )\n if (parked.length === 0) break // stuck or complete: `assembleGraphResult` classifies it\n if (options.waitForWakes) {\n rearmWakeSignal()\n await wakeSignal\n continue\n }\n // Offline (#976): no host will answer, so a `default` suspension resolves now; `wait` and a\n // future `fail` deadline park the run as a resumable artifact.\n const defaulting = parked.filter((suspension) => suspension.onExpire === 'default')\n if (defaulting.length === 0) break\n for (const suspension of defaulting) await wake(suspension, 'fired', suspension.defaultRef)\n continue\n }\n pendingNext ??= scope.next()\n const raced = await Promise.race([\n pendingNext.then((settle) => ({ settle })),\n wakeSignal.then(() => 'wake' as const),\n ])\n if (raced === 'wake') {\n rearmWakeSignal()\n continue // the queued wakes run on the next turn; `pendingNext` stays armed\n }\n pendingNext = undefined\n if (raced.settle === null) break\n await handleSettle(raced.settle)\n for (const label of waitingForBudget.splice(0)) await spawnInstance(label)\n }\n\n detachOuterAbort()\n abort.abort('graph loop complete')\n while ((await (pendingNext ?? scope.next())) !== null) pendingNext = undefined\n\n return assembleGraphResult({\n compiled,\n state,\n blobs,\n scope,\n outCache,\n ledger: ledger.entries,\n ...(options.finalizer !== undefined ? { finalizer: options.finalizer } : {}),\n ...(failure !== undefined ? { failure } : {}),\n aborted: options.signal?.aborted ?? false,\n })\n}\n"],"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,g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AAG;GAC7B,KAAK,MAAM,cAAc,YAAY,MAAM,KAAK,YAAY,SAAS,WAAW,UAAU;GAC1F;EACF;EACA,gBAAgB,MAAM,KAAK;EAC3B,MAAM,QAAQ,MAAM,QAAQ,KAAK,CAC/B,YAAY,MAAM,YAAY,EAAE,OAAO,EAAE,GACzC,WAAW,WAAW,MAAe,CACvC,CAAC;EACD,IAAI,UAAU,QAAQ;GACpB,gBAAgB;GAChB;EACF;EACA,cAAc,KAAA;EACd,IAAI,MAAM,WAAW,MAAM;EAC3B,MAAM,aAAa,MAAM,MAAM;EAC/B,KAAK,MAAM,SAAS,iBAAiB,OAAO,CAAC,GAAG,MAAM,cAAc,KAAK;CAC3E;CAEA,iBAAiB;CACjB,MAAM,MAAM,qBAAqB;CACjC,OAAQ,OAAO,eAAe,MAAM,KAAK,OAAQ,MAAM,cAAc,KAAA;CAErE,OAAO,oBAAoB;EACzB;EACA;EACA;EACA;EACA;EACA,QAAQ,OAAO;EACf,GAAI,QAAQ,cAAc,KAAA,IAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC1E,GAAI,YAAY,KAAA,IAAY,EAAE,QAAQ,IAAI,CAAC;EAC3C,SAAS,QAAQ,QAAQ,WAAW;CACtC,CAAC;AACH"}
|
|
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/join.ts","../src/runtime/graph/kinds.ts","../src/runtime/graph/ledger.ts","../src/runtime/graph/preset-run-graph.ts","../src/runtime/graph/admit.ts","../src/runtime/graph/result.ts","../src/runtime/graph/run-context.ts","../src/runtime/graph/suspension.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 /** Force a node out of (or into) the run's entry set. Absent, a node with no inbound edge is an\n * entry, and the declared root always is. A node another node SPAWNS — the `runGraph` preset's\n * workers and analysts — sets `false`: the scheduler must never enter it on its own. */\n readonly entry?: boolean\n /** Profile fields merged over the engine-authored `{ name: id }` for this node's spawns. */\n readonly profile?: Readonly<Partial<AgentProfile>>\n /** Per-instance reservation for this node's spawns; falls back to the run's `perNode`. */\n readonly budget?: Budget\n}\n\nexport interface EngineGraphEdge {\n /** Stable id for the ledger; defaults to `<from>-><to>#<ordinal>`. */\n readonly id?: string\n readonly kind: GraphEdgeKind\n readonly from: { readonly node: string; readonly port?: string }\n readonly to: { readonly node: string; readonly port?: string }\n /** Evaluated over the source's settle context; absent = satisfied by completion. */\n readonly guard?: Condition\n /** `data` edges only: ONE pure reshape of the admitted payload. */\n readonly projection?: Projection\n /** Refuses the traversal past this many firings (ledgered `unpropagated`); `0` closes the edge from the start. */\n readonly maxTraversals?: number\n /** `delegates`/`analyzes`: the versioned directive appended to the target's task. */\n readonly directive?: PromptHandle\n}\n\nexport interface EngineGraphSpec {\n readonly nodes: ReadonlyArray<EngineGraphNode>\n readonly edges: ReadonlyArray<EngineGraphEdge>\n /** Root node for the graph-level completion check. Defaults to the single entry node. */\n readonly root?: string\n /** Becomes the ROOT node's completion check when the root declares none (#973). */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly maxNodeVisits?: number\n}\n\nexport interface ParsedGraphNode extends EngineGraphNode {\n readonly kindHandle: RegistryHandle\n readonly join: JoinRule\n readonly maxVisits: number\n}\n\n/** Structural validation only — everything a registry is not needed for. */\nexport function validateEngineGraphSpec(spec: EngineGraphSpec, context = 'compileGraph'): void {\n if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) {\n throw new ValidationError(`${context}: a graph needs at least one node`)\n }\n const ids = new Set<string>()\n for (const node of spec.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError(`${context}: every node needs a non-empty id`)\n }\n if (ids.has(node.id))\n throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`)\n ids.add(node.id)\n parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`)\n if (node.join !== undefined && !(JOIN_RULES as ReadonlyArray<string>).includes(node.join)) {\n throw new ValidationError(\n `${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(', ')}`,\n )\n }\n if (node.maxVisits !== undefined) {\n if (\n !Number.isSafeInteger(node.maxVisits) ||\n node.maxVisits < 1 ||\n node.maxVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: node ${node.id} maxVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n }\n if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`)\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}]`\n if (edge.kind !== 'delegates' && edge.kind !== 'analyzes' && edge.kind !== 'data') {\n throw new ValidationError(`${who}: kind must be delegates | analyzes | data`)\n }\n for (const end of ['from', 'to'] as const) {\n const ref = edge[end]\n if (\n typeof ref !== 'object' ||\n ref === null ||\n typeof ref.node !== 'string' ||\n !ids.has(ref.node)\n ) {\n throw new ValidationError(`${who}: ${end}.node must name a node in this graph`)\n }\n }\n if (edge.guard !== undefined) validateCondition(edge.guard, `${who} guard`)\n if (edge.projection !== undefined) {\n if (edge.kind !== 'data') {\n throw new ValidationError(`${who}: only a data edge carries a projection`)\n }\n validateProjection(edge.projection, `${who} projection`)\n }\n if (edge.maxTraversals !== undefined) {\n // Zero is meaningful and authored in practice: an edge closed from the start, which the\n // scheduler refuses on its first consumption and ledgers `unpropagated`.\n if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 0) {\n throw new ValidationError(`${who}: maxTraversals must be a non-negative integer`)\n }\n }\n if (edge.kind === 'data' && edge.directive !== undefined) {\n throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`)\n }\n }\n if (spec.root !== undefined && !ids.has(spec.root)) {\n throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`)\n }\n if (spec.maxNodeVisits !== undefined) {\n if (\n !Number.isSafeInteger(spec.maxNodeVisits) ||\n spec.maxNodeVisits < 1 ||\n spec.maxNodeVisits > MAX_MAX_NODE_VISITS\n ) {\n throw new ValidationError(\n `${context}: maxNodeVisits must be an integer in [1, ${MAX_MAX_NODE_VISITS}]`,\n )\n }\n }\n}\n","/**\n * Compile an authored graph against an engine's kind registry into the schedulable form. Every\n * refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`\n * binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no\n * completion check (agent-runtime#971, #973).\n */\nimport { ValidationError } from '../../errors'\nimport type { DeliverableSpec } from '../supervise/completion-gate'\nimport {\n DEFAULT_MAX_NODE_VISITS,\n type EngineGraphEdge,\n type EngineGraphSpec,\n type JoinRule,\n validateEngineGraphSpec,\n} from './definition'\nimport type { GraphEngine } from './engine'\nimport type { JsonSchema, NodeKind, PortSpec } from './kind'\nimport { formatRegistryHandle, parseRegistryHandle } from './registry'\n\n/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */\nexport const IMPLICIT_OUTPUT_PORTS = ['out', 'trace'] as const\n\nexport interface CompiledEdge {\n readonly id: string\n readonly spec: EngineGraphEdge\n readonly fromPort: string\n readonly toPort: string\n}\n\n/** `delegates` is the one MODEL-fired edge kind (agent-runtime#971): its payload is a directive and\n * its target is spawned by the source supervisor through the coordination protocol, not released\n * by the scheduler. `data` and `analyzes` are engine-fired. */\nexport function isEngineFired(edge: CompiledEdge): boolean {\n return edge.spec.kind !== 'delegates'\n}\n\nexport interface CompiledNode {\n readonly id: string\n readonly kind: NodeKind\n readonly config: unknown\n readonly join: JoinRule\n readonly maxVisits: number\n readonly oracle: boolean\n readonly pure: boolean\n readonly terminal: boolean\n /** The check this node must pass to count DELIVERED; resolved per #973. */\n readonly deliverable?: DeliverableSpec<unknown>\n readonly inbound: ReadonlyArray<CompiledEdge>\n readonly outbound: ReadonlyArray<CompiledEdge>\n /** Spawned by a supervisor through a `delegates` edge, never entered by the scheduler. */\n readonly modelFired: boolean\n readonly spec: EngineGraphSpec['nodes'][number]\n}\n\nexport interface CompiledGraph {\n readonly nodes: ReadonlyMap<string, CompiledNode>\n readonly edges: ReadonlyArray<CompiledEdge>\n readonly entries: ReadonlyArray<string>\n readonly terminals: ReadonlyArray<string>\n readonly root: string\n readonly maxNodeVisits: number\n}\n\ntype NodePorts = {\n readonly inputs: ReadonlyArray<PortSpec>\n readonly outputs: ReadonlyArray<PortSpec>\n}\n\n/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */\nfunction nodePorts(kind: NodeKind, node: EngineGraphSpec['nodes'][number]): NodePorts {\n const merge = (\n declared: ReadonlyArray<PortSpec>,\n own: ReadonlyArray<PortSpec> | undefined,\n ): ReadonlyArray<PortSpec> => {\n if (own === undefined || own.length === 0) return declared\n const names = new Set(own.map((port) => port.name))\n return [...own, ...declared.filter((port) => !names.has(port.name))]\n }\n return {\n inputs: merge(kind.inputs, node.ports?.inputs),\n outputs: merge(kind.outputs, node.ports?.outputs),\n }\n}\n\nfunction outputPort(ports: NodePorts, port: string): PortSpec | undefined {\n if ((IMPLICIT_OUTPUT_PORTS as ReadonlyArray<string>).includes(port)) {\n return { name: port, schema: {} }\n }\n return ports.outputs.find((candidate) => candidate.name === port)\n}\n\nfunction inputPort(ports: NodePorts, port: string): PortSpec | undefined {\n return ports.inputs.find((candidate) => candidate.name === port)\n}\n\n/**\n * Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no\n * `type` accept anything; object targets require their `required` properties to be present and\n * accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,\n * not a full JSON Schema validator.\n */\nexport function schemaAccepts(source: JsonSchema, target: JsonSchema, depth = 0): boolean {\n if (depth > 6) return true\n const sourceType = source.type\n const targetType = target.type\n if (targetType === undefined || sourceType === undefined) return true\n const targets = Array.isArray(targetType) ? targetType : [targetType]\n const sources = Array.isArray(sourceType) ? sourceType : [sourceType]\n const overlap = sources.filter(\n (candidate) =>\n targets.includes(candidate === 'integer' ? 'number' : candidate) ||\n targets.includes(candidate),\n )\n if (overlap.length === 0) return false\n if (targets.includes('object') && sources.includes('object')) {\n const required = Array.isArray(target.required) ? (target.required as string[]) : []\n const sourceProps = source.properties as Record<string, JsonSchema> | undefined\n const targetProps = target.properties as Record<string, JsonSchema> | undefined\n if (sourceProps !== undefined) {\n for (const name of required) {\n const sourceProp = sourceProps[name]\n if (sourceProp === undefined) return false\n const targetProp = targetProps?.[name]\n if (targetProp !== undefined && !schemaAccepts(sourceProp, targetProp, depth + 1)) {\n return false\n }\n }\n }\n }\n if (targets.includes('array') && sources.includes('array')) {\n const sourceItems = source.items as JsonSchema | undefined\n const targetItems = target.items as JsonSchema | undefined\n if (sourceItems !== undefined && targetItems !== undefined) {\n return schemaAccepts(sourceItems, targetItems, depth + 1)\n }\n }\n return true\n}\n\n/**\n * Lower an authored graph against an engine's kind registry into the schedulable form, refusing\n * every structural defect before any spend.\n */\nexport function compileGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec,\n context = 'compileGraph',\n): CompiledGraph {\n validateEngineGraphSpec(spec, context)\n const kinds = new Map<string, NodeKind>()\n const configs = new Map<string, unknown>()\n for (const node of spec.nodes) {\n const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`)\n const kind = engine.kinds.require(handle, `${context}: node ${node.id}`)\n kinds.set(node.id, kind)\n configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`))\n if (node.flags?.pure && kind.id !== 'script') {\n throw new ValidationError(\n `${context}: node ${node.id} sets pure, which only a script node may claim`,\n )\n }\n }\n\n const compiledEdges: CompiledEdge[] = []\n const inbound = new Map<string, CompiledEdge[]>()\n const outbound = new Map<string, CompiledEdge[]>()\n for (const [index, edge] of spec.edges.entries()) {\n const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`\n const fromKind = kinds.get(edge.from.node)\n const toKind = kinds.get(edge.to.node)\n if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`)\n const toNode = spec.nodes.find((node) => node.id === edge.to.node)\n if (edge.kind !== 'analyzes' && toNode?.flags?.oracle) {\n // An edge to a grader leaks the rubric: an oracle is bound only by `analyzes`.\n throw new ValidationError(\n `${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`,\n )\n }\n const fromPort = edge.from.port ?? (edge.kind === 'analyzes' ? 'trace' : 'out')\n if (edge.kind === 'analyzes' && fromPort !== 'trace') {\n throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`)\n }\n const fromNode = spec.nodes.find((node) => node.id === edge.from.node)\n const fromPorts = nodePorts(fromKind, fromNode as EngineGraphSpec['nodes'][number])\n const toPorts = nodePorts(toKind, toNode as EngineGraphSpec['nodes'][number])\n const sourcePort = outputPort(fromPorts, fromPort)\n if (!sourcePort) {\n const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)]\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(', ')}`,\n )\n }\n let toPort = edge.to.port ?? ''\n if (edge.kind === 'data') {\n if (toPort === '') {\n if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? ''\n else {\n throw new ValidationError(\n `${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`,\n )\n }\n }\n const targetPort = inputPort(toPorts, toPort)\n if (!targetPort) {\n throw new ValidationError(\n `${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(', ') || '(none)'}`,\n )\n }\n // A projection reshapes the payload, so the source schema no longer describes it; the\n // projected shape is checked at admission, not statically.\n if (edge.projection === undefined && !schemaAccepts(sourcePort.schema, targetPort.schema)) {\n throw new ValidationError(\n `${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? 'any')}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? 'any')})`,\n )\n }\n }\n const compiled: CompiledEdge = {\n id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,\n spec: edge,\n fromPort,\n toPort: toPort === '' ? 'out' : toPort,\n }\n compiledEdges.push(compiled)\n outbound.set(edge.from.node, [...(outbound.get(edge.from.node) ?? []), compiled])\n inbound.set(edge.to.node, [...(inbound.get(edge.to.node) ?? []), compiled])\n }\n const dupes = new Set<string>()\n for (const edge of compiledEdges) {\n if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`)\n dupes.add(edge.id)\n }\n\n // A node reached only by `delegates` is spawned by its supervisor, so it is neither an entry nor\n // a scheduler-released node; a node with no ENGINE-fired outbound edge is terminal, because a\n // delegation does not continue the scheduler's flow.\n const engineInbound = (id: string) => (inbound.get(id) ?? []).filter(isEngineFired)\n const engineOutbound = (id: string) => (outbound.get(id) ?? []).filter(isEngineFired)\n const unfed = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0)\n if (unfed.length === 0 && spec.root === undefined) {\n throw new ValidationError(`${context}: no entry node — every node has an inbound edge`)\n }\n const root =\n spec.root ??\n (unfed.length === 1\n ? (unfed[0]?.id ?? '')\n : (() => {\n throw new ValidationError(\n `${context}: ${unfed.length} entry nodes (${unfed.map((node) => node.id).join(', ')}) — name spec.root`,\n )\n })())\n // The declared root always starts the run, even when an edge feeds back INTO it — a findings\n // route to the driver, or a cycle's closing edge, never stops the run from beginning there. A\n // node that declares `entry: false` is spawned by another node and never entered here.\n const declaredOut = new Set(\n spec.nodes.filter((node) => node.entry === false).map((node) => node.id),\n )\n const entries = [root, ...unfed.map((node) => node.id).filter((id) => id !== root)].filter(\n (id) => !declaredOut.has(id),\n )\n if (entries.length === 0) {\n throw new ValidationError(`${context}: every entry node declares entry: false — nothing starts`)\n }\n\n const nodes = new Map<string, CompiledNode>()\n const terminals: string[] = []\n for (const node of spec.nodes) {\n const kind = kinds.get(node.id)\n if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`)\n const modelFired = (inbound.get(node.id) ?? []).some((edge) => !isEngineFired(edge))\n const terminal = node.terminal ?? (!modelFired && engineOutbound(node.id).length === 0)\n const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : undefined)\n if (terminal) terminals.push(node.id)\n nodes.set(node.id, {\n id: node.id,\n kind,\n config: configs.get(node.id),\n join: node.join ?? 'all',\n maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n oracle: node.flags?.oracle ?? false,\n pure: node.flags?.pure ?? false,\n terminal,\n ...(deliverable === undefined ? {} : { deliverable }),\n inbound: engineInbound(node.id),\n outbound: outbound.get(node.id) ?? [],\n modelFired,\n spec: node,\n })\n }\n const unchecked = terminals.filter((id) => nodes.get(id)?.deliverable === undefined)\n if (unchecked.length === terminals.length) {\n // Termination is mandatory per terminal (#973): a graph none of whose terminals declares a\n // completion check (own, or the graph's on the root) can never prove it is done.\n throw new ValidationError(\n `${context}: no terminal declares a completion check (terminals: ${terminals.join(', ')}); give a node a deliverable or set spec.deliverable`,\n )\n }\n return {\n nodes,\n edges: compiledEdges,\n entries,\n terminals,\n root,\n maxNodeVisits: spec.maxNodeVisits ?? DEFAULT_MAX_NODE_VISITS,\n }\n}\n","/**\n * `NodeKind` — what a consumer registers to add a node kind to the graph engine without forking\n * it (agent-runtime#969, #970).\n *\n * The engine owns the graph: scheduling over typed data edges, guards, joins, cycles, the\n * conserved pool, the journal. It does NOT own execution — `run` returns an `Agent`, the\n * kernel's spawn contract (`Scope.spawn` takes an `Agent { name, act }`; a leaf `Agent` carries its\n * `Executor` as `executorSpec: AgentSpec`, and a supervisor `Agent` is `supervisorAgent(...)`). So\n * every node rides `supervise()`'s machinery unchanged: the pool's reserve/reconcile, the\n * content-addressed journal, the completion gate, `Settled`, trace evidence. An engine that\n * re-implemented any of those would be a second kernel.\n *\n * Every kernel-owned extension contract is a TS interface plus a hand-written validator that\n * throws `ValidationError` by name (the kernel has no zod), and this one follows suit. JSON Schema\n * is the PORTABLE form of a config/port shape — a `Record<string, unknown>`, as `McpToolDescriptor`\n * and `DeliveryBinding` already spell it — so a kind's declaration can be published in a manifest\n * and lifted by a host on another stack.\n *\n * The bar this file is measured against: the scheduler's source names no kind that is not\n * universal. A kind the engine ships (`agent`, `supervisor`, `subgraph`, `script`) is universal by\n * the rule \"the model cannot decide it with the verbs it has\"; everything else — integrations,\n * notifications, sandbox provisioning, human decisions — is registered by a host.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport type { Agent } from '../supervise/types'\nimport type { Registered, RegistryHandle } from './registry'\n\n/** A JSON Schema document as the kernel already spells it: an opaque record, validated by the\n * consumer's own validator, published verbatim. */\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\n/**\n * One declared port on a node. Ports are how a `data` edge binds one node's output to another's\n * input with a type the compiler can check structurally before any spend. A node has two implicit\n * output ports beside its declared ones: `out` (its result) and `trace` (its `WorkerTraceEvidence`\n * by `traceRef`); only an `analyzes` edge may bind `trace`.\n */\nexport interface PortSpec {\n readonly name: string\n readonly schema: JsonSchema\n readonly description?: string\n}\n\n/**\n * What a kind declares it needs from the host. The engine never imports a host capability; it\n * knows only that a kind SAID it needs something under this name and the host PROVIDED something\n * under it. The context a kind receives is narrowed to exactly its declaration — an undeclared\n * effect is `undefined`, never a service locator.\n */\n/** What a nesting kind needs from its host: run one graph, on the host's own kinds and effects.\n * Declared here (not imported from the scheduler) so the contract module stays dependency-free. */\nexport interface GraphHost {\n runNested(\n graph: unknown,\n task: string,\n options: {\n readonly budget: unknown\n readonly perNode?: unknown\n readonly runId: string\n readonly signal?: AbortSignal\n },\n ): Promise<{ readonly kind: string; readonly out?: unknown }>\n}\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 /** The engine hosting this node, for a kind that runs a graph of its own (`subgraph`). The\n * scheduler supplies it; a kind that does not nest ignores it. */\n readonly host?: GraphHost\n }) => Agent<unknown, unknown>\n}\n\n/**\n * A kind of ANY config shape — what a registry holds and what every engine signature accepts.\n *\n * `NodeKind<Config>` puts `Config` in a parameter position (`run({ config })`), so it is\n * contravariant: an array of differently-configured kinds is not assignable to\n * `ReadonlyArray<NodeKind<unknown>>`, and every caller composing a heterogeneous kind set would\n * need a cast. That cost belongs here, once, not at each consumer: a registry is heterogeneous by\n * definition, and each kind validates its own config at its own boundary through\n * `validateConfig`, which is where the type is actually enforced.\n */\nexport type AnyNodeKind = NodeKind<any, ReadonlyArray<EffectName>>\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: AnyNodeKind, context = 'registerNodeKind'): AnyNodeKind {\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 { AnyNodeKind, EffectName } 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<AnyNodeKind>\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<AnyNodeKind>\n}\n\nexport interface GraphEngine {\n readonly kinds: Registry<AnyNodeKind>\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<AnyNodeKind>('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 /** Next settle ordinal; the fold is the only writer, so replay reproduces the same order. */\n settleSeq: { value: number }\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 settleSeq: { value: 0 },\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 seq: state.settleSeq.value++,\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 seq: state.settleSeq.value++,\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 seq: state.settleSeq.value++,\n ...(ev.outRef !== undefined ? { outRef: ev.outRef } : {}),\n }\n instance.settle = settle\n state.nodes.get(suspension.node)?.settles.push(settle)\n }\n return\n }\n default:\n return\n }\n}\n\n/** Fold a loaded journal (append order) into scheduler state. */\nexport function foldGraphJournal(\n events: ReadonlyArray<SpawnEvent>,\n compiled: CompiledGraph,\n): GraphFoldState {\n const state = emptyFoldState(compiled)\n for (const ev of events) applyGraphFoldEvent(state, ev, compiled)\n return state\n}\n","/**\n * Join evaluation: which gating-edge outcomes release a node. Adopted whole from ADC's workflow\n * graph (agent-runtime#968) and kept PURE — the scheduler decides nothing here, so the rule can be\n * read, tested and reasoned about on its own.\n *\n * An edge settles SATISFIED / DEAD / FAILED per its source's LATEST completion. A release consumes\n * the outcomes that produced it; the caller re-arms them and marks any still-pending edge\n * consumed-once, so an OR-diamond's second completer never double-fires.\n */\nimport type { CompiledEdge } from './compile'\nimport type { JoinRule } from './definition'\nimport type { FoldEdge } from './fold'\n\nexport interface GatingEdge {\n readonly edge: CompiledEdge\n readonly folded: FoldEdge | undefined\n}\n\nexport interface JoinDecision {\n /** Whether the node releases now. */\n readonly release: boolean\n /** The edges whose outcomes produced this release — the ones a traversal cap judges. */\n readonly consuming: ReadonlyArray<GatingEdge>\n /** Whether the node can never release again on this wave (recorded like skipped-by-guard). */\n readonly blocked: boolean\n}\n\nconst NOTHING: JoinDecision = { release: false, consuming: [], blocked: false }\n\n/** Decide whether a node's gating edges release it, and which of them the release consumes. */\nexport function decideJoin(rule: JoinRule, gating: ReadonlyArray<GatingEdge>): JoinDecision {\n if (gating.length === 0) return NOTHING\n const settled = gating.filter((entry) => entry.folded && entry.folded.state !== 'pending')\n const satisfied = gating.filter((entry) => entry.folded?.state === 'satisfied')\n const failed = gating.filter((entry) => entry.folded?.state === 'failed')\n const allSettled = settled.length === gating.length\n switch (rule) {\n case 'all': {\n // A dead or failed edge can never satisfy an `all` join on this wave.\n const spoiled = gating.some(\n (entry) => entry.folded?.state === 'dead' || entry.folded?.state === 'failed',\n )\n const release = !spoiled && satisfied.length === gating.length\n return { release, consuming: release ? settled : [], blocked: false }\n }\n case 'any': {\n const first = satisfied[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'any_failed': {\n const first = failed[0]\n if (first === undefined) return { release: false, consuming: [], blocked: allSettled }\n return { release: true, consuming: [first], blocked: false }\n }\n case 'all_done':\n return { release: allSettled, consuming: allSettled ? settled : [], blocked: false }\n default:\n return NOTHING\n }\n}\n","/**\n * The 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 */\n/** Config for a nesting node: the inner graph, and the pool the inner run is given. */\nexport interface SubgraphKindConfig {\n readonly graph: unknown\n /** The inner run's conserved pool. Its spend is the inner pool's, never re-charged here. */\n readonly budget?: unknown\n readonly perNode?: unknown\n}\n\n/** A node carrying its own graph: it runs as a full engine run on the host's kinds and effects. */\nexport function subgraphKind(): NodeKind<SubgraphKindConfig> {\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 {\n graph: config.graph,\n ...(config.budget === undefined ? {} : { budget: config.budget }),\n ...(config.perNode === undefined ? {} : { perNode: config.perNode }),\n }\n },\n configSchema: {\n type: 'object',\n properties: { graph: { type: 'object' } },\n required: ['graph'],\n },\n inputs: [],\n outputs: [],\n effects: [],\n onCrash: 'restart',\n budget: 'metered',\n run: ({ config, profile, host }) => {\n const name = profile.name ?? 'subgraph'\n if (!host) {\n throw new ValidationError(\n `subgraph kind: node ${JSON.stringify(name)} needs its hosting engine; run it through the scheduler, which supplies one`,\n )\n }\n let artifact: ExecutorResult<unknown> | undefined\n const executor: Executor<unknown> = {\n runtime: 'inline',\n async execute(_task, signal): Promise<ExecutorResult<unknown>> {\n // The inner run is a FULL engine run on the host's kinds and effects: its own scope,\n // pool and journal tree, nested under this node's id so the two never collide.\n const inner = await host.runNested(config.graph, name, {\n budget: config.budget ?? { maxIterations: 1, maxTokens: 0 },\n ...(config.perNode === undefined ? {} : { perNode: config.perNode }),\n runId: `${name}:subgraph`,\n signal,\n })\n const out = { kind: inner.kind, out: inner.out }\n artifact = {\n outRef: contentAddress(out),\n out,\n // The inner run debits the pool it was given; this node reports the wall clock only.\n spent: { iterations: 1, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n }\n return artifact\n },\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact: () => {\n if (!artifact)\n throw new ValidationError(`subgraph: resultArtifact() read before execute()`)\n return artifact\n },\n }\n return {\n name,\n act: () => Promise.reject(new ValidationError('subgraph: act() is not the execution path')),\n executorSpec: { profile, harness: null, executor } as AgentSpec,\n } as Agent<unknown, unknown> & { executorSpec: AgentSpec }\n },\n }\n}\n\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 edge ledger: what the runtime actually DELIVERED across each edge. It is observability, not\n * a fold input (agent-runtime#974) — `edge-verdict` carries the scheduler's decision, and this\n * carries the delivery, so a change to what an optimizer wants to see never changes resume\n * semantics. Its ordinals live in their own namespace, outside the kernel's cursor.\n */\n\nimport type { SpawnJournal } from '../supervise/types'\nimport type { CompiledEdge } from './compile'\nimport type { GraphEdgeTraversal } from './scheduler-types'\n\nexport interface EdgeLedger {\n readonly entries: ReadonlyArray<GraphEdgeTraversal>\n record(\n edge: CompiledEdge,\n traversal: number,\n outcome: GraphEdgeTraversal['outcome'],\n reason?: string,\n ): Promise<void>\n}\n\n/** Open a ledger for one run; its ordinals continue past whatever a prior process recorded. */\nexport function createEdgeLedger(args: {\n readonly journal: SpawnJournal\n readonly runId: string\n readonly now: () => number\n readonly startSeq: number\n}): EdgeLedger {\n const entries: GraphEdgeTraversal[] = []\n let seq = args.startSeq\n return {\n entries,\n async record(edge, traversal, outcome, reason) {\n const spec = edge.spec\n const entry: GraphEdgeTraversal = {\n edge: edge.id,\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n traversal,\n outcome,\n ...(spec.directive !== undefined\n ? { directive: `${spec.directive.surface}/v${spec.directive.version}` }\n : {}),\n ...(spec.kind === 'data' ? { port: edge.toPort } : {}),\n ...(reason !== undefined ? { reason } : {}),\n }\n entries.push(entry)\n await args.journal.appendEvent(args.runId, {\n kind: 'edge',\n id: `graph:${spec.to.node}`,\n edge: {\n kind: spec.kind,\n from: spec.from.node,\n to: spec.to.node,\n ...(entry.directive !== undefined ? { directive: entry.directive } : {}),\n ...(entry.port !== undefined ? { port: entry.port } : {}),\n },\n traversal,\n outcome,\n bytes: 0,\n ...(reason !== undefined ? { reason } : {}),\n seq: seq++,\n at: new Date(args.now()).toISOString(),\n })\n },\n }\n}\n","/**\n * `runGraph` as an engine graph (agent-runtime#982, #975) — a COMPILER, not a second runtime.\n *\n * `graphFromRunGraph` lowers today's `AgentGraph` into the engine's vocabulary: one supervisor\n * root carrying the graph, one pinned `agent` node per worker, the authored `delegates`/`analyzes`\n * edges. That gives a `runGraph` consumer a first-class engine graph it can inspect, diff, and use\n * as the starting point for authoring one natively — the migration path #975 asked for.\n *\n * WHAT THIS DELIBERATELY DOES NOT DO: run it. `runGraph` executes through `superviseAgentGraph`,\n * exactly as it always has. An earlier version of this module wrapped that call in a one-node\n * engine run, which read as \"runGraph runs on the engine\" while changing nothing about execution\n * and costing a second journal tree, a second budget pool and a second `Scope`. A wrapper that\n * moves no behaviour is a second source of truth, so it is gone: the graph a consumer runs and the\n * graph they can inspect are produced from the same `AgentGraph`, and only one of them executes.\n *\n * The engine EXECUTES a graph a consumer authors directly (`runEngineGraph`), where nodes are\n * scheduled over `data` edges, guards decide traversal, and the fold makes it restartable.\n */\nimport { ValidationError } from '../../errors'\nimport type { AgentGraph, RunGraphOptions } from '../supervise/graph'\nimport type { EngineGraphEdge, EngineGraphNode, EngineGraphSpec } from './definition'\n\n/** The kind id the root node carries: a supervisor holding the whole `AgentGraph`. */\nexport const RUN_GRAPH_ROOT_KIND = 'supervisor/v1'\n\n/**\n * Compile an `AgentGraph` into the engine graph that describes it. Pure: nothing runs, nothing is\n * registered, no executor is built. A `delegates` edge is MODEL-fired (#971) — its target is\n * spawned by the supervisor through the coordination protocol — so every worker node is marked\n * `entry: false`, which is exactly what the engine's scheduler would honour if this graph were\n * handed to it.\n */\nexport function graphFromRunGraph(graph: AgentGraph, options: RunGraphOptions): EngineGraphSpec {\n const root = graph.nodes[0]\n if (root === undefined) throw new ValidationError('graphFromRunGraph: a graph needs a root node')\n const nodes: EngineGraphNode[] = graph.nodes.map((node, index) =>\n index === 0\n ? {\n id: node.id,\n kind: RUN_GRAPH_ROOT_KIND,\n config: {\n perWorker: options.perWorker ?? graph.budget,\n ...(options.maxLiveWorkers === undefined\n ? {}\n : { maxLiveWorkers: options.maxLiveWorkers }),\n },\n profile: node.profile,\n budget: graph.budget,\n terminal: true,\n deliverable: graph.deliverable,\n }\n : {\n id: node.id,\n kind: 'agent/v1',\n profile: node.profile,\n entry: false,\n terminal: false,\n budget: options.perWorker ?? graph.budget,\n },\n )\n const edges: EngineGraphEdge[] = graph.edges.flatMap((edge): EngineGraphEdge[] =>\n edge.kind === 'delegates'\n ? [\n {\n kind: 'delegates',\n from: { node: edge.from },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n },\n ]\n : // One engine edge per analysed source: engine edges are 1:1, the authored form fans in.\n edge.over.map((source) => ({\n kind: 'analyzes' as const,\n from: { node: source, port: 'trace' },\n to: { node: edge.to },\n directive: edge.directive,\n ...(edge.maxTraversals !== undefined ? { maxTraversals: edge.maxTraversals } : {}),\n })),\n )\n return { nodes, edges, root: root.id, deliverable: graph.deliverable }\n}\n","/**\n * Edge payload admission (agent-runtime#971): every value crossing an edge is JSON round-tripped,\n * `undefined` stripped to absence, and a non-representable value (a cycle, a BigInt, a function)\n * becomes a RECORD of that fact. This is the kernel's existing findings-guard rule, and it is what\n * makes `inputRef` stable and `onCrash: 'restart'` well defined — a degraded record beats a\n * vanished edge.\n */\nexport function admitPayload(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n const text = JSON.stringify(value)\n // JSON.stringify answers `undefined` for a bare function or symbol — record it, never vanish.\n if (text === undefined) return { nonCanonical: `payload of type ${typeof value}` }\n return JSON.parse(text)\n } catch (error) {\n return { nonCanonical: error instanceof Error ? error.message : String(error) }\n }\n}\n","/**\n * Turning a finished run into its result: rehydrate each settle's output, reduce the terminals\n * through the kernel's finalizer seam, and name the honest cause when nothing delivered\n * (agent-runtime#973). Separate from the loop so \"what happened\" is readable without reading\n * \"what ran\".\n */\nimport {\n bestDelivered,\n collectDelivered,\n type FinalizerSettled,\n runFinalizer,\n type SupervisorFinalizer,\n} from '../supervise/finalizer'\nimport { GraphEdgeCapError } from '../supervise/graph'\nimport type { ResultBlobStore, Scope } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport type { CompiledGraph } from './compile'\nimport type { GraphFoldState } from './fold'\nimport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\n\nexport type FinalizerChoice = 'bestDelivered' | 'collectDelivered' | SupervisorFinalizer\n\nfunction resolveFinalizer(choice: FinalizerChoice | undefined): SupervisorFinalizer {\n if (choice === undefined || choice === 'bestDelivered') return bestDelivered\n if (choice === 'collectDelivered') return collectDelivered\n return choice\n}\n\n/** Every node settlement with its output rehydrated and its completion check applied. */\nexport async function materializeSettles(\n compiled: CompiledGraph,\n state: GraphFoldState,\n blobs: ResultBlobStore,\n outCache: ReadonlyMap<string, unknown>,\n): Promise<GraphNodeSettle[]> {\n const rehydrate = async (settle: GraphNodeSettle): Promise<GraphNodeSettle> => {\n if (settle.out !== undefined || settle.outRef === undefined) return settle\n const out = outCache.get(settle.outRef) ?? admitPayload(await blobs.get(settle.outRef))\n const node = compiled.nodes.get(settle.node)\n let valid = settle.valid\n if (valid === undefined && node?.deliverable !== undefined && settle.status === 'done') {\n try {\n valid = await node.deliverable.check(out)\n } catch {\n valid = false\n }\n }\n return { ...settle, out, ...(valid !== undefined ? { valid } : {}) }\n }\n // Chronological, not grouped by node: the array reads in the order the run settled.\n return Promise.all(\n [...compiled.nodes.keys()]\n .flatMap((id) => state.nodes.get(id)?.settles ?? [])\n .sort((a, b) => a.seq - b.seq)\n .map(rehydrate),\n )\n}\n\n/** Turn a finished run into its result: rehydrate, reduce the terminals, classify a no-winner. */\nexport async function assembleGraphResult(args: {\n readonly compiled: CompiledGraph\n readonly state: GraphFoldState\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly outCache: ReadonlyMap<string, unknown>\n readonly ledger: ReadonlyArray<GraphEdgeTraversal>\n readonly finalizer?: FinalizerChoice\n readonly failure?: {\n readonly reason: GraphRunReason\n readonly error?: { name: string; message: string }\n }\n readonly aborted: boolean\n}): Promise<GraphRunResult> {\n const settles = await materializeSettles(args.compiled, args.state, args.blobs, args.outCache)\n const terminals = settles.filter((settle) => args.compiled.nodes.get(settle.node)?.terminal)\n const ledger = args.ledger\n\n // A capped edge that left the run winnerless is a NAMED failure, not a quiet no-winner (#973).\n const finish = (result: GraphRunResult): GraphRunResult => {\n if (result.kind === 'no-winner' && args.state.exhaustedEdges.size > 0) {\n throw new GraphEdgeCapError(\n Object.freeze([...args.state.exhaustedEdges]),\n Object.freeze([...ledger]) as never,\n result as never,\n )\n }\n return result\n }\n\n if (args.failure) {\n return finish({\n kind: 'no-winner',\n reason: args.failure.reason,\n ...(args.failure.error ? { error: args.failure.error } : {}),\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const allTerminalsSettled = args.compiled.terminals.every(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) > 0,\n )\n const pendingTokens = [...args.state.suspensions.values()]\n .filter((suspension) => suspension.status === 'pending')\n .map((suspension) => suspension.token)\n if (pendingTokens.length > 0 && !allTerminalsSettled) {\n return { kind: 'suspended', tokens: pendingTokens, terminals, settles, ledger }\n }\n if (args.aborted) {\n return finish({\n kind: 'no-winner',\n reason: 'aborted',\n terminals,\n settles,\n ledger,\n unreachable: [],\n })\n }\n const delivered = terminals.filter((settle) => settle.status === 'done' && settle.valid !== false)\n const out =\n delivered.length === 0\n ? undefined\n : await runFinalizer(resolveFinalizer(args.finalizer), {\n settled: terminals.map(\n (settle): FinalizerSettled => ({\n id: settle.node,\n status: settle.status,\n valid: settle.status === 'done' && settle.valid !== false,\n ...(settle.outRef !== undefined ? { outRef: settle.outRef } : {}),\n }),\n ),\n blobs: args.blobs,\n tree: args.scope.view,\n budget: args.scope.budget,\n })\n if (out !== undefined) return { kind: 'winner', out, terminals, settles, ledger }\n\n const unreachable = [...args.compiled.nodes.keys()].filter(\n (id) => (args.state.nodes.get(id)?.settles.length ?? 0) === 0,\n )\n const reason: GraphRunReason = args.compiled.terminals.some((id) => unreachable.includes(id))\n ? unreachable.length === args.compiled.nodes.size\n ? 'budget-exhausted'\n : 'unreachable-terminal'\n : 'all-children-down'\n return finish({ kind: 'no-winner', reason, terminals, settles, ledger, unreachable })\n}\n","/**\n * Opening a graph run: begin or resume the journaled tree, rebuild the pool and the kernel `Scope`\n * on the SAME recipe the kernel supervisor uses for its own resume, and fold the prior journal\n * into scheduler state. Extracted so the restart contract is one readable unit rather than a\n * preamble inside the loop.\n */\nimport {\n closesCursorSlot,\n InMemoryResultBlobStore,\n InMemorySpawnJournal,\n materializeTreeView,\n pendingWaits,\n replaySpawnTree,\n} from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { createBudgetPool } from '../supervise/budget'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createScope } from '../supervise/scope'\nimport {\n maxSeqOf,\n sumMeasuredSpendFromEvents,\n uncertainSpawnBudgets,\n} from '../supervise/supervisor'\nimport type { Budget, ResultBlobStore, Scope, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { addSpend } from '../util'\nimport type { CompiledGraph } from './compile'\nimport { applyGraphFoldEvent, emptyFoldState, type GraphFoldState } from './fold'\n\n/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter, so the two\n * counters can advance independently without ever colliding. */\nexport const ENGINE_WOKEN_SEQ_BASE = 10_000_000\n\nexport interface GraphRunContext {\n readonly runId: string\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly scope: Scope<unknown>\n readonly abort: AbortController\n readonly state: GraphFoldState\n readonly resuming: boolean\n /** Journal events present before this process started; empty on a fresh run. */\n readonly prior: ReadonlyArray<SpawnEvent>\n /** Next engine fold-event ordinal, and next engine `woken` ordinal. */\n readonly engineSeq: number\n readonly engineWokenSeq: number\n /** Ledger ordinals already used by a prior process. */\n readonly ledgerSeq: number\n}\n\n/** Begin or resume a run's journaled tree, pool, scope and folded state. */\nexport async function openGraphRun(args: {\n readonly compiled: CompiledGraph\n readonly runId: string\n readonly budget: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly now: () => number\n readonly resume?: boolean\n readonly signal?: AbortSignal\n readonly onAbort: (listener: () => void) => void\n}): Promise<GraphRunContext> {\n const journal = args.journal ?? new InMemorySpawnJournal()\n const blobs = args.blobs ?? new InMemoryResultBlobStore()\n const loaded = await journal.loadTree(args.runId)\n if (loaded !== undefined && args.resume !== true) {\n throw new ValidationError(\n `runEngineGraph: runId '${args.runId}' already exists; pass resume: true to continue it or use a new runId`,\n )\n }\n const prior = loaded ?? []\n const resuming = args.resume === true && prior.length > 0\n let runEpochMs = args.now()\n let rootBudget = args.budget\n if (loaded === undefined) {\n await journal.beginTree(args.runId, new Date(runEpochMs).toISOString())\n }\n if (resuming) {\n const root = prior.find((ev) => ev.kind === 'spawned' && ev.id === args.runId)\n if (root?.kind === 'spawned') {\n runEpochMs = Date.parse(root.at)\n rootBudget = root.budget\n }\n } else {\n // The engine's root anchor: what a restart reads its epoch and deadline from, exactly as the\n // kernel supervisor journals its own root. A begun-but-empty journal writes it here too.\n await journal.appendEvent(args.runId, {\n kind: 'spawned',\n id: args.runId,\n label: 'graph-root',\n budget: args.budget,\n runtime: 'inline',\n seq: 0,\n at: new Date(runEpochMs).toISOString(),\n })\n }\n\n const elapsed = () => args.now() - runEpochMs\n const measured = resuming ? sumMeasuredSpendFromEvents([...prior]) : undefined\n const pool = createBudgetPool(\n rootBudget,\n elapsed,\n measured === undefined\n ? undefined\n : {\n committed: addSpend(measured.childWork, measured.driverInference),\n uncertainReservations: uncertainSpawnBudgets([...prior]),\n ...(rootBudget.deadlineMs !== undefined\n ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs }\n : {}),\n },\n )\n const abort = new AbortController()\n if (args.signal !== undefined) {\n const forward = () => abort.abort(args.signal?.reason)\n args.signal.addEventListener('abort', forward, { once: true })\n args.onAbort(() => args.signal?.removeEventListener('abort', forward))\n if (args.signal.aborted) abort.abort(args.signal.reason)\n }\n const scope = createScope<unknown>({\n parentId: args.runId,\n root: args.runId,\n pool,\n journal,\n blobs,\n executors: createExecutorRegistry(),\n seams: {},\n depth: 0,\n signal: abort.signal,\n now: args.now,\n ...(resuming\n ? {\n resumeFrom: {\n settled: await replaySpawnTree(journal, blobs, args.runId),\n view: materializeTreeView([...prior]),\n maxSpawnOrdinal: maxSeqOf([...prior], (ev) => ev.kind === 'spawned'),\n maxCursorSeq: maxSeqOf([...prior], closesCursorSlot),\n maxWaitOrdinal: maxSeqOf([...prior], (ev) => ev.kind === 'waiting'),\n waits: pendingWaits([...prior]),\n keys: new Map(),\n priorSpend: sumMeasuredSpendFromEvents([...prior]),\n },\n }\n : {}),\n })\n\n const state = emptyFoldState(args.compiled)\n if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, args.compiled)\n\n return {\n runId: args.runId,\n journal,\n blobs,\n scope,\n abort,\n state,\n resuming,\n prior,\n engineSeq: resuming ? maxEngineSeq(prior) + 1 : 0,\n engineWokenSeq:\n ENGINE_WOKEN_SEQ_BASE +\n (resuming\n ? prior.filter((ev) => ev.kind === 'woken' && ev.seq >= ENGINE_WOKEN_SEQ_BASE).length\n : 0),\n ledgerSeq: prior.filter((ev) => ev.kind === 'edge').length,\n }\n}\n\nfunction maxEngineSeq(events: ReadonlyArray<SpawnEvent>): number {\n let max = -1\n for (const ev of events) {\n const engineEvent =\n ev.kind === 'node-inputs-resolved' ||\n ev.kind === 'edge-verdict' ||\n ev.kind === 'join-state' ||\n (ev.kind === 'waiting' && ev.spec.kind === 'token')\n if (engineEvent && ev.seq > max) max = ev.seq\n }\n return max\n}\n","/**\n * Suspensions (agent-runtime#976): a node parks on a host wake as the kernel's `waiting`/`woken`\n * pair. The engine owns the transition table; a host owns only how the wake arrives.\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\n\nconst SUSPEND_MARK = '__graphSuspension'\n\n/** What a kind's executor returns to park its node until a host wakes it. */\nexport interface SuspensionRequest {\n readonly [SUSPEND_MARK]: true\n readonly onExpire: 'wait' | 'fail' | 'default'\n /** Milliseconds from the suspension's journaling instant; absent with `onExpire: 'wait'`. */\n readonly expiresInMs?: number\n readonly default?: unknown\n}\n\n/** Build a suspension request. `wait` never expires; `fail` settles the node down at its deadline;\n * `default` resolves with the given payload. */\nexport function suspended(\n options: {\n readonly onExpire?: 'wait' | 'fail' | 'default'\n readonly expiresInMs?: number\n readonly default?: unknown\n } = {},\n): SuspensionRequest {\n const onExpire = options.onExpire ?? 'wait'\n if (onExpire !== 'wait' && options.expiresInMs === undefined) {\n throw new ValidationError(`suspended: onExpire '${onExpire}' requires expiresInMs`)\n }\n if (onExpire === 'wait' && options.expiresInMs !== undefined) {\n throw new ValidationError(\"suspended: onExpire 'wait' never expires — remove expiresInMs\")\n }\n if (onExpire === 'default' && options.default === undefined) {\n throw new ValidationError(\"suspended: onExpire 'default' requires a default payload\")\n }\n return {\n [SUSPEND_MARK]: true,\n onExpire,\n ...(options.expiresInMs !== undefined ? { expiresInMs: options.expiresInMs } : {}),\n ...(options.default !== undefined ? { default: options.default } : {}),\n }\n}\n\n/** Whether a node's output is a park request rather than its result. */\nexport function isSuspensionRequest(value: unknown): value is SuspensionRequest {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)[SUSPEND_MARK] === true\n )\n}\n\n/** Content-addressed over the run identity, so a restart recomputes it and needs no token table. */\nexport function mintSuspensionToken(runId: string, instance: string): string {\n return contentAddress({ runId, instance, kind: 'graph-suspension' })\n}\n\n/** The journal id one suspension's `waiting`/`woken` pair shares. */\nexport function suspensionNodeId(token: string): string {\n return `graphwait:${token}`\n}\n\n/** The token inside a suspension node id, or `undefined` for any other id. */\nexport function tokenFromSuspensionNodeId(id: string): string | undefined {\n return id.startsWith('graphwait:') ? id.slice('graphwait:'.length) : undefined\n}\n","/**\n * The engine scheduler (agent-runtime#980, durable per #974/#976): run a compiled graph by hosting\n * every node instance on one kernel `Scope`. The pool, the journal, the blob store and\n * cancellation are the kernel's; the scheduler owns only what a graph adds — releasing nodes over\n * guarded edges, delivering payloads and directives, the two cycle caps, and suspensions.\n *\n * DURABILITY — fold, never checkpoint. Every decision is journaled BEFORE its effect is visible\n * (blob-then-journal where a ref is minted), then applied to live state through the SAME reducer\n * (`applyGraphFoldEvent`) a restart replays the journal through. Kill the process at any journal\n * boundary and a restart re-enters the exact state: settled nodes restore from `outRef` and never\n * re-execute; a released-but-unspawned instance re-enters from its pinned `inputRef`; an in-flight\n * instance is in-doubt and re-enters per its kind's `onCrash`.\n *\n * The parts this file does NOT own, so it stays a loop and not a god object: payload admission\n * (`admit.ts`), the edge ledger (`ledger.ts`), the join rule (`join.ts`), suspension vocabulary\n * (`suspension.ts`), the journal/pool/scope bootstrap (`run-context.ts`), and result assembly\n * (`result.ts`).\n */\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { PromptRegistry } from '../supervise/prompt-registry'\nimport type { Budget, ResultBlobStore, Settled, SpawnEvent, SpawnJournal } from '../supervise/types'\nimport { admitPayload } from './admit'\nimport { type CompiledGraph, compileGraph, isEngineFired } from './compile'\nimport { evaluateCondition } from './condition'\nimport type { EngineGraphSpec } from './definition'\nimport type { GraphEngine } from './engine'\nimport { applyGraphFoldEvent, type FoldSuspension } from './fold'\nimport { decideJoin, type GatingEdge } from './join'\nimport { narrowEffects } from './kind'\nimport { createEdgeLedger } from './ledger'\nimport { applyProjection } from './projection'\nimport { assembleGraphResult, type FinalizerChoice } from './result'\nimport { openGraphRun } from './run-context'\nimport type { GraphNodeSettle, GraphRunReason, GraphRunResult } from './scheduler-types'\nimport {\n isSuspensionRequest,\n mintSuspensionToken,\n type SuspensionRequest,\n suspensionNodeId,\n} from './suspension'\n\nexport { admitPayload } from './admit'\nexport { ENGINE_WOKEN_SEQ_BASE } from './run-context'\nexport type {\n GraphEdgeTraversal,\n GraphNodeSettle,\n GraphRunReason,\n GraphRunResult,\n} from './scheduler-types'\nexport { type SuspensionRequest, suspended } from './suspension'\n\nexport interface GraphRunOptions {\n /** The run's conserved pool. */\n readonly budget: Budget\n /** Default per-instance reservation for nodes that declare no `budget` of their own.\n * Required when any such node exists — the engine invents no split. */\n readonly perNode?: Budget\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n /** Resolves `delegates`/`analyzes` directives; required when any edge carries one. */\n readonly prompts?: PromptRegistry\n /** How terminal settles reduce to `out`. Default `bestDelivered`. */\n readonly finalizer?: FinalizerChoice\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly runId?: string\n /** Continue an existing journaled run. An existing tree without this refuses, like the kernel. */\n readonly resume?: boolean\n /** Hold a fully-suspended run open for live `resume()` calls instead of returning\n * `{ kind: 'suspended' }`. Offline callers leave this off and restart later (#976). */\n readonly waitForWakes?: boolean\n}\n\n/** A live run: await `done`; deliver host wakes through `resume`/`expire` (#976). */\nexport interface GraphRunHandle {\n readonly done: Promise<GraphRunResult>\n resume(token: string, payload: unknown): Promise<void>\n expire(token: string): Promise<void>\n}\n\ninterface QueuedWake {\n readonly token: string\n readonly payload?: unknown\n readonly expire: boolean\n readonly settle: () => void\n readonly fail: (error: unknown) => void\n}\n\n/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs no\n * live host wakes. */\nexport async function runEngineGraph(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): Promise<GraphRunResult> {\n return createGraphRun(engine, spec, task, options).done\n}\n\n/**\n * Start (or resume) a graph run and return its handle: await `done` for the result; deliver host\n * wakes through `resume`/`expire` while it runs (#976).\n */\nexport function createGraphRun(\n engine: GraphEngine,\n spec: EngineGraphSpec | CompiledGraph,\n task: string,\n options: GraphRunOptions,\n): GraphRunHandle {\n const compiled = asCompiled(engine, spec)\n const wakes: QueuedWake[] = []\n let signalWake: () => void = () => {}\n let finished = false\n const done = runGraphLoop(engine, compiled, task, options, wakes, (fn) => {\n signalWake = fn\n }).finally(() => {\n finished = true\n })\n const queue = (token: string, payload: unknown, expire: boolean): Promise<void> => {\n if (finished) {\n return Promise.reject(\n new ValidationError(\n `graph resume: run completed; start a new run over the same journal to wake '${token}'`,\n ),\n )\n }\n return new Promise<void>((settle, fail) => {\n wakes.push({ token, payload, expire, settle, fail })\n signalWake()\n })\n }\n return {\n done,\n resume: (token, payload) => queue(token, payload, false),\n expire: (token) => queue(token, undefined, true),\n }\n}\n\nfunction asCompiled(engine: GraphEngine, spec: EngineGraphSpec | CompiledGraph): CompiledGraph {\n return 'nodes' in spec && spec.nodes instanceof Map\n ? (spec as CompiledGraph)\n : compileGraph(engine, spec as EngineGraphSpec)\n}\n\n/** Everything a run must be able to satisfy before it spends anything. */\nfunction assertRunnable(\n engine: GraphEngine,\n compiled: CompiledGraph,\n options: GraphRunOptions,\n): void {\n const context = 'runEngineGraph'\n for (const node of compiled.nodes.values()) {\n const missing = node.kind.effects.filter((name) => !(name in engine.effects))\n if (missing.length > 0) {\n throw new ValidationError(\n `${context}: node ${node.id} needs effect(s) ${missing.join(', ')} the host did not provide`,\n )\n }\n if (node.spec.budget === undefined && options.perNode === undefined) {\n throw new ValidationError(\n `${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`,\n )\n }\n }\n for (const edge of compiled.edges) {\n // Only an ENGINE-fired edge's directive is the scheduler's to resolve; a `delegates` directive\n // is resolved by the supervisor that spawns the target (#971).\n if (isEngineFired(edge) && edge.spec.directive !== undefined && options.prompts === undefined) {\n throw new ValidationError(\n `${context}: edge ${edge.id} carries a directive but options.prompts is absent`,\n )\n }\n }\n}\n\nasync function runGraphLoop(\n engine: GraphEngine,\n compiled: CompiledGraph,\n task: string,\n options: GraphRunOptions,\n wakes: QueuedWake[],\n onWakeSignal: (fn: () => void) => void,\n): Promise<GraphRunResult> {\n assertRunnable(engine, compiled, options)\n const now = options.now ?? Date.now\n const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`\n let detachOuterAbort: () => void = () => {}\n const context = await openGraphRun({\n compiled,\n runId,\n budget: options.budget,\n ...(options.journal !== undefined ? { journal: options.journal } : {}),\n ...(options.blobs !== undefined ? { blobs: options.blobs } : {}),\n now,\n ...(options.resume !== undefined ? { resume: options.resume } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n onAbort: (detach) => {\n detachOuterAbort = detach\n },\n })\n const { abort, blobs, journal, scope, state } = context\n const ledger = createEdgeLedger({ journal, runId, now, startSeq: context.ledgerSeq })\n let engineSeq = context.engineSeq\n let wokenSeq = context.engineWokenSeq\n\n const liveHandles = new Map<string, string>() // kernel node id -> engine instance label\n const waitingForBudget: string[] = []\n const outCache = new Map<string, unknown>()\n let liveCount = 0\n let failure: { reason: GraphRunReason; error?: { name: string; message: string } } | undefined\n\n /** Journal one engine event, then apply it through the reducer a restart will replay. */\n const emit = async (ev: SpawnEvent): Promise<void> => {\n await journal.appendEvent(runId, ev)\n applyGraphFoldEvent(state, ev, compiled)\n }\n const stamp = () => new Date(now()).toISOString()\n\n const fail = (reason: GraphRunReason, name: string, message: string): void => {\n failure = { reason, error: { name, message } }\n abort.abort(`${reason}: ${message}`)\n }\n\n // ── Spawning ───────────────────────────────────────────────────────────────────\n\n /** The ONE entry path: spawn a released instance from its journaled envelope. Used by a fresh\n * release, a budget-parked retry, and a restart re-entry alike. */\n const spawnInstance = async (label: string): Promise<void> => {\n if (failure) return\n const instance = state.instances.get(label)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node || instance.inputRef === undefined) {\n throw new ValidationError(`runEngineGraph: instance ${label} has no journaled envelope`)\n }\n const envelope = (await blobs.get(instance.inputRef)) as\n | { task: string; inputs: Record<string, unknown> }\n | undefined\n if (envelope === undefined) {\n throw new ValidationError(\n `runEngineGraph: envelope ${instance.inputRef} is not in the blob store`,\n )\n }\n const agent = node.kind.run({\n config: node.config,\n profile: { name: node.id, ...(node.spec.profile ?? {}) },\n inputs: envelope.inputs,\n effects: narrowEffects(node.kind.effects, engine.effects, `runEngineGraph: node ${node.id}`),\n // A nesting kind (`subgraph`) runs its inner graph on THIS engine — same kinds, same\n // effects — with its own scope, pool and journal tree under a derived run id.\n host: {\n runNested: (inner, task, opts) =>\n runEngineGraph(engine, inner as EngineGraphSpec, task, {\n budget: opts.budget as Budget,\n ...(opts.perNode === undefined ? {} : { perNode: opts.perNode as Budget }),\n journal,\n blobs,\n ...(options.prompts === undefined ? {} : { prompts: options.prompts }),\n runId: `${runId}:${opts.runId}`,\n ...(opts.signal === undefined ? {} : { signal: opts.signal }),\n now,\n }).then((result) => ({\n kind: result.kind,\n ...(result.kind === 'winner' ? { out: result.out } : {}),\n })),\n },\n })\n const budget = node.spec.budget ?? (options.perNode as Budget)\n const spawned = scope.spawn(agent, envelope.task, { label, budget })\n if (spawned.ok) {\n liveCount += 1\n liveHandles.set(spawned.handle.id, label)\n // The kernel journaled its own `spawned` row inside `scope.spawn`; mirror the two fields the\n // reducer folds, so live state matches what a restart reconstructs.\n applyGraphFoldEvent(\n state,\n {\n kind: 'spawned',\n id: spawned.handle.id,\n label,\n budget,\n runtime: 'inline',\n seq: 0,\n at: '',\n },\n compiled,\n )\n return\n }\n if (spawned.reason === 'budget-exhausted' || spawned.reason === 'max-live-workers') {\n waitingForBudget.push(label) // never overcommit: retry after the next settle frees capacity\n return\n }\n fail('driver-failed', 'SpawnRefused', `node ${node.id}: ${spawned.reason}`)\n }\n\n /** Pin an instance's envelope (inputs + task) by content address; answers the instance label. */\n const openInstance = async (\n nodeId: string,\n visit: number,\n envelope: { task: string; inputs: Record<string, unknown> },\n ): Promise<string> => {\n const label = `${nodeId}#${visit}`\n const inputRef = contentAddress(envelope)\n await blobs.put(inputRef, envelope)\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: nodeId,\n instance: label,\n inputRef,\n seq: engineSeq++,\n at: stamp(),\n })\n return label\n }\n\n const enterEntryNode = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) return\n await spawnInstance(await openInstance(nodeId, visit, { task, inputs: {} }))\n }\n\n // ── Releasing ──────────────────────────────────────────────────────────────────\n\n /** Build the released instance's envelope from its wave: data payloads projected and admitted,\n * directives resolved, trace refs lined up — every consumption ledgered as it is taken. */\n const consumeWave = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n ): Promise<{ task: string; inputs: Record<string, unknown> }> => {\n const inputs: Record<string, unknown> = {}\n const directives: string[] = []\n const traces: string[] = []\n for (const { edge, folded } of consuming) {\n const spec = edge.spec\n const traversal = (folded?.traversals ?? 0) + 1\n if (spec.kind === 'data' && folded?.state === 'satisfied') {\n let payload =\n folded.payloadRef === undefined\n ? undefined\n : (outCache.get(folded.payloadRef) ?? admitPayload(await blobs.get(folded.payloadRef)))\n let outcome: 'delivered' | 'empty' = 'delivered'\n let reason: string | undefined\n if (spec.projection !== undefined) {\n try {\n payload = admitPayload(applyProjection(payload, spec.projection, `edge ${edge.id}`))\n } catch (error) {\n outcome = 'empty'\n reason = error instanceof Error ? error.message : String(error)\n payload = undefined\n }\n }\n if (payload === undefined) outcome = 'empty'\n await ledger.record(edge, traversal, outcome, reason)\n if (payload !== undefined) inputs[edge.toPort] = payload\n continue\n }\n if (spec.directive !== undefined && options.prompts !== undefined) {\n directives.push(options.prompts.resolve(spec.directive).text)\n }\n if (spec.kind === 'analyzes' && folded?.state === 'satisfied') {\n traces.push(`trace of ${spec.from.node}: ${folded.payloadRef ?? '(no traceRef)'}`)\n }\n await ledger.record(edge, traversal, 'delivered')\n }\n const composed = [nodeId === compiled.root ? task : '', ...directives, ...traces]\n .filter((part) => part.length > 0)\n .join('\\n\\n')\n return { task: composed.length > 0 ? composed : task, inputs }\n }\n\n const release = async (\n nodeId: string,\n consuming: ReadonlyArray<GatingEdge>,\n consumedPending: ReadonlyArray<string>,\n ): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded) return\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n const envelope = await consumeWave(nodeId, consuming)\n const label = await openInstance(nodeId, visit, envelope)\n await emit({\n kind: 'join-state',\n id: label,\n node: nodeId,\n rule: node.join,\n satisfiedBy: consuming.map(({ edge }) => edge.id),\n consumedPending: [...consumedPending],\n instance: label,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n\n const tryRelease = async (nodeId: string): Promise<void> => {\n const node = compiled.nodes.get(nodeId)\n const folded = state.nodes.get(nodeId)\n if (!node || !folded || folded.blocked || failure) return\n const gating: GatingEdge[] = node.inbound.map((edge) => ({\n edge,\n folded: state.edges.get(edge.id),\n }))\n const decision = decideJoin(node.join, gating)\n if (decision.blocked) folded.blocked = true\n if (!decision.release) return\n // Caps are judged on the consuming edges BEFORE anything else happens, and the refusal is\n // journaled so a restart sees the same exhaustion.\n for (const entry of decision.consuming) {\n const cap = entry.edge.spec.maxTraversals\n if (cap !== undefined && (entry.folded?.traversals ?? 0) >= cap) {\n await ledger.record(\n entry.edge,\n (entry.folded?.traversals ?? 0) + 1,\n 'unpropagated',\n `traversal-cap-exhausted (max ${cap})`,\n )\n await emit({\n kind: 'edge-verdict',\n id: `graph:${nodeId}`,\n edge: entry.edge.id,\n fired: false,\n sourceStatus: 'done',\n capped: true,\n seq: engineSeq++,\n at: stamp(),\n })\n return\n }\n }\n const consumedPending = gating\n .filter(\n (entry) => entry.folded?.state === 'pending' && hasLiveInstance(entry.edge.spec.from.node),\n )\n .map((entry) => entry.edge.id)\n await release(nodeId, decision.consuming, consumedPending)\n }\n\n const hasLiveInstance = (nodeId: string): boolean => {\n for (const label of liveHandles.values()) {\n if (state.instances.get(label)?.node === nodeId) return true\n }\n return false\n }\n\n // ── Judging ────────────────────────────────────────────────────────────────────\n\n /** Journal a verdict for every unaccounted outbound edge of a settle, then try the joins. */\n const propagate = async (label: string, settle: GraphNodeSettle): Promise<void> => {\n const node = compiled.nodes.get(settle.node)\n if (!node) return\n const succeeded = settle.status === 'done' && settle.valid !== false\n const sourceSettles = state.nodes.get(settle.node)?.settles.length ?? 0\n for (const edge of node.outbound) {\n // A `delegates` target is spawned by its supervisor inside the kernel's authorized path,\n // with the pin and the directive applied there — the scheduler judges nothing (#971).\n if (!isEngineFired(edge)) continue\n const folded = state.edges.get(edge.id)\n if (!folded || folded.judgedSourceSettles >= sourceSettles) {\n // Accounted — by an earlier verdict, or absorbed by the wave that consumed it. This is\n // what makes propagate idempotent, so a restart may re-propagate every settled node.\n continue\n }\n let fired = false\n let inputRef: string | undefined\n if (succeeded) {\n fired =\n edge.spec.guard === undefined ||\n evaluateCondition(edge.spec.guard, {\n node: settle.node,\n out: settle.out,\n visits: state.nodes.get(settle.node)?.visits ?? 0,\n valid: settle.valid ?? true,\n })\n if (fired) {\n inputRef =\n edge.spec.kind === 'analyzes'\n ? (settle as { traceRef?: string }).traceRef\n : settle.outRef\n }\n }\n await emit({\n kind: 'edge-verdict',\n id: label,\n edge: edge.id,\n fired,\n sourceStatus: settle.status === 'down' ? 'down' : succeeded ? 'done' : 'invalid',\n ...(inputRef !== undefined ? { inputRef } : {}),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n for (const edge of node.outbound) {\n if (isEngineFired(edge)) await tryRelease(edge.spec.to.node)\n }\n }\n\n // ── Suspensions ────────────────────────────────────────────────────────────────\n\n const park = async (label: string, request: SuspensionRequest): Promise<void> => {\n const token = mintSuspensionToken(runId, label)\n let defaultRef: string | undefined\n if (request.default !== undefined) {\n const admitted = admitPayload(request.default)\n defaultRef = contentAddress(admitted)\n await blobs.put(defaultRef, admitted)\n }\n await emit({\n kind: 'waiting',\n id: suspensionNodeId(token),\n label,\n spec: {\n kind: 'token',\n token,\n onExpire: request.onExpire,\n ...(request.expiresInMs !== undefined ? { expiresAtMs: now() + request.expiresInMs } : {}),\n ...(defaultRef !== undefined ? { defaultRef } : {}),\n },\n armedAt: now(),\n seq: engineSeq++,\n at: stamp(),\n })\n }\n\n const wake = async (\n suspension: FoldSuspension,\n by: 'fired' | 'expired',\n outRef?: string,\n ): Promise<void> => {\n await emit({\n kind: 'woken',\n id: suspensionNodeId(suspension.token),\n by,\n ...(outRef !== undefined ? { outRef } : {}),\n seq: wokenSeq++,\n at: stamp(),\n })\n const settle = state.instances.get(suspension.instance)?.settle\n if (settle === undefined) return\n const out =\n settle.outRef === undefined ? undefined : admitPayload(await blobs.get(settle.outRef))\n if (settle.outRef !== undefined && out !== undefined) outCache.set(settle.outRef, out)\n await propagate(suspension.instance, out === undefined ? settle : { ...settle, out })\n }\n\n /** Expiries are engine-clocked, so an offline run transitions them without a host sweep (#976). */\n const expireDue = async (): Promise<boolean> => {\n let transitioned = false\n for (const suspension of [...state.suspensions.values()]) {\n if (suspension.status !== 'pending') continue\n if (suspension.expiresAtMs === undefined || now() < suspension.expiresAtMs) continue\n if (suspension.onExpire === 'fail') await wake(suspension, 'expired')\n else if (suspension.onExpire === 'default')\n await wake(suspension, 'fired', suspension.defaultRef)\n else continue\n transitioned = true\n }\n return transitioned\n }\n\n const drainWakes = async (): Promise<void> => {\n while (wakes.length > 0) {\n const request = wakes.shift()\n if (!request) return\n try {\n const suspension = state.suspensions.get(request.token)\n if (!suspension) throw new ValidationError(`graph resume: unknown token '${request.token}'`)\n if (suspension.status !== 'pending') {\n throw new ValidationError(`graph resume: token '${request.token}' already woken`)\n }\n if (request.expire) {\n await wake(\n suspension,\n suspension.onExpire === 'default' ? 'fired' : 'expired',\n suspension.onExpire === 'default' ? suspension.defaultRef : undefined,\n )\n } else {\n const admitted = admitPayload(request.payload)\n const outRef = contentAddress(admitted)\n await blobs.put(outRef, admitted)\n outCache.set(outRef, admitted)\n await wake(suspension, 'fired', outRef)\n }\n request.settle()\n } catch (error) {\n request.fail(error)\n }\n }\n }\n\n // ── Settling ───────────────────────────────────────────────────────────────────\n\n const handleSettle = async (settled: Settled<unknown>): Promise<void> => {\n const label = liveHandles.get(settled.handle.id)\n if (label === undefined) return\n liveHandles.delete(settled.handle.id)\n liveCount -= 1\n const instance = state.instances.get(label)\n const node = instance === undefined ? undefined : compiled.nodes.get(instance.node)\n if (!instance || !node) return\n if (settled.kind === 'done' && isSuspensionRequest(settled.out)) {\n await park(label, settled.out)\n return\n }\n // Mirror the kernel's own journaled settle through the reducer, then enrich it for judging.\n applyGraphFoldEvent(\n state,\n {\n kind: 'settled',\n id: settled.handle.id,\n status: settled.kind === 'done' ? 'done' : 'down',\n ...(settled.kind === 'done' ? { outRef: settled.outRef } : {}),\n ...(settled.kind === 'down' ? { reason: settled.reason } : {}),\n ...(settled.kind === 'done' && settled.trace?.status === 'available'\n ? { trace: settled.trace }\n : {}),\n spent: { iterations: 0, tokens: { input: 0, output: 0 }, usd: 0, ms: 0 },\n seq: 0,\n at: '',\n },\n compiled,\n )\n const folded = state.instances.get(label)?.settle\n if (!folded) return\n let enriched = folded\n if (settled.kind === 'done') {\n const admitted = admitPayload(settled.out)\n if (settled.outRef !== undefined) outCache.set(settled.outRef, admitted)\n enriched = { ...folded, out: admitted, ...(await checkDeliverable(node, admitted)) }\n const settles = state.nodes.get(instance.node)?.settles\n if (settles) settles[settles.length - 1] = enriched\n ;(state.instances.get(label) as { settle?: GraphNodeSettle }).settle = enriched\n }\n // Root completion ends the run the moment its check passes (#973).\n if (instance.node === compiled.root && enriched.status === 'done' && enriched.valid === true) {\n abort.abort('root delivered')\n return\n }\n await propagate(label, enriched)\n }\n\n const checkDeliverable = async (\n node: CompiledGraph['nodes'] extends ReadonlyMap<string, infer N> ? N : never,\n out: unknown,\n ): Promise<{ valid?: boolean }> => {\n if (node.deliverable === undefined) return {}\n try {\n return { valid: await node.deliverable.check(out) }\n } catch {\n return { valid: false }\n }\n }\n\n // ── Entry / restart ────────────────────────────────────────────────────────────\n\n if (!context.resuming) {\n for (const id of compiled.entries) await enterEntryNode(id)\n } else {\n await reenterAfterCrash()\n }\n\n /** Kill-anywhere re-entry: finish every half-done transition the crashed process left, from the\n * pinned envelopes and journaled settles only — never by re-deriving anything (#974). */\n async function reenterAfterCrash(): Promise<void> {\n for (const instance of [...state.instances.values()]) {\n if (instance.status === 'released') {\n await spawnInstance(instance.instance)\n continue\n }\n if (instance.status !== 'live') continue\n const node = compiled.nodes.get(instance.node)\n const folded = state.nodes.get(instance.node)\n if (!node || !folded) continue\n const visit = folded.visits + 1\n if (visit > node.maxVisits) {\n fail(\n 'cycle-budget-exceeded',\n 'GraphCycleBudget',\n `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`,\n )\n return\n }\n // In-doubt: the journal keeps its reservation charged (the kernel's rule), and the restart\n // re-enters from the SAME pinned envelope.\n instance.status = 'down'\n const label = `${instance.node}#${visit}`\n await emit({\n kind: 'node-inputs-resolved',\n id: label,\n node: instance.node,\n instance: label,\n inputRef: instance.inputRef as string,\n seq: engineSeq++,\n at: stamp(),\n })\n await spawnInstance(label)\n }\n for (const [nodeId, folded] of state.nodes) {\n const latest = folded.settles.at(-1)\n if (latest === undefined) continue\n const label = `${nodeId}#${latest.visit}`\n if (latest.status === 'done' && latest.outRef !== undefined) {\n const out = admitPayload(await blobs.get(latest.outRef))\n if (isSuspensionRequest(out)) {\n // Killed between the kernel settle and the `waiting` event: finish the transition\n // instead of propagating the park marker as data.\n folded.settles.pop()\n const instance = state.instances.get(label)\n if (instance) instance.settle = undefined\n await park(label, out)\n continue\n }\n outCache.set(latest.outRef, out)\n const node = compiled.nodes.get(nodeId)\n await propagate(label, {\n ...latest,\n out,\n ...(node === undefined ? {} : await checkDeliverable(node, out)),\n })\n continue\n }\n await propagate(label, latest)\n }\n for (const id of compiled.entries) {\n if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id)\n }\n for (const id of compiled.nodes.keys()) await tryRelease(id)\n }\n\n // ── The loop ───────────────────────────────────────────────────────────────────\n\n const allTerminalsSettled = () =>\n compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0)\n\n let wakeSignal = Promise.resolve()\n const rearmWakeSignal = () => {\n wakeSignal = new Promise<void>((fire) => {\n onWakeSignal(fire)\n })\n }\n rearmWakeSignal()\n\n let pendingNext: Promise<Settled<unknown> | null> | undefined\n while (!failure) {\n if (await expireDue()) continue\n if (wakes.length > 0) {\n await drainWakes()\n continue\n }\n if (allTerminalsSettled()) break\n if (liveCount === 0) {\n const parked = [...state.suspensions.values()].filter(\n (suspension) => suspension.status === 'pending',\n )\n if (parked.length === 0) break // stuck or complete: `assembleGraphResult` classifies it\n if (options.waitForWakes) {\n rearmWakeSignal()\n await wakeSignal\n continue\n }\n // Offline (#976): no host will answer, so a `default` suspension resolves now; `wait` and a\n // future `fail` deadline park the run as a resumable artifact.\n const defaulting = parked.filter((suspension) => suspension.onExpire === 'default')\n if (defaulting.length === 0) break\n for (const suspension of defaulting) await wake(suspension, 'fired', suspension.defaultRef)\n continue\n }\n pendingNext ??= scope.next()\n const raced = await Promise.race([\n pendingNext.then((settle) => ({ settle })),\n wakeSignal.then(() => 'wake' as const),\n ])\n if (raced === 'wake') {\n rearmWakeSignal()\n continue // the queued wakes run on the next turn; `pendingNext` stays armed\n }\n pendingNext = undefined\n if (raced.settle === null) break\n await handleSettle(raced.settle)\n for (const label of waitingForBudget.splice(0)) await spawnInstance(label)\n }\n\n detachOuterAbort()\n abort.abort('graph loop complete')\n while ((await (pendingNext ?? scope.next())) !== null) pendingNext = undefined\n\n return assembleGraphResult({\n compiled,\n state,\n blobs,\n scope,\n outCache,\n ledger: ledger.entries,\n ...(options.finalizer !== undefined ? { finalizer: options.finalizer } : {}),\n ...(failure !== undefined ? { failure } : {}),\n aborted: options.signal?.aborted ?? false,\n })\n}\n"],"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,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QAAQ,eAAe,WAAW,aAAa,SAAS;GAClF,IAAI,WAAW,WAAW,GAAG;GAC7B,KAAK,MAAM,cAAc,YAAY,MAAM,KAAK,YAAY,SAAS,WAAW,UAAU;GAC1F;EACF;EACA,gBAAgB,MAAM,KAAK;EAC3B,MAAM,QAAQ,MAAM,QAAQ,KAAK,CAC/B,YAAY,MAAM,YAAY,EAAE,OAAO,EAAE,GACzC,WAAW,WAAW,MAAe,CACvC,CAAC;EACD,IAAI,UAAU,QAAQ;GACpB,gBAAgB;GAChB;EACF;EACA,cAAc,KAAA;EACd,IAAI,MAAM,WAAW,MAAM;EAC3B,MAAM,aAAa,MAAM,MAAM;EAC/B,KAAK,MAAM,SAAS,iBAAiB,OAAO,CAAC,GAAG,MAAM,cAAc,KAAK;CAC3E;CAEA,iBAAiB;CACjB,MAAM,MAAM,qBAAqB;CACjC,OAAQ,OAAO,eAAe,MAAM,KAAK,OAAQ,MAAM,cAAc,KAAA;CAErE,OAAO,oBAAoB;EACzB;EACA;EACA;EACA;EACA;EACA,QAAQ,OAAO;EACf,GAAI,QAAQ,cAAc,KAAA,IAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC1E,GAAI,YAAY,KAAA,IAAY,EAAE,QAAQ,IAAI,CAAC;EAC3C,SAAS,QAAQ,QAAQ,WAAW;CACtC,CAAC;AACH"}
|
package/dist/testing.js
CHANGED
|
@@ -6,7 +6,7 @@ import { SANDBOX_SIZE_PRESET_NAMES } from "@tangle-network/agent-interface";
|
|
|
6
6
|
//#region src/testing/fixtures/agent-improvement-proposal.json
|
|
7
7
|
var agent_improvement_proposal_default = {
|
|
8
8
|
changedSurfaces: ["prompt"],
|
|
9
|
-
digest: "sha256:
|
|
9
|
+
digest: "sha256:11d743eaab24db35601c84e2f17a7b36dbf2974fb5678838360293f220a969ef",
|
|
10
10
|
evaluation: {
|
|
11
11
|
"decision": {
|
|
12
12
|
"contributingChecks": [
|
|
@@ -4577,7 +4577,7 @@ var agent_improvement_proposal_default = {
|
|
|
4577
4577
|
],
|
|
4578
4578
|
"metadata": {
|
|
4579
4579
|
"fixture": "agent-improvement-proposal",
|
|
4580
|
-
"runtimeVersion": "0.
|
|
4580
|
+
"runtimeVersion": "0.168.0"
|
|
4581
4581
|
},
|
|
4582
4582
|
"objectives": [
|
|
4583
4583
|
{
|
|
@@ -4688,8 +4688,8 @@ var agent_improvement_proposal_default = {
|
|
|
4688
4688
|
"baselineContentHash": "sha256:5c21ee53e513fc604cb09754e21c392b24a424da0ef37dbf8f1ee4a8a0b08f09",
|
|
4689
4689
|
"candidateContentHash": "sha256:60fcbb1c728194bd51d7d19cb732d1c3f1881dce7e0a6266b41c8b98cfd65693",
|
|
4690
4690
|
"kind": "agent-eval-loop",
|
|
4691
|
-
"recordDigest": "sha256:
|
|
4692
|
-
"runId": "agent-runtime-0.
|
|
4691
|
+
"recordDigest": "sha256:aa5899c94f12c8551e49a34eed6a273e3eaa576edfc29f08fccae2f587b692b6",
|
|
4692
|
+
"runId": "agent-runtime-0.168.0-proposal-fixture",
|
|
4693
4693
|
"schema": "agent-candidate-experiment"
|
|
4694
4694
|
}
|
|
4695
4695
|
},
|
|
@@ -4712,13 +4712,13 @@ var agent_improvement_proposal_default = {
|
|
|
4712
4712
|
}],
|
|
4713
4713
|
kind: "agent-improvement-proposal",
|
|
4714
4714
|
proposedAt: "2026-07-10T01:00:00.000Z",
|
|
4715
|
-
runId: "agent-runtime-0.
|
|
4715
|
+
runId: "agent-runtime-0.168.0-proposal-fixture"
|
|
4716
4716
|
};
|
|
4717
4717
|
//#endregion
|
|
4718
4718
|
//#region src/testing/fixtures/agent-profile-improvement-proposal.json
|
|
4719
4719
|
var agent_profile_improvement_proposal_default = {
|
|
4720
4720
|
changedSurfaces: ["prompt", "skills"],
|
|
4721
|
-
digest: "sha256:
|
|
4721
|
+
digest: "sha256:c869e70215e5f34bf9fc72edbfab994e0591db72eaab5bbc43fd2506867a2c1f",
|
|
4722
4722
|
evaluation: {
|
|
4723
4723
|
"decision": {
|
|
4724
4724
|
"contributingChecks": [
|
|
@@ -6352,7 +6352,7 @@ var agent_profile_improvement_proposal_default = {
|
|
|
6352
6352
|
],
|
|
6353
6353
|
"metadata": {
|
|
6354
6354
|
"fixture": "agent-profile-improvement-proposal",
|
|
6355
|
-
"runtimeVersion": "0.
|
|
6355
|
+
"runtimeVersion": "0.168.0"
|
|
6356
6356
|
},
|
|
6357
6357
|
"objectives": [
|
|
6358
6358
|
{
|
|
@@ -6463,7 +6463,7 @@ var agent_profile_improvement_proposal_default = {
|
|
|
6463
6463
|
"baselineContentHash": "sha256:21c495a37c418c10bde64fbaa188beddeed31f1f051ea60a6a6582a9ee0db704",
|
|
6464
6464
|
"candidateContentHash": "sha256:103f77bc8481601eef1ad5fe6ba84a40dffabc3a44f421f8c8559121edab84e9",
|
|
6465
6465
|
"kind": "agent-eval-loop",
|
|
6466
|
-
"recordDigest": "sha256:
|
|
6466
|
+
"recordDigest": "sha256:3fd2e658bd7ce49643b936205aa5701f516f415d751f935ee05cb8e8ab30d0a2",
|
|
6467
6467
|
"runId": "profile-improvement-1",
|
|
6468
6468
|
"schema": "agent-profile-improvement-experiment"
|
|
6469
6469
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.168.0",
|
|
4
4
|
"description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-runtime#readme",
|
|
6
6
|
"repository": {
|