@fbp/evaluator 1.5.0 → 1.7.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/cycles.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { Edge } from '@fbp/types';
2
+ /**
3
+ * Find a dependency cycle among the named nodes, the way pgpm's dependency
4
+ * resolver does: walk upstream depth-first, keeping the nodes still being
5
+ * resolved on a stack. Reaching a node that is already on the stack means the
6
+ * graph loops back on itself.
7
+ *
8
+ * Nodes are visited in the order given and their upstream sources in edge
9
+ * order, so the reported cycle is stable for a given graph. Edges to or from
10
+ * nodes not in `nodeNames` are ignored (they are dangling, not cyclic).
11
+ *
12
+ * @returns the cycle as an ordered path that starts and ends on the same node
13
+ * (`['a', 'b', 'a']` for a -> b -> a, `['a', 'a']` for a self-loop), or
14
+ * `null` when the graph is acyclic.
15
+ */
16
+ export declare function findCycle(nodeNames: string[], edges: Edge[]): string[] | null;
17
+ /** Format a cycle path for error messages: `a -> b -> a`. */
18
+ export declare function formatCycle(path: string[]): string;
package/cycles.js ADDED
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findCycle = findCycle;
4
+ exports.formatCycle = formatCycle;
5
+ /**
6
+ * Find a dependency cycle among the named nodes, the way pgpm's dependency
7
+ * resolver does: walk upstream depth-first, keeping the nodes still being
8
+ * resolved on a stack. Reaching a node that is already on the stack means the
9
+ * graph loops back on itself.
10
+ *
11
+ * Nodes are visited in the order given and their upstream sources in edge
12
+ * order, so the reported cycle is stable for a given graph. Edges to or from
13
+ * nodes not in `nodeNames` are ignored (they are dangling, not cyclic).
14
+ *
15
+ * @returns the cycle as an ordered path that starts and ends on the same node
16
+ * (`['a', 'b', 'a']` for a -> b -> a, `['a', 'a']` for a self-loop), or
17
+ * `null` when the graph is acyclic.
18
+ */
19
+ function findCycle(nodeNames, edges) {
20
+ const known = new Set(nodeNames);
21
+ const upstream = new Map();
22
+ for (const edge of edges) {
23
+ const src = edge.src?.node;
24
+ const dst = edge.dst?.node;
25
+ if (!known.has(src) || !known.has(dst))
26
+ continue;
27
+ let sources = upstream.get(dst);
28
+ if (!sources) {
29
+ sources = [];
30
+ upstream.set(dst, sources);
31
+ }
32
+ sources.push(src);
33
+ }
34
+ const resolved = new Set();
35
+ const stack = [];
36
+ const onStack = new Set();
37
+ const visit = (name) => {
38
+ if (resolved.has(name))
39
+ return null;
40
+ if (onStack.has(name)) {
41
+ return [...stack.slice(stack.indexOf(name)), name].reverse();
42
+ }
43
+ stack.push(name);
44
+ onStack.add(name);
45
+ for (const src of upstream.get(name) ?? []) {
46
+ const cycle = visit(src);
47
+ if (cycle)
48
+ return cycle;
49
+ }
50
+ stack.pop();
51
+ onStack.delete(name);
52
+ resolved.add(name);
53
+ return null;
54
+ };
55
+ for (const name of nodeNames) {
56
+ const cycle = visit(name);
57
+ if (cycle)
58
+ return cycle;
59
+ }
60
+ return null;
61
+ }
62
+ /** Format a cycle path for error messages: `a -> b -> a`. */
63
+ function formatCycle(path) {
64
+ return path.join(' -> ');
65
+ }
package/esm/cycles.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Find a dependency cycle among the named nodes, the way pgpm's dependency
3
+ * resolver does: walk upstream depth-first, keeping the nodes still being
4
+ * resolved on a stack. Reaching a node that is already on the stack means the
5
+ * graph loops back on itself.
6
+ *
7
+ * Nodes are visited in the order given and their upstream sources in edge
8
+ * order, so the reported cycle is stable for a given graph. Edges to or from
9
+ * nodes not in `nodeNames` are ignored (they are dangling, not cyclic).
10
+ *
11
+ * @returns the cycle as an ordered path that starts and ends on the same node
12
+ * (`['a', 'b', 'a']` for a -> b -> a, `['a', 'a']` for a self-loop), or
13
+ * `null` when the graph is acyclic.
14
+ */
15
+ export function findCycle(nodeNames, edges) {
16
+ const known = new Set(nodeNames);
17
+ const upstream = new Map();
18
+ for (const edge of edges) {
19
+ const src = edge.src?.node;
20
+ const dst = edge.dst?.node;
21
+ if (!known.has(src) || !known.has(dst))
22
+ continue;
23
+ let sources = upstream.get(dst);
24
+ if (!sources) {
25
+ sources = [];
26
+ upstream.set(dst, sources);
27
+ }
28
+ sources.push(src);
29
+ }
30
+ const resolved = new Set();
31
+ const stack = [];
32
+ const onStack = new Set();
33
+ const visit = (name) => {
34
+ if (resolved.has(name))
35
+ return null;
36
+ if (onStack.has(name)) {
37
+ return [...stack.slice(stack.indexOf(name)), name].reverse();
38
+ }
39
+ stack.push(name);
40
+ onStack.add(name);
41
+ for (const src of upstream.get(name) ?? []) {
42
+ const cycle = visit(src);
43
+ if (cycle)
44
+ return cycle;
45
+ }
46
+ stack.pop();
47
+ onStack.delete(name);
48
+ resolved.add(name);
49
+ return null;
50
+ };
51
+ for (const name of nodeNames) {
52
+ const cycle = visit(name);
53
+ if (cycle)
54
+ return cycle;
55
+ }
56
+ return null;
57
+ }
58
+ /** Format a cycle path for error messages: `a -> b -> a`. */
59
+ export function formatCycle(path) {
60
+ return path.join(' -> ');
61
+ }
package/esm/evaluate.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { derivePorts, derivePropDefinitions, isRef, joinPath, parsePath, resolveRef } from '@fbp/spec';
2
+ import { findCycle, formatCycle } from './cycles';
1
3
  /**
2
4
  * Build a definition map key from context, category, and name.
3
5
  */
@@ -28,7 +30,51 @@ function parseTaskIdentifier(type) {
28
30
  * @returns Promise resolving to the value at the specified output port
29
31
  */
30
32
  export async function evaluate(graph, options) {
31
- const { definitions, outputNode, outputPort, inputs = {}, props = {} } = options;
33
+ const outputs = await openGraph(graph, options, [])(options.outputNode);
34
+ return outputs[options.outputPort];
35
+ }
36
+ /**
37
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
38
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
39
+ */
40
+ export function refEdges(nodes, scopePath = []) {
41
+ const names = new Set(nodes.map(n => n.name));
42
+ const scope = joinPath(scopePath);
43
+ const edges = [];
44
+ for (const node of nodes) {
45
+ for (const prop of node.props ?? []) {
46
+ if (!isRef(prop.value))
47
+ continue;
48
+ let target;
49
+ try {
50
+ target = resolveRef(scope, prop.value.ref);
51
+ }
52
+ catch {
53
+ continue;
54
+ }
55
+ const segments = parsePath(target.path);
56
+ const sibling = segments[segments.length - 1];
57
+ if (target.prop === undefined && sibling !== undefined && names.has(sibling) &&
58
+ joinPath(segments.slice(0, -1)) === scope) {
59
+ edges.push({ src: { node: sibling, port: 'value' }, dst: { node: node.name, port: prop.name } });
60
+ }
61
+ }
62
+ }
63
+ return edges;
64
+ }
65
+ /**
66
+ * @param assetPath - definition keys of the digital assets being evaluated,
67
+ * outermost first, so an asset that contains itself throws instead of
68
+ * recursing forever.
69
+ */
70
+ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
71
+ const { definitions, inputs = {}, props = {}, absent } = options;
72
+ // Reject cycles up front, as the validator and the SQL gate do: pulling
73
+ // through a loop would otherwise recurse until the stack overflows.
74
+ const cycle = findCycle(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
75
+ if (cycle) {
76
+ throw new Error(`Graph "${graph.name}" contains a cycle: ${formatCycle(cycle)}`);
77
+ }
32
78
  // Build lookup maps
33
79
  const nodeMap = new Map();
34
80
  for (const node of graph.nodes) {
@@ -56,6 +102,42 @@ export async function evaluate(graph, options) {
56
102
  }
57
103
  // Cache for evaluated node outputs to avoid re-evaluation
58
104
  const cache = new Map();
105
+ /**
106
+ * Resolve a prop value: a `{ ref }` takes the value of the node it points at
107
+ * (its `value` output, or the named prop for a '.prop' reference). The target
108
+ * is in this scope or one that encloses it.
109
+ */
110
+ async function resolve(value, holder, chain = []) {
111
+ if (!isRef(value))
112
+ return value;
113
+ const target = resolveRef(joinPath(scopePath), value.ref);
114
+ const segments = parsePath(target.path);
115
+ const name = segments[segments.length - 1];
116
+ const owner = segments.slice(0, -1).join('/');
117
+ let found = scope;
118
+ while (found && found.path.join('/') !== owner)
119
+ found = found.parent;
120
+ if (!found || name === undefined || !found.getNode(name)) {
121
+ throw new Error(`Reference "${value.ref}" on node "${holder}" does not point at a node in its scope or an enclosing one`);
122
+ }
123
+ if (target.prop !== undefined) {
124
+ const key = `${target.path}.${target.prop}`;
125
+ if (chain.includes(key)) {
126
+ throw new Error(`Reference "${value.ref}" on node "${holder}" refers back to itself`);
127
+ }
128
+ const prop = found.getNode(name).props?.find(p => p.name === target.prop);
129
+ return found.resolve(prop?.value, name, [...chain, key]);
130
+ }
131
+ const outputs = await found.evaluateNode(name);
132
+ return 'value' in outputs ? outputs.value : Object.values(outputs)[0];
133
+ }
134
+ const scope = {
135
+ path: scopePath,
136
+ parent: parentScope,
137
+ getNode: name => nodeMap.get(name),
138
+ evaluateNode: name => evaluateNode(name),
139
+ resolve
140
+ };
59
141
  /**
60
142
  * Recursively evaluate a node and return all its outputs.
61
143
  * Fully async to support async node implementations.
@@ -75,6 +157,11 @@ export async function evaluate(graph, options) {
75
157
  // Get the port name from the portName property
76
158
  const portNameProp = node.props?.find(p => p.name === 'portName');
77
159
  const inputName = portNameProp?.value || nodeName;
160
+ // A wired input whose arm was not taken stays dark, default or not, as it would in the flat graph.
161
+ if (absent?.has(inputName)) {
162
+ cache.set(nodeName, {});
163
+ return {};
164
+ }
78
165
  // Check external inputs first, then fall back to node's default prop
79
166
  let value = inputs[inputName];
80
167
  if (value === undefined) {
@@ -89,7 +176,10 @@ export async function evaluate(graph, options) {
89
176
  // Get the prop name from the propName property
90
177
  const propNameProp = node.props?.find(p => p.name === 'propName');
91
178
  const propName = propNameProp?.value || nodeName;
92
- const value = props[propName];
179
+ let value = props[propName];
180
+ if (value === undefined) {
181
+ value = node.props?.find(p => p.name === 'default')?.value;
182
+ }
93
183
  const result = { value };
94
184
  cache.set(nodeName, result);
95
185
  return result;
@@ -102,6 +192,10 @@ export async function evaluate(graph, options) {
102
192
  if (edges.length > 0) {
103
193
  const edge = edges[0];
104
194
  const upstreamOutputs = await evaluateNode(edge.src.node);
195
+ if (!(edge.src.port in upstreamOutputs)) {
196
+ cache.set(nodeName, {});
197
+ return {};
198
+ }
105
199
  value = upstreamOutputs[edge.src.port];
106
200
  }
107
201
  const result = { value };
@@ -109,48 +203,49 @@ export async function evaluate(graph, options) {
109
203
  return result;
110
204
  }
111
205
  // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
112
- if (node.type === 'subnet' && node.nodes && node.edges) {
206
+ if (node.type === 'subnet' && node.nodes) {
207
+ // The interface is derived from the boundary nodes inside the subnet.
208
+ const derived = derivePorts(node);
209
+ const inputPorts = node.inputs ?? derived.inputs;
210
+ const outputPorts = node.outputs ?? derived.outputs;
113
211
  // Collect inputs for the subnet by evaluating upstream nodes
114
212
  const subnetInputs = {};
213
+ const absentInputs = new Set();
115
214
  const subnetPortEdges = edgesByDst.get(nodeName);
116
- if (node.inputs && subnetPortEdges) {
117
- for (const inputPort of node.inputs) {
215
+ if (subnetPortEdges) {
216
+ for (const inputPort of inputPorts) {
118
217
  const edges = subnetPortEdges.get(inputPort.name) ?? [];
119
218
  if (edges.length > 0) {
120
219
  const edge = edges[0];
121
220
  const upstreamOutputs = await evaluateNode(edge.src.node);
122
- subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
221
+ if (edge.src.port in upstreamOutputs) {
222
+ subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
223
+ }
224
+ else {
225
+ absentInputs.add(inputPort.name);
226
+ }
123
227
  }
124
228
  }
125
229
  }
126
- // Find the output boundary nodes in the subnet
230
+ // Promoted parameters: the value set on the subnet node, else the graphProp's default.
231
+ const subnetProps = {};
232
+ for (const propDef of derivePropDefinitions(node)) {
233
+ const instanceProp = node.props?.find(p => p.name === propDef.name);
234
+ if (instanceProp !== undefined && instanceProp.value !== undefined) {
235
+ subnetProps[propDef.name] = await resolve(instanceProp.value, nodeName);
236
+ }
237
+ }
238
+ // One evaluation of the inner graph serves every output port.
239
+ const pull = openGraph({ name: `${nodeName}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
127
240
  const subnetOutputs = {};
128
- if (node.outputs) {
129
- for (const outputPort of node.outputs) {
130
- // Find the graphOutput boundary node by matching portName property
131
- const outputBoundaryNode = node.nodes.find(n => {
132
- if (n.type !== 'graphOutput')
133
- return false;
134
- const portNameProp = n.props?.find(p => p.name === 'portName');
135
- return portNameProp?.value === outputPort.name;
136
- });
137
- if (!outputBoundaryNode) {
138
- throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
139
- }
140
- // Recursively evaluate the subnet's internal graph
141
- const subnetResult = await evaluate({
142
- name: `${nodeName}_subnet`,
143
- context: graphContext || undefined,
144
- nodes: node.nodes,
145
- edges: node.edges
146
- }, {
147
- definitions,
148
- outputNode: outputBoundaryNode.name,
149
- outputPort: 'value',
150
- inputs: subnetInputs
151
- });
152
- subnetOutputs[outputPort.name] = subnetResult;
241
+ for (const outputPort of outputPorts) {
242
+ const outputBoundaryNode = node.nodes.find(n => n.type === 'graphOutput' && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
243
+ if (!outputBoundaryNode) {
244
+ throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
153
245
  }
246
+ const result = await pull(outputBoundaryNode.name);
247
+ if ('value' in result)
248
+ subnetOutputs[outputPort.name] = result.value;
154
249
  }
155
250
  cache.set(nodeName, subnetOutputs);
156
251
  return subnetOutputs;
@@ -158,7 +253,8 @@ export async function evaluate(graph, options) {
158
253
  // Get the definition for this node — resolve context from node override or graph default
159
254
  const nodeContext = node.context || graphContext;
160
255
  const [nodeCategory, nodeDefName] = parseTaskIdentifier(node.type);
161
- const definition = defMap.get(defKey(nodeContext, nodeCategory, nodeDefName));
256
+ const key = defKey(nodeContext, nodeCategory, nodeDefName);
257
+ const definition = defMap.get(key);
162
258
  if (!definition) {
163
259
  throw new Error(`No definition found for node: ${nodeContext}:${node.type}`);
164
260
  }
@@ -233,7 +329,7 @@ export async function evaluate(graph, options) {
233
329
  for (const propDef of definition.props) {
234
330
  const instanceProp = node.props?.find(p => p.name === propDef.name);
235
331
  if (instanceProp !== undefined && instanceProp.value !== undefined) {
236
- nodeProps[propDef.name] = instanceProp.value;
332
+ nodeProps[propDef.name] = await resolve(instanceProp.value, nodeName);
237
333
  }
238
334
  else if (propDef.default !== undefined) {
239
335
  nodeProps[propDef.name] = propDef.default;
@@ -242,15 +338,18 @@ export async function evaluate(graph, options) {
242
338
  }
243
339
  // Digital asset: definition has an internal graph — evaluate it recursively
244
340
  if (definition.graph) {
341
+ if (assetPath.includes(key)) {
342
+ throw new Error(`Digital asset "${nodeContext}:${node.type}" contains itself: ${formatCycle([...assetPath, key])}`);
343
+ }
245
344
  const assetGraph = definition.graph;
246
- // Find all output boundary nodes in the asset's graph
345
+ // One evaluation of the asset's graph serves every output port.
346
+ const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, inputs: nodeInputs, props: nodeProps }, [...assetPath, key]);
247
347
  const assetOutputs = {};
248
- const outputBoundaryNodes = assetGraph.nodes.filter(n => n.type === 'graphOutput');
249
- for (const outputBoundaryNode of outputBoundaryNodes) {
348
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
250
349
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
251
- const portName = portNameProp?.value || outputBoundaryNode.name;
252
- const result = await evaluate({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, outputNode: outputBoundaryNode.name, outputPort: 'value', inputs: nodeInputs, props: nodeProps });
253
- assetOutputs[portName] = result;
350
+ const result = await pull(outputBoundaryNode.name);
351
+ if ('value' in result)
352
+ assetOutputs[portNameProp?.value || outputBoundaryNode.name] = result.value;
254
353
  }
255
354
  cache.set(nodeName, assetOutputs);
256
355
  return assetOutputs;
@@ -263,7 +362,5 @@ export async function evaluate(graph, options) {
263
362
  cache.set(nodeName, outputs);
264
363
  return outputs;
265
364
  }
266
- // Evaluate starting from the output node
267
- const outputs = await evaluateNode(outputNode);
268
- return outputs[outputPort];
365
+ return evaluateNode;
269
366
  }
package/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { findCycle, formatCycle } from './cycles';
1
2
  export { evaluate } from './evaluate';
2
3
  export { validateGraph } from './validate';
3
4
  // Re-export node definitions for convenience
package/esm/validate.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { derivePorts, derivePropDefinitions } from '@fbp/spec';
2
+ import { findCycle, formatCycle } from './cycles';
3
+ import { refEdges } from './evaluate';
1
4
  /**
2
5
  * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
3
6
  * receive values from the execution payload; graphOutput is a pass-through), so
@@ -52,6 +55,10 @@ function nodeHasProp(node, propName) {
52
55
  * and recursed into.
53
56
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
54
57
  * recursed into.
58
+ * - Each graph level (top level, inline subnet, asset graph) must be acyclic,
59
+ * else `CYCLE_DETECTED` with the ordered cycle path, like the SQL validator.
60
+ * A digital asset whose graph uses itself, directly or through other assets,
61
+ * is also a `CYCLE_DETECTED`.
55
62
  *
56
63
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
57
64
  * - `graphInput` / `graphProp` boundaries — supplied at runtime.
@@ -76,20 +83,37 @@ export function validateGraph(graph, options = {}) {
76
83
  }
77
84
  };
78
85
  registerDefs(options.definitions);
79
- const visit = (g, pathPrefix) => {
86
+ const qualify = (pathPrefix, name) => (pathPrefix ? `${pathPrefix}/${name}` : name);
87
+ // Digital assets currently being visited, outermost first, so an asset that
88
+ // contains itself is reported instead of recursed into forever.
89
+ const assetStack = [];
90
+ const visit = (g, pathPrefix, scope = []) => {
80
91
  // Definitions can be embedded per-graph (digital assets carry their own).
81
92
  registerDefs(g.definitions);
82
93
  const graphContext = g.context || '';
83
94
  const connected = connectedPorts(g.edges ?? []);
95
+ const cycle = findCycle((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...refEdges(g.nodes ?? [], scope)]);
96
+ if (cycle) {
97
+ const path = cycle.map(name => qualify(pathPrefix, name));
98
+ errors.push({
99
+ code: 'CYCLE_DETECTED',
100
+ node: path[0],
101
+ path,
102
+ message: `Graph contains a cycle: ${formatCycle(path)}`,
103
+ });
104
+ }
84
105
  for (const node of g.nodes ?? []) {
85
106
  if (BOUNDARY_TYPES.has(node.type))
86
107
  continue;
87
- const qualifiedName = pathPrefix ? `${pathPrefix}/${node.name}` : node.name;
108
+ const qualifiedName = qualify(pathPrefix, node.name);
88
109
  const nodeConnected = connected.get(node.name) ?? new Set();
89
110
  // Inline subnet: validate against its declared interface, then recurse.
90
111
  if (node.type === 'subnet' && node.nodes) {
91
- for (const port of node.inputs ?? []) {
92
- if (port.optional === true || port.multi === true)
112
+ const defaulted = new Set(node.nodes
113
+ .filter(n => n.type === 'graphInput' && nodeHasProp(n, 'default'))
114
+ .map(n => n.props.find(p => p.name === 'portName')?.value ?? n.name));
115
+ for (const port of node.inputs ?? derivePorts(node).inputs) {
116
+ if (port.optional === true || port.multi === true || defaulted.has(port.name))
93
117
  continue;
94
118
  if (!nodeConnected.has(port.name)) {
95
119
  errors.push({
@@ -100,12 +124,25 @@ export function validateGraph(graph, options = {}) {
100
124
  });
101
125
  }
102
126
  }
103
- visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
127
+ for (const prop of derivePropDefinitions(node)) {
128
+ if (prop.required !== true || prop.default !== undefined)
129
+ continue;
130
+ if (!nodeHasProp(node, prop.name)) {
131
+ errors.push({
132
+ code: 'MISSING_REQUIRED_PROP',
133
+ node: qualifiedName,
134
+ prop: prop.name,
135
+ message: `Required prop "${prop.name}" of subnet "${qualifiedName}" is not set`,
136
+ });
137
+ }
138
+ }
139
+ visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
104
140
  continue;
105
141
  }
106
142
  const nodeContext = node.context || graphContext;
107
143
  const [category, name] = parseTaskIdentifier(node.type);
108
- const definition = defMap.get(defKey(nodeContext, category, name));
144
+ const key = defKey(nodeContext, category, name);
145
+ const definition = defMap.get(key);
109
146
  // Unknown definition: opaque node (possibly a runtime handler). Skip —
110
147
  // matches the SQL validator + evaluator, which do not require a definition.
111
148
  if (!definition)
@@ -138,7 +175,20 @@ export function validateGraph(graph, options = {}) {
138
175
  }
139
176
  // Digital asset: recurse into the definition's internal graph.
140
177
  if (definition.graph) {
178
+ const repeat = assetStack.findIndex(entry => entry.key === key);
179
+ if (repeat !== -1) {
180
+ const path = [...assetStack.slice(repeat).map(entry => entry.node), qualifiedName];
181
+ errors.push({
182
+ code: 'CYCLE_DETECTED',
183
+ node: qualifiedName,
184
+ path,
185
+ message: `Digital asset "${node.type}" contains itself: ${formatCycle(path)}`,
186
+ });
187
+ continue;
188
+ }
189
+ assetStack.push({ key, node: qualifiedName });
141
190
  visit(definition.graph, qualifiedName);
191
+ assetStack.pop();
142
192
  }
143
193
  }
144
194
  };
package/evaluate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Graph } from '@fbp/types';
1
+ import type { Edge, Graph, Node } from '@fbp/types';
2
2
  import type { EvaluateOptions } from './types';
3
3
  /**
4
4
  * Evaluate a graph starting from the specified output node/port.
@@ -10,3 +10,8 @@ import type { EvaluateOptions } from './types';
10
10
  * @returns Promise resolving to the value at the specified output port
11
11
  */
12
12
  export declare function evaluate(graph: Graph, options: EvaluateOptions): Promise<any>;
13
+ /**
14
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
15
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
16
+ */
17
+ export declare function refEdges(nodes: Node[], scopePath?: string[]): Edge[];
package/evaluate.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluate = evaluate;
4
+ exports.refEdges = refEdges;
5
+ const spec_1 = require("@fbp/spec");
6
+ const cycles_1 = require("./cycles");
4
7
  /**
5
8
  * Build a definition map key from context, category, and name.
6
9
  */
@@ -31,7 +34,51 @@ function parseTaskIdentifier(type) {
31
34
  * @returns Promise resolving to the value at the specified output port
32
35
  */
33
36
  async function evaluate(graph, options) {
34
- const { definitions, outputNode, outputPort, inputs = {}, props = {} } = options;
37
+ const outputs = await openGraph(graph, options, [])(options.outputNode);
38
+ return outputs[options.outputPort];
39
+ }
40
+ /**
41
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
42
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
43
+ */
44
+ function refEdges(nodes, scopePath = []) {
45
+ const names = new Set(nodes.map(n => n.name));
46
+ const scope = (0, spec_1.joinPath)(scopePath);
47
+ const edges = [];
48
+ for (const node of nodes) {
49
+ for (const prop of node.props ?? []) {
50
+ if (!(0, spec_1.isRef)(prop.value))
51
+ continue;
52
+ let target;
53
+ try {
54
+ target = (0, spec_1.resolveRef)(scope, prop.value.ref);
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ const segments = (0, spec_1.parsePath)(target.path);
60
+ const sibling = segments[segments.length - 1];
61
+ if (target.prop === undefined && sibling !== undefined && names.has(sibling) &&
62
+ (0, spec_1.joinPath)(segments.slice(0, -1)) === scope) {
63
+ edges.push({ src: { node: sibling, port: 'value' }, dst: { node: node.name, port: prop.name } });
64
+ }
65
+ }
66
+ }
67
+ return edges;
68
+ }
69
+ /**
70
+ * @param assetPath - definition keys of the digital assets being evaluated,
71
+ * outermost first, so an asset that contains itself throws instead of
72
+ * recursing forever.
73
+ */
74
+ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
75
+ const { definitions, inputs = {}, props = {}, absent } = options;
76
+ // Reject cycles up front, as the validator and the SQL gate do: pulling
77
+ // through a loop would otherwise recurse until the stack overflows.
78
+ const cycle = (0, cycles_1.findCycle)(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
79
+ if (cycle) {
80
+ throw new Error(`Graph "${graph.name}" contains a cycle: ${(0, cycles_1.formatCycle)(cycle)}`);
81
+ }
35
82
  // Build lookup maps
36
83
  const nodeMap = new Map();
37
84
  for (const node of graph.nodes) {
@@ -59,6 +106,42 @@ async function evaluate(graph, options) {
59
106
  }
60
107
  // Cache for evaluated node outputs to avoid re-evaluation
61
108
  const cache = new Map();
109
+ /**
110
+ * Resolve a prop value: a `{ ref }` takes the value of the node it points at
111
+ * (its `value` output, or the named prop for a '.prop' reference). The target
112
+ * is in this scope or one that encloses it.
113
+ */
114
+ async function resolve(value, holder, chain = []) {
115
+ if (!(0, spec_1.isRef)(value))
116
+ return value;
117
+ const target = (0, spec_1.resolveRef)((0, spec_1.joinPath)(scopePath), value.ref);
118
+ const segments = (0, spec_1.parsePath)(target.path);
119
+ const name = segments[segments.length - 1];
120
+ const owner = segments.slice(0, -1).join('/');
121
+ let found = scope;
122
+ while (found && found.path.join('/') !== owner)
123
+ found = found.parent;
124
+ if (!found || name === undefined || !found.getNode(name)) {
125
+ throw new Error(`Reference "${value.ref}" on node "${holder}" does not point at a node in its scope or an enclosing one`);
126
+ }
127
+ if (target.prop !== undefined) {
128
+ const key = `${target.path}.${target.prop}`;
129
+ if (chain.includes(key)) {
130
+ throw new Error(`Reference "${value.ref}" on node "${holder}" refers back to itself`);
131
+ }
132
+ const prop = found.getNode(name).props?.find(p => p.name === target.prop);
133
+ return found.resolve(prop?.value, name, [...chain, key]);
134
+ }
135
+ const outputs = await found.evaluateNode(name);
136
+ return 'value' in outputs ? outputs.value : Object.values(outputs)[0];
137
+ }
138
+ const scope = {
139
+ path: scopePath,
140
+ parent: parentScope,
141
+ getNode: name => nodeMap.get(name),
142
+ evaluateNode: name => evaluateNode(name),
143
+ resolve
144
+ };
62
145
  /**
63
146
  * Recursively evaluate a node and return all its outputs.
64
147
  * Fully async to support async node implementations.
@@ -78,6 +161,11 @@ async function evaluate(graph, options) {
78
161
  // Get the port name from the portName property
79
162
  const portNameProp = node.props?.find(p => p.name === 'portName');
80
163
  const inputName = portNameProp?.value || nodeName;
164
+ // A wired input whose arm was not taken stays dark, default or not, as it would in the flat graph.
165
+ if (absent?.has(inputName)) {
166
+ cache.set(nodeName, {});
167
+ return {};
168
+ }
81
169
  // Check external inputs first, then fall back to node's default prop
82
170
  let value = inputs[inputName];
83
171
  if (value === undefined) {
@@ -92,7 +180,10 @@ async function evaluate(graph, options) {
92
180
  // Get the prop name from the propName property
93
181
  const propNameProp = node.props?.find(p => p.name === 'propName');
94
182
  const propName = propNameProp?.value || nodeName;
95
- const value = props[propName];
183
+ let value = props[propName];
184
+ if (value === undefined) {
185
+ value = node.props?.find(p => p.name === 'default')?.value;
186
+ }
96
187
  const result = { value };
97
188
  cache.set(nodeName, result);
98
189
  return result;
@@ -105,6 +196,10 @@ async function evaluate(graph, options) {
105
196
  if (edges.length > 0) {
106
197
  const edge = edges[0];
107
198
  const upstreamOutputs = await evaluateNode(edge.src.node);
199
+ if (!(edge.src.port in upstreamOutputs)) {
200
+ cache.set(nodeName, {});
201
+ return {};
202
+ }
108
203
  value = upstreamOutputs[edge.src.port];
109
204
  }
110
205
  const result = { value };
@@ -112,48 +207,49 @@ async function evaluate(graph, options) {
112
207
  return result;
113
208
  }
114
209
  // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
115
- if (node.type === 'subnet' && node.nodes && node.edges) {
210
+ if (node.type === 'subnet' && node.nodes) {
211
+ // The interface is derived from the boundary nodes inside the subnet.
212
+ const derived = (0, spec_1.derivePorts)(node);
213
+ const inputPorts = node.inputs ?? derived.inputs;
214
+ const outputPorts = node.outputs ?? derived.outputs;
116
215
  // Collect inputs for the subnet by evaluating upstream nodes
117
216
  const subnetInputs = {};
217
+ const absentInputs = new Set();
118
218
  const subnetPortEdges = edgesByDst.get(nodeName);
119
- if (node.inputs && subnetPortEdges) {
120
- for (const inputPort of node.inputs) {
219
+ if (subnetPortEdges) {
220
+ for (const inputPort of inputPorts) {
121
221
  const edges = subnetPortEdges.get(inputPort.name) ?? [];
122
222
  if (edges.length > 0) {
123
223
  const edge = edges[0];
124
224
  const upstreamOutputs = await evaluateNode(edge.src.node);
125
- subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
225
+ if (edge.src.port in upstreamOutputs) {
226
+ subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
227
+ }
228
+ else {
229
+ absentInputs.add(inputPort.name);
230
+ }
126
231
  }
127
232
  }
128
233
  }
129
- // Find the output boundary nodes in the subnet
234
+ // Promoted parameters: the value set on the subnet node, else the graphProp's default.
235
+ const subnetProps = {};
236
+ for (const propDef of (0, spec_1.derivePropDefinitions)(node)) {
237
+ const instanceProp = node.props?.find(p => p.name === propDef.name);
238
+ if (instanceProp !== undefined && instanceProp.value !== undefined) {
239
+ subnetProps[propDef.name] = await resolve(instanceProp.value, nodeName);
240
+ }
241
+ }
242
+ // One evaluation of the inner graph serves every output port.
243
+ const pull = openGraph({ name: `${nodeName}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
130
244
  const subnetOutputs = {};
131
- if (node.outputs) {
132
- for (const outputPort of node.outputs) {
133
- // Find the graphOutput boundary node by matching portName property
134
- const outputBoundaryNode = node.nodes.find(n => {
135
- if (n.type !== 'graphOutput')
136
- return false;
137
- const portNameProp = n.props?.find(p => p.name === 'portName');
138
- return portNameProp?.value === outputPort.name;
139
- });
140
- if (!outputBoundaryNode) {
141
- throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
142
- }
143
- // Recursively evaluate the subnet's internal graph
144
- const subnetResult = await evaluate({
145
- name: `${nodeName}_subnet`,
146
- context: graphContext || undefined,
147
- nodes: node.nodes,
148
- edges: node.edges
149
- }, {
150
- definitions,
151
- outputNode: outputBoundaryNode.name,
152
- outputPort: 'value',
153
- inputs: subnetInputs
154
- });
155
- subnetOutputs[outputPort.name] = subnetResult;
245
+ for (const outputPort of outputPorts) {
246
+ const outputBoundaryNode = node.nodes.find(n => n.type === 'graphOutput' && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
247
+ if (!outputBoundaryNode) {
248
+ throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
156
249
  }
250
+ const result = await pull(outputBoundaryNode.name);
251
+ if ('value' in result)
252
+ subnetOutputs[outputPort.name] = result.value;
157
253
  }
158
254
  cache.set(nodeName, subnetOutputs);
159
255
  return subnetOutputs;
@@ -161,7 +257,8 @@ async function evaluate(graph, options) {
161
257
  // Get the definition for this node — resolve context from node override or graph default
162
258
  const nodeContext = node.context || graphContext;
163
259
  const [nodeCategory, nodeDefName] = parseTaskIdentifier(node.type);
164
- const definition = defMap.get(defKey(nodeContext, nodeCategory, nodeDefName));
260
+ const key = defKey(nodeContext, nodeCategory, nodeDefName);
261
+ const definition = defMap.get(key);
165
262
  if (!definition) {
166
263
  throw new Error(`No definition found for node: ${nodeContext}:${node.type}`);
167
264
  }
@@ -236,7 +333,7 @@ async function evaluate(graph, options) {
236
333
  for (const propDef of definition.props) {
237
334
  const instanceProp = node.props?.find(p => p.name === propDef.name);
238
335
  if (instanceProp !== undefined && instanceProp.value !== undefined) {
239
- nodeProps[propDef.name] = instanceProp.value;
336
+ nodeProps[propDef.name] = await resolve(instanceProp.value, nodeName);
240
337
  }
241
338
  else if (propDef.default !== undefined) {
242
339
  nodeProps[propDef.name] = propDef.default;
@@ -245,15 +342,18 @@ async function evaluate(graph, options) {
245
342
  }
246
343
  // Digital asset: definition has an internal graph — evaluate it recursively
247
344
  if (definition.graph) {
345
+ if (assetPath.includes(key)) {
346
+ throw new Error(`Digital asset "${nodeContext}:${node.type}" contains itself: ${(0, cycles_1.formatCycle)([...assetPath, key])}`);
347
+ }
248
348
  const assetGraph = definition.graph;
249
- // Find all output boundary nodes in the asset's graph
349
+ // One evaluation of the asset's graph serves every output port.
350
+ const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, inputs: nodeInputs, props: nodeProps }, [...assetPath, key]);
250
351
  const assetOutputs = {};
251
- const outputBoundaryNodes = assetGraph.nodes.filter(n => n.type === 'graphOutput');
252
- for (const outputBoundaryNode of outputBoundaryNodes) {
352
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
253
353
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
254
- const portName = portNameProp?.value || outputBoundaryNode.name;
255
- const result = await evaluate({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, outputNode: outputBoundaryNode.name, outputPort: 'value', inputs: nodeInputs, props: nodeProps });
256
- assetOutputs[portName] = result;
354
+ const result = await pull(outputBoundaryNode.name);
355
+ if ('value' in result)
356
+ assetOutputs[portNameProp?.value || outputBoundaryNode.name] = result.value;
257
357
  }
258
358
  cache.set(nodeName, assetOutputs);
259
359
  return assetOutputs;
@@ -266,7 +366,5 @@ async function evaluate(graph, options) {
266
366
  cache.set(nodeName, outputs);
267
367
  return outputs;
268
368
  }
269
- // Evaluate starting from the output node
270
- const outputs = await evaluateNode(outputNode);
271
- return outputs[outputPort];
369
+ return evaluateNode;
272
370
  }
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { findCycle, formatCycle } from './cycles';
1
2
  export { evaluate } from './evaluate';
2
3
  export type { EvaluateOptions, NodeDefinitionWithImpl, NodeImplFn, PropDefinitionWithOptions } from './types';
3
4
  export type { GraphValidationError, GraphValidationErrorCode, ValidateGraphOptions } from './validate';
package/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.uiDefinitions = exports.textDef = exports.pageDef = exports.inputDef = exports.graphPropDef = exports.graphOutputDef = exports.graphInputDef = exports.formDef = exports.buttonDef = exports.netDefinitions = exports.graphqlRequestDef = exports.subtractDef = exports.multiplyDef = exports.mathDefinitions = exports.constNumberDef = exports.addDef = exports.stringTemplateDef = exports.stringConcatDef = exports.jsonSplitDef = exports.jsonSelectDef = exports.jsonObjectDef = exports.jsonMergeDef = exports.flowSwitchDef = exports.flowMergeDef = exports.flowGuardDef = exports.flowForEachDef = exports.flowFilterDef = exports.flowCoerceDef = exports.flowBranchDef = exports.coreDefinitions = exports.constStringDef = exports.constBooleanDef = exports.validateGraph = exports.evaluate = void 0;
3
+ exports.uiDefinitions = exports.textDef = exports.pageDef = exports.inputDef = exports.graphPropDef = exports.graphOutputDef = exports.graphInputDef = exports.formDef = exports.buttonDef = exports.netDefinitions = exports.graphqlRequestDef = exports.subtractDef = exports.multiplyDef = exports.mathDefinitions = exports.constNumberDef = exports.addDef = exports.stringTemplateDef = exports.stringConcatDef = exports.jsonSplitDef = exports.jsonSelectDef = exports.jsonObjectDef = exports.jsonMergeDef = exports.flowSwitchDef = exports.flowMergeDef = exports.flowGuardDef = exports.flowForEachDef = exports.flowFilterDef = exports.flowCoerceDef = exports.flowBranchDef = exports.coreDefinitions = exports.constStringDef = exports.constBooleanDef = exports.validateGraph = exports.evaluate = exports.formatCycle = exports.findCycle = void 0;
4
+ var cycles_1 = require("./cycles");
5
+ Object.defineProperty(exports, "findCycle", { enumerable: true, get: function () { return cycles_1.findCycle; } });
6
+ Object.defineProperty(exports, "formatCycle", { enumerable: true, get: function () { return cycles_1.formatCycle; } });
4
7
  var evaluate_1 = require("./evaluate");
5
8
  Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return evaluate_1.evaluate; } });
6
9
  var validate_1 = require("./validate");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fbp/evaluator",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "FBP graph evaluator — node definitions, graph evaluation and validation",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "license": "MIT",
@@ -11,15 +11,9 @@
11
11
  "access": "public",
12
12
  "directory": "dist"
13
13
  },
14
- "scripts": {
15
- "prepack": "npm run build",
16
- "build": "makage build",
17
- "build:dev": "makage build --dev",
18
- "clean": "makage clean",
19
- "test": "jest --config jest.config.js"
20
- },
21
14
  "dependencies": {
22
- "@fbp/types": "1.4.0"
15
+ "@fbp/spec": "1.4.0",
16
+ "@fbp/types": "1.5.0"
23
17
  },
24
18
  "devDependencies": {
25
19
  "@types/jest": "^30.0.0",
@@ -36,5 +30,10 @@
36
30
  "bugs": {
37
31
  "url": "https://github.com/constructive-io/fbp/issues"
38
32
  },
39
- "gitHead": "fd04c0023546988a5bcdfca01821dd8a2839c586"
40
- }
33
+ "scripts": {
34
+ "build": "makage build",
35
+ "build:dev": "makage build --dev",
36
+ "clean": "makage clean",
37
+ "test": "jest --config jest.config.js"
38
+ }
39
+ }
package/validate.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { NodeDefinitionWithImpl } from './types';
5
5
  * `validate_function_graph` definition-aware checks so the editor pre-flight and
6
6
  * the database gate agree on what "invalid" means.
7
7
  */
8
- export type GraphValidationErrorCode = 'MISSING_REQUIRED_INPUT' | 'MISSING_REQUIRED_PROP';
8
+ export type GraphValidationErrorCode = 'MISSING_REQUIRED_INPUT' | 'MISSING_REQUIRED_PROP' | 'CYCLE_DETECTED';
9
9
  export interface GraphValidationError {
10
10
  code: GraphValidationErrorCode;
11
11
  /** The offending node's name (qualified with the subnet/asset path). */
@@ -14,6 +14,12 @@ export interface GraphValidationError {
14
14
  port?: string;
15
15
  /** For MISSING_REQUIRED_PROP: the unsupplied required prop. */
16
16
  prop?: string;
17
+ /**
18
+ * For CYCLE_DETECTED: the cycle in data-flow order, starting and ending on
19
+ * the same node (qualified like `node`), e.g. `['a', 'b', 'a']`. For a
20
+ * digital asset that contains itself, the asset path down to the repeat.
21
+ */
22
+ path?: string[];
17
23
  message: string;
18
24
  }
19
25
  export interface ValidateGraphOptions {
@@ -39,6 +45,10 @@ export interface ValidateGraphOptions {
39
45
  * and recursed into.
40
46
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
41
47
  * recursed into.
48
+ * - Each graph level (top level, inline subnet, asset graph) must be acyclic,
49
+ * else `CYCLE_DETECTED` with the ordered cycle path, like the SQL validator.
50
+ * A digital asset whose graph uses itself, directly or through other assets,
51
+ * is also a `CYCLE_DETECTED`.
42
52
  *
43
53
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
44
54
  * - `graphInput` / `graphProp` boundaries — supplied at runtime.
package/validate.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateGraph = validateGraph;
4
+ const spec_1 = require("@fbp/spec");
5
+ const cycles_1 = require("./cycles");
6
+ const evaluate_1 = require("./evaluate");
4
7
  /**
5
8
  * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
6
9
  * receive values from the execution payload; graphOutput is a pass-through), so
@@ -55,6 +58,10 @@ function nodeHasProp(node, propName) {
55
58
  * and recursed into.
56
59
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
57
60
  * recursed into.
61
+ * - Each graph level (top level, inline subnet, asset graph) must be acyclic,
62
+ * else `CYCLE_DETECTED` with the ordered cycle path, like the SQL validator.
63
+ * A digital asset whose graph uses itself, directly or through other assets,
64
+ * is also a `CYCLE_DETECTED`.
58
65
  *
59
66
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
60
67
  * - `graphInput` / `graphProp` boundaries — supplied at runtime.
@@ -79,20 +86,37 @@ function validateGraph(graph, options = {}) {
79
86
  }
80
87
  };
81
88
  registerDefs(options.definitions);
82
- const visit = (g, pathPrefix) => {
89
+ const qualify = (pathPrefix, name) => (pathPrefix ? `${pathPrefix}/${name}` : name);
90
+ // Digital assets currently being visited, outermost first, so an asset that
91
+ // contains itself is reported instead of recursed into forever.
92
+ const assetStack = [];
93
+ const visit = (g, pathPrefix, scope = []) => {
83
94
  // Definitions can be embedded per-graph (digital assets carry their own).
84
95
  registerDefs(g.definitions);
85
96
  const graphContext = g.context || '';
86
97
  const connected = connectedPorts(g.edges ?? []);
98
+ const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...(0, evaluate_1.refEdges)(g.nodes ?? [], scope)]);
99
+ if (cycle) {
100
+ const path = cycle.map(name => qualify(pathPrefix, name));
101
+ errors.push({
102
+ code: 'CYCLE_DETECTED',
103
+ node: path[0],
104
+ path,
105
+ message: `Graph contains a cycle: ${(0, cycles_1.formatCycle)(path)}`,
106
+ });
107
+ }
87
108
  for (const node of g.nodes ?? []) {
88
109
  if (BOUNDARY_TYPES.has(node.type))
89
110
  continue;
90
- const qualifiedName = pathPrefix ? `${pathPrefix}/${node.name}` : node.name;
111
+ const qualifiedName = qualify(pathPrefix, node.name);
91
112
  const nodeConnected = connected.get(node.name) ?? new Set();
92
113
  // Inline subnet: validate against its declared interface, then recurse.
93
114
  if (node.type === 'subnet' && node.nodes) {
94
- for (const port of node.inputs ?? []) {
95
- if (port.optional === true || port.multi === true)
115
+ const defaulted = new Set(node.nodes
116
+ .filter(n => n.type === 'graphInput' && nodeHasProp(n, 'default'))
117
+ .map(n => n.props.find(p => p.name === 'portName')?.value ?? n.name));
118
+ for (const port of node.inputs ?? (0, spec_1.derivePorts)(node).inputs) {
119
+ if (port.optional === true || port.multi === true || defaulted.has(port.name))
96
120
  continue;
97
121
  if (!nodeConnected.has(port.name)) {
98
122
  errors.push({
@@ -103,12 +127,25 @@ function validateGraph(graph, options = {}) {
103
127
  });
104
128
  }
105
129
  }
106
- visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
130
+ for (const prop of (0, spec_1.derivePropDefinitions)(node)) {
131
+ if (prop.required !== true || prop.default !== undefined)
132
+ continue;
133
+ if (!nodeHasProp(node, prop.name)) {
134
+ errors.push({
135
+ code: 'MISSING_REQUIRED_PROP',
136
+ node: qualifiedName,
137
+ prop: prop.name,
138
+ message: `Required prop "${prop.name}" of subnet "${qualifiedName}" is not set`,
139
+ });
140
+ }
141
+ }
142
+ visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
107
143
  continue;
108
144
  }
109
145
  const nodeContext = node.context || graphContext;
110
146
  const [category, name] = parseTaskIdentifier(node.type);
111
- const definition = defMap.get(defKey(nodeContext, category, name));
147
+ const key = defKey(nodeContext, category, name);
148
+ const definition = defMap.get(key);
112
149
  // Unknown definition: opaque node (possibly a runtime handler). Skip —
113
150
  // matches the SQL validator + evaluator, which do not require a definition.
114
151
  if (!definition)
@@ -141,7 +178,20 @@ function validateGraph(graph, options = {}) {
141
178
  }
142
179
  // Digital asset: recurse into the definition's internal graph.
143
180
  if (definition.graph) {
181
+ const repeat = assetStack.findIndex(entry => entry.key === key);
182
+ if (repeat !== -1) {
183
+ const path = [...assetStack.slice(repeat).map(entry => entry.node), qualifiedName];
184
+ errors.push({
185
+ code: 'CYCLE_DETECTED',
186
+ node: qualifiedName,
187
+ path,
188
+ message: `Digital asset "${node.type}" contains itself: ${(0, cycles_1.formatCycle)(path)}`,
189
+ });
190
+ continue;
191
+ }
192
+ assetStack.push({ key, node: qualifiedName });
144
193
  visit(definition.graph, qualifiedName);
194
+ assetStack.pop();
145
195
  }
146
196
  }
147
197
  };