@nodetool-ai/kernel 0.7.0-rc.23 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +51 -0
  2. package/dist/.nodetool-build-stamp +1 -0
  3. package/dist/actor.d.ts +387 -20
  4. package/dist/actor.d.ts.map +1 -1
  5. package/dist/actor.js +1658 -187
  6. package/dist/actor.js.map +1 -1
  7. package/dist/correlation-analysis.d.ts +104 -0
  8. package/dist/correlation-analysis.d.ts.map +1 -0
  9. package/dist/correlation-analysis.js +840 -0
  10. package/dist/correlation-analysis.js.map +1 -0
  11. package/dist/durable-inbox.d.ts +9 -0
  12. package/dist/durable-inbox.d.ts.map +1 -1
  13. package/dist/durable-inbox.js +55 -2
  14. package/dist/durable-inbox.js.map +1 -1
  15. package/dist/dynamic-slots.d.ts +73 -0
  16. package/dist/dynamic-slots.d.ts.map +1 -0
  17. package/dist/dynamic-slots.js +192 -0
  18. package/dist/dynamic-slots.js.map +1 -0
  19. package/dist/edge-ids.d.ts +11 -0
  20. package/dist/edge-ids.d.ts.map +1 -0
  21. package/dist/edge-ids.js +15 -0
  22. package/dist/edge-ids.js.map +1 -0
  23. package/dist/graph-utils.d.ts +12 -0
  24. package/dist/graph-utils.d.ts.map +1 -1
  25. package/dist/graph-utils.js +51 -16
  26. package/dist/graph-utils.js.map +1 -1
  27. package/dist/graph.d.ts +60 -9
  28. package/dist/graph.d.ts.map +1 -1
  29. package/dist/graph.js +313 -101
  30. package/dist/graph.js.map +1 -1
  31. package/dist/inbox.d.ts +158 -2
  32. package/dist/inbox.d.ts.map +1 -1
  33. package/dist/inbox.js +253 -11
  34. package/dist/inbox.js.map +1 -1
  35. package/dist/index.d.ts +14 -10
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +11 -7
  38. package/dist/index.js.map +1 -1
  39. package/dist/io.d.ts +103 -6
  40. package/dist/io.d.ts.map +1 -1
  41. package/dist/io.js +123 -12
  42. package/dist/io.js.map +1 -1
  43. package/dist/loop.d.ts +36 -0
  44. package/dist/loop.d.ts.map +1 -0
  45. package/dist/loop.js +166 -0
  46. package/dist/loop.js.map +1 -0
  47. package/dist/message-stream.d.ts +32 -0
  48. package/dist/message-stream.d.ts.map +1 -0
  49. package/dist/message-stream.js +64 -0
  50. package/dist/message-stream.js.map +1 -0
  51. package/dist/predicates.d.ts +8 -0
  52. package/dist/predicates.d.ts.map +1 -0
  53. package/dist/predicates.js +8 -0
  54. package/dist/predicates.js.map +1 -0
  55. package/dist/run-state.d.ts +65 -0
  56. package/dist/run-state.d.ts.map +1 -0
  57. package/dist/run-state.js +42 -0
  58. package/dist/run-state.js.map +1 -0
  59. package/dist/runner.d.ts +312 -15
  60. package/dist/runner.d.ts.map +1 -1
  61. package/dist/runner.js +1226 -157
  62. package/dist/runner.js.map +1 -1
  63. package/dist/substitute-validator.d.ts +44 -0
  64. package/dist/substitute-validator.d.ts.map +1 -0
  65. package/dist/substitute-validator.js +169 -0
  66. package/dist/substitute-validator.js.map +1 -0
  67. package/dist/supervisor.d.ts +148 -0
  68. package/dist/supervisor.d.ts.map +1 -0
  69. package/dist/supervisor.js +287 -0
  70. package/dist/supervisor.js.map +1 -0
  71. package/dist/trigger-wakeup.d.ts +74 -5
  72. package/dist/trigger-wakeup.d.ts.map +1 -1
  73. package/dist/trigger-wakeup.js +167 -45
  74. package/dist/trigger-wakeup.js.map +1 -1
  75. package/package.json +27 -9
  76. package/dist/channel.d.ts +0 -46
  77. package/dist/channel.d.ts.map +0 -1
  78. package/dist/channel.js +0 -191
  79. package/dist/channel.js.map +0 -1
  80. package/dist/suspendable.d.ts +0 -68
  81. package/dist/suspendable.d.ts.map +0 -1
  82. package/dist/suspendable.js +0 -108
  83. package/dist/suspendable.js.map +0 -1
  84. package/dist/trigger-manager.d.ts +0 -107
  85. package/dist/trigger-manager.d.ts.map +0 -1
  86. package/dist/trigger-manager.js +0 -214
  87. package/dist/trigger-manager.js.map +0 -1
  88. package/dist/trigger.d.ts +0 -57
  89. package/dist/trigger.d.ts.map +0 -1
  90. package/dist/trigger.js +0 -145
  91. package/dist/trigger.js.map +0 -1
package/dist/graph.js CHANGED
@@ -9,8 +9,12 @@
9
9
  * - Streaming upstream computation
10
10
  */
11
11
  import { createLogger } from "@nodetool-ai/config";
12
+ // Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
12
13
  const log = createLogger("nodetool.kernel.graph");
13
- import { isControlEdge, isDataEdge, TypeMetadata } from "@nodetool-ai/protocol";
14
+ import { isControlEdge, isDataEdge, isLoopBackEdge, migrateGraphNodeTypes, TypeMetadata } from "@nodetool-ai/protocol";
15
+ import { syntheticEdgeId } from "./edge-ids.js";
16
+ import { dynamicSlotPropertyTypes, mergeDerivedSlots } from "./dynamic-slots.js";
17
+ import { isCallable, isObjectValue, isString } from "./predicates.js";
14
18
  export class GraphValidationError extends Error {
15
19
  issues;
16
20
  constructor(message, issues = []) {
@@ -23,6 +27,7 @@ export class GraphValidationError extends Error {
23
27
  // Helpers
24
28
  // ---------------------------------------------------------------------------
25
29
  function nodeTypeToJsonSchema(typeStr) {
30
+ // Stryker disable next-line ConditionalExpression: equivalent — a falsy typeStr falls through to the default case, which also returns "string"
26
31
  if (!typeStr)
27
32
  return "string";
28
33
  switch (typeStr) {
@@ -30,8 +35,10 @@ function nodeTypeToJsonSchema(typeStr) {
30
35
  case "float":
31
36
  case "number":
32
37
  return "number";
38
+ // Stryker disable StringLiteral: equivalent — both labels return "string", the same value as the default branch
33
39
  case "str":
34
40
  case "string":
41
+ // Stryker restore StringLiteral
35
42
  return "string";
36
43
  case "bool":
37
44
  case "boolean":
@@ -41,7 +48,7 @@ function nodeTypeToJsonSchema(typeStr) {
41
48
  }
42
49
  }
43
50
  function resolveNodeTypeWith(resolver, nodeType) {
44
- if (typeof resolver === "function") {
51
+ if (isCallable(resolver)) {
45
52
  return resolver(nodeType);
46
53
  }
47
54
  return resolver.resolveNodeType(nodeType);
@@ -49,6 +56,28 @@ function resolveNodeTypeWith(resolver, nodeType) {
49
56
  // ---------------------------------------------------------------------------
50
57
  // Graph
51
58
  // ---------------------------------------------------------------------------
59
+ /**
60
+ * Mark a code-constructed graph as hydrated by defaulting absent behavior
61
+ * flags to false. For graphs built in code (tests, DSL output) where the
62
+ * author already set the flags that matter. NOT a substitute for registry
63
+ * hydration of client/wire graphs — there an absent flag means "unknown",
64
+ * not "off"; use `Graph.loadFromDict` or node-sdk's `hydrateGraphNodeFlags`.
65
+ */
66
+ export function withExplicitNodeFlags(graph) {
67
+ return {
68
+ nodes: graph.nodes.map((node) => ({
69
+ ...node,
70
+ is_streaming_input: node.is_streaming_input ?? false,
71
+ is_streaming_output: node.is_streaming_output ?? false,
72
+ is_controlled: node.is_controlled ?? false,
73
+ is_join_node: node.is_join_node ?? false,
74
+ // Here — unlike `loadFromDict` — the descriptor's author is code, not a
75
+ // saved file, so a declared `retry_safe` is the class's own declaration.
76
+ retry_safe: node.retry_safe ?? false
77
+ })),
78
+ edges: [...graph.edges]
79
+ };
80
+ }
52
81
  export class Graph {
53
82
  nodes;
54
83
  edges;
@@ -63,16 +92,17 @@ export class Graph {
63
92
  /** Cache: nodes that have streaming upstream */
64
93
  _streamingUpstream = null;
65
94
  constructor(data) {
66
- this.nodes = data.nodes;
95
+ // Auto-detect is_controlled from incoming control edges (Python parity:
96
+ // BaseNode.is_controlled() checks graph edges at runtime). Affected nodes
97
+ // are replaced with shallow copies rather than mutated in place, so a
98
+ // WorkflowRunner.run() never writes back onto the caller's graph data.
99
+ this.nodes = Graph._withControlledFlags(data.nodes, data.edges);
67
100
  this.edges = data.edges;
68
101
  this._nodeIndex = new Map();
69
102
  this._incomingEdges = new Map();
70
103
  this._outgoingEdges = new Map();
71
104
  this._outgoingByHandle = new Map();
72
105
  this._buildIndices();
73
- // Auto-detect is_controlled from incoming control edges (Python parity:
74
- // BaseNode.is_controlled() checks graph edges at runtime).
75
- this._detectControlledNodes();
76
106
  }
77
107
  /**
78
108
  * Create a Graph from a plain object, validating the input shape.
@@ -80,7 +110,7 @@ export class Graph {
80
110
  */
81
111
  static fromDict(data, options = {}) {
82
112
  const { skipErrors = true, allowUndefinedProperties = true, validateNodeType } = options;
83
- if (!data || typeof data !== "object") {
113
+ if (!isObjectValue(data)) {
84
114
  throw new GraphValidationError("Graph data must be an object");
85
115
  }
86
116
  const obj = data;
@@ -93,38 +123,23 @@ export class Graph {
93
123
  if (!Array.isArray(obj.edges)) {
94
124
  throw new GraphValidationError("'edges' must be an array");
95
125
  }
96
- const propertiesWithEdges = new Map();
97
- for (const edge of obj.edges) {
98
- if (!edge || typeof edge !== "object") {
99
- if (skipErrors)
100
- continue;
101
- throw new GraphValidationError("Edge entries must be objects");
102
- }
103
- const edgeObj = edge;
104
- const targetId = typeof edgeObj.target === "string" ? edgeObj.target : undefined;
105
- const targetHandle = typeof edgeObj.targetHandle === "string"
106
- ? edgeObj.targetHandle
107
- : undefined;
108
- if (!targetId || !targetHandle)
109
- continue;
110
- let handles = propertiesWithEdges.get(targetId);
111
- if (!handles) {
112
- handles = new Set();
113
- propertiesWithEdges.set(targetId, handles);
114
- }
115
- handles.add(targetHandle);
116
- }
126
+ // Rewrite removed node types (e.g. FormatText -> Prompt) before validation
127
+ // so legacy workflows keep loading. See NODE_TYPE_MIGRATIONS in protocol.
128
+ const migrated = migrateGraphNodeTypes(obj);
129
+ const migratedNodes = migrated.nodes;
130
+ const migratedEdges = migrated.edges;
117
131
  const validNodes = [];
118
132
  const validNodeIds = new Set();
119
- for (const node of obj.nodes) {
120
- if (!node || typeof node !== "object") {
133
+ for (const node of migratedNodes) {
134
+ // Stryker disable next-line ConditionalExpression,LogicalOperator: the typeof/operator variants are equivalent — a non-object node yields {} after the spread below and is then dropped by the id/type guard
135
+ if (!isObjectValue(node)) {
121
136
  if (skipErrors)
122
137
  continue;
123
138
  throw new GraphValidationError("Node entries must be objects");
124
139
  }
125
140
  const nodeObj = { ...node };
126
- const id = typeof nodeObj.id === "string" ? nodeObj.id : undefined;
127
- const type = typeof nodeObj.type === "string" ? nodeObj.type : undefined;
141
+ const id = isString(nodeObj.id) ? nodeObj.id : undefined;
142
+ const type = isString(nodeObj.type) ? nodeObj.type : undefined;
128
143
  if (!id || !type) {
129
144
  if (skipErrors)
130
145
  continue;
@@ -135,24 +150,39 @@ export class Graph {
135
150
  continue;
136
151
  throw new GraphValidationError(`Invalid node type: ${type}`);
137
152
  }
138
- const rawProperties = nodeObj.properties && typeof nodeObj.properties === "object"
153
+ const rawProperties =
154
+ // Stryker disable next-line ConditionalExpression,LogicalOperator: equivalent — a non-object properties value spreads to {}, the same as falling through to data/{}
155
+ isObjectValue(nodeObj.properties)
139
156
  ? { ...nodeObj.properties }
140
- : nodeObj.data && typeof nodeObj.data === "object"
141
- ? { ...nodeObj.data }
142
- : {};
157
+ : // Stryker disable next-line ConditionalExpression,LogicalOperator: equivalent — a non-object data value spreads to {}
158
+ isObjectValue(nodeObj.data)
159
+ ? { ...nodeObj.data }
160
+ : {};
143
161
  // Merge dynamic_properties into the node's properties so that
144
162
  // dynamic nodes (e.g. WorkflowNode) receive user-provided values
145
163
  // for inputs that aren't connected via edges.
146
- if (nodeObj.dynamic_properties &&
147
- typeof nodeObj.dynamic_properties === "object") {
164
+ if (isObjectValue(nodeObj.dynamic_properties)) {
148
165
  Object.assign(rawProperties, nodeObj.dynamic_properties);
149
166
  }
167
+ // Declared dynamic slots are real, typed handles: register their type
168
+ // in propertyTypes so the undefined-property guard below keeps them and
169
+ // downstream type lookups see a type instead of `any`. Only merged into
170
+ // an existing non-empty map — synthesizing propertyTypes here would
171
+ // switch the guard on for a node that had no type map at all.
172
+ const slotTypes = dynamicSlotPropertyTypes(nodeObj.dynamic_inputs);
173
+ if (Object.keys(slotTypes).length > 0 &&
174
+ isObjectValue(nodeObj.propertyTypes) &&
175
+ Object.keys(nodeObj.propertyTypes).length > 0) {
176
+ nodeObj.propertyTypes = {
177
+ ...slotTypes,
178
+ ...nodeObj.propertyTypes
179
+ };
180
+ }
150
181
  if (!allowUndefinedProperties) {
151
182
  // Only validate against propertyTypes when it is explicitly provided.
152
183
  // Using properties itself as a source of truth would defeat the purpose
153
184
  // of this check, since every property key would always be "defined".
154
- const hasPropertyTypes = nodeObj.propertyTypes != null &&
155
- typeof nodeObj.propertyTypes === "object" &&
185
+ const hasPropertyTypes = isObjectValue(nodeObj.propertyTypes) &&
156
186
  Object.keys(nodeObj.propertyTypes).length >
157
187
  0;
158
188
  if (hasPropertyTypes) {
@@ -169,26 +199,25 @@ export class Graph {
169
199
  }
170
200
  }
171
201
  }
172
- for (const handle of propertiesWithEdges.get(id) ?? []) {
173
- delete rawProperties[handle];
174
- }
175
202
  nodeObj.properties = rawProperties;
176
203
  delete nodeObj.data;
177
- validNodes.push(nodeObj);
204
+ // SAFETY: `properties` was just set, and `id`/`type` were proved to be
205
+ // strings by the guard above; they are re-stated so the compiler sees it.
206
+ validNodes.push({ ...nodeObj, id, type });
178
207
  validNodeIds.add(id);
179
208
  }
180
209
  const validEdges = [];
181
- for (const edge of obj.edges) {
182
- if (!edge || typeof edge !== "object") {
210
+ for (const edge of migratedEdges) {
211
+ if (!isObjectValue(edge)) {
183
212
  if (skipErrors)
184
213
  continue;
185
214
  throw new GraphValidationError("Edge entries must be objects");
186
215
  }
187
216
  const edgeObj = edge;
188
- const hasRequiredFields = typeof edgeObj.source === "string" &&
189
- typeof edgeObj.sourceHandle === "string" &&
190
- typeof edgeObj.target === "string" &&
191
- typeof edgeObj.targetHandle === "string";
217
+ const hasRequiredFields = isString(edgeObj.source) &&
218
+ isString(edgeObj.sourceHandle) &&
219
+ isString(edgeObj.target) &&
220
+ isString(edgeObj.targetHandle);
192
221
  if (!hasRequiredFields) {
193
222
  if (skipErrors)
194
223
  continue;
@@ -200,6 +229,8 @@ export class Graph {
200
229
  (!validNodeIds.has(source) || !validNodeIds.has(target))) {
201
230
  continue;
202
231
  }
232
+ // SAFETY: `hasRequiredFields` above proved source/sourceHandle/target/
233
+ // targetHandle are all strings.
203
234
  validEdges.push(edgeObj);
204
235
  }
205
236
  return new Graph({ nodes: validNodes, edges: validEdges });
@@ -208,6 +239,7 @@ export class Graph {
208
239
  const { resolver, skipErrors = true, allowUndefinedProperties = true } = options;
209
240
  const normalized = Graph.fromDict(data, {
210
241
  skipErrors,
242
+ // Stryker disable next-line BooleanLiteral: must stay true — property validation happens later against the RESOLVED types, not the saved cache (see comment in loadFromDict)
211
243
  allowUndefinedProperties: true
212
244
  });
213
245
  const resolvedNodes = [];
@@ -224,7 +256,7 @@ export class Graph {
224
256
  const mergedProperties = {
225
257
  ...(node.properties ?? {})
226
258
  };
227
- const effectiveAllowUndefined = resolved.isDynamic || allowUndefinedProperties;
259
+ const effectiveAllowUndefined = resolved.supportsDynamicInputs || allowUndefinedProperties;
228
260
  if (!effectiveAllowUndefined) {
229
261
  for (const key of Object.keys(mergedProperties)) {
230
262
  if (!allowedProperties.has(key)) {
@@ -238,40 +270,81 @@ export class Graph {
238
270
  }
239
271
  }
240
272
  const descriptorDefaults = resolved.descriptorDefaults ?? {};
273
+ // A per-instance answer, when the resolver has one for this type, is read
274
+ // from the node as saved — the same properties the node will run with.
275
+ const instanceFlags = resolved.resolveInstanceFlags?.(node) ?? {};
276
+ const derivedSlots = resolved.resolveInstanceSlots?.(node);
277
+ const dynamicInputs = mergeDerivedSlots(derivedSlots?.dynamic_inputs, node.dynamic_inputs);
278
+ const dynamicOutputs = mergeDerivedSlots(derivedSlots?.dynamic_outputs, node.dynamic_outputs);
241
279
  const hydratedNode = {
242
280
  ...descriptorDefaults,
243
281
  ...node,
282
+ ...(dynamicInputs && { dynamic_inputs: dynamicInputs }),
283
+ ...(dynamicOutputs && { dynamic_outputs: dynamicOutputs }),
244
284
  type: resolved.nodeType,
245
285
  properties: mergedProperties,
246
286
  propertyTypes: {
247
287
  ...resolvedPropertyTypes,
288
+ // Declared dynamic slots type their handles, but never shadow a
289
+ // static property the registry already declares.
290
+ ...Object.fromEntries(Object.entries(dynamicSlotPropertyTypes(dynamicInputs)).filter(([name]) => !Object.hasOwn(resolvedPropertyTypes, name))),
248
291
  ...(node.propertyTypes ?? {})
249
292
  },
250
293
  outputs: {
251
294
  ...(resolved.outputs ?? {}),
252
295
  ...(node.outputs ?? {})
253
296
  },
254
- sync_mode: node.sync_mode ??
255
- node.properties
256
- ?.sync_mode ??
257
- descriptorDefaults.sync_mode ??
258
- "on_any",
259
297
  // Streaming/control flags: registry metadata (descriptorDefaults) is
260
- // the source of truth. Saved graph data may have stale or missing
261
- // values, so always prefer the registry if it declares true.
262
- is_streaming_input: descriptorDefaults.is_streaming_input ||
263
- node.is_streaming_input ||
298
+ // authoritative when it speaks. An explicit registry boolean — true OR
299
+ // false — wins; the saved value applies only when the resolver omits
300
+ // the flag (undefined), e.g. for unresolved/dynamic types. OR-ing here
301
+ // would let a stale saved `true` survive a registry that migrated the
302
+ // type to buffered/uncontrolled, silently running the wrong mode.
303
+ // A per-instance answer takes the slot the per-type default holds: it
304
+ // was resolved from this node's own properties, so it is the more
305
+ // specific registry opinion, not a saved claim.
306
+ is_streaming_input: instanceFlags.is_streaming_input ??
307
+ descriptorDefaults.is_streaming_input ??
308
+ node.is_streaming_input ??
264
309
  false,
265
- is_streaming_output: descriptorDefaults.is_streaming_output ||
266
- node.is_streaming_output ||
310
+ is_streaming_output: descriptorDefaults.is_streaming_output ??
311
+ node.is_streaming_output ??
267
312
  false,
268
- is_controlled: descriptorDefaults.is_controlled || node.is_controlled || false
313
+ // Correlation metadata is authoritative from the registry. Saved JSON
314
+ // is treated as a cache and overwritten — including when the resolver
315
+ // intentionally returns undefined for a node type that no longer
316
+ // declares correlation. See docs/correlation-design.md §1.
317
+ input_mode: descriptorDefaults.input_mode,
318
+ output_correlation: descriptorDefaults.output_correlation,
319
+ is_controlled: descriptorDefaults.is_controlled ?? node.is_controlled ?? false,
320
+ is_join_node: descriptorDefaults.is_join_node ?? node.is_join_node ?? false,
321
+ // Without this the flag is dropped, because saved workflow JSON never
322
+ // carries it and only the registry knows. `actor.ts` gates the trigger
323
+ // entry point on `node.is_trigger`, so a webhook/manual/file-watch
324
+ // event delivered to a graph hydrated here was accepted and then
325
+ // silently ignored — the node fell through to `genProcess()`, waited
326
+ // for a live adapter that a delivered-event run does not have, and
327
+ // emitted nothing. Every host that passes `resolveNodeType` took this
328
+ // path, including the websocket server.
329
+ is_trigger: descriptorDefaults.is_trigger ?? node.is_trigger ?? false,
330
+ // Retry safety comes from the registry or not at all — note there is
331
+ // no `?? node.retry_safe` here, unlike every flag above. Whether
332
+ // re-running a node duplicates a payment or a publish is a property of
333
+ // its implementation, not of a file: a saved graph asserting
334
+ // `retry_safe: true` for a node whose class never declared it would
335
+ // hand the supervisor a retry on a side-effecting node. An unresolved
336
+ // type therefore gets no retry rather than the saved claim.
337
+ retry_safe: descriptorDefaults.retry_safe ?? false
269
338
  };
270
339
  resolvedNodes.push(hydratedNode);
271
340
  validNodeIds.add(hydratedNode.id);
272
341
  }
273
342
  const validEdges = normalized.edges.filter((edge) => validNodeIds.has(edge.source) && validNodeIds.has(edge.target));
274
- return new Graph({ nodes: resolvedNodes, edges: validEdges });
343
+ // Sound: resolvedNodes were built as HydratedNodeDescriptor above.
344
+ return new Graph({
345
+ nodes: resolvedNodes,
346
+ edges: validEdges
347
+ });
275
348
  }
276
349
  // -----------------------------------------------------------------------
277
350
  // Index building
@@ -309,21 +382,28 @@ export class Graph {
309
382
  }
310
383
  }
311
384
  /**
312
- * Auto-detect is_controlled from incoming control edges.
313
- * In Python, BaseNode.is_controlled() is a runtime method that checks
314
- * the graph context. In TS, we set the flag on the descriptor so that
315
- * the actor knows to use _runControlled().
385
+ * Return the node list with is_controlled set on every control-edge target.
386
+ * In Python, BaseNode.is_controlled() is a runtime method that checks the
387
+ * graph context; in TS we set the flag on the descriptor so the actor knows
388
+ * to use _runControlled(). Node objects are caller-owned (the runner passes
389
+ * `graphData.nodes` straight through), so a target lacking the flag is
390
+ * replaced with a shallow copy — the original is left untouched. Every other
391
+ * node keeps its identity.
316
392
  */
317
- _detectControlledNodes() {
318
- for (const edge of this.edges) {
319
- if (!isControlEdge(edge))
320
- continue;
321
- const target = this._nodeIndex.get(edge.target);
322
- if (target && !target.is_controlled) {
323
- // NodeDescriptor is readonly in the type, but we own the instances
324
- target.is_controlled = true;
325
- }
393
+ static _withControlledFlags(nodes, edges) {
394
+ const controlledIds = new Set();
395
+ for (const edge of edges) {
396
+ if (isControlEdge(edge))
397
+ controlledIds.add(edge.target);
326
398
  }
399
+ // Stryker disable next-line ConditionalExpression: equivalent — with no control edges the map below returns every node unchanged, so the early return only avoids allocating a new array
400
+ if (controlledIds.size === 0)
401
+ return nodes;
402
+ return nodes.map((node) =>
403
+ // Stryker disable next-line ConditionalExpression,LogicalOperator,BooleanLiteral: equivalent — re-copying an already-controlled node yields the same is_controlled value; the guard only preserves object identity (a micro-optimization)
404
+ controlledIds.has(node.id) && !node.is_controlled
405
+ ? { ...node, is_controlled: true }
406
+ : node);
327
407
  }
328
408
  // -----------------------------------------------------------------------
329
409
  // Lookups
@@ -361,9 +441,12 @@ export class Graph {
361
441
  (targetId === undefined || edge.target === targetId));
362
442
  }
363
443
  getControllerNodes(targetId) {
364
- const ids = new Set((targetId === undefined
444
+ const controlEdges =
445
+ // Stryker disable next-line ConditionalExpression: redundant ternary — getControlEdges(undefined) already returns all control edges, identical to getControlEdges()
446
+ targetId === undefined
365
447
  ? this.getControlEdges()
366
- : this.getControlEdges(targetId)).map((e) => e.source));
448
+ : this.getControlEdges(targetId);
449
+ const ids = new Set(controlEdges.map((e) => e.source));
367
450
  return this.nodes.filter((n) => ids.has(n.id));
368
451
  }
369
452
  getControlledNodes(sourceId) {
@@ -382,13 +465,25 @@ export class Graph {
382
465
  * Return nodes that have no incoming data edges (source nodes).
383
466
  */
384
467
  inputNodes() {
385
- return this.nodes.filter((n) => this.findDataEdges(n.id).length === 0);
468
+ const hasIncomingData = new Set();
469
+ for (const edge of this.edges) {
470
+ if (isDataEdge(edge)) {
471
+ hasIncomingData.add(edge.target);
472
+ }
473
+ }
474
+ return this.nodes.filter((n) => !hasIncomingData.has(n.id));
386
475
  }
387
476
  /**
388
477
  * Return nodes that have no outgoing data edges (sink nodes).
389
478
  */
390
479
  outputNodes() {
391
- return this.nodes.filter((n) => this.findOutgoingEdges(n.id).filter(isDataEdge).length === 0);
480
+ const hasOutgoingData = new Set();
481
+ for (const edge of this.edges) {
482
+ if (isDataEdge(edge)) {
483
+ hasOutgoingData.add(edge.source);
484
+ }
485
+ }
486
+ return this.nodes.filter((n) => !hasOutgoingData.has(n.id));
392
487
  }
393
488
  // -----------------------------------------------------------------------
394
489
  // Streaming upstream detection
@@ -398,6 +493,7 @@ export class Graph {
398
493
  * of a streaming-output node via data edges).
399
494
  */
400
495
  hasStreamingUpstream(nodeId) {
496
+ // Stryker disable next-line ConditionalExpression: caching optimization — recomputing yields the same set
401
497
  if (!this._streamingUpstream) {
402
498
  this._streamingUpstream = this._computeStreamingUpstream();
403
499
  }
@@ -407,6 +503,7 @@ export class Graph {
407
503
  const result = new Set();
408
504
  // BFS from every streaming-output node along data edges
409
505
  const streamingSources = this.nodes.filter((n) => n.is_streaming_output);
506
+ // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus node id has no outgoing edges, so BFS adds nothing
410
507
  const queue = [];
411
508
  for (const src of streamingSources) {
412
509
  for (const edge of this.findOutgoingEdges(src.id)) {
@@ -441,19 +538,37 @@ export class Graph {
441
538
  .filter((node) => node.type === "GroupNode" || node.type.endsWith(".GroupNode"))
442
539
  .map((node) => node.id))
443
540
  : new Set();
444
- const filteredNodes = this.nodes.filter((node) => (node.parent_id ?? null) === parentId ||
445
- (node.parent_id != null && groupNodeIds.has(node.parent_id)));
541
+ const isInScope = (node) => {
542
+ const directlyInScope = (node.parent_id ?? null) === parentId;
543
+ const inScopedGroup =
544
+ // Stryker disable next-line ConditionalExpression: the `!= null` guard is redundant — groupNodeIds only holds real node-id strings, so has(null/undefined) is already false
545
+ node.parent_id != null && groupNodeIds.has(node.parent_id);
546
+ return directlyInScope || inScopedGroup;
547
+ };
548
+ const filteredNodes = this.nodes.filter(isInScope);
446
549
  const filteredNodeIds = new Set(filteredNodes.map((node) => node.id));
447
- const filteredEdges = this.edges.filter((edge) => filteredNodeIds.has(edge.source) && filteredNodeIds.has(edge.target));
550
+ // Only data edges define the ordering (see docstring). Including control
551
+ // edges would turn a legal data-A→B + control-B→A controller feedback
552
+ // pattern into a mixed cycle, silently dropping both nodes from the
553
+ // returned levels.
554
+ // Loop back edges close the only cycles a graph may contain; leaving them
555
+ // out keeps loop bodies in the levels (docs/workflow-loops.md).
556
+ const nodeTypeOf = (id) => this.findNode(id)?.type;
557
+ const filteredEdges = this.edges.filter((edge) => isDataEdge(edge) &&
558
+ !isLoopBackEdge(edge, nodeTypeOf) &&
559
+ filteredNodeIds.has(edge.source) &&
560
+ filteredNodeIds.has(edge.target));
448
561
  // In-degree count across filtered edges.
449
562
  const inDeg = new Map();
450
563
  for (const node of filteredNodes) {
451
564
  inDeg.set(node.id, 0);
452
565
  }
453
566
  for (const edge of filteredEdges) {
567
+ // Stryker disable next-line LogicalOperator: equivalent — same-level nodes are all processed before the next level, so an off-by-one in-degree count does not change the produced levels
454
568
  inDeg.set(edge.target, (inDeg.get(edge.target) ?? 0) + 1);
455
569
  }
456
570
  // Seed with zero-in-degree nodes
571
+ // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus id matches no node/edge and is dropped
457
572
  let currentLevel = [];
458
573
  for (const [id, deg] of inDeg) {
459
574
  if (deg === 0)
@@ -467,11 +582,13 @@ export class Graph {
467
582
  for (const id of currentLevel) {
468
583
  visited.add(id);
469
584
  const node = this.findNode(id);
585
+ // Stryker disable next-line ConditionalExpression: equivalent — ids come from filteredNodes, so findNode always returns a node
470
586
  if (node)
471
587
  levelNodes.push(node);
472
588
  for (const edge of filteredEdges) {
473
589
  if (edge.source !== id)
474
590
  continue;
591
+ // Stryker disable next-line LogicalOperator: equivalent — every edge target was seeded in inDeg, and same-level processing means the decrement order does not change the produced levels
475
592
  const newDeg = (inDeg.get(edge.target) ?? 1) - 1;
476
593
  inDeg.set(edge.target, newDeg);
477
594
  if (newDeg === 0 && !visited.has(edge.target)) {
@@ -479,11 +596,14 @@ export class Graph {
479
596
  }
480
597
  }
481
598
  }
599
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent — currentLevel ids all resolve to nodes, so levelNodes is never empty when currentLevel is non-empty
482
600
  if (levelNodes.length > 0)
483
601
  levels.push(levelNodes);
484
602
  currentLevel = nextLevel;
485
603
  }
604
+ // Stryker disable next-line ConditionalExpression,EqualityOperator,BlockStatement: this only emits a diagnostic warning; the returned levels are unaffected
486
605
  if (visited.size !== filteredNodes.length) {
606
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
487
607
  log.warn("Graph contains at least one cycle", {
488
608
  visited: visited.size,
489
609
  total: filteredNodes.length
@@ -499,13 +619,20 @@ export class Graph {
499
619
  * Each input node contributes a property named after node.name (or node.id).
500
620
  */
501
621
  getInputSchema() {
502
- return this._buildSchema((n) => n.type.includes("Input"));
622
+ // Match the input-node namespace, not any type merely CONTAINING "Input":
623
+ // a loose substring pulled in mid-graph nodes like
624
+ // `nodetool.test.StreamingInputProcessor` (phantom required input) and
625
+ // missed real ones like `nodetool.input.MessageDeconstructor`.
626
+ return this._buildSchema((n) => n.type.startsWith("nodetool.input."));
503
627
  }
504
628
  /**
505
- * Build a JSON Schema object from output nodes (type contains "Output").
629
+ * Build a JSON Schema object from output nodes (`nodetool.output.*`).
506
630
  */
507
631
  getOutputSchema() {
508
- return this._buildSchema((n) => n.type.includes("Output"));
632
+ // Namespace match, not a substring: `nodetool.generators.
633
+ // StructuredOutputGenerator` / `nodetool.audio.realtime.AudioOutput`
634
+ // contain "Output" but are not workflow output nodes.
635
+ return this._buildSchema((n) => n.type.startsWith("nodetool.output."));
509
636
  }
510
637
  _buildSchema(filter) {
511
638
  const properties = {};
@@ -532,21 +659,82 @@ export class Graph {
532
659
  */
533
660
  validate() {
534
661
  this.validateEdgeEndpoints();
662
+ this.validateDataEdgeSourceHandles();
535
663
  this.validateControlEdges();
536
664
  this.validateEdgeTypes();
537
665
  }
666
+ /**
667
+ * Verify that every data edge's `sourceHandle` is a declared output of its
668
+ * source node. Without this, an edge wired to a nonexistent output handle
669
+ * passes validation and then silently never delivers a value at runtime
670
+ * (`validateEdgeTypes` skips it for lack of a source type), leaving the
671
+ * target node waiting forever.
672
+ *
673
+ * Only enforced when the source node declares a non-empty static `outputs`
674
+ * map and does not produce dynamic outputs (whose handles aren't known
675
+ * statically). Nodes without output metadata are left untouched.
676
+ */
677
+ validateDataEdgeSourceHandles() {
678
+ for (const edge of this.edges) {
679
+ if (!isDataEdge(edge))
680
+ continue;
681
+ const sourceNode = this._nodeIndex.get(edge.source);
682
+ // Endpoint existence is enforced by validateEdgeEndpoints().
683
+ if (!sourceNode)
684
+ continue;
685
+ const outputs = sourceNode.outputs;
686
+ if (!outputs || Object.keys(outputs).length === 0)
687
+ continue;
688
+ if (sourceNode.dynamic_outputs &&
689
+ Object.keys(sourceNode.dynamic_outputs).length > 0) {
690
+ continue;
691
+ }
692
+ // Own-property check, not `in`: `in` walks the prototype chain, so a
693
+ // sourceHandle named after an Object.prototype member ("toString",
694
+ // "constructor", …) would spuriously pass this guard and then hang at
695
+ // runtime when the source node emits nothing on that handle.
696
+ if (!Object.hasOwn(outputs, edge.sourceHandle)) {
697
+ throw new GraphValidationError(`Edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)} ` +
698
+ `references unknown output "${edge.sourceHandle}" on node "${edge.source}"` +
699
+ `${sourceNode.type ? ` (${sourceNode.type})` : ""}`, [
700
+ {
701
+ nodeId: edge.source,
702
+ nodeType: sourceNode.type,
703
+ property: edge.sourceHandle,
704
+ message: `Unknown output "${edge.sourceHandle}"`
705
+ }
706
+ ]);
707
+ }
708
+ }
709
+ }
538
710
  /**
539
711
  * Verify that every edge references existing nodes.
540
712
  */
541
713
  validateEdgeEndpoints() {
542
714
  for (const edge of this.edges) {
715
+ // Self-loops pass control-cycle detection and deadlock at runtime:
716
+ // the node waits on an input handle that only the node itself can
717
+ // close. The correlation analyzer reports data self-loops as cycles;
718
+ // this guard also covers direct validate() callers and control edges.
719
+ if (edge.source === edge.target) {
720
+ throw new GraphValidationError(`Edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)} ` +
721
+ `connects node "${edge.source}" to itself; self-loop edges are not supported`, [
722
+ {
723
+ nodeId: edge.source,
724
+ property: edge.targetHandle,
725
+ message: "Self-loop edges are not supported"
726
+ }
727
+ ]);
728
+ }
543
729
  if (!this._nodeIndex.has(edge.source)) {
730
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
544
731
  log.error("Edge references unknown source node", {
545
732
  source: edge.source
546
733
  });
547
734
  throw new GraphValidationError(`Edge references unknown source node: ${edge.source}`);
548
735
  }
549
736
  if (!this._nodeIndex.has(edge.target)) {
737
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
550
738
  log.error("Edge references unknown target node", {
551
739
  target: edge.target
552
740
  });
@@ -579,40 +767,61 @@ export class Graph {
579
767
  */
580
768
  validateEdgeTypes() {
581
769
  for (const edge of this.edges) {
770
+ // Stryker disable next-line ConditionalExpression: equivalent — a control edge has no source output type for its handle and is skipped by the !sourceType guard below anyway
582
771
  if (isControlEdge(edge))
583
772
  continue;
584
773
  const sourceNode = this._nodeIndex.get(edge.source);
585
774
  const targetNode = this._nodeIndex.get(edge.target);
586
775
  if (!sourceNode || !targetNode)
587
776
  continue;
588
- // Get source output type from node.outputs[sourceHandle]
589
- const sourceType = sourceNode.outputs?.[edge.sourceHandle];
777
+ // Get source output type from node.outputs[sourceHandle]. Own-property
778
+ // guard: a prototype-named handle ("toString", "constructor", …) would
779
+ // otherwise read an inherited Object.prototype member (a truthy function)
780
+ // and pass it to TypeMetadata.fromString, crashing on a runnable graph.
781
+ const sourceType = sourceNode.outputs &&
782
+ Object.hasOwn(sourceNode.outputs, edge.sourceHandle)
783
+ ? sourceNode.outputs[edge.sourceHandle]
784
+ : undefined;
590
785
  if (!sourceType)
591
786
  continue; // no type info, skip
592
- // Get target input type from node.properties[targetHandle].type
593
- const targetProp = targetNode.properties?.[edge.targetHandle];
594
- let targetType;
595
- if (typeof targetProp === "object" &&
596
- targetProp !== null &&
597
- "type" in targetProp) {
598
- targetType = targetProp.type;
599
- }
600
- else if (typeof targetProp === "string") {
601
- targetType = targetProp;
787
+ // Get target input type: propertyTypes is the authoritative map after
788
+ // graph load. Fall back to a property value carrying an explicit
789
+ // `type` descriptor for raw payloads. Plain string property values
790
+ // are runtime data (e.g. saved literals), never type names.
791
+ let targetType = targetNode.propertyTypes &&
792
+ Object.hasOwn(targetNode.propertyTypes, edge.targetHandle)
793
+ ? targetNode.propertyTypes[edge.targetHandle]
794
+ : undefined;
795
+ if (!targetType) {
796
+ const targetProp = targetNode.properties?.[edge.targetHandle];
797
+ if (isObjectValue(targetProp) &&
798
+ "type" in targetProp &&
799
+ isString(targetProp.type)) {
800
+ targetType = targetProp.type;
801
+ }
602
802
  }
603
803
  if (!targetType)
604
804
  continue; // no type info, skip
605
805
  // Use TypeMetadata for full compatibility check (handles list[X], union, numeric widening)
606
806
  const sourceMeta = TypeMetadata.fromString(sourceType);
607
807
  const targetMeta = TypeMetadata.fromString(targetType);
608
- if (!sourceMeta.isCompatibleWith(targetMeta)) {
808
+ // Scalar-into-list aggregation: a value edge may feed a list-typed
809
+ // input (multi-edge list inputs collect items into a list, and a
810
+ // single item edge wraps). Accept when the source is compatible with
811
+ // the list's element type.
812
+ const elementCompatible = targetMeta.isListType() &&
813
+ !sourceMeta.isListType() &&
814
+ (targetMeta.args.length === 0 ||
815
+ sourceMeta.isCompatibleWith(targetMeta.args[0]));
816
+ if (!sourceMeta.isCompatibleWith(targetMeta) && !elementCompatible) {
817
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
609
818
  log.warn("Type mismatch on edge", {
610
819
  source: edge.source,
611
820
  target: edge.target,
612
821
  sourceType,
613
822
  targetType
614
823
  });
615
- throw new GraphValidationError(`Type mismatch on edge ${edge.id ?? `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`}: ` +
824
+ throw new GraphValidationError(`Type mismatch on edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)}: ` +
616
825
  `source outputs "${sourceType}" but target expects "${targetType}"`);
617
826
  }
618
827
  }
@@ -637,6 +846,7 @@ export class Graph {
637
846
  const c = color.get(neighbor) ?? WHITE;
638
847
  if (c === GRAY)
639
848
  return true; // back edge → cycle
849
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: the `c === WHITE` guard only avoids redundant re-visits; cycles are still caught by the GRAY check above, so the detection result is unchanged
640
850
  if (c === WHITE && dfs(neighbor))
641
851
  return true;
642
852
  }
@@ -644,8 +854,10 @@ export class Graph {
644
854
  return false;
645
855
  };
646
856
  for (const node of adj.keys()) {
857
+ // Stryker disable next-line ConditionalExpression: equivalent — re-running dfs on an already-coloured node is redundant work with the same cycle-detection result
647
858
  if ((color.get(node) ?? WHITE) === WHITE) {
648
859
  if (dfs(node)) {
860
+ // Stryker disable next-line StringLiteral: diagnostic log message only
649
861
  log.error("Graph contains a cycle in control edges");
650
862
  throw new GraphValidationError("Graph contains a cycle in control edges");
651
863
  }