@nodetool-ai/kernel 0.8.8 → 0.8.9-beta.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 (74) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/actor.d.ts +1 -479
  3. package/dist/actor.d.ts.map +1 -1
  4. package/dist/actor.js +1 -1911
  5. package/dist/actor.js.map +1 -1
  6. package/dist/correlation-analysis.d.ts +1 -103
  7. package/dist/correlation-analysis.d.ts.map +1 -1
  8. package/dist/correlation-analysis.js +1 -845
  9. package/dist/correlation-analysis.js.map +1 -1
  10. package/dist/durable-inbox.d.ts +1 -90
  11. package/dist/durable-inbox.d.ts.map +1 -1
  12. package/dist/durable-inbox.js +1 -210
  13. package/dist/durable-inbox.js.map +1 -1
  14. package/dist/dynamic-slots.d.ts +1 -72
  15. package/dist/dynamic-slots.d.ts.map +1 -1
  16. package/dist/dynamic-slots.js +1 -191
  17. package/dist/dynamic-slots.js.map +1 -1
  18. package/dist/edge-ids.d.ts +1 -10
  19. package/dist/edge-ids.d.ts.map +1 -1
  20. package/dist/edge-ids.js +1 -14
  21. package/dist/edge-ids.js.map +1 -1
  22. package/dist/graph-utils.d.ts +1 -71
  23. package/dist/graph-utils.d.ts.map +1 -1
  24. package/dist/graph-utils.js +1 -283
  25. package/dist/graph-utils.js.map +1 -1
  26. package/dist/graph.d.ts +1 -203
  27. package/dist/graph.d.ts.map +1 -1
  28. package/dist/graph.js +1 -867
  29. package/dist/graph.js.map +1 -1
  30. package/dist/inbox.d.ts +1 -264
  31. package/dist/inbox.d.ts.map +1 -1
  32. package/dist/inbox.js +1 -551
  33. package/dist/inbox.js.map +1 -1
  34. package/dist/index.d.ts +1 -19
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -19
  37. package/dist/index.js.map +1 -1
  38. package/dist/io.d.ts +1 -188
  39. package/dist/io.d.ts.map +1 -1
  40. package/dist/io.js +1 -238
  41. package/dist/io.js.map +1 -1
  42. package/dist/loop.d.ts +1 -35
  43. package/dist/loop.d.ts.map +1 -1
  44. package/dist/loop.js +1 -165
  45. package/dist/loop.js.map +1 -1
  46. package/dist/message-stream.d.ts +1 -31
  47. package/dist/message-stream.d.ts.map +1 -1
  48. package/dist/message-stream.js +1 -63
  49. package/dist/message-stream.js.map +1 -1
  50. package/dist/predicates.d.ts +1 -7
  51. package/dist/predicates.d.ts.map +1 -1
  52. package/dist/predicates.js +1 -7
  53. package/dist/predicates.js.map +1 -1
  54. package/dist/run-state.d.ts +1 -64
  55. package/dist/run-state.d.ts.map +1 -1
  56. package/dist/run-state.js +1 -41
  57. package/dist/run-state.js.map +1 -1
  58. package/dist/runner.d.ts +1 -523
  59. package/dist/runner.d.ts.map +1 -1
  60. package/dist/runner.js +1 -2126
  61. package/dist/runner.js.map +1 -1
  62. package/dist/substitute-validator.d.ts +1 -43
  63. package/dist/substitute-validator.d.ts.map +1 -1
  64. package/dist/substitute-validator.js +1 -168
  65. package/dist/substitute-validator.js.map +1 -1
  66. package/dist/supervisor.d.ts +1 -147
  67. package/dist/supervisor.d.ts.map +1 -1
  68. package/dist/supervisor.js +1 -286
  69. package/dist/supervisor.js.map +1 -1
  70. package/dist/trigger-wakeup.d.ts +1 -122
  71. package/dist/trigger-wakeup.d.ts.map +1 -1
  72. package/dist/trigger-wakeup.js +1 -220
  73. package/dist/trigger-wakeup.js.map +1 -1
  74. package/package.json +4 -4
@@ -1,846 +1,2 @@
1
- /**
2
- * Static correlation analysis (`_analyzeCorrelation`).
3
- *
4
- * Computes, at graph load time, for each data edge and each node output:
5
- * - an ordered scope (root chain from outermost parent to innermost child),
6
- * - a `repeats_per_key` flag,
7
- * - the set of possible child roots reachable through this output (for EOS
8
- * synthesis),
9
- * - the source-edge ids that contribute to the output's close barrier.
10
- *
11
- * Per docs/correlation-design.md §3.
12
- *
13
- * The runtime correlation lineage is a token map; the static scope supplies
14
- * the ordering needed for projection, prefix checks, and `collapse: "innermost"`.
15
- *
16
- * This pass is consumed by `_runCorrelated` and runs for every workflow before
17
- * execution.
18
- */
19
- import { LOOP_FEEDBACK_HANDLES, LOOP_NODE_TYPE, TypeMetadata, isDataEdge, isLoopBackEdge, loopRootId } from "@nodetool-ai/protocol";
20
- import { isNonEmptyString } from "./predicates.js";
21
- export class CorrelationAnalysisError extends Error {
22
- issues;
23
- constructor(issues) {
24
- const lines = issues.map((i) => {
25
- const ctx = i.nodeId ? ` (node ${i.nodeId}` : "";
26
- const handle = i.handle ? `, handle ${i.handle}` : "";
27
- const close = ctx ? `${handle})` : "";
28
- return ` - ${i.message}${ctx}${close}`;
29
- });
30
- super(`Correlation analysis failed:\n${lines.join("\n")}`);
31
- this.name = "CorrelationAnalysisError";
32
- this.issues = issues;
33
- }
34
- }
35
- // ---------------------------------------------------------------------------
36
- // Helpers
37
- // ---------------------------------------------------------------------------
38
- /** Edge identity used as a key throughout the analyzer. */
39
- export function edgeKey(edge) {
40
- return (edge.id ??
41
- `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`);
42
- }
43
- /** Returns true if `a` is a prefix of `b` (or equal). */
44
- export function isPrefixOf(a, b) {
45
- // Stryker disable next-line ConditionalExpression: equivalent fast-path — when a is longer, the loop below hits an undefined b[i] and returns false anyway
46
- if (a.length > b.length)
47
- return false;
48
- for (let i = 0; i < a.length; i++) {
49
- if (a[i] !== b[i])
50
- return false;
51
- }
52
- return true;
53
- }
54
- /** Returns true if `a` and `b` are comparable (one is a prefix of the other). */
55
- export function comparable(a, b) {
56
- return isPrefixOf(a, b) || isPrefixOf(b, a);
57
- }
58
- /** Returns the longer of two prefix-comparable scopes (or null if not comparable). */
59
- function largerScope(a, b) {
60
- if (isPrefixOf(a, b))
61
- return b;
62
- if (isPrefixOf(b, a))
63
- return a;
64
- return null;
65
- }
66
- /** Root id for an iteration output emitted by `(nodeId, handle, group?)`. */
67
- export function iterationRootId(nodeId, handle, group) {
68
- return group ? `${nodeId}:${group}` : `${nodeId}:${handle}`;
69
- }
70
- const EMPTY_SET = new Set();
71
- // ---------------------------------------------------------------------------
72
- // Topological sort over data edges
73
- // ---------------------------------------------------------------------------
74
- function topoSort(nodes, edges) {
75
- const byId = new Map();
76
- for (const n of nodes)
77
- byId.set(n.id, n);
78
- const incoming = new Map();
79
- const outgoing = new Map();
80
- for (const n of nodes) {
81
- incoming.set(n.id, 0);
82
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus target is not a real node and is dropped by the incoming-count logic
83
- outgoing.set(n.id, []);
84
- }
85
- // A data edge from a node to itself is a one-node cycle. It must be
86
- // reported like any other cycle: at runtime the self-edge counts as an
87
- // upstream that is only marked done after the node's own actor completes,
88
- // so the actor waits on itself and the whole run hangs.
89
- const selfLoopNodes = new Set();
90
- for (const edge of edges) {
91
- if (!isDataEdge(edge))
92
- continue;
93
- if (!byId.has(edge.source) || !byId.has(edge.target))
94
- continue;
95
- if (edge.source === edge.target) {
96
- selfLoopNodes.add(edge.source);
97
- continue;
98
- }
99
- outgoing.get(edge.source).push(edge.target);
100
- incoming.set(edge.target, (incoming.get(edge.target) ?? 0) + 1);
101
- }
102
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus id has no byId entry and is skipped in the drain loop
103
- const queue = [];
104
- for (const [id, count] of incoming) {
105
- if (count === 0)
106
- queue.push(id);
107
- }
108
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus string never equals a real node (by reference) and can only mask a 1-node cycle, which self-loop skipping already prevents
109
- const order = [];
110
- while (queue.length > 0) {
111
- const id = queue.shift();
112
- const node = byId.get(id);
113
- // Stryker disable next-line ConditionalExpression: defensive — ids come from byId/queue, so node is always present
114
- if (!node)
115
- continue;
116
- order.push(node);
117
- // Stryker disable next-line ArrayDeclaration: defensive ?? fallback — every real id has an outgoing entry seeded above
118
- for (const t of outgoing.get(id) ?? []) {
119
- const next = (incoming.get(t) ?? 0) - 1;
120
- incoming.set(t, next);
121
- // Stryker disable next-line ConditionalExpression: the true-direction is equivalent — pushing a node before all deps are processed only reprocesses it; the final facts converge to the same values
122
- if (next === 0)
123
- queue.push(t);
124
- }
125
- }
126
- // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent — the only consumer (analyzeCorrelation) reports a cycle iff `cycle.length > 0`, so taking this branch for an acyclic graph yields an empty `remaining` that is indistinguishable from the `cycle: null` path; only the non-empty (real cycle) contents are observable
127
- if (order.length < nodes.length || selfLoopNodes.size > 0) {
128
- const orderSet = new Set(order);
129
- const remaining = nodes.filter((n) => !orderSet.has(n)).map((n) => n.id);
130
- for (const id of selfLoopNodes) {
131
- if (!remaining.includes(id))
132
- remaining.push(id);
133
- }
134
- return { order, cycle: remaining };
135
- }
136
- return { order, cycle: null };
137
- }
138
- // ---------------------------------------------------------------------------
139
- // Output correlation kind transformation
140
- // ---------------------------------------------------------------------------
141
- /**
142
- * Apply the per-output-kind transformation to a base (scope, repeats, roots)
143
- * triple. Mirrors §3 of the design.
144
- */
145
- function applyOutputKind(kind, group, collapse, nodeId, handle, base) {
146
- switch (kind) {
147
- case "single":
148
- case "forward":
149
- return {
150
- scope: base.scope,
151
- repeats: base.repeats,
152
- possibleChildRoots: base.possibleChildRoots
153
- };
154
- case "chunk":
155
- return {
156
- scope: base.scope,
157
- repeats: true,
158
- possibleChildRoots: base.possibleChildRoots
159
- };
160
- case "iteration": {
161
- const root = iterationRootId(nodeId, handle, group);
162
- const newScope = [...base.scope, root];
163
- const newRoots = new Set(base.possibleChildRoots);
164
- newRoots.add(root);
165
- return {
166
- scope: newScope,
167
- repeats: false,
168
- possibleChildRoots: newRoots
169
- };
170
- }
171
- case "aggregate": {
172
- // collapse: "innermost" drops the last root in the base scope.
173
- if (collapse !== "innermost") {
174
- // Defensive — validated earlier; treat as identity.
175
- return {
176
- scope: base.scope,
177
- repeats: base.repeats,
178
- possibleChildRoots: base.possibleChildRoots
179
- };
180
- }
181
- // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — for an empty base, dropping the last root (slice(0,-1) of []) also yields [] with the same roots
182
- if (base.scope.length === 0) {
183
- return {
184
- scope: base.scope,
185
- repeats: base.repeats,
186
- possibleChildRoots: base.possibleChildRoots
187
- };
188
- }
189
- const dropped = base.scope[base.scope.length - 1];
190
- const newScope = base.scope.slice(0, -1);
191
- const newRoots = new Set(base.possibleChildRoots);
192
- newRoots.delete(dropped);
193
- return {
194
- scope: newScope,
195
- repeats: false,
196
- possibleChildRoots: newRoots
197
- };
198
- }
199
- }
200
- }
201
- // ---------------------------------------------------------------------------
202
- // Multi-edge list detection (kernel parity helper)
203
- // ---------------------------------------------------------------------------
204
- function isListTypeHandle(node, handle) {
205
- const propertyTypes = node.propertyTypes;
206
- if (!propertyTypes)
207
- return false;
208
- const typeStr = propertyTypes[handle];
209
- // Guard non-string/empty values here so TypeMetadata.fromString only ever
210
- // sees a valid type string (it is total over strings and never throws).
211
- if (!isNonEmptyString(typeStr))
212
- return false;
213
- return TypeMetadata.fromString(typeStr).isListType();
214
- }
215
- export function analyzeCorrelation(graphData, options = {}) {
216
- const issues = [];
217
- const edgeFacts = new Map();
218
- const nodeFacts = new Map();
219
- // Loop back edges (into a Loop node's feedback inputs) close the only
220
- // cycles a graph may contain. They are left out of the topological order;
221
- // the Loop node assigns its feedback inputs the loop scope and each back
222
- // edge is checked against it once its source has been analyzed.
223
- // docs/workflow-loops.md.
224
- const nodeTypeById = new Map();
225
- for (const n of graphData.nodes)
226
- nodeTypeById.set(n.id, n.type);
227
- const nodeTypeOf = (id) => nodeTypeById.get(id);
228
- const backEdges = graphData.edges.filter((e) => isLoopBackEdge(e, nodeTypeOf));
229
- const backEdgeSet = new Set(backEdges);
230
- const forwardEdges = graphData.edges.filter((e) => !backEdgeSet.has(e));
231
- const dataEdges = forwardEdges.filter(isDataEdge);
232
- const { order, cycle } = topoSort(graphData.nodes, forwardEdges);
233
- // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent — topoSort returns either null or a non-empty cycle, so `> 0` vs `>= 0`/true do not differ
234
- if (cycle && cycle.length > 0) {
235
- issues.push({
236
- message: `Cycle detected in graph; a cycle may only close on the "next" or "condition" input of a Loop node. Involved nodes: ${cycle.join(", ")}`
237
- });
238
- if (options.throwOnIssue) {
239
- throw new CorrelationAnalysisError(issues);
240
- }
241
- return { edges: edgeFacts, nodes: nodeFacts, issues };
242
- }
243
- // Index incoming edges per (target node, handle).
244
- const incomingByNode = new Map();
245
- for (const edge of dataEdges) {
246
- let arr = incomingByNode.get(edge.target);
247
- if (!arr) {
248
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus edge has no edgeFacts entry and is skipped
249
- arr = [];
250
- incomingByNode.set(edge.target, arr);
251
- }
252
- arr.push(edge);
253
- }
254
- const backEdgesByLoop = new Map();
255
- for (const edge of backEdges) {
256
- const arr = backEdgesByLoop.get(edge.target);
257
- if (arr)
258
- arr.push(edge);
259
- else
260
- backEdgesByLoop.set(edge.target, [edge]);
261
- }
262
- const recordNode = (node, facts) => {
263
- nodeFacts.set(node.id, facts);
264
- // Write outgoing edge facts (back edges included: their source is
265
- // analyzed here like any other edge's).
266
- const outgoing = graphData.edges.filter((e) => isDataEdge(e) && e.source === node.id);
267
- for (const edge of outgoing) {
268
- const outInfo = facts.outputs.get(edge.sourceHandle);
269
- if (!outInfo) {
270
- edgeFacts.set(edgeKey(edge), {
271
- scope: [],
272
- repeatsPerKey: false,
273
- possibleChildRoots: EMPTY_SET
274
- });
275
- continue;
276
- }
277
- edgeFacts.set(edgeKey(edge), {
278
- scope: outInfo.scope,
279
- repeatsPerKey: outInfo.repeatsPerKey,
280
- possibleChildRoots: outInfo.possibleChildRoots
281
- });
282
- }
283
- };
284
- for (const node of order) {
285
- if (node.type === LOOP_NODE_TYPE) {
286
- recordNode(node, analyzeLoopNode(node, incomingByNode.get(node.id) ?? [], backEdgesByLoop.get(node.id) ?? [], edgeFacts, issues));
287
- continue;
288
- }
289
- const inputs = new Map();
290
- const outputs = new Map();
291
- // Stryker disable next-line ArrayDeclaration: defensive ?? fallback equivalent — a bogus incoming entry has an undefined handle and empty scope, contributing nothing
292
- const incoming = incomingByNode.get(node.id) ?? [];
293
- // Group edges by target handle.
294
- const byHandle = new Map();
295
- for (const edge of incoming) {
296
- let arr = byHandle.get(edge.targetHandle);
297
- if (!arr) {
298
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus edge has no edgeFacts entry and is skipped
299
- arr = [];
300
- byHandle.set(edge.targetHandle, arr);
301
- }
302
- arr.push(edge);
303
- }
304
- // Compute per-input-handle effective scope.
305
- for (const [handle, edges] of byHandle) {
306
- // Stryker disable next-line ConditionalExpression,EqualityOperator: `isList` is only consulted under `edges.length > 1`, so the count test here is redundant with that guard
307
- const isList = edges.length > 1 && isListTypeHandle(node, handle);
308
- if (edges.length > 1 && !isList) {
309
- issues.push({
310
- nodeId: node.id,
311
- nodeType: node.type,
312
- handle,
313
- message: `Handle "${handle}" receives ${edges.length} edges but is not a list type; this is invalid under correlation analysis. ` +
314
- "To gather several values into one list, wire them into a list-typed input such as `value` on nodetool.constant.List."
315
- });
316
- }
317
- let effectiveScope = [];
318
- let repeats = false;
319
- const childRoots = new Set();
320
- for (const edge of edges) {
321
- const ef = edgeFacts.get(edgeKey(edge));
322
- if (!ef) {
323
- // Edge from a node we haven't analyzed yet — shouldn't happen with
324
- // a valid topo order. Treat as empty.
325
- continue;
326
- }
327
- // Stryker disable next-line ConditionalExpression: equivalent — largerScope([], ef.scope) returns ef.scope, so the else branch yields the same result on the first edge
328
- if (effectiveScope.length === 0) {
329
- effectiveScope = ef.scope;
330
- }
331
- else {
332
- const larger = largerScope(effectiveScope, ef.scope);
333
- if (larger === null) {
334
- issues.push({
335
- nodeId: node.id,
336
- nodeType: node.type,
337
- handle,
338
- message: `Multi-edge list handle "${handle}" has incomparable source-edge scopes (${formatScope(effectiveScope)} vs ${formatScope(ef.scope)}); reject the graph or aggregate upstream.`
339
- });
340
- continue;
341
- }
342
- effectiveScope = larger;
343
- }
344
- if (ef.repeatsPerKey)
345
- repeats = true;
346
- for (const r of ef.possibleChildRoots)
347
- childRoots.add(r);
348
- }
349
- inputs.set(handle, {
350
- scope: effectiveScope,
351
- repeatsPerKey: repeats,
352
- isMultiEdge: edges.length > 1,
353
- possibleChildRoots: childRoots
354
- });
355
- }
356
- // Compute invocation scope: the largest non-empty input scope. Validate
357
- // that all non-empty input scopes are pairwise prefix-comparable.
358
- //
359
- // Join nodes (Zip/Cross, §7) are the only nodes allowed to receive
360
- // incomparable scopes. Their invocation scope is the longest common
361
- // parent prefix across all non-empty input scopes; their iteration
362
- // outputs append the join root on top of that prefix.
363
- let invocationScope = [];
364
- const nonEmptyHandles = [];
365
- for (const [handle, info] of inputs) {
366
- if (info.scope.length === 0)
367
- continue;
368
- nonEmptyHandles.push(handle);
369
- }
370
- if (!node.is_join_node) {
371
- // Stryker disable next-line EqualityOperator: `<=` is equivalent — the extra outer iteration runs an empty inner loop (j starts past the end), touching nothing
372
- for (let i = 0; i < nonEmptyHandles.length; i++) {
373
- for (let j = i + 1; j < nonEmptyHandles.length; j++) {
374
- const a = inputs.get(nonEmptyHandles[i]).scope;
375
- const b = inputs.get(nonEmptyHandles[j]).scope;
376
- if (!comparable(a, b)) {
377
- issues.push({
378
- nodeId: node.id,
379
- nodeType: node.type,
380
- message: `Inputs "${nonEmptyHandles[i]}" and "${nonEmptyHandles[j]}" come from independent iteration sources (scopes ${formatScope(a)} and ${formatScope(b)}). Add Zip or Cross to declare how they should join.`
381
- });
382
- }
383
- }
384
- }
385
- for (const handle of nonEmptyHandles) {
386
- const sc = inputs.get(handle).scope;
387
- // Stryker disable next-line EqualityOperator: `>=` is equivalent — non-join inputs are pairwise comparable, so equal-length scopes are identical and reassigning changes nothing
388
- if (sc.length > invocationScope.length)
389
- invocationScope = sc;
390
- }
391
- }
392
- else {
393
- // Compute longest common parent prefix across all non-empty inputs.
394
- let common = null;
395
- for (const handle of nonEmptyHandles) {
396
- const sc = inputs.get(handle).scope;
397
- if (common === null) {
398
- common = sc;
399
- continue;
400
- }
401
- let i = 0;
402
- // Stryker disable next-line EqualityOperator,LogicalOperator,ConditionalExpression: variants are equivalent — the `common[i] === sc[i]` element check (undefined past either end) stops the loop at the same index
403
- while (i < common.length && i < sc.length && common[i] === sc[i])
404
- i++;
405
- common = common.slice(0, i);
406
- }
407
- // Stryker disable next-line LogicalOperator,ArrayDeclaration: defensive ?? — a join node always has at least one non-empty input here, so common is non-null
408
- invocationScope = common ?? [];
409
- }
410
- // Determine input mode (for output validation rules).
411
- const isBuffered = !node.input_mode || node.input_mode === "buffered" || node.input_mode === "controlled";
412
- // Compute per-output static facts.
413
- const outputCorr = node.output_correlation ?? {};
414
- // A dynamic output (a Code node's handles) is a declared output too: the
415
- // editor saves it only in `dynamic_outputs`, not in `outputs`.
416
- const outputHandles = [
417
- ...new Set([
418
- ...Object.keys(node.outputs ?? {}),
419
- ...Object.keys(node.dynamic_outputs ?? {})
420
- ])
421
- ];
422
- // For source nodes (no inputs declared) with no output_correlation entries,
423
- // we still need to emit empty-scope facts so downstream edges work.
424
- const handlesToProcess = outputHandles.length > 0
425
- ? outputHandles
426
- : Object.keys(outputCorr);
427
- // A dynamic output has no class-level entry: its handle exists only on
428
- // this instance, so the instance may say how it emits (an App node whose
429
- // inner workflow streams that output).
430
- const dynamicCorr = node.dynamic_output_correlation ?? {};
431
- const dynamicHandles = new Set(Object.keys(node.dynamic_outputs ?? {}));
432
- for (const handle of handlesToProcess) {
433
- const corr = outputCorr[handle] ??
434
- (dynamicHandles.has(handle) ? dynamicCorr[handle] : undefined);
435
- // Default behavior when no correlation metadata is provided: treat as
436
- // `single` with `__execution__` source. This keeps the analyzer usable
437
- // on legacy/test graphs where not every node has filled in metadata.
438
- const kind = corr?.kind ?? "single";
439
- const source = corr?.source ?? "__execution__";
440
- const group = corr?.group;
441
- const collapse = corr?.collapse;
442
- // Resolve base scope.
443
- let base;
444
- let contributorEdges = EMPTY_SET;
445
- if (source === "__execution__") {
446
- // Repeats propagate from any single-edge non-list input at the
447
- // invocation scope that itself repeats.
448
- let repeatsAtExec = false;
449
- const roots = new Set();
450
- for (const [, info] of inputs) {
451
- // Stryker disable next-line ConditionalExpression: equivalent — an empty-scope input contributes no child roots and never repeats at a non-empty invocation scope
452
- if (info.scope.length === 0)
453
- continue;
454
- // Only inputs whose scope can satisfy the invocation scope.
455
- // Stryker disable next-line ConditionalExpression: equivalent — in a valid graph every input scope is comparable with the invocation scope, so this only skips inputs after an already-reported incomparability error, where downstream facts are moot
456
- if (!comparable(info.scope, invocationScope))
457
- continue;
458
- if (info.repeatsPerKey && info.scope.length === invocationScope.length) {
459
- repeatsAtExec = true;
460
- }
461
- for (const r of info.possibleChildRoots)
462
- roots.add(r);
463
- }
464
- base = { scope: invocationScope, repeats: repeatsAtExec, possibleChildRoots: roots };
465
- // Close-barrier contributors: all connected data source edges with
466
- // non-empty scopes that are prefix-comparable with the output scope.
467
- const set = new Set();
468
- for (const edge of incoming) {
469
- const ef = edgeFacts.get(edgeKey(edge));
470
- if (!ef)
471
- continue;
472
- if (ef.scope.length === 0)
473
- continue; // config / empty-scope
474
- // Stryker disable next-line ConditionalExpression: equivalent — incoming edge scopes are comparable with the invocation/base scope in valid graphs; this only skips after an already-reported error
475
- if (!comparable(ef.scope, base.scope))
476
- continue;
477
- set.add(edgeKey(edge));
478
- }
479
- contributorEdges = set;
480
- }
481
- else {
482
- // Source names an input handle.
483
- const sourceInput = inputs.get(source);
484
- if (!sourceInput) {
485
- // No edge connected to that handle: treat the source as empty scope.
486
- base = {
487
- scope: [],
488
- repeats: false,
489
- possibleChildRoots: EMPTY_SET
490
- };
491
- }
492
- else {
493
- base = {
494
- scope: sourceInput.scope,
495
- repeats: sourceInput.repeatsPerKey,
496
- possibleChildRoots: sourceInput.possibleChildRoots
497
- };
498
- // Validate forward's source is single-edge.
499
- if (kind === "forward" && sourceInput.isMultiEdge) {
500
- issues.push({
501
- nodeId: node.id,
502
- nodeType: node.type,
503
- handle,
504
- message: `forward outputs may not name a multi-edge list handle ("${source}") as source.`
505
- });
506
- }
507
- // Contributors: source edges feeding that handle whose scopes are
508
- // comparable with the output scope.
509
- const set = new Set();
510
- // Stryker disable next-line ArrayDeclaration: defensive ?? — sourceInput exists, so byHandle has this source handle
511
- const handleEdges = byHandle.get(source) ?? [];
512
- for (const edge of handleEdges) {
513
- const ef = edgeFacts.get(edgeKey(edge));
514
- // Stryker disable next-line ConditionalExpression: defensive — edges on a resolved handle always have facts in topo order
515
- if (!ef)
516
- continue;
517
- // Stryker disable next-line ConditionalExpression: equivalent — an empty-scope (config) edge is never a close-barrier contributor; excluding vs including it does not change observable scheduling here
518
- if (ef.scope.length === 0)
519
- continue;
520
- set.add(edgeKey(edge));
521
- }
522
- contributorEdges = set;
523
- }
524
- }
525
- // Validate metadata shapes.
526
- if (corr && !corr.source) {
527
- issues.push({
528
- nodeId: node.id,
529
- nodeType: node.type,
530
- handle,
531
- message: `Output "${handle}" omits required "source".`
532
- });
533
- }
534
- if (kind === "forward" && source === "__execution__") {
535
- issues.push({
536
- nodeId: node.id,
537
- nodeType: node.type,
538
- handle,
539
- message: `forward outputs may not use source "__execution__".`
540
- });
541
- }
542
- if (kind === "aggregate") {
543
- if (!collapse) {
544
- issues.push({
545
- nodeId: node.id,
546
- nodeType: node.type,
547
- handle,
548
- message: `aggregate output requires "collapse".`
549
- });
550
- }
551
- if (isBuffered) {
552
- issues.push({
553
- nodeId: node.id,
554
- nodeType: node.type,
555
- handle,
556
- message: `aggregate outputs are only valid on input_mode: "stream"; node is buffered.`
557
- });
558
- }
559
- }
560
- const transformed = applyOutputKind(kind, group, collapse, node.id, handle, base);
561
- // Validate non-aggregate buffered outputs are not strict-prefix of invocation.
562
- if (isBuffered &&
563
- kind !== "aggregate" &&
564
- // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent — with a zero-length invocation, the `transformed.scope.length < invocationScope.length` check below is already false, so > 0 vs >= 0/true do not differ
565
- invocationScope.length > 0 &&
566
- transformed.scope.length < invocationScope.length &&
567
- isPrefixOf(transformed.scope, invocationScope)) {
568
- issues.push({
569
- nodeId: node.id,
570
- nodeType: node.type,
571
- handle,
572
- message: `Buffered output "${handle}" has scope ${formatScope(transformed.scope)} which is a strict prefix of the invocation scope ${formatScope(invocationScope)}.`
573
- });
574
- }
575
- outputs.set(handle, {
576
- scope: transformed.scope,
577
- repeatsPerKey: transformed.repeats,
578
- possibleChildRoots: transformed.possibleChildRoots,
579
- closeBarrierContributors: contributorEdges
580
- });
581
- }
582
- // Validate buffered node repeats_per_key rules.
583
- if (isBuffered) {
584
- const repeatingAtExec = [];
585
- for (const [handle, info] of inputs) {
586
- if (info.scope.length !== invocationScope.length)
587
- continue;
588
- if (!info.repeatsPerKey)
589
- continue;
590
- repeatingAtExec.push(handle);
591
- }
592
- if (repeatingAtExec.length > 1) {
593
- issues.push({
594
- nodeId: node.id,
595
- nodeType: node.type,
596
- message: `Buffered node has more than one repeats_per_key input at the execution scope: ${repeatingAtExec.join(", ")}.`
597
- });
598
- }
599
- if (repeatingAtExec.length === 1) {
600
- const handle = repeatingAtExec[0];
601
- const info = inputs.get(handle);
602
- if (info.isMultiEdge) {
603
- issues.push({
604
- nodeId: node.id,
605
- nodeType: node.type,
606
- handle,
607
- message: `Buffered node's only repeats_per_key execution-scope input "${handle}" is a multi-edge list handle; repeating list handles need stream/aggregate handling.`
608
- });
609
- }
610
- }
611
- // Repeating chunk input as strict-prefix sticky value:
612
- for (const [handle, info] of inputs) {
613
- if (!info.repeatsPerKey)
614
- continue;
615
- if (info.scope.length === 0)
616
- continue;
617
- if (info.scope.length < invocationScope.length) {
618
- issues.push({
619
- nodeId: node.id,
620
- nodeType: node.type,
621
- handle,
622
- message: `Buffered node may not use repeats_per_key input "${handle}" as a strict-prefix sticky value.`
623
- });
624
- }
625
- }
626
- }
627
- recordNode(node, { invocationScope, inputs, outputs });
628
- }
629
- validateLoops(graphData.nodes, dataEdges, backEdgesByLoop, edgeFacts, nodeFacts, issues);
630
- if (options.throwOnIssue && issues.length > 0) {
631
- throw new CorrelationAnalysisError(issues);
632
- }
633
- return { edges: edgeFacts, nodes: nodeFacts, issues };
634
- }
635
- // ---------------------------------------------------------------------------
636
- // Loops (docs/workflow-loops.md)
637
- // ---------------------------------------------------------------------------
638
- /**
639
- * Static facts for a Loop node. Its invocation scope is the scope of
640
- * `initial`; `value`/`index` add the loop root on top of it and `done`
641
- * returns to it. The feedback inputs are assigned the loop scope up front,
642
- * before the body that feeds them has been analyzed.
643
- */
644
- function analyzeLoopNode(node, incoming, backEdges, edgeFacts, issues) {
645
- const inputs = new Map();
646
- const outputs = new Map();
647
- const issue = (message, handle) => issues.push({ nodeId: node.id, nodeType: node.type, handle, message });
648
- let invocationScope = [];
649
- let initialRoots = EMPTY_SET;
650
- const initialContributors = new Set();
651
- const initialEdges = incoming.filter((e) => e.targetHandle === "initial");
652
- if (initialEdges.length > 1) {
653
- issue(`Loop input "initial" receives ${initialEdges.length} edges; a loop run starts from one value.`, "initial");
654
- }
655
- const initialEdge = initialEdges[0];
656
- if (initialEdge) {
657
- const ef = edgeFacts.get(edgeKey(initialEdge));
658
- if (ef) {
659
- invocationScope = ef.scope;
660
- initialRoots = ef.possibleChildRoots;
661
- if (ef.repeatsPerKey) {
662
- issue(`Loop input "initial" receives a chunk stream; a loop run starts from one value. Collect the stream first.`, "initial");
663
- }
664
- if (ef.scope.length > 0)
665
- initialContributors.add(edgeKey(initialEdge));
666
- }
667
- inputs.set("initial", {
668
- scope: invocationScope,
669
- repeatsPerKey: false,
670
- isMultiEdge: false,
671
- possibleChildRoots: initialRoots
672
- });
673
- }
674
- for (const edge of incoming) {
675
- if (edge.targetHandle === "initial")
676
- continue;
677
- issue(`Loop input "${edge.targetHandle}" cannot be wired; set it as a property.`, edge.targetHandle);
678
- }
679
- const root = loopRootId(node.id);
680
- const loopScope = [...invocationScope, root];
681
- const loopRoots = new Set(initialRoots);
682
- loopRoots.add(root);
683
- for (const handle of LOOP_FEEDBACK_HANDLES) {
684
- const edges = backEdges.filter((e) => e.targetHandle === handle);
685
- if (edges.length === 0)
686
- continue;
687
- if (edges.length > 1) {
688
- issue(`Loop input "${handle}" receives ${edges.length} edges; each iteration feeds back one value.`, handle);
689
- }
690
- inputs.set(handle, {
691
- scope: loopScope,
692
- repeatsPerKey: false,
693
- isMultiEdge: edges.length > 1,
694
- possibleChildRoots: loopRoots
695
- });
696
- }
697
- if (!backEdges.some((e) => e.targetHandle === "next")) {
698
- issue(`Loop has no feedback: connect the loop body's result to its "next" input.`, "next");
699
- }
700
- const iterationFacts = {
701
- scope: loopScope,
702
- repeatsPerKey: false,
703
- possibleChildRoots: loopRoots,
704
- closeBarrierContributors: initialContributors
705
- };
706
- outputs.set("value", iterationFacts);
707
- outputs.set("index", iterationFacts);
708
- outputs.set("done", {
709
- scope: invocationScope,
710
- repeatsPerKey: false,
711
- possibleChildRoots: initialRoots,
712
- closeBarrierContributors: initialContributors
713
- });
714
- return { invocationScope, inputs, outputs };
715
- }
716
- /**
717
- * Checks that need the whole graph analyzed: every back edge carries its
718
- * loop's scope, and no node in a loop body aggregates a stream.
719
- */
720
- function validateLoops(nodes, forwardDataEdges, backEdgesByLoop, edgeFacts, nodeFacts, issues) {
721
- if (backEdgesByLoop.size === 0)
722
- return;
723
- const byId = new Map(nodes.map((n) => [n.id, n]));
724
- const successors = new Map();
725
- const predecessors = new Map();
726
- const link = (adj, from, to) => {
727
- const list = adj.get(from);
728
- if (list)
729
- list.push(to);
730
- else
731
- adj.set(from, [to]);
732
- };
733
- for (const edge of forwardDataEdges) {
734
- link(successors, edge.source, edge.target);
735
- link(predecessors, edge.target, edge.source);
736
- }
737
- const reach = (starts, adj) => {
738
- const seen = new Set();
739
- const pending = [...starts];
740
- while (pending.length > 0) {
741
- const id = pending.pop();
742
- if (seen.has(id))
743
- continue;
744
- seen.add(id);
745
- pending.push(...(adj.get(id) ?? []));
746
- }
747
- return seen;
748
- };
749
- for (const [loopId, backEdges] of backEdgesByLoop) {
750
- const loop = byId.get(loopId);
751
- const loopFacts = nodeFacts.get(loopId);
752
- if (!loop || !loopFacts)
753
- continue;
754
- const loopName = loop.name ?? loopId;
755
- for (const edge of backEdges) {
756
- const ef = edgeFacts.get(edgeKey(edge));
757
- const expected = loopFacts.inputs.get(edge.targetHandle)?.scope;
758
- if (!ef || !expected)
759
- continue;
760
- const issue = (message) => issues.push({
761
- nodeId: loopId,
762
- nodeType: loop.type,
763
- handle: edge.targetHandle,
764
- message
765
- });
766
- if (ef.repeatsPerKey) {
767
- issue(`Loop "${loopName}" input "${edge.targetHandle}" receives a chunk stream from "${edge.source}"; each iteration must feed back one value.`);
768
- }
769
- if (sameScope(ef.scope, expected))
770
- continue;
771
- if (ef.scope.length < expected.length && isPrefixOf(ef.scope, expected)) {
772
- issue(`Loop "${loopName}" input "${edge.targetHandle}" is wired from "${edge.source}", which is outside the loop body (scope ${formatScope(ef.scope)}, expected ${formatScope(expected)}). Wire it from a node downstream of the loop's "value" or "index" output, or set it as a property.`);
773
- }
774
- else if (isPrefixOf(expected, ef.scope)) {
775
- issue(`Loop "${loopName}" input "${edge.targetHandle}" receives one value per item of a nested iteration (scope ${formatScope(ef.scope)}, expected ${formatScope(expected)}). Each iteration must feed back exactly one value.`);
776
- }
777
- else {
778
- issue(`Loop "${loopName}" input "${edge.targetHandle}" is wired from "${edge.source}", which belongs to a different iteration (scope ${formatScope(ef.scope)}, expected ${formatScope(expected)}).`);
779
- }
780
- }
781
- // Body: reachable from the loop and able to reach one of its back edges.
782
- const fromLoop = reach(successors.get(loopId) ?? [], successors);
783
- const toBack = reach(backEdges.map((e) => e.source), predecessors);
784
- for (const id of fromLoop) {
785
- if (id === loopId || !toBack.has(id))
786
- continue;
787
- const bodyNode = byId.get(id);
788
- if (!bodyNode)
789
- continue;
790
- for (const [handle, corr] of Object.entries(bodyNode.output_correlation ?? {})) {
791
- if (corr.kind !== "aggregate")
792
- continue;
793
- issues.push({
794
- nodeId: id,
795
- nodeType: bodyNode.type,
796
- handle,
797
- message: `Node "${bodyNode.name ?? id}" aggregates a stream inside the body of loop "${loopName}". An aggregate emits when its input stream ends, which inside a loop body happens only after the loop has finished.`
798
- });
799
- }
800
- }
801
- }
802
- }
803
- function sameScope(a, b) {
804
- return a.length === b.length && isPrefixOf(a, b);
805
- }
806
- function formatScope(scope) {
807
- return `[${scope.join(", ")}]`;
808
- }
809
- /**
810
- * Project a runtime lineage onto an ordered static scope.
811
- *
812
- * Inboxes use this to bucket envelopes by the correct prefix without relying
813
- * on JavaScript object property order. The result is a canonical string key
814
- * built from `root=index` pairs in scope order.
815
- */
816
- export function projectLineageKey(lineage, scope) {
817
- // Stryker disable next-line ConditionalExpression: equivalent fast-path — an empty scope yields an empty parts array, which joins to "" anyway
818
- if (scope.length === 0)
819
- return "";
820
- const parts = [];
821
- for (const root of scope) {
822
- const tok = lineage[root];
823
- if (!tok)
824
- return ""; // not enough lineage to project; caller decides
825
- parts.push(`${root}=${tok.index}`);
826
- }
827
- return parts.join(",");
828
- }
829
- /**
830
- * Same as `projectLineageKey` but returns `null` if any root is missing,
831
- * letting the caller distinguish "empty key" from "incomplete projection".
832
- */
833
- export function tryProjectLineageKey(lineage, scope) {
834
- // Stryker disable next-line ConditionalExpression: equivalent fast-path — an empty scope joins to "" anyway
835
- if (scope.length === 0)
836
- return "";
837
- const parts = [];
838
- for (const root of scope) {
839
- const tok = lineage[root];
840
- if (!tok)
841
- return null;
842
- parts.push(`${root}=${tok.index}`);
843
- }
844
- return parts.join(",");
845
- }
1
+ export * from "@nodetool-ai/execution-core/correlation-analysis";
846
2
  //# sourceMappingURL=correlation-analysis.js.map