Repository navigation
Expand file tree
/
Copy pathlint-flow-patterns.test.ts
More file actions
3858 lines (3600 loc) · 193 KB
/
Copy pathlint-flow-patterns.test.ts
File metadata and controls
3858 lines (3600 loc) · 193 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import { TimeRelativeTriggerSchema, LoopConfigSchema, ParallelConfigSchema, TryCatchConfigSchema, HttpConfigSchema, FlowSchema, NotifyConfigSchema, textSlotTemplateRefusal } from '@objectstack/spec/automation';
// [#19939] The value-slot judge, asked by the `flow-bare-dollar-reference` pins
// below for the spelling its hint must carry and for the verdict on it.
import { flowNodeValueTemplateRefusals, VALUE_SLOT_TEMPLATE_REFUSAL, valueSlotTemplateRefusals } from '@objectstack/spec/automation';
import { TYPED_EXPRESSION_DIALECT_ONLY, TYPED_EXPRESSION_SOURCE_REQUIRED } from '@objectstack/spec/shared';
// [#5659] The shared identity reduction, asserted beside the rule that consumes
// it — the rule's verdict and the drivers' verdict are one object now.
import { reduceFilterVerdict } from '@objectstack/spec/data';
// [#17495] The published sentence the blank-condition refusal leads with,
// asserted from the spec's own export rather than re-spelled here — see the
// re-judged pin in `flow-inert-node-condition` below.
import { EVALUATED_EXPRESSION_SOURCE_REQUIRED } from '@objectstack/spec';
import { AUTHORING_RULES } from './authoring-rules.js';
import { explainRule } from './rule-explanations.js';
import {
lintFlowPatterns as lintFlowPatternsUnrecorded,
FLOW_TIME_RELATIVE_ANTIPATTERN,
FLOW_DATE_EQUALITY_FILTER,
FLOW_PHANTOM_AGGREGATION,
FLOW_DOUBLE_BRACE_INTERP,
FLOW_BARE_DOLLAR_REF,
FLOW_APPROVAL_REVISE_DEAD_END,
FLOW_APPROVAL_REVISE_UNMARKED_BACKEDGE,
FLOW_APPROVAL_REVISE_DISABLED,
FLOW_APPROVAL_REVISE_TARGET_NOT_SERVICE_OWNED,
FLOW_RUNAS_UNSCOPED,
FLOW_ERROR_LABEL_NOT_FAULT,
FLOW_BRANCH_LABEL_UNMATCHED,
FLOW_DECISION_UNCONDITIONAL_BRANCH,
FLOW_DEFAULT_EDGE_WITH_CONDITION,
FLOW_MULTIPLE_DEFAULT_EDGES,
FLOW_INERT_NODE_CONDITION,
FLOW_NODE_UNREACHABLE,
FLOW_MULTI_WRITE_UNFILTERED,
FLOW_LOOP_BODY_UNCONTAINED,
FLOW_TRY_CATCH_WITHOUT_CATCH,
FLOW_DECISION_MODE_INVALID,
FLOW_DECISION_INCLUSIVE_OVERLAP,
} from './lint-flow-patterns.js';
// [#17495] Cross-site pin only — the re-judged `flow-inert-node-condition`
// case below. This family's own coverage is unaffected by it;
// `validate-expressions.test.ts` owns the rest of that rule's coverage.
import { validateStackExpressions } from './validate-expressions.js';
// [#22161] Slice 19: every finding of the two wrong-syntax ids is recorded, and
// the hint block at the foot of the file holds each recorded `fix:` line to one
// line of at most 200 characters.
const firedHints: Array<{ rule: string; message: string; hint: string }> = [];
// [#22161] Slice 20: the twelve anti-pattern ids, recorded the same way for the
// second hint block at the foot of the file.
const SLICE_20_IDS: readonly string[] = [
FLOW_LOOP_BODY_UNCONTAINED,
FLOW_MULTI_WRITE_UNFILTERED,
FLOW_TRY_CATCH_WITHOUT_CATCH,
FLOW_DECISION_INCLUSIVE_OVERLAP,
FLOW_APPROVAL_REVISE_TARGET_NOT_SERVICE_OWNED,
FLOW_TIME_RELATIVE_ANTIPATTERN,
FLOW_DATE_EQUALITY_FILTER,
FLOW_RUNAS_UNSCOPED,
FLOW_DECISION_MODE_INVALID,
FLOW_DECISION_UNCONDITIONAL_BRANCH,
FLOW_ERROR_LABEL_NOT_FAULT,
FLOW_BRANCH_LABEL_UNMATCHED,
];
const firedSlice20Hints: Array<{ rule: string; message: string; hint: string }> = [];
const lintFlowPatterns: typeof lintFlowPatternsUnrecorded = (...args) => {
const findings = lintFlowPatternsUnrecorded(...args);
for (const f of findings) {
if (f.rule === FLOW_DOUBLE_BRACE_INTERP || f.rule === FLOW_BARE_DOLLAR_REF) firedHints.push(f as { rule: string; message: string; hint: string });
if (SLICE_20_IDS.includes(f.rule)) firedSlice20Hints.push(f as { rule: string; message: string; hint: string });
}
return findings;
};
/** [#22161] What `os explain RULE_ID` prints for `rule`, one paragraph per line. */
const explained = (rule: string) => explainRule(rule)!.paragraphs.join('\n');
const CEL = (source: string) => ({ dialect: 'cel', source });
/**
* A scheduled flow with a get_record node carrying `filter`. Declares
* `runAs: 'system'` so it is the correct shape for a scheduled data flow and
* does not also trip the user-less runAs lint (FLOW_RUNAS_UNSCOPED) —
* keeping these date-equality cases focused on the filter rule.
*/
const filterFlow = (filter: unknown) => ({
flows: [{
name: 'expiry_alert',
runAs: 'system',
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'schedule', schedule: 'cron:0 9 * * *' } },
{ id: 'query', type: 'get_record', config: { objectName: 'contract', filter } },
],
edges: [{ id: 'e1', source: 'start', target: 'query' }],
}],
});
const flow = (condition: unknown, triggerType = 'record-after-update') => ({
flows: [{
name: 'renewal_alert',
nodes: [{ id: 'start', type: 'start', config: { objectName: 'contract', triggerType, condition } }],
edges: [],
}],
});
/**
* The keys a container schema REFUSED on a fixture — `[]` when the shape spells
* only declared keys, whatever the schema thinks of their VALUES (#5700).
*
* The criterion is deliberately key-level, and the same one
* `validate-security-posture.test.ts` writes down for its reachability guard: a
* rejected KEY and a rejected VALUE are different facts. A key the schema does
* not declare is not an authoring surface at all — a fixture spelling one
* describes a container no author can save, which is exactly the defect #5700
* catalogued. A rejected value is a fixture choice these rules are often
* entitled to make.
*
* So the container audits below use this, NOT flat `safeParse` success: most of
* this file's fixtures are hand-written raw literals that omit the `label`
* `FlowNodeSchema` requires on every node, and demanding full-parse green would
* either delete that coverage or drag in a file-wide re-write #5700 explicitly
* defers. Where a fixture IS fully authorable, it is pinned with full green
* instead (see the `LoopConfigSchema` pins).
*/
function refusedKeys(result: {
success: boolean;
error?: { issues: readonly { code: string; path: readonly PropertyKey[]; message: string }[] };
}): string[] {
if (result.success) return [];
return (result.error?.issues ?? [])
.filter((i) => i.code === 'unrecognized_keys')
.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
}
describe('lintFlowPatterns — time-relative anti-pattern (#1874)', () => {
it('flags record-change date-EQUALITY against a time function', () => {
const fnds = lintFlowPatterns(flow('end_date == daysFromNow(60)'));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_TIME_RELATIVE_ANTIPATTERN);
expect(fnds[0].where).toContain("renewal_alert");
expect(fnds[0].hint).toMatch(/schedule/i);
});
it('flags the function-on-the-left form too', () => {
expect(lintFlowPatterns(flow('today() != record.start_date'))).toHaveLength(1);
});
it('flags an Expression-envelope condition', () => {
expect(lintFlowPatterns(flow({ dialect: 'cel', source: 'record.due == daysFromNow(7)' }))).toHaveLength(1);
});
describe('does NOT flag (false-positive guards)', () => {
it('a RANGE comparison (the correct building block)', () => {
expect(lintFlowPatterns(flow('end_date <= daysFromNow(60)'))).toHaveLength(0);
expect(lintFlowPatterns(flow('end_date >= daysFromNow(7) && end_date <= daysFromNow(30)'))).toHaveLength(0);
});
it('equality on a non-time field', () => {
expect(lintFlowPatterns(flow('status == "expired"'))).toHaveLength(0);
});
it('a SCHEDULE trigger (only record-* triggers are linted)', () => {
expect(lintFlowPatterns(flow('end_date == daysFromNow(60)', 'schedule'))).toHaveLength(0);
});
it('no condition', () => {
expect(lintFlowPatterns(flow(undefined))).toHaveLength(0);
});
});
});
describe('lintFlowPatterns — date-equality in query filter (#1874)', () => {
it('flags a field bound directly to a time value (implicit equality)', () => {
const fnds = lintFlowPatterns(filterFlow({ expires_at: CEL('daysFromNow(30)') }));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_DATE_EQUALITY_FILTER);
expect(fnds[0].hint).toMatch(/\$gte.*daysFromNow\(N\).*\$lt/);
});
it('flags `$in` against time values (the original renewal_alert bug)', () => {
const fnds = lintFlowPatterns(filterFlow({
status: 'active',
end_date: { $in: [CEL('daysFromNow(60)'), CEL('daysFromNow(30)'), CEL('daysFromNow(7)')] },
}));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_DATE_EQUALITY_FILTER);
});
it('flags `$eq` against a time value', () => {
expect(lintFlowPatterns(filterFlow({ d: { $eq: CEL('today()') } }))).toHaveLength(1);
});
describe('does NOT flag (false-positive guards)', () => {
it('a one-day window (the correct fix)', () => {
expect(lintFlowPatterns(filterFlow({
end_date: { $gte: CEL('daysFromNow(7)'), $lt: CEL('daysFromNow(8)') },
}))).toHaveLength(0);
});
it('multi-tier windows wrapped in $or', () => {
expect(lintFlowPatterns(filterFlow({
status: 'active',
$or: [
{ end_date: { $gte: CEL('daysFromNow(7)'), $lt: CEL('daysFromNow(8)') } },
{ end_date: { $gte: CEL('daysFromNow(30)'), $lt: CEL('daysFromNow(31)') } },
],
}))).toHaveLength(0);
});
it('a plain range like `due_date < today()` (overdue query)', () => {
expect(lintFlowPatterns(filterFlow({ status: 'open', due_date: { $lt: CEL('today()') } }))).toHaveLength(0);
});
it('equality against a non-time value (status, interpolated id)', () => {
expect(lintFlowPatterns(filterFlow({ status: 'active', id: CEL('record.id') }))).toHaveLength(0);
expect(lintFlowPatterns(filterFlow({ amount: { $eq: CEL('record.threshold') } }))).toHaveLength(0);
});
});
});
describe('lintFlowPatterns — phantom aggregation capability (#1870)', () => {
const scriptNode = (config: Record<string, unknown>) => ({
flows: [{
name: 'rollup',
nodes: [
{ id: 'start', type: 'start', config: {} },
{ id: 'sum', type: 'script', config },
],
edges: [{ id: 'e1', source: 'start', target: 'sum' }],
}],
});
it('flags `aggregations` on a script node (publication_rollup bug)', () => {
const fnds = lintFlowPatterns(scriptNode({ aggregations: { total: { sum: 'amount' } } }));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_PHANTOM_AGGREGATION);
expect(fnds[0].hint).toMatch(/Field\.summary/);
});
it('flags groupBy / rollup / aggregate / having too', () => {
for (const key of ['groupBy', 'rollup', 'aggregate', 'having']) {
expect(lintFlowPatterns(scriptNode({ [key]: {} })).map((f) => f.rule)).toContain(FLOW_PHANTOM_AGGREGATION);
}
});
it('does NOT flag an ordinary script/function node', () => {
expect(lintFlowPatterns(scriptNode({ function: 'helpdesk.triage', inputs: { x: 1 } }))).toHaveLength(0);
});
});
/** A flow with a create_record node carrying `config`. */
const nodeFlow = (config: Record<string, unknown>) => ({
flows: [{
name: 'mk',
nodes: [
{ id: 'start', type: 'start', config: {} },
{ id: 'create', type: 'create_record', config },
],
edges: [{ id: 'e1', source: 'start', target: 'create' }],
}],
});
const rules = (s: any) => lintFlowPatterns(s).map((f) => f.rule);
describe('lintFlowPatterns — wrong interpolation syntax (#1315)', () => {
it('flags double-brace interpolation in a node value', () => {
expect(rules(nodeFlow({ objectName: 'm', fields: { body: '{{ai_reply}}' } })))
.toContain(FLOW_DOUBLE_BRACE_INTERP);
});
it('flags a bare $ref.field written as a literal', () => {
expect(rules(nodeFlow({ objectName: 'm', fields: { ticket: '$source.id' } })))
.toContain(FLOW_BARE_DOLLAR_REF);
});
describe('does NOT flag (false-positive guards)', () => {
// A single-brace token is neither a double brace nor a bare `$` reference,
// so neither #1315 rule fires on it. In a value slot like this one the
// token is refused anyway — by the value-slot judge (#19939), a different
// finding (`expression-invalid` at `objectstack validate`), not this rule's.
it('a single-brace token draws neither interpolation rule (the value-slot judge refuses it, a different finding)', () => {
expect(rules(nodeFlow({ objectName: 'm', fields: { body: '{ai_reply}', t: 'Hi {record.name}' } }))).toEqual([]);
});
it('a braced $User token is not a BARE $ reference (the value-slot judge refuses it, a different finding)', () => {
expect(rules(nodeFlow({ objectName: 'm', fields: { owner: '{$User.Id}' } }))).toEqual([]);
});
it('a currency literal', () => {
expect(rules(nodeFlow({ objectName: 'm', fields: { price: '$5.00', label: 'Total $5' } }))).toEqual([]);
});
it('a CEL condition (skipped — not a template value)', () => {
// Scoped to the #1315 interpolation rules on purpose: this shape DOES
// trip `flow-inert-node-condition` (#4414 — a decision never reads
// `config.condition`), a different finding about a different defect,
// which must not make this case read as a brace mistake.
const found = rules({ flows: [{ name: 'd', nodes: [
{ id: 'start', type: 'start', config: {} },
{ id: 'dec', type: 'decision', config: { condition: 'record.amount > 100' } },
], edges: [] }] });
expect(found).not.toContain(FLOW_DOUBLE_BRACE_INTERP);
expect(found).not.toContain(FLOW_BARE_DOLLAR_REF);
});
});
});
describe('lintFlowPatterns — approval revise loop (ADR-0044)', () => {
const approvalFlow = (
edges: Array<{ source: string; target: string; label?: string; type?: string }>,
approvalConfig: Record<string, unknown> = {},
) => ({
flows: [{
name: 'budget_approval',
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'manual' } },
{ id: 'mgr', type: 'approval', config: approvalConfig },
// #3823 — the revise window is the service-owned `approval_revise`
// node, not the bare `wait` ADR-0044 D3 originally prescribed. The
// dedicated case below pins that the old shape is now an error.
{ id: 'wait', type: 'approval_revise' },
{ id: 'ok', type: 'end' },
{ id: 'no', type: 'end' },
],
edges,
}],
});
/** The same flow with the revise edge pointed at a plain `wait` (pre-#3823). */
const legacyWaitFlow = (
edges: Array<{ source: string; target: string; label?: string; type?: string }>,
) => {
const stack = approvalFlow(edges) as any;
stack.flows[0].nodes = stack.flows[0].nodes.map((n: any) =>
n.id === 'wait' ? { id: 'wait', type: 'wait', waitEventConfig: { eventType: 'signal' } } : n,
);
return stack;
};
const declaredLoop = [
{ source: 'start', target: 'mgr' },
{ source: 'mgr', target: 'ok', label: 'approve' },
{ source: 'mgr', target: 'no', label: 'reject' },
{ source: 'mgr', target: 'wait', label: 'revise' },
{ source: 'wait', target: 'mgr', label: 'resubmit', type: 'back' },
];
it('accepts a properly declared revise loop (closing edge type:back)', () => {
expect(lintFlowPatterns(approvalFlow(declaredLoop))).toEqual([]);
});
it('flags a revise loop whose closing edge is NOT type:back', () => {
const edges = declaredLoop.map((e) =>
e.source === 'wait' && e.target === 'mgr' ? { source: 'wait', target: 'mgr', label: 'resubmit' } : e,
);
const fnds = lintFlowPatterns(approvalFlow(edges));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_APPROVAL_REVISE_UNMARKED_BACKEDGE);
expect(fnds[0].where).toContain('mgr');
expect(fnds[0].hint).toMatch(/back/i);
});
it('flags a revise branch that never loops back (dead-end; registerFlow would accept it)', () => {
const edges = [
{ source: 'start', target: 'mgr' },
{ source: 'mgr', target: 'ok', label: 'approve' },
{ source: 'mgr', target: 'no', label: 'reject' },
{ source: 'mgr', target: 'wait', label: 'revise' },
];
const fnds = lintFlowPatterns(approvalFlow(edges));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_APPROVAL_REVISE_DEAD_END);
});
it('flags maxRevisions:0 alongside a revise edge', () => {
const fnds = lintFlowPatterns(approvalFlow(declaredLoop, { maxRevisions: 0 }));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_APPROVAL_REVISE_DISABLED);
});
it('does NOT flag a normal approval with no revise edge', () => {
const edges = [
{ source: 'start', target: 'mgr' },
{ source: 'mgr', target: 'ok', label: 'approve' },
{ source: 'mgr', target: 'no', label: 'reject' },
];
// No revise edge, so no revise node either: one left in place with no edge
// into it would draw `flow-node-unreachable` (it could never run).
const stack = approvalFlow(edges) as any;
stack.flows[0].nodes = stack.flows[0].nodes.filter((n: any) => n.id !== 'wait');
expect(lintFlowPatterns(stack)).toEqual([]);
});
// #3823 — the shape ADR-0044 D3 prescribed until its 2026-07-28 amendment.
// `error`, because `ApprovalService.sendBack` refuses this metadata outright:
// the revise branch can never run, and before that refusal the pause it
// produced was resumable by anyone holding the run id.
it('flags a revise edge into a bare wait node as an ERROR', () => {
const fnds = lintFlowPatterns(legacyWaitFlow(declaredLoop));
expect(fnds).toHaveLength(1);
expect(fnds[0]).toMatchObject({
rule: FLOW_APPROVAL_REVISE_TARGET_NOT_SERVICE_OWNED,
severity: 'error',
});
expect(fnds[0].where).toContain('mgr');
expect(fnds[0].message).toMatch(/node 'wait' of type 'wait'/);
expect(fnds[0].hint).toMatch(/type: 'approval_revise'/);
});
it('flags a revise edge into any other node type too (screen, not just wait)', () => {
const stack = approvalFlow(declaredLoop) as any;
stack.flows[0].nodes = stack.flows[0].nodes.map((n: any) =>
n.id === 'wait' ? { id: 'wait', type: 'screen', config: { fields: [{ name: 'note', type: 'text' }] } } : n,
);
const fnds = lintFlowPatterns(stack);
expect(fnds.map((f) => f.rule)).toEqual([FLOW_APPROVAL_REVISE_TARGET_NOT_SERVICE_OWNED]);
expect(fnds[0].message).toMatch(/type 'screen'/);
});
});
describe('lintFlowPatterns — user-less runAs unscoped (#1888 / ADR-0049 / ADR-0073 D5 / #3760)', () => {
/** A schedule-triggered flow that performs a data op, parameterized by runAs / detection signal. */
const scheduledDataFlow = (opts: {
runAs?: 'system' | 'user';
flowType?: string;
startConfig?: Record<string, unknown>;
nodeType?: string;
} = {}) => ({
flows: [{
name: 'nightly_sweep',
...(opts.flowType !== undefined ? { type: opts.flowType } : { type: 'schedule' }),
...(opts.runAs ? { runAs: opts.runAs } : {}),
nodes: [
{ id: 'start', type: 'start', config: opts.startConfig ?? { triggerType: 'schedule', cron: '0 8 * * *' } },
{ id: 'op', type: opts.nodeType ?? 'create_record', config: { objectName: 'thing', fields: { a: 1 } } },
],
edges: [{ id: 'e1', source: 'start', target: 'op' }],
}],
});
it('flags a schedule flow whose runAs is unset (defaults to user → unscoped)', () => {
const fnds = lintFlowPatterns(scheduledDataFlow());
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_RUNAS_UNSCOPED);
expect(fnds[0].where).toContain('nightly_sweep');
// #5693 — one wording for both authoring inputs; see the dedicated block below.
expect(fnds[0].message).toMatch(/runAs:'user'` \(the default when none is declared\)/);
expect(fnds[0].message).toMatch(/REFUSED/);
expect(fnds[0].hint).toMatch(/runAs:'system'/);
});
it("flags an EXPLICIT runAs:'user' on a schedule (incoherent — no user to scope to)", () => {
const fnds = lintFlowPatterns(scheduledDataFlow({ runAs: 'user' }));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_RUNAS_UNSCOPED);
expect(fnds[0].message).toMatch(/runAs:'user'/);
});
it('detects the schedule trigger via any of the three signals', () => {
// (a) flow.type === 'schedule' (default in the helper)
expect(lintFlowPatterns(scheduledDataFlow({ startConfig: {} }))).toHaveLength(1);
// (b) start config.triggerType === 'schedule'
expect(lintFlowPatterns(scheduledDataFlow({ flowType: 'autolaunched', startConfig: { triggerType: 'schedule' } }))).toHaveLength(1);
// (c) start config carries a schedule descriptor
expect(lintFlowPatterns(scheduledDataFlow({ flowType: 'autolaunched', startConfig: { schedule: { type: 'interval', intervalMs: 60000 } } }))).toHaveLength(1);
});
it('flags each data-op node type (get/create/update/delete)', () => {
for (const t of ['get_record', 'create_record', 'update_record', 'delete_record']) {
const fnds = lintFlowPatterns(scheduledDataFlow({ nodeType: t }));
expect(fnds.map((f) => f.rule), `node ${t}`).toContain(FLOW_RUNAS_UNSCOPED);
}
});
// #3760 — this rule FAILS the build. Every other rule in this file is
// advisory; this one flags metadata the runtime refuses to execute, so a
// warning would just be a slower way of finding out. If this assertion is ever
// relaxed the gate silently becomes a comment again — which is exactly the
// state #3760 found it in.
it('is a BLOCKING finding (severity: error), unlike every advisory rule here', () => {
const fnds = lintFlowPatterns(scheduledDataFlow());
expect(fnds[0].severity).toBe('error');
});
// ADR-0073 D5 — the rule was scoped to `schedule`, but a schedule is not the
// boundary: these triggers build an AutomationContext with no `userId` at all,
// so they hit the identical refusal.
it('flags the OTHER provably user-less triggers too — time-relative and api', () => {
// #4966 — the descriptor must be one the runtime can actually BIND. This rule
// decides `time-relative` from `startCfg.timeRelative != null` alone
// (`lint-flow-patterns.ts`), never from the shape, so this fixture used to
// read `{ object, field: 'due_at', offsetDays: -1 }` and stayed green while
// describing a flow that never gets a sweep: `TimeRelativeTriggerPlugin.start()`
// `safeParse`s `config.timeRelative` against `TimeRelativeTriggerSchema` and
// refuses on both counts — `field` is a diagnostic alias, not an accepted key
// (the declared one is `dateField`), and `offsetDays` is `z.array(int).min(1)`,
// not a scalar. A fixture the runtime would refuse teaches the wrong shape to
// every reader of this file (#4001's first-class finding class). Hence the
// parse assertion below: the fixture is pinned against the same schema the
// bind path uses, so it cannot rot back into an unbindable descriptor.
const timeRelativeDescriptor = { object: 'task', dateField: 'due_at', offsetDays: [-1] };
expect(TimeRelativeTriggerSchema.safeParse(timeRelativeDescriptor).success).toBe(true);
const timeRelative = lintFlowPatterns(
scheduledDataFlow({ flowType: 'autolaunched', startConfig: { timeRelative: timeRelativeDescriptor } }),
);
expect(timeRelative.map((f) => f.rule)).toContain(FLOW_RUNAS_UNSCOPED);
expect(timeRelative[0].message).toMatch(/time-relative/);
const api = lintFlowPatterns(scheduledDataFlow({ flowType: 'api', startConfig: {} }));
expect(api.map((f) => f.rule)).toContain(FLOW_RUNAS_UNSCOPED);
expect(api[0].message).toMatch(/api/);
const apiByTriggerType = lintFlowPatterns(
scheduledDataFlow({ flowType: 'autolaunched', startConfig: { triggerType: 'api' } }),
);
expect(apiByTriggerType.map((f) => f.rule)).toContain(FLOW_RUNAS_UNSCOPED);
});
// The deliberate limit of this rule. A record-change flow hits the same
// refusal when its triggering write carried no user, but that is a RUNTIME
// property — approximating it here would fire on every record-change flow in
// existence. Pinned so nobody "fixes" the gap by guessing.
it('does NOT flag record_change — undecidable at authoring time, caught at run time', () => {
const fnds = lintFlowPatterns(
// #6637 — the token was `'record_change'` (the flow TYPE echoed into the
// trigger slot), which is not an authored trigger token at all: the engine
// routes only `record-*`, so that fixture described a flow that never fires.
// The pin is about a record-change flow, so it spells one — the same token
// the sibling guard below already uses.
scheduledDataFlow({ flowType: 'record_change', startConfig: { triggerType: 'record-after-update', objectName: 'invoice' } }),
);
expect(fnds.map((f) => f.rule)).not.toContain(FLOW_RUNAS_UNSCOPED);
});
describe('does NOT flag (false-positive guards)', () => {
it("a schedule flow that declares runAs:'system' (the correct shape)", () => {
expect(lintFlowPatterns(scheduledDataFlow({ runAs: 'system' }))).toHaveLength(0);
});
it('a schedule flow with NO data node (runAs is moot — e.g. a notify-only digest)', () => {
expect(lintFlowPatterns({
flows: [{
name: 'digest',
type: 'schedule',
nodes: [
{ id: 'start', type: 'start', config: { schedule: { type: 'interval', intervalMs: 60000 } } },
{ id: 'notify', type: 'notify', config: { topic: 'x' } },
],
edges: [{ id: 'e1', source: 'start', target: 'notify' }],
}],
})).toHaveLength(0);
});
it('a NON-schedule flow with a data op (record-change / screen runs carry a user)', () => {
expect(lintFlowPatterns(scheduledDataFlow({ flowType: 'record_change', startConfig: { triggerType: 'record-after-update', objectName: 'thing' } }))).toHaveLength(0);
expect(lintFlowPatterns(scheduledDataFlow({ flowType: 'screen', startConfig: {} }))).toHaveLength(0);
});
});
/**
* #5633 — the data-node search descends into every ADR-0031 region.
*
* #5383/#5635 gave this whole rule family the per-region walk and deliberately
* left THIS rule reading the top-level `nodes` only, because widening a
* build-GATING rule is its own change with its own blast radius. That exemption
* is what this block removes.
*
* The evidence and the verdict are at different altitudes here, and keeping
* them apart is the whole design:
*
* - the VERDICT is flow-level. `runAs` is a flow property and the trigger is a
* property of the start node, so a flow is either unscoped or it is not —
* one finding per flow, `where` = `flow 'x' · runAs`, never per region and
* never once per data node.
* - the EVIDENCE is "does this flow touch data at all", and a `loop` body is
* as much part of the flow as its top level. A data node one level down is
* refused by exactly the same `resolveRunAsIdentity` check (#3760) as one at
* the top; the nesting depth is not a property the runtime consults.
*
* The shape missed until now is not a corner but the DEFAULT shape of a
* scheduled data flow — query a set, loop it, write per item — so the write is
* almost always the nested node. Every case below pins the nested finding
* against its top-level twin, and the twin's message is asserted byte-for-byte
* so the widening cannot drift the wording authors already see.
*/
describe('#5633 — descends into nested regions for the data-node evidence', () => {
/** The canonical scheduled sweep: the write lives in the loop BODY. */
const loopConfig = (bodyNodeType = 'update_record') => ({
collection: { dialect: 'cel', source: 'vars.rows' },
iteratorVariable: 'row',
body: {
nodes: [{
id: 'touch',
type: bodyNodeType,
label: 'Touch Row',
config: { objectName: 'thing', recordId: '{row.id}', fields: { seen: true } },
}],
edges: [],
},
});
const sweepFlow = (opts: { runAs?: 'system' | 'user'; bodyNodeType?: string } = {}) => ({
flows: [{
name: 'nightly_sweep',
type: 'schedule',
...(opts.runAs ? { runAs: opts.runAs } : {}),
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'schedule', cron: '0 8 * * *' } },
{ id: 'loop_rows', type: 'loop', config: loopConfig(opts.bodyNodeType) },
{ id: 'end', type: 'end' },
],
edges: [
{ id: 'e1', source: 'start', target: 'loop_rows' },
{ id: 'e2', source: 'loop_rows', target: 'end' },
],
}],
});
/**
* The container these fixtures nest the write inside must be a shape the
* schema ACCEPTS, or the rule is only proven on metadata that never reaches
* it — the #4966 trap, one container down (see the `TimeRelativeTriggerSchema`
* pin above for the same guard on a trigger descriptor).
*
* This one is not hypothetical: the item-binding key here is
* `iteratorVariable`, and `LoopConfigSchema` is a `strictObject`, so the
* plausible-looking `itemVar` is reported as an `unrecognized_key` rather
* than quietly ignored (#4001). A fixture spelling it would still exercise
* this rule — region collection reads `config.body`, which is unaffected —
* so nothing here would have gone red while the fixture taught a `loop` the
* author cannot actually write.
*
* Full `safeParse` green rather than merely "no unrecognized keys", because
* what this rule judges is a VALUE verdict (`runAs` against the trigger
* kind), and its evidence is a node that must really be reachable inside a
* really-authorable container.
*/
it('pins the loop container against the schema — the fixture must be authorable', () => {
const parsed = LoopConfigSchema.safeParse(loopConfig());
expect(parsed.success).toBe(true);
// And the near-miss spelling really is rejected, so the pin has teeth.
const near = LoopConfigSchema.safeParse({ ...loopConfig(), iteratorVariable: undefined, itemVar: 'row' });
expect(near.success).toBe(false);
});
it('flags a loop-body write — the shape that passed the build and is refused at run time', () => {
// Scoped to this rule (#14394): the same fixture now also trips the
// containment warning — an `update_record` inside a `loop` body with no
// `try_catch` — a different verdict about a different node. The twin
// below pins that co-occurrence explicitly rather than filtering it away.
const fnds = lintFlowPatterns(sweepFlow()).filter((f) => f.rule === FLOW_RUNAS_UNSCOPED);
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_RUNAS_UNSCOPED);
expect(fnds[0].severity).toBe('error');
// The verdict stays FLOW-level: `runAs` is a flow property, so the region
// never enters `where` — it is evidence, not location.
expect(fnds[0].where).toBe("flow 'nightly_sweep' · runAs");
expect(fnds[0].where).not.toContain('loop');
// …but the message names the region, or the author has to hunt for the node.
expect(fnds[0].message).toContain("its data node 'touch' (update_record), in loop 'loop_rows' body,");
});
it('flags a loop-body delete_record the same way', () => {
const fnds = lintFlowPatterns(sweepFlow({ bodyNodeType: 'delete_record' }));
// Both verdicts, in the order the pass emits them: the flow-level `runAs`
// error, then the #14394 containment warning for the same nested write —
// an unscoped loop-body write is ALSO an uncontained one, and each rule
// says its own thing about it exactly once.
expect(fnds.map((f) => f.rule)).toEqual([FLOW_RUNAS_UNSCOPED, FLOW_LOOP_BODY_UNCONTAINED]);
expect(fnds[0].message).toContain("its data node 'touch' (delete_record), in loop 'loop_rows' body,");
});
// The A/B twin. Same flow, same node, moved out of the body — this was
// already flagged before #5633, and its message must carry no region clause.
// (The sentence itself was re-worded once since, by #5693 — see the block at
// the end of this file for why the authored-vs-defaulted branch it used to
// carry could not survive.)
it('leaves the TOP-LEVEL twin without a region clause (no regression)', () => {
const fnds = lintFlowPatterns({
flows: [{
name: 'nightly_sweep',
type: 'schedule',
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'schedule', cron: '0 8 * * *' } },
{ id: 'touch', type: 'update_record', config: { objectName: 'thing', fields: { seen: true } } },
],
edges: [{ id: 'e1', source: 'start', target: 'touch' }],
}],
});
expect(fnds).toHaveLength(1);
expect(fnds[0].where).toBe("flow 'nightly_sweep' · runAs");
expect(fnds[0].message).toBe(
"schedule-triggered flow runs under `runAs:'user'` (the default when none is declared), but a " +
"schedule run has no trigger user — so its data node 'touch' (update_record) has no identity to scope to and " +
"will be REFUSED at run time.",
);
expect(fnds[0].message).not.toContain('in loop');
});
it('descends two levels — a loop inside a loop', () => {
const fnds = lintFlowPatterns({
flows: [{
name: 'nightly_sweep',
type: 'schedule',
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'schedule', cron: '0 8 * * *' } },
{
id: 'loop_rows', type: 'loop',
config: {
collection: { dialect: 'cel', source: 'vars.rows' }, iteratorVariable: 'row',
body: {
nodes: [{
id: 'loop_children', type: 'loop', label: 'Loop Children',
config: {
collection: { dialect: 'cel', source: 'row.children' }, iteratorVariable: 'child',
body: {
nodes: [{ id: 'touch', type: 'create_record', label: 'Create', config: { objectName: 'thing', fields: { a: 1 } } }],
edges: [],
},
},
}],
edges: [],
},
},
},
],
edges: [{ id: 'e1', source: 'start', target: 'loop_rows' }],
}],
}).filter((f) => f.rule === FLOW_RUNAS_UNSCOPED);
expect(fnds).toHaveLength(1);
expect(fnds[0].message).toContain(
"its data node 'touch' (create_record), in loop 'loop_rows' body → loop 'loop_children' body,",
);
});
// Exactly ONE finding, not one per data node and not one per region: a
// container's config physically contains its body, and the walk visits the
// body in its own right, so a rule that pushed per hit would double-report.
it('reports ONCE for a flow whose regions hold several data nodes', () => {
const fanConfig = {
branches: [
{ name: 'writes', nodes: [{ id: 'w1', type: 'update_record', label: 'Write', config: { objectName: 'a' } }], edges: [] },
{ name: 'deletes', nodes: [{ id: 'w2', type: 'delete_record', label: 'Delete', config: { objectName: 'b' } }], edges: [] },
],
};
// #5700 container audit — the `parallel` twin of the `loop` pin above. This
// block already declares `name`/`nodes`/`edges` and labels its branch nodes,
// so it clears the strongest bar available: full `safeParse` green.
expect(ParallelConfigSchema.safeParse(fanConfig).success).toBe(true);
const fnds = lintFlowPatterns({
flows: [{
name: 'nightly_sweep',
type: 'schedule',
nodes: [
{ id: 'start', type: 'start', config: { triggerType: 'schedule', cron: '0 8 * * *' } },
{ id: 'fan', type: 'parallel', config: fanConfig },
],
edges: [{ id: 'e1', source: 'start', target: 'fan' }],
}],
}).filter((f) => f.rule === FLOW_RUNAS_UNSCOPED);
expect(fnds).toHaveLength(1);
expect(fnds[0].message).toContain("in parallel 'fan' branch 0,");
});
// The top-level graph comes first out of `collectFlowGraphs`, so a flow with
// data nodes at BOTH altitudes still cites the top-level one — the exact node
// it cited before #5633.
it('prefers the top-level node as evidence when the flow has both', () => {
const stack = sweepFlow() as { flows: Array<{ nodes: unknown[] }> };
stack.flows[0].nodes.splice(1, 0, {
id: 'query', type: 'get_record', config: { objectName: 'thing', filter: { done: false } },
});
const fnds = lintFlowPatterns(stack).filter((f) => f.rule === FLOW_RUNAS_UNSCOPED);
expect(fnds).toHaveLength(1);
expect(fnds[0].message).toContain("its data node 'query' (get_record) has no identity");
expect(fnds[0].message).not.toContain('in loop');
});
describe('does NOT flag', () => {
it("a loop-body write under runAs:'system' (the correct shape for a sweep)", () => {
expect(lintFlowPatterns(sweepFlow({ runAs: 'system' }))
.filter((f) => f.rule === FLOW_RUNAS_UNSCOPED)).toHaveLength(0);
});
it('a loop-body write on a non-user-less trigger (a record-change run carries a user)', () => {
const stack = sweepFlow() as { flows: Array<Record<string, unknown>> };
stack.flows[0].type = 'record_change';
(stack.flows[0].nodes as Array<Record<string, unknown>>)[0] = {
id: 'start', type: 'start', config: { triggerType: 'record-after-update', objectName: 'thing' },
};
expect(lintFlowPatterns(stack).filter((f) => f.rule === FLOW_RUNAS_UNSCOPED)).toHaveLength(0);
});
it('a loop body holding no data node at all (runAs stays moot — a notify-only sweep)', () => {
expect(lintFlowPatterns(sweepFlow({ bodyNodeType: 'notify' }))
.filter((f) => f.rule === FLOW_RUNAS_UNSCOPED)).toHaveLength(0);
});
});
});
/**
* #5693 — ONE wording, true whether the author declared `runAs:'user'` or
* declared nothing.
*
* The message used to branch: `` `runAs:'user'` `` when `flow.runAs` was a
* string, `the default …` when it was absent. The distinction is real and
* useful — "you wrote something incoherent" is not "you inherited a default
* that does not fit a user-less trigger" — but *this rule cannot observe it*,
* and which arm an author got depended on the SURFACE rather than on their
* file:
*
* - **CLI** — always the explicit arm. `FlowSchema.runAs` carries
* `.default('user')` and the registry wires this rule `input: 'parsed'`, so
* `flow.runAs` is the string `'user'` either way. `os lint` does not parse,
* but `defineStack`/`defineFlow` parse at *definition* time, so even it
* receives the default already materialized. Measured on `app-todo` with the
* `runAs` line deleted: `os validate` AND `os lint` both told an author who
* had declared nothing that their flow "runs as `runAs:'user'`".
* - **Runtime publish gate (#4463)** — both arms, because it judges the
* verbatim authored body (`saveMetaItem` keeps `request.item` past the
* schema check).
*
* So the branch was not merely dead: it made one flow get two different
* sentences from two shipped surfaces, and on the surface authors meet first it
* produced the one that reads as an accusation. #5693 removed it in favour of a
* sentence that is true of both inputs on every surface.
*
* These two cases split the work deliberately, and only the second has teeth
* against a re-introduction — say so rather than let the pair read as one
* assertion made twice:
*
* - the PARSED case pins *why* the branch was pointless (both inputs arrive as
* the same object). A re-introduced branch would still pass it — that is the
* point: the CLI cannot tell these apart, which is the whole defect.
* - the UNPARSED case is the regression guard. It is the one input shape where
* the two authoring choices are still distinguishable (and the shape the
* runtime gate really passes), so any future `typeof flow.runAs === 'string'`
* branch in the message fails it immediately.
*/
describe("#5693 — one wording for authored `runAs:'user'` and for none at all", () => {
/**
* Authorable on purpose: `FlowSchema` requires `label` on the flow and on
* every node, so the raw literals the rest of this file feeds would fail the
* parse — and a fixture that cannot be parsed cannot demonstrate anything
* about the parsed tier. This one is the same sweep, declared in full.
*/
const sweep = (runAs?: 'user') => ({
name: 'nightly_sweep',
label: 'Nightly Sweep',
type: 'schedule',
...(runAs ? { runAs } : {}),
nodes: [
{ id: 'start', type: 'start', label: 'Start', config: { triggerType: 'schedule', cron: '0 8 * * *' } },
{ id: 'op', type: 'update_record', label: 'Touch', config: { objectName: 'thing', fields: { a: 1 } } },
],
edges: [{ id: 'e1', source: 'start', target: 'op' }],
});
const EXPECTED =
"schedule-triggered flow runs under `runAs:'user'` (the default when none is declared), but a " +
"schedule run has no trigger user — so its data node 'op' (update_record) has no identity to scope to and " +
"will be REFUSED at run time.";
const messagesFor = (flow: unknown) =>
lintFlowPatterns({ flows: [flow] })
.filter((f) => f.rule === FLOW_RUNAS_UNSCOPED)
.map((f) => f.message);
it('is wired to the tier where the default has already been filled in', () => {
const wiring = AUTHORING_RULES.find((r) => r.name === 'lintFlowPatterns');
expect(wiring?.input).toBe('parsed');
});
it('PARSED input: the two authoring choices are literally the same object here', () => {
const authored = FlowSchema.parse(sweep('user'));
const defaulted = FlowSchema.parse(sweep());
// The premise, asserted rather than assumed: the parse materializes the
// default, so `flow.runAs` carries no trace of what was authored.
expect(defaulted.runAs).toBe('user');
expect(authored.runAs).toBe('user');
expect(messagesFor(defaulted)).toEqual([EXPECTED]);
expect(messagesFor(authored)).toEqual([EXPECTED]);
});
it('UNPARSED input: an absent key and an explicit one still get the same sentence', () => {
// The runtime publish gate's shape — the only surface where the omission
// survives to the rule. Both must read the same, or the surfaces disagree
// about one flow again.
expect(messagesFor(sweep())).toEqual([EXPECTED]);
expect(messagesFor(sweep('user'))).toEqual([EXPECTED]);
});
it('says the same thing to both surfaces about the same flow', () => {
expect(messagesFor(FlowSchema.parse(sweep()))).toEqual(messagesFor(sweep()));
});
});
});
/**
* #3863 — `label: 'error'` without `type: 'fault'`.
*
* The label is cosmetic on an ordinary edge, so the handler runs on every
* SUCCESS (unconditional out-edges all traverse, in parallel) and never on a
* failure. Both halves are silent, which is why this is worth a build-time
* diagnostic rather than a runtime one.
*/
function edgeFlow(edge: Record<string, unknown>, sourceType = 'http') {
return {
flows: [{
name: 'edge_flow',
type: 'autolaunched',
nodes: [
{ id: 'start', type: 'start', config: {} },
{ id: 'op', type: sourceType, config: { url: 'https://x.test' } },
{ id: 'handler', type: 'notify', config: { topic: 'x' } },
{ id: 'end', type: 'end' },
],
edges: [
{ id: 'e1', source: 'start', target: 'op' },
{ id: 'e2', source: 'op', target: 'end' },
{ id: 'e_h', source: 'op', target: 'handler', ...edge },
],
}],
};
}
describe('flow-error-label-not-fault (#3863)', () => {
it("flags label:'error' left at the default type", () => {
const fnds = lintFlowPatterns(edgeFlow({ label: 'error' }));
expect(fnds).toHaveLength(1);
expect(fnds[0].rule).toBe(FLOW_ERROR_LABEL_NOT_FAULT);
// The message must name the actual consequence, not just the mismatch.
expect(fnds[0].message).toContain('SUCCESSFUL');
expect(fnds[0].hint).toContain("type: 'fault'");
});
it.each(['Error', 'FAILURE', 'catch', 'on_error', 'fault'])(
"flags the equivalent label %s",
(label) => {
const fnds = lintFlowPatterns(edgeFlow({ label }));
expect(fnds.map((f) => f.rule)).toContain(FLOW_ERROR_LABEL_NOT_FAULT);
},
);
it("does NOT flag the correct shape (type: 'fault')", () => {
expect(lintFlowPatterns(edgeFlow({ label: 'error', type: 'fault' }))).toHaveLength(0);
});
it('does NOT flag an unlabelled fault edge', () => {
expect(lintFlowPatterns(edgeFlow({ type: 'fault' }))).toHaveLength(0);
});
it('does NOT flag an ordinary labelled edge', () => {
expect(lintFlowPatterns(edgeFlow({ label: 'approved' }))).toHaveLength(0);
});
it('does NOT flag a CONDITIONAL edge — a guarded path is not the footgun', () => {
expect(lintFlowPatterns(edgeFlow({ label: 'error', condition: "status == 'bad'" }))).toHaveLength(0);
});
it.each(['decision', 'approval'])(
"does NOT flag label:'error' out of a %s node — the label IS the branch selector",
(sourceType) => {
// Scoped to THIS rule since #16093. The assertion was a global zero,
// which held only because the fully-inert decision was invisible: the
// `decision` half of this fixture declares no `conditions[]` and no edge
// is guarded, so it now (correctly) draws a `flow-decision-unconditional-
// branch` warning of its own. A bare `label` is not a guard in either
// half of that rule — the mixed branch has always counted a labelled
// edge the decision cannot select as ungated — so exempting it here to
// keep the zero would make one rule id answer two ways. What this case
// tests is unchanged: an error-ish label out of a branching node is not
// the #3863 footgun.
const fnds = lintFlowPatterns(edgeFlow({ label: 'error' }, sourceType));
expect(fnds.filter((f) => f.rule === FLOW_ERROR_LABEL_NOT_FAULT)).toHaveLength(0);
},
);
});
/**
* #4414 — a decision that declares a branch it cannot route.
*
* `guardFlow` is `examples/app-crm/src/flows/convert-lead.flow.ts`'s guard,
* reduced: one CEL-guarded abort branch and one fallback branch.
*/
function guardFlow(opts: {
conditions?: Array<{ label: string; expression: string }>;
proceed?: Record<string, unknown>;
extra?: Array<Record<string, unknown>>;
} = {}) {
return {
flows: [{
name: 'convert_lead',
type: 'screen',
nodes: [
{ id: 'start', type: 'start', config: {} },
{
id: 'check', type: 'decision',
...(opts.conditions ? { config: { conditions: opts.conditions } } : {}),
},
{ id: 'abort', type: 'screen', config: {} },
{ id: 'proceed', type: 'screen', config: {} },
],
edges: [
{ id: 'e1', source: 'start', target: 'check' },
{ id: 'e_yes', source: 'check', target: 'abort', label: 'Yes', condition: "lead.status == 'converted'" },
{ id: 'e_no', source: 'check', target: 'proceed', label: 'No', ...(opts.proceed ?? {}) },
...(opts.extra ?? []),
],
}],
};