@beehexa/hexasync-template-validate 2608.15.1 → 2608.20.18

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 (121) hide show
  1. package/package.json +6 -6
  2. package/dist/index.d.ts +0 -39
  3. package/dist/index.d.ts.map +0 -1
  4. package/dist/index.js +0 -39
  5. package/dist/index.js.map +0 -1
  6. package/dist/validate/agentAnswers.d.ts +0 -48
  7. package/dist/validate/agentAnswers.d.ts.map +0 -1
  8. package/dist/validate/agentAnswers.js +0 -84
  9. package/dist/validate/agentAnswers.js.map +0 -1
  10. package/dist/validate/agentTools.d.ts +0 -37
  11. package/dist/validate/agentTools.d.ts.map +0 -1
  12. package/dist/validate/agentTools.js +0 -141
  13. package/dist/validate/agentTools.js.map +0 -1
  14. package/dist/validate/buildValidationModel.d.ts +0 -31
  15. package/dist/validate/buildValidationModel.d.ts.map +0 -1
  16. package/dist/validate/buildValidationModel.js +0 -68
  17. package/dist/validate/buildValidationModel.js.map +0 -1
  18. package/dist/validate/context.d.ts +0 -108
  19. package/dist/validate/context.d.ts.map +0 -1
  20. package/dist/validate/context.js +0 -95
  21. package/dist/validate/context.js.map +0 -1
  22. package/dist/validate/contextFromGraph.d.ts +0 -68
  23. package/dist/validate/contextFromGraph.d.ts.map +0 -1
  24. package/dist/validate/contextFromGraph.js +0 -81
  25. package/dist/validate/contextFromGraph.js.map +0 -1
  26. package/dist/validate/harvestPullerTaskIds.d.ts +0 -60
  27. package/dist/validate/harvestPullerTaskIds.d.ts.map +0 -1
  28. package/dist/validate/harvestPullerTaskIds.js +0 -116
  29. package/dist/validate/harvestPullerTaskIds.js.map +0 -1
  30. package/dist/validate/model.d.ts +0 -14
  31. package/dist/validate/model.d.ts.map +0 -1
  32. package/dist/validate/model.js +0 -97
  33. package/dist/validate/model.js.map +0 -1
  34. package/dist/validate/registry.d.ts +0 -24
  35. package/dist/validate/registry.d.ts.map +0 -1
  36. package/dist/validate/registry.js +0 -101
  37. package/dist/validate/registry.js.map +0 -1
  38. package/dist/validate/retrieve.d.ts +0 -125
  39. package/dist/validate/retrieve.d.ts.map +0 -1
  40. package/dist/validate/retrieve.js +0 -272
  41. package/dist/validate/retrieve.js.map +0 -1
  42. package/dist/validate/rule.d.ts +0 -18
  43. package/dist/validate/rule.d.ts.map +0 -1
  44. package/dist/validate/rule.js +0 -2
  45. package/dist/validate/rule.js.map +0 -1
  46. package/dist/validate/ruleCatalog.d.ts +0 -22
  47. package/dist/validate/ruleCatalog.d.ts.map +0 -1
  48. package/dist/validate/ruleCatalog.js +0 -473
  49. package/dist/validate/ruleCatalog.js.map +0 -1
  50. package/dist/validate/rules/apiShape.d.ts +0 -51
  51. package/dist/validate/rules/apiShape.d.ts.map +0 -1
  52. package/dist/validate/rules/apiShape.js +0 -150
  53. package/dist/validate/rules/apiShape.js.map +0 -1
  54. package/dist/validate/rules/arguments.d.ts +0 -3
  55. package/dist/validate/rules/arguments.d.ts.map +0 -1
  56. package/dist/validate/rules/arguments.js +0 -301
  57. package/dist/validate/rules/arguments.js.map +0 -1
  58. package/dist/validate/rules/connectorIdentity.d.ts +0 -3
  59. package/dist/validate/rules/connectorIdentity.d.ts.map +0 -1
  60. package/dist/validate/rules/connectorIdentity.js +0 -347
  61. package/dist/validate/rules/connectorIdentity.js.map +0 -1
  62. package/dist/validate/rules/context.d.ts +0 -42
  63. package/dist/validate/rules/context.d.ts.map +0 -1
  64. package/dist/validate/rules/context.js +0 -92
  65. package/dist/validate/rules/context.js.map +0 -1
  66. package/dist/validate/rules/dependencyIntegrity.d.ts +0 -60
  67. package/dist/validate/rules/dependencyIntegrity.d.ts.map +0 -1
  68. package/dist/validate/rules/dependencyIntegrity.js +0 -296
  69. package/dist/validate/rules/dependencyIntegrity.js.map +0 -1
  70. package/dist/validate/rules/duplicates.d.ts +0 -27
  71. package/dist/validate/rules/duplicates.d.ts.map +0 -1
  72. package/dist/validate/rules/duplicates.js +0 -337
  73. package/dist/validate/rules/duplicates.js.map +0 -1
  74. package/dist/validate/rules/flow.d.ts +0 -57
  75. package/dist/validate/rules/flow.d.ts.map +0 -1
  76. package/dist/validate/rules/flow.js +0 -714
  77. package/dist/validate/rules/flow.js.map +0 -1
  78. package/dist/validate/rules/overwriteLoss.d.ts +0 -23
  79. package/dist/validate/rules/overwriteLoss.d.ts.map +0 -1
  80. package/dist/validate/rules/overwriteLoss.js +0 -40
  81. package/dist/validate/rules/overwriteLoss.js.map +0 -1
  82. package/dist/validate/rules/pullerKind.d.ts +0 -3
  83. package/dist/validate/rules/pullerKind.d.ts.map +0 -1
  84. package/dist/validate/rules/pullerKind.js +0 -92
  85. package/dist/validate/rules/pullerKind.js.map +0 -1
  86. package/dist/validate/rules/reference.d.ts +0 -44
  87. package/dist/validate/rules/reference.d.ts.map +0 -1
  88. package/dist/validate/rules/reference.js +0 -405
  89. package/dist/validate/rules/reference.js.map +0 -1
  90. package/dist/validate/rules/referenceKind.d.ts +0 -25
  91. package/dist/validate/rules/referenceKind.d.ts.map +0 -1
  92. package/dist/validate/rules/referenceKind.js +0 -235
  93. package/dist/validate/rules/referenceKind.js.map +0 -1
  94. package/dist/validate/rules/retiredType.d.ts +0 -149
  95. package/dist/validate/rules/retiredType.d.ts.map +0 -1
  96. package/dist/validate/rules/retiredType.js +0 -235
  97. package/dist/validate/rules/retiredType.js.map +0 -1
  98. package/dist/validate/rules/stepData.d.ts +0 -122
  99. package/dist/validate/rules/stepData.d.ts.map +0 -1
  100. package/dist/validate/rules/stepData.js +0 -249
  101. package/dist/validate/rules/stepData.js.map +0 -1
  102. package/dist/validate/rules/stepIterations.d.ts +0 -49
  103. package/dist/validate/rules/stepIterations.d.ts.map +0 -1
  104. package/dist/validate/rules/stepIterations.js +0 -156
  105. package/dist/validate/rules/stepIterations.js.map +0 -1
  106. package/dist/validate/rules/tables.d.ts +0 -8
  107. package/dist/validate/rules/tables.d.ts.map +0 -1
  108. package/dist/validate/rules/tables.js +0 -116
  109. package/dist/validate/rules/tables.js.map +0 -1
  110. package/dist/validate/rules/variableDrift.d.ts +0 -63
  111. package/dist/validate/rules/variableDrift.d.ts.map +0 -1
  112. package/dist/validate/rules/variableDrift.js +0 -132
  113. package/dist/validate/rules/variableDrift.js.map +0 -1
  114. package/dist/validate/rules/variables.d.ts +0 -12
  115. package/dist/validate/rules/variables.d.ts.map +0 -1
  116. package/dist/validate/rules/variables.js +0 -207
  117. package/dist/validate/rules/variables.js.map +0 -1
  118. package/dist/validate/sourceLocator.d.ts +0 -32
  119. package/dist/validate/sourceLocator.d.ts.map +0 -1
  120. package/dist/validate/sourceLocator.js +0 -166
  121. package/dist/validate/sourceLocator.js.map +0 -1
@@ -1,714 +0,0 @@
1
- import { isNewKindPuller, stepType as stepKind, } from '../harvestPullerTaskIds.js';
2
- function arr(cnf, key) {
3
- const v = cnf?.[key];
4
- return Array.isArray(v) ? v : [];
5
- }
6
- function isDynamic(v) {
7
- return typeof v === 'string' && /\{\{[\s\S]*\}\}/.test(v);
8
- }
9
- // blank = unset for routing purposes (null/undefined or an empty/whitespace string).
10
- function isBlank(v) {
11
- return v == null || (typeof v === 'string' && v.trim() === '');
12
- }
13
- /** Every real step key in an array. Used to mark EACH step of an independently-scheduled
14
- * phase (onErrorSteps / finalSteps) as a valid graph entry (F4): those phases are step
15
- * lists the engine runs in sequence (with next/branch control flow), so a step that is
16
- * not the head — and is reached only by fall-through, not a `next` edge — is still
17
- * legitimately reachable and must not be reported as a FLOW-3 orphan. */
18
- function allStepKeys(steps) {
19
- const a = Array.isArray(steps) ? steps : [];
20
- const out = [];
21
- for (const s of a)
22
- if (s && typeof s === 'object' && s.key != null)
23
- out.push(String(s.key));
24
- return out;
25
- }
26
- /** True when the puller declares a loop bound at the PULLER level (`maxIterations`). A
27
- * step-level bound is NOT considered here (F3): a step's maxIterations only counts when
28
- * the step is ON the cycle path, which analyzeWorkflow decides against `cycleSet` — a
29
- * bound on some unrelated step in another phase must not satisfy an unrelated cycle. */
30
- function pullerHasMaxIterations(p) {
31
- return p?.maxIterations != null && String(p.maxIterations).trim() !== '';
32
- }
33
- const REMOVED_BIT = 2;
34
- /**
35
- * True when a status value includes the Removed bit, across EVERY ItemStatusParser form
36
- * (worker-data-raw-enhancement AD-3): a name array, a numeric bitfield, a numeric string, or enum
37
- * text (a single name or a comma-combined set, case-insensitive). This intentionally also detects
38
- * the legacy integer form (`2`/`3`) that the previous string-only check missed.
39
- */
40
- export function statusHasRemoved(raw) {
41
- if (raw == null)
42
- return false;
43
- if (Array.isArray(raw))
44
- return raw.some(statusHasRemoved);
45
- if (typeof raw === 'number')
46
- return Number.isInteger(raw) && (raw & REMOVED_BIT) !== 0;
47
- const s = String(raw).trim();
48
- if (s === '')
49
- return false;
50
- // Split on commas so a comma-combined set is checked element-by-element; a numeric element (e.g. "2,3")
51
- // is bitwise-tested, matching the C# ItemStatusParser, so a numeric removal recipe is not missed.
52
- return s.split(',').some((tok) => {
53
- const t = tok.trim();
54
- if (t === '')
55
- return false;
56
- if (/^[+-]?\d+$/.test(t))
57
- return (parseInt(t, 10) & REMOVED_BIT) !== 0;
58
- return t.toLowerCase() === 'removed';
59
- });
60
- }
61
- /**
62
- * True when a step is a removal recipe: an UPDATE_TASK_DATA_STATUS whose statusToAdd includes Removed, OR a
63
- * TRACK_FOR_REMOVAL (which defaults to Removed|Changed when statusToAdd is omitted, and is a removal step by design).
64
- */
65
- function isRemovalSweep(s) {
66
- const kind = stepKind(s);
67
- // TRACK_FOR_REMOVAL is ALWAYS a removal sweep: the executor bakes in the __last_seen<runStart AND
68
- // NOT_HAS_BITS Removed `where` regardless of statusToAdd, so it rewrites unseen rows no matter the status bits.
69
- if (kind === 'TRACK_FOR_REMOVAL')
70
- return true;
71
- if (kind !== 'UPDATE_TASK_DATA_STATUS')
72
- return false;
73
- return statusHasRemoved(s?.statusToAdd ?? s?.data?.statusToAdd);
74
- }
75
- /** Collect outgoing targets from a `next`-shaped value (string key, dynamic, or if/then/else). */
76
- function nextTargets(next, into) {
77
- if (isBlank(next))
78
- return;
79
- if (typeof next === 'string') {
80
- into.push(isDynamic(next) ? { dynamic: true } : { key: next });
81
- return;
82
- }
83
- if (typeof next === 'object') {
84
- const n = next;
85
- nextTargets(n.then, into);
86
- nextTargets(n.else, into);
87
- }
88
- }
89
- /**
90
- * Defects in a `next` TREE, per the step schema's own contract (reported 2026-08-06).
91
- *
92
- * `assets/steps/step.json` models `next` as `oneOf`, and `NextStepBuilder.ResolveNext` implements it:
93
- *
94
- * * a **string** — a step key, or a scriban expression that renders to one. The runtime transforms it and
95
- * returns the result unless it parses as a nested conditional, so a string is a ROUTE and asks nothing;
96
- * * an **object** `{ description?, if, then, else }` with **`required: ['if','then','else']`**, whose `then`
97
- * and `else` each `$ref` back to `next` — so the two forms nest arbitrarily.
98
- *
99
- * An EMPTY branch is not a missing one: it resolves to the empty string, which is "no next step", and the flow
100
- * ends there deliberately.
101
- *
102
- * So the rule is exactly what was reported: *"if there is `if`, then `then` and `else` are required; but if it
103
- * is just a string, it is as is."* A string is a route and needs nothing; an object is a branch and needs all
104
- * three, at every depth.
105
- *
106
- * Iterative, with an explicit stack: `then`/`else` recurse without bound and this walks authored data.
107
- *
108
- * Returns one entry per defective conditional — what is missing, and the `if` expression that identifies it,
109
- * so a report can point at the line the defect is ON rather than at the step's first textual mention.
110
- */
111
- function conditionalDefects(next) {
112
- const out = [];
113
- const stack = [next];
114
- const seen = new Set();
115
- while (stack.length > 0) {
116
- const node = stack.pop();
117
- // A STRING (or a blank) is a route, not a branch. Nothing is required of it — this is the false positive
118
- // the report was about, in one line.
119
- if (node == null || typeof node !== 'object' || Array.isArray(node))
120
- continue;
121
- if (seen.has(node))
122
- continue;
123
- seen.add(node);
124
- const n = node;
125
- /**
126
- * All three keys are required — and an EMPTY one is not missing.
127
- *
128
- * Corrected against the runtime (`core.api/hexasync.steps/Execution/NextStepBuilder.cs`), which the report
129
- * named as the authority. `ResolveNext` transforms a string branch and, when the result does not parse as
130
- * a nested conditional, RETURNS it — so `else: ""` resolves to the empty string, which is "no next step":
131
- * the flow ends there. That is a deliberate terminator and appears in the corpus as one.
132
- *
133
- * My first version of this rule tested `isBlank`, which would have reported every authored `else: ""` as
134
- * a defect — the same false positive the report was about, reintroduced one layer down. The schema agrees
135
- * with the runtime: all three keys are `required`, and `then`/`else` `$ref` a `next` whose string form has
136
- * no minimum length.
137
- */
138
- const missing = ['if', 'then', 'else'].filter((k) => !Object.prototype.hasOwnProperty.call(n, k));
139
- if (missing.length > 0) {
140
- out.push({
141
- missing: [...missing],
142
- ...(typeof n.if === 'string' && n.if.trim() !== '' ? { at: n.if } : {}),
143
- });
144
- }
145
- stack.push(n.then, n.else);
146
- }
147
- return out;
148
- }
149
- /**
150
- * Analyze one workflow's step array for graph-integrity problems (FLOW-3/4/5/6).
151
- * Pure over the array; returns findings (attribution/rendering is the caller's job).
152
- *
153
- * Entry model matches the composer's own flowChart.ts: EVERY `rootStep: true` step is
154
- * an entry node (multiple roots = multiple valid entry chains, a real pattern in shipped
155
- * profiles); if none carry `rootStep`, the first step is the entry. There is intentionally
156
- * NO "multiple roots" or "no root" finding — both are valid per the runtime.
157
- */
158
- export function analyzeWorkflow(steps, opts = {}) {
159
- const findings = [];
160
- const valid = steps.filter((s) => s && typeof s === 'object');
161
- if (valid.length === 0)
162
- return findings;
163
- const keyOf = (s) => (s.key != null ? String(s.key) : undefined);
164
- // Step-type read (F2): match harvest/toFlowStep/isRemovalSweep, which all read
165
- // `displayType ?? type ?? provider`, so a guard authored as `{type:'IF'}` gets its
166
- // then/else edges built and every rule agrees on the same step. The `type` field is
167
- // honoured ONLY for new-kind graphs — old-kind edge building stays byte-identical
168
- // (old steps carry displayType/provider, never `type`, but we gate to be certain).
169
- const typeOf = (s) => String((opts.newKind
170
- ? (s.displayType ?? s.type ?? s.provider)
171
- : (s.displayType ?? s.provider)) ?? '');
172
- const keySet = new Set();
173
- for (const s of valid) {
174
- const k = keyOf(s);
175
- if (k != null)
176
- keySet.add(k);
177
- }
178
- // Entries = all rootStep steps (like flowChart.ts); else the first step. Plus any
179
- // caller-supplied extra entries (new-kind onErrorSteps / finalSteps heads, which run
180
- // independently and so legitimately have no inbound `next` edge).
181
- const entrySet = new Set();
182
- for (const s of valid) {
183
- if (s.rootStep === true) {
184
- const k = keyOf(s);
185
- if (k != null)
186
- entrySet.add(k);
187
- }
188
- }
189
- if (entrySet.size === 0) {
190
- const first = keyOf(valid[0]);
191
- if (first != null)
192
- entrySet.add(first);
193
- }
194
- for (const k of opts.extraEntryKeys ?? [])
195
- if (keySet.has(k))
196
- entrySet.add(k);
197
- // Build outgoing edges per step (FIRST occurrence wins, matching keySet dedupe).
198
- const edges = new Map();
199
- // Exception steps (new-kind): an `EXCEPTION` step (or any step carrying `fromStep`)
200
- // is entered when its `fromStep` throws — a back-reference edge fromStep → this step.
201
- const exceptionSteps = [];
202
- let hasDynamic = false;
203
- for (const s of valid) {
204
- const sk = keyOf(s);
205
- if (sk == null || edges.has(sk))
206
- continue;
207
- const targets = [];
208
- const dt = typeOf(s);
209
- if (dt === 'SWITCH') {
210
- const data = s.data;
211
- const branchKeys = data && typeof data === 'object' && !Array.isArray(data)
212
- ? Object.keys(data)
213
- : [];
214
- if (branchKeys.length === 0) {
215
- findings.push({
216
- ruleId: 'FLOW-6',
217
- severity: 'medium',
218
- message: `SWITCH step "${sk}" has no branches`,
219
- locateValue: sk,
220
- });
221
- }
222
- for (const bk of branchKeys)
223
- targets.push({ key: bk });
224
- }
225
- else if (dt === 'IF') {
226
- const data = s.data;
227
- const then = data && typeof data === 'object' ? data.then : undefined;
228
- const els = data && typeof data === 'object' ? data.else : undefined;
229
- /**
230
- * An IF step's `data` IS its conditional next — verified in the runtime, not inferred.
231
- *
232
- * `IfStepExecutor.ExecuteAsync` passes `StepData` — the step's own `data` block — straight into
233
- * `NextStepBuilder.BuildWithTrace`. So `data: { if, then, else }` is resolved by exactly the same
234
- * `ResolveNext` walk as a `next:` object, and the two forms are one thing wearing two names.
235
- *
236
- * A branch may therefore live in `data` or on `next`, and an EMPTY branch is a terminator rather than a
237
- * defect (see `conditionalDefects`). What remains worth reporting is a step that declares no routing at
238
- * all: no `next`, and no `then`/`else` keys in `data`.
239
- */
240
- const dataObject = data && typeof data === 'object' && !Array.isArray(data)
241
- ? data
242
- : undefined;
243
- const declaresBranch = dataObject !== undefined &&
244
- (Object.prototype.hasOwnProperty.call(dataObject, 'then') ||
245
- Object.prototype.hasOwnProperty.call(dataObject, 'else'));
246
- if (!declaresBranch && isBlank(s.next)) {
247
- findings.push({
248
- ruleId: 'FLOW-6',
249
- severity: 'medium',
250
- message: `IF step "${sk}" routes nowhere — no \`next\`, and no \`then\`/\`else\``,
251
- locateValue: sk,
252
- });
253
- }
254
- // The SAME contract as a `next:` object, because it is the same structure — one missing key, reported
255
- // once, wherever the conditional was written.
256
- for (const defect of conditionalDefects(dataObject)) {
257
- findings.push({
258
- ruleId: 'FLOW-6',
259
- severity: 'medium',
260
- message: `IF step "${sk}" is missing ` +
261
- defect.missing.map((k) => `\`${k}\``).join(' and '),
262
- locateValue: defect.at ?? sk,
263
- });
264
- }
265
- nextTargets(then, targets);
266
- nextTargets(els, targets);
267
- nextTargets(s.next, targets);
268
- }
269
- else {
270
- nextTargets(s.next, targets);
271
- }
272
- /**
273
- * The CONDITIONAL contract, for every step — the check the schema states and the rule never made.
274
- *
275
- * `next: { if, then, else }` requires all three at every depth. Reported as its own finding per defective
276
- * conditional, and located by the `if` EXPRESSION rather than by the step key: the other half of the
277
- * report was that the excerpt pointed at a `next:` line belonging to a different step, because a step key
278
- * matches its first textual mention — usually somebody else's reference to it — long before its own
279
- * declaration.
280
- */
281
- for (const defect of conditionalDefects(s.next)) {
282
- findings.push({
283
- ruleId: 'FLOW-6',
284
- severity: 'medium',
285
- message: `step "${sk}" has a conditional \`next\` missing ` +
286
- defect.missing.map((k) => `\`${k}\``).join(' and '),
287
- locateValue: defect.at ?? sk,
288
- });
289
- }
290
- // New-kind per-step `onError` recovery edge (a step key to route to on failure).
291
- // Inert for legacy steps (no `onError`), so old-kind graphs are unchanged.
292
- nextTargets(s.onError, targets);
293
- // Register EXCEPTION steps (or any step declaring `fromStep`) for the back-reference
294
- // edge + FLOW-7 fromStep validation below.
295
- if (dt.toUpperCase() === 'EXCEPTION' || s.fromStep != null) {
296
- const fromStep = s.fromStep;
297
- exceptionSteps.push({
298
- key: sk,
299
- fromStep: fromStep != null ? String(fromStep) : undefined,
300
- });
301
- }
302
- if (targets.some((t) => 'dynamic' in t))
303
- hasDynamic = true;
304
- edges.set(sk, targets);
305
- }
306
- // Exception back-reference edges: an EXCEPTION step is reached from its `fromStep`, so
307
- // add fromStep → exceptionStep. This keeps the exception step from being a false orphan
308
- // and lets a downstream throw be seen as routing into the handler.
309
- for (const ex of exceptionSteps) {
310
- if (ex.fromStep && keySet.has(ex.fromStep)) {
311
- const t = edges.get(ex.fromStep) ?? [];
312
- t.push({ key: ex.key });
313
- edges.set(ex.fromStep, t);
314
- }
315
- }
316
- // FLOW-4 - dangling targets (attribute to the SOURCE step, which is locatable).
317
- const danglingSeen = new Set();
318
- for (const [sk, targets] of edges) {
319
- for (const t of targets) {
320
- if ('dynamic' in t || keySet.has(t.key))
321
- continue;
322
- const dedupe = `${sk}->${t.key}`;
323
- if (danglingSeen.has(dedupe))
324
- continue;
325
- danglingSeen.add(dedupe);
326
- findings.push({
327
- ruleId: 'FLOW-4',
328
- severity: 'high',
329
- message: `step "${sk}" routes to missing step "${t.key}"`,
330
- locateValue: sk,
331
- });
332
- }
333
- }
334
- // In-degree over static, resolvable edges.
335
- const inDegree = new Map();
336
- for (const k of keySet)
337
- inDegree.set(k, 0);
338
- for (const targets of edges.values()) {
339
- for (const t of targets) {
340
- if ('dynamic' in t)
341
- continue;
342
- if (inDegree.has(t.key))
343
- inDegree.set(t.key, inDegree.get(t.key) + 1);
344
- }
345
- }
346
- // FLOW-3 - orphan (a non-entry step with no incoming edge), once per key. Every
347
- // rootStep is an entry, so extra roots are never flagged. Suppressed when the
348
- // workflow has any dynamic next (a step could be reached dynamically).
349
- if (!hasDynamic) {
350
- for (const k of keySet) {
351
- if (entrySet.has(k))
352
- continue;
353
- if ((inDegree.get(k) ?? 0) === 0) {
354
- findings.push({
355
- ruleId: 'FLOW-3',
356
- severity: 'high',
357
- message: `step "${k}" is unreachable (no incoming edge)`,
358
- locateValue: k,
359
- });
360
- }
361
- }
362
- }
363
- // FLOW-5 - a static cycle (iterative DFS with an explicit stack; no recursion so a
364
- // long chain can't overflow — mirrors reference.ts's cycle-safe walk precedent).
365
- const color = new Map(); // 0 unseen, 1 in-stack, 2 done
366
- let cycleAt;
367
- let cycleStackKeys = [];
368
- for (const start of keySet) {
369
- if (color.get(start))
370
- continue;
371
- const stack = [{ key: start, i: 0 }];
372
- color.set(start, 1);
373
- while (stack.length) {
374
- const frame = stack[stack.length - 1];
375
- const targets = edges.get(frame.key) ?? [];
376
- let advanced = false;
377
- while (frame.i < targets.length) {
378
- const t = targets[frame.i++];
379
- if ('dynamic' in t || !keySet.has(t.key))
380
- continue;
381
- const c = color.get(t.key) ?? 0;
382
- if (c === 1) {
383
- cycleAt = t.key;
384
- cycleStackKeys = stack.map((f) => f.key);
385
- break;
386
- }
387
- if (c === 0) {
388
- color.set(t.key, 1);
389
- stack.push({ key: t.key, i: 0 });
390
- advanced = true;
391
- break;
392
- }
393
- }
394
- if (cycleAt)
395
- break;
396
- if (!advanced) {
397
- color.set(frame.key, 2);
398
- stack.pop();
399
- }
400
- }
401
- if (cycleAt)
402
- break;
403
- }
404
- if (cycleAt) {
405
- if (!opts.newKind) {
406
- /**
407
- * Old-kind: ANY back-edge, reported at **`low`** — an advisory, not a defect claim.
408
- *
409
- * Reported by Jazz on 2026-08-11 against
410
- * `001-projects/catafa/sapo-misa/partials/pullers/SapoWeb_SalesOrder_Puller.yaml`: the cycle through
411
- * `CHECK_COUNT` is a paginating loop that terminates, verified by hand, and the rule called it `high`.
412
- *
413
- * The severity now matches what the check actually knows. The new-kind branch below decides something — it tests
414
- * the cycle for a guard, an exit branch and a bound, and only fires when one is missing, so `high` there is a
415
- * finding about the document. This branch tests nothing of the sort: an old-kind puller declares no
416
- * `maxIterations` and the loop's exit lives in a Scriban `next` the static graph cannot evaluate, so EVERY
417
- * old-kind pagination loop — the normal way to write one — lands here. A rule that fires on correct documents as
418
- * loudly as on broken ones teaches readers to skim past its family.
419
- *
420
- * Kept rather than dropped: a back-edge is still worth a reader's eye, and the wording no longer asserts the
421
- * loop is wrong.
422
- */
423
- findings.push({
424
- ruleId: 'FLOW-5',
425
- severity: 'low',
426
- message: `the workflow loops back through step "${cycleAt}" — check that some branch leaves the loop (a static read cannot tell a paginating loop from a runaway one)`,
427
- why: 'a loop with no exit would never terminate — this one may well be fine',
428
- locateValue: cycleAt,
429
- });
430
- }
431
- else {
432
- // New-kind (Story 7.4): a guarded pagination loop is VALID. A back-edge is only a
433
- // finding when it is unguarded (no conditional on the cycle gates re-entry),
434
- // inescapable (no conditional on the cycle has a branch that leaves the loop), or
435
- // unbounded (no maxIterations governs the cycle).
436
- const idxC = cycleStackKeys.indexOf(cycleAt);
437
- const cycleSet = new Set(idxC >= 0 ? cycleStackKeys.slice(idxC) : cycleStackKeys);
438
- // Guarded/escapable (F1): decided by the conditional(s) ON the cycle path, NOT by
439
- // the back-edge's source step. A valid guard-at-top loop (guard IF → body → back to
440
- // guard) has a non-IF back-edge owner but is still correctly gated by the IF; the
441
- // old source-type test false-flagged it. A cycle is GUARDED when it contains an
442
- // IF/SWITCH node, and ESCAPABLE when such a node has a branch that leaves the cycle
443
- // — an explicit target outside cycleSet, or an implicit fall-through (a missing IF
444
- // then/else, or a SWITCH with no default) that ends the loop when re-entry is not
445
- // chosen.
446
- let guarded = false;
447
- let escapable = false;
448
- for (const cs of valid) {
449
- const ck = keyOf(cs);
450
- if (ck == null || !cycleSet.has(ck))
451
- continue;
452
- const ct = typeOf(cs).toUpperCase();
453
- if (ct !== 'IF' && ct !== 'SWITCH')
454
- continue;
455
- guarded = true;
456
- const csTargets = edges.get(ck) ?? [];
457
- const hasExitTarget = csTargets.some((t) => !('dynamic' in t) && keySet.has(t.key) && !cycleSet.has(t.key));
458
- let implicitExit = false;
459
- const d = cs.data;
460
- if (ct === 'IF') {
461
- const hasThen = d && typeof d === 'object' && !isBlank(d.then);
462
- const hasElse = d && typeof d === 'object' && !isBlank(d.else);
463
- implicitExit = !(hasThen && hasElse);
464
- }
465
- else {
466
- const hasDefault = d && typeof d === 'object' && !isBlank(d.default);
467
- implicitExit = !hasDefault;
468
- }
469
- if (hasExitTarget || implicitExit) {
470
- escapable = true;
471
- break;
472
- }
473
- }
474
- // Bounded (F3): a maxIterations governs THIS cycle only when declared at the puller
475
- // level (opts.hasMaxIterations) OR on a step that is ON the cycle path — a bound on
476
- // some unrelated step in another phase must not satisfy this cycle.
477
- const cycleStepBound = valid.some((s) => {
478
- const sk2 = keyOf(s);
479
- if (sk2 == null || !cycleSet.has(sk2))
480
- return false;
481
- const m = s?.maxIterations ?? s?.data?.maxIterations;
482
- return m != null && String(m).trim() !== '';
483
- });
484
- const bounded = !!opts.hasMaxIterations || cycleStepBound;
485
- if (!(guarded && escapable && bounded)) {
486
- const reasons = [];
487
- if (!guarded)
488
- reasons.push('the back-edge is not guarded by a conditional');
489
- else if (!escapable)
490
- reasons.push('the loop has no reachable exit branch');
491
- if (!bounded)
492
- reasons.push('no maxIterations is declared');
493
- findings.push({
494
- ruleId: 'FLOW-5',
495
- severity: 'high',
496
- message: `the workflow loops back through step "${cycleAt}" — ${reasons.join('; ')} (risk of an unbounded loop)`,
497
- locateValue: cycleAt,
498
- });
499
- }
500
- }
501
- }
502
- // FLOW-7 (Story 7.5) — an Exception step whose `fromStep` names no existing step in the
503
- // workflow. New-kind only (old-kind has no Exception steps).
504
- if (opts.newKind) {
505
- for (const ex of exceptionSteps) {
506
- if (!ex.fromStep || !keySet.has(ex.fromStep)) {
507
- findings.push({
508
- ruleId: 'FLOW-7',
509
- severity: 'high',
510
- message: `Exception step "${ex.key}" fromStep "${ex.fromStep ?? ''}" names no existing step`,
511
- locateValue: ex.key,
512
- });
513
- }
514
- }
515
- }
516
- return findings;
517
- }
518
- /**
519
- * Workflow graph-integrity rule (FLOW family). Runs analyzeWorkflow over every step
520
- * array and attributes findings to the owning puller/pusher/webhook.
521
- */
522
- /**
523
- * FLOW-8 — `_outputs.<KEY>` reads that name no step in the component (Story 5.7 AC-3).
524
- *
525
- * ### Why the whole component, never one stage
526
- *
527
- * Reading an EARLIER stage’s output is legitimate and common: an `onErrorSteps` step may read what `steps`
528
- * produced, and `finalSteps` may read either. A per-stage check would report every one of those as dangling — the
529
- * same shape of false positive that put `Missing property "dataPath"` on 27 correct steps in 24 files.
530
- *
531
- * ### Existence, not reachability, and that is deliberate
532
- *
533
- * The AC says *"no reachable step declares"*. This reports only keys declared **nowhere**, which is a strict subset
534
- * and cannot be wrong. Reporting a key that exists but is unreachable from the reading step is a stronger claim that
535
- * needs the flow model’s node index (Story 5.8 built it, on the extension side) and would fire on a guarded loop or
536
- * a stage arrangement this rule cannot see. Existence first; the stronger tier can follow once it can be measured
537
- * against a corpus that uses the namespace at all.
538
- *
539
- * ### Measured before it was written
540
- *
541
- * **Zero corpus files contain `_outputs.`**, and zero use the five new step types that produce the interesting
542
- * outputs. So this fires on nothing today and carries no false-positive risk — it is a guard for a capability as it
543
- * is adopted, not a report on one in use. Stated because "fires on nothing" and "is broken" look identical in a log.
544
- */
545
- const OUTPUTS_REF = /_outputs\.([A-Za-z0-9_-]+)/g;
546
- export function danglingOutputRefs(steps) {
547
- const declared = new Set();
548
- for (const s of steps) {
549
- if (s && typeof s === 'object' && s.key != null)
550
- declared.add(String(s.key));
551
- }
552
- /**
553
- * ⛔ There is deliberately NO `!`-prefix normalisation here, and the first version's was dead code.
554
- *
555
- * A `!KEY` entry is a composer REMOVAL directive rather than a step that runs, so it was skipped when building
556
- * this set — with a comment claiming that counting it "would hide a genuinely dangling read". A mutation removing
557
- * the skip changed nothing and every test still passed, which is correct: the directive is stored under the
558
- * literal key `!FETCH`, and that never matches a read of `FETCH` either way. The guard was inert.
559
- *
560
- * Removed rather than kept-and-explained, because an inert guard invites a future reader to "fix" it by
561
- * NORMALISING — stripping the `!` — and that really would let a removed step satisfy a read of the step it
562
- * removes. The behaviour is asserted below so the absence is deliberate rather than accidental.
563
- */
564
- const out = [];
565
- const seen = new Set();
566
- for (const s of steps) {
567
- if (!s || typeof s !== 'object')
568
- continue;
569
- const at = s.key != null ? String(s.key) : '(step)';
570
- // The step SERIALISED, so a reference anywhere inside `data`, `arguments`, `next` or a nested transform is seen.
571
- let text;
572
- try {
573
- text = JSON.stringify(s) ?? '';
574
- }
575
- catch {
576
- continue; // A cyclic step object is the composer's problem, not this rule's.
577
- }
578
- OUTPUTS_REF.lastIndex = 0;
579
- let m;
580
- while ((m = OUTPUTS_REF.exec(text)) !== null) {
581
- const key = m[1];
582
- if (declared.has(key))
583
- continue;
584
- const dedupe = `${at}->${key}`;
585
- if (seen.has(dedupe))
586
- continue;
587
- seen.add(dedupe);
588
- out.push({ key, at });
589
- }
590
- }
591
- return out;
592
- }
593
- export const flowRule = {
594
- id: 'FLOW',
595
- family: 'FLOW',
596
- run(ctx) {
597
- const cnf = ctx.tokenForm;
598
- if (!cnf || typeof cnf !== 'object')
599
- return [];
600
- const issues = [];
601
- const emit = (parentKey, idOrKey, label, f) => issues.push({
602
- ruleId: f.ruleId,
603
- family: 'FLOW',
604
- severity: f.severity,
605
- parentKey,
606
- idOrKey,
607
- message: `${label}: ${f.message}`,
608
- // The family line, unless the finding knows better — see `FlowFinding.why`.
609
- why: f.why ?? 'the workflow does not execute as authored',
610
- locateValue: f.locateValue,
611
- });
612
- /**
613
- * FLOW-8 over the component's WHOLE step set (Story 5.7 AC-3).
614
- *
615
- * Separate from `check`, which is per stage: reading an earlier stage's output is legitimate, so a per-stage
616
- * dangling check would report every cross-stage read. Called once per component with every stage's steps.
617
- */
618
- const checkOutputs = (component, stages, parentKey, idOrKey) => {
619
- const steps = stages.flatMap((stage) => arr(component, stage));
620
- if (steps.length === 0)
621
- return;
622
- for (const { key, at } of danglingOutputRefs(steps))
623
- emit(parentKey, idOrKey, 'steps', {
624
- ruleId: 'FLOW-8',
625
- severity: 'high',
626
- message: `step "${at}" reads _outputs."${key}", and no step in this component declares that key`,
627
- why: 'the value resolves to nothing at run time, with no error to notice',
628
- locateValue: at,
629
- });
630
- };
631
- const check = (steps, parentKey, idOrKey, label) => {
632
- if (!Array.isArray(steps) || steps.length === 0)
633
- return;
634
- for (const f of analyzeWorkflow(steps))
635
- emit(parentKey, idOrKey, label, f);
636
- };
637
- for (const p of arr(cnf, 'pullers')) {
638
- const pid = p?.id != null ? String(p.id) : undefined;
639
- // Every stage a puller may declare, old kind or new — the union is what a `_outputs` read may legally name.
640
- checkOutputs(p, [
641
- 'beforePullSteps',
642
- 'pullSteps',
643
- 'afterPullSteps',
644
- 'steps',
645
- 'onErrorSteps',
646
- 'finalSteps',
647
- ], 'pullers', pid);
648
- if (isNewKindPuller(p)) {
649
- // New-kind (Stories 7.3–7.5): steps / onErrorSteps / finalSteps form ONE graph —
650
- // `onError` links steps → recovery, and `Exception.fromStep` links back into the
651
- // main flow — so analyze the union. onErrorSteps / finalSteps heads are extra
652
- // entries (scheduled independently, not reached by a `next` edge).
653
- const combined = [
654
- ...arr(p, 'steps'),
655
- ...arr(p, 'onErrorSteps'),
656
- ...arr(p, 'finalSteps'),
657
- ];
658
- // Every onErrorSteps / finalSteps step is a valid entry (F4): these phases are
659
- // step lists the engine runs in sequence, so steps reached by fall-through (not a
660
- // `next` edge) are legitimately reachable — marking them all as entries prevents
661
- // spurious FLOW-3 orphans on a multi-headed phase.
662
- const extraEntryKeys = [
663
- ...allStepKeys(p?.onErrorSteps),
664
- ...allStepKeys(p?.finalSteps),
665
- ];
666
- for (const f of analyzeWorkflow(combined, {
667
- newKind: true,
668
- extraEntryKeys,
669
- hasMaxIterations: pullerHasMaxIterations(p),
670
- }))
671
- emit('pullers', pid, 'steps', f);
672
- // FLOW-7 (Story 7.5) — a removal-recipe UPDATE_TASK_DATA_STATUS
673
- // (statusToAdd includes Removed) in finalSteps would sweep un-pulled pages on a
674
- // partial/mid-loop run; it belongs in `steps`.
675
- for (const s of arr(p, 'finalSteps')) {
676
- if (!s || typeof s !== 'object' || !isRemovalSweep(s))
677
- continue;
678
- const key = s.key != null ? String(s.key) : '(step)';
679
- emit('pullers', pid, 'finalSteps', {
680
- ruleId: 'FLOW-7',
681
- severity: 'high',
682
- message: `removal step "${key}" (statusToAdd includes Removed) is in finalSteps — a partial run would sweep un-pulled pages`,
683
- locateValue: key,
684
- });
685
- }
686
- }
687
- else {
688
- check(p?.beforePullSteps, 'pullers', pid, 'beforePullSteps');
689
- check(p?.pullSteps, 'pullers', pid, 'pullSteps');
690
- check(p?.afterPullSteps, 'pullers', pid, 'afterPullSteps');
691
- }
692
- }
693
- for (const p of arr(cnf, 'pushers')) {
694
- const pid = p?.id != null ? String(p.id) : undefined;
695
- checkOutputs(p, ['beforePushSteps', 'pushSteps', 'afterPushSteps', 'finalSteps'], 'pushers', pid);
696
- check(p?.beforePushSteps, 'pushers', pid, 'beforePushSteps');
697
- check(p?.pushSteps, 'pushers', pid, 'pushSteps');
698
- check(p?.afterPushSteps, 'pushers', pid, 'afterPushSteps');
699
- // The worker runs a pusher's `finalSteps` in a `finally` (`Pusher.cs:509` → `PushStepAccessor.cs:50`), so every
700
- // FLOW-* routing check skipped it — found by Story 4.5's review (H2), together with four other lists.
701
- check(p?.finalSteps, 'pushers', pid, 'finalSteps');
702
- }
703
- for (const w of arr(cnf, 'webhooks')) {
704
- const wid = w?.id != null ? String(w.id) : undefined;
705
- const targets = w?.targets && typeof w.targets === 'object' && !Array.isArray(w.targets)
706
- ? w.targets
707
- : {};
708
- for (const [tk, t] of Object.entries(targets))
709
- check(t?.pullSteps, 'webhooks', wid, `target ${tk} pullSteps`);
710
- }
711
- return issues;
712
- },
713
- };
714
- //# sourceMappingURL=flow.js.map