Repository navigation
Expand file tree
/
Copy pathruntime-gate.test.ts
More file actions
1079 lines (994 loc) · 53.5 KB
/
Copy pathruntime-gate.test.ts
File metadata and controls
1079 lines (994 loc) · 53.5 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) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// Behaviour of the runtime publish gate (#4463).
//
// The wiring guard (`authoring-rule-wiring.test.ts`) proves the gate READS the
// shared registry. This file proves it FINDS things — the distinction #4449
// was filed about, where a rule was registered, exported, unit-tested and
// produced output on no real stack.
import { describe, it, expect } from 'vitest';
import {
buildRuntimeWriteSnapshots,
runRuntimeAuthoringRules,
runtimeAuthoringRulesFor,
runtimeGatedTypes,
stackKeyForType,
} from './runtime-gate.js';
import type { AuthoringFinding } from './authoring-rules.js';
import { validateVisibilityPredicates } from './validate-visibility-predicates.js';
import { validatePredicatePathRefs } from './validate-predicate-path-refs.js';
import { validateWidgetBindings } from './validate-widget-bindings.js';
/** The issue's measured example: an approval flow whose expression approver is broken CEL. */
// [#29233] Spelled as a body the flow schema accepts (a `type`, node labels,
// an edge list, no top-level `trigger`), since the publish gate now runs the
// region-shape rule, which refuses a flow the schema refuses. Each case below
// still isolates the one thing it pins: the approver expression.
const brokenApprovalFlow = {
name: 'leave_approval',
label: 'Leave approval',
type: 'autolaunched',
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
{
id: 'approve',
type: 'approval',
label: 'Approve',
config: { approvers: [{ type: 'expression', value: 'record.owner ==' }] },
},
],
edges: [{ id: 'e1', source: 'start', target: 'approve' }],
};
/** The same flow with an approver expression that parses and uses a legal root. */
const cleanApprovalFlow = {
...brokenApprovalFlow,
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
{
id: 'approve',
type: 'approval',
label: 'Approve',
config: {
approvers: [{ type: 'expression', value: 'current.owner' }],
},
},
],
};
const objects = [
{ name: 'leave_request', fields: { owner: { type: 'text' }, status: { type: 'text' } } },
];
describe('runtime publish gate (#4463)', () => {
it('rejects the issue\'s worked example with a located, fixable finding', () => {
const result = runRuntimeAuthoringRules({
type: 'flow',
item: brokenApprovalFlow,
context: { objects },
});
const finding = result.errors.find((f) => f.rule === 'approval-expression-invalid');
expect(
finding,
`the broken CEL approver must be REFUSED at the runtime publish gate — this exact body is what ` +
`#4409 taught the three CLI commands to reject, and what a Studio tenant could still save.`,
).toBeDefined();
// D3: the four keys the 422 envelope carries. A gate that says "no" without
// saying WHERE and HOW TO FIX is a gate an author routes around.
expect(finding!.path).toBe('flows[0].nodes[1].config.approvers[0].value');
expect(finding!.where).toContain('leave_approval');
expect(finding!.message).toMatch(/does not parse as CEL/);
expect(finding!.hint.length).toBeGreaterThan(10);
expect(finding!.severity).toBe('error');
});
it('passes the same flow once the expression is valid', () => {
const result = runRuntimeAuthoringRules({
type: 'flow',
item: cleanApprovalFlow,
context: { objects },
});
expect(result.errors, `a valid flow must publish: ${JSON.stringify(result.errors)}`).toEqual([]);
// The rules still RAN — "clean" and "nothing ran" must be distinguishable.
expect(result.rulesRun.length).toBeGreaterThan(0);
});
it('runs the four rule families #4463 P1 wired, from the shared table', () => {
const { rulesRun } = runRuntimeAuthoringRules({
type: 'flow',
item: cleanApprovalFlow,
context: { objects },
});
expect(rulesRun).toEqual(runtimeAuthoringRulesFor('flow').map((r) => r.name));
expect(rulesRun).toContain('validateStackExpressions'); // expression
expect(rulesRun).toContain('validateApprovalApprovers'); // approval
expect(rulesRun).toContain('validateFlowTriggerReadiness'); // flow
expect(rulesRun).toContain('lintFlowPatterns'); // flow
expect(rulesRun).toContain('validateReferenceIntegrity'); // reference
});
it('a rule that gates only `error` leaves warnings out of the blocking set', () => {
// The empty-approver-policy advisory rides along on both flows above. It
// must never be a reason to refuse a publish (P1 gates on `error`; P2 puts
// advisories on the response).
const result = runRuntimeAuthoringRules({
type: 'flow',
item: brokenApprovalFlow,
context: { objects },
});
expect(result.advisories.every((f) => f.severity !== 'error')).toBe(true);
expect(result.errors.every((f) => f.severity === 'error')).toBe(true);
});
// ── D4: only this write is judged ────────────────────────────────────
it('does not blame a write for a PRE-EXISTING violation in the context', () => {
// A tenant's stored object carries a validation rule with broken CEL —
// written before the gate existed, and legal to keep reading (ADR-0087's
// asymmetry). Publishing an unrelated flow must not 422 because of it.
const brokenContext = [
{
name: 'leave_request',
fields: { owner: { type: 'text' } },
// Spelled with the two keys the spec declares (`validations` /
// `condition`). Written as `validationRules` / `expression` — both
// rejected aliases — the broken CEL was not reachable by the rule at
// all, so this fixture proved the subtraction worked by having nothing
// to subtract (#5017).
validations: [{ type: 'script', name: 'bad', message: 'x', condition: 'record.owner ==' }],
},
];
const result = runRuntimeAuthoringRules({
type: 'flow',
item: cleanApprovalFlow,
context: { objects: brokenContext },
});
expect(
result.errors,
`the gate blocks NEW writes only (#4463 D4). A stored row's pre-existing violation showing up ` +
`as an error on somebody else's publish would make the tenant's metadata un-editable, which ` +
`is a worse outcome than the hole this gate closes.`,
).toEqual([]);
});
it('still catches the write when the context is ALSO broken', () => {
// The subtraction must not swallow a real finding just because the context
// is noisy: the fingerprints differ, so the flow's own error survives.
const brokenContext = [
{
name: 'leave_request',
fields: { owner: { type: 'text' } },
// Spelled with the two keys the spec declares (`validations` /
// `condition`). Written as `validationRules` / `expression` — both
// rejected aliases — the broken CEL was not reachable by the rule at
// all, so this fixture proved the subtraction worked by having nothing
// to subtract (#5017).
validations: [{ type: 'script', name: 'bad', message: 'x', condition: 'record.owner ==' }],
},
];
const result = runRuntimeAuthoringRules({
type: 'flow',
item: brokenApprovalFlow,
context: { objects: brokenContext },
});
expect(result.errors.map((f) => f.rule)).toContain('approval-expression-invalid');
});
// ── Dispatch ─────────────────────────────────────────────────────────
it('runs nothing for a metadata type no rule gates', () => {
// `doc`: `translation` held this place until #38623 crossed it.
const result = runRuntimeAuthoringRules({ type: 'doc', item: { name: 'x' } });
expect(result.rulesRun).toEqual([]);
expect(result.errors).toEqual([]);
});
it('tolerates a body that is not an object', () => {
for (const item of [null, undefined, 'a string', 42]) {
expect(runRuntimeAuthoringRules({ type: 'flow', item }).errors).toEqual([]);
}
});
it('works with no object context at all', () => {
// A host without a registry (a metadata-only store, a test double) still
// gets the rules that need no object universe, and must not throw.
const result = runRuntimeAuthoringRules({ type: 'flow', item: brokenApprovalFlow });
expect(result.errors.map((f) => f.rule)).toContain('approval-expression-invalid');
});
it('exposes its dispatch table as data', () => {
expect(runtimeGatedTypes()).toContain('flow');
expect(stackKeyForType('flow')).toBe('flows');
expect(stackKeyForType('no_such_type')).toBeNull();
// [#8309] The two mappings that landed ahead of their registration (#8310)
// — the `seed` order (#7576 → #8307) repeated. Inert until a rule declares
// the type, because dispatch filters by `runtimeTypes` before this table.
expect(stackKeyForType('permission')).toBe('permissions');
expect(stackKeyForType('book')).toBe('books');
});
// ── #8309: the per-write snapshot carries the sibling collections ────
describe('buildRuntimeWriteSnapshots (#8309)', () => {
const context = {
objects: [{ name: 'acct' }],
permissions: [{ name: 'ops' }, { name: 'sales' }],
books: [{ name: 'guide' }],
// [#7529] The fourth context collection — the dataset universe
// `validateWidgetBindings` resolves widget bindings against.
datasets: [{ name: 'orders_ds' }],
};
it('returns null for an unmapped type or a non-object body', () => {
// `doc` is unmapped; `translation` held this place until #38623 mapped it.
expect(buildRuntimeWriteSnapshots({ type: 'doc', item: { name: 'x' }, context })).toBeNull();
expect(buildRuntimeWriteSnapshots({ type: 'flow', item: 'not-an-object', context })).toBeNull();
});
it('carries every context collection IDENTICALLY in both passes for a non-context write', () => {
// The isolation property PR #8390's seed proof rests on, now for all
// four collections: a `flow` write may only differ from its baseline in
// its own collection, so any finding derived from objects/permissions/
// books/datasets cancels in the gate's diff.
const s = buildRuntimeWriteSnapshots({ type: 'flow', item: { name: 'f1' }, context })!;
for (const key of ['objects', 'permissions', 'books', 'datasets'] as const) {
expect(s.baseline[key]).toEqual(context[key]);
expect(s.candidate[key]).toEqual(context[key]);
}
// [#32666] `flows` is a context collection now, carried as judged
// subjects of an object write; a flow write's own collection is still
// just the written flow.
expect(s.baseline.flows).toEqual([]);
expect(s.candidate.flows).toEqual([{ name: 'f1' }]);
});
it('[#32666] drops a passed `flows` context on a flow write, so `flows[0]` stays the write', () => {
const withFlows = { ...context, flows: [{ name: 'live_a' }, { name: 'f1', stale: true }] };
const s = buildRuntimeWriteSnapshots({ type: 'flow', item: { name: 'f1' }, context: withFlows })!;
expect(s.baseline.flows).toEqual([]);
expect(s.candidate.flows).toEqual([{ name: 'f1' }]);
// On an object write the same context is carried in both passes.
const o = buildRuntimeWriteSnapshots({ type: 'object', item: { name: 'acct' }, context: withFlows })!;
expect(o.baseline.flows).toEqual(withFlows.flows);
expect(o.candidate.flows).toEqual(withFlows.flows);
});
it('REPLACES the stored self for a write into a context collection', () => {
// The replace-not-erase rule, generalized from `objects` to every
// context collection: updating `ops` judges a universe with ONE `ops`.
const s = buildRuntimeWriteSnapshots({
type: 'permission',
item: { name: 'ops', objects: {} },
context,
})!;
expect(s.baseline.permissions).toEqual([{ name: 'sales' }]);
expect(s.candidate.permissions).toEqual([{ name: 'sales' }, { name: 'ops', objects: {} }]);
// The sibling collections ride along untouched, in both passes.
expect(s.baseline.objects).toEqual(context.objects);
expect(s.candidate.books).toEqual(context.books);
});
it('an absent context still yields empty collections, never a throw', () => {
const s = buildRuntimeWriteSnapshots({ type: 'book', item: { name: 'b1' } })!;
// [#13216 / #17063] `pages` joined CONTEXT_STACK_KEYS with
// `validateViewPageRefs` and left with it — no runtime-crossed rule reads
// `stack.pages` any more. The expectation moves rather than being relaxed:
// the invariant under test is "every context collection is present and
// empty", so it has to name the whole set or it stops measuring the shape
// it exists for.
expect(s.baseline).toEqual({ objects: [], permissions: [], books: [], datasets: [], flows: [] });
expect(s.candidate.books).toEqual([{ name: 'b1' }]);
});
});
it('a rule that throws degrades to a warning instead of failing the write', () => {
// A gate whose internal error blocks a publish is worse than the hole it
// closes: the author gets a refusal they cannot act on. Proven through the
// real dispatch path with a body shaped to break a walk.
const cyclic: Record<string, unknown> = { name: 'loop', nodes: [] };
cyclic.self = cyclic;
expect(() =>
runRuntimeAuthoringRules({ type: 'flow', item: cyclic, context: { objects } }),
).not.toThrow();
});
});
// ────────────────────────────────────────────────────────────────────────────
// #7220 — the `views[]` visibility-predicate FAMILY at the runtime door
// ────────────────────────────────────────────────────────────────────────────
//
// The registry move is a two-word edit per entry, and a two-word edit that
// nobody drives is indistinguishable from a declaration nobody reads (#4449,
// and the reason `runtime-gate.test.ts` exists next to the wiring guard at all).
// These tests drive the REAL dispatch path — `runRuntimeAuthoringRules`, the
// same function `packages/metadata-protocol/src/runtime-authoring-gate.ts`
// calls — with `view` bodies a Studio / REST `/meta` / MCP author could save,
// and assert the door now answers.
//
// The card this closes is specifically about the FAMILY, so the last test here
// is the one that matters most: it pins that no input exists on which one member
// fires and another does not. That asymmetry — a `view` refused for an
// unresolvable predicate PATH while a predicate that does not parse at all walks
// through — is exactly what #7214's implementer built, measured and reverted.
/** A plain runtime view: `record` / `current_user` are the bound roots. */
const runtimeView = (visibleWhen: string) => ({
name: 'account_form',
label: 'Account',
object: 'account',
form: { sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }] },
});
/**
* A schema-bound metadata FORM published as a view — `data` is the bound root.
* `validatePredicatePathRefs` judges only this shape (`#7010`: the `record.*`
* layer's addressable path set is not closed), so the family's path half needs
* it to be non-vacuous.
*/
const schemaBoundForm = (visibleWhen: string) => ({
name: 'field_editor',
label: 'Field editor',
form: {
data: { provider: 'schema', schemaId: 'field' },
sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }],
},
});
/** A predicate that is flawless CEL and overruns `DEFAULT_LIMITS.maxAstNodes`. */
const overBudget = Array.from({ length: 120 }, (_, i) => `record.name == 'n${i}'`).join(' || ');
const gateView = (item: unknown) =>
runRuntimeAuthoringRules({ type: 'view', item, context: { objects: [] } });
describe('the views[] visibility-predicate family at the runtime publish gate (#7220)', () => {
it('dispatches `view` writes to both family rules, from the shared table', () => {
expect(runtimeGatedTypes()).toContain('view');
expect(stackKeyForType('view')).toBe('views');
expect(runtimeAuthoringRulesFor('view').map((r) => r.name)).toEqual([
// #24798 — the expression rule runs ONE pass on a view write: the bulk
// `confirmText` template slots, errors since #25205.
'validateStackExpressions',
// #8793 — filter comparands, not predicates; registered ahead of the
// family and dispatched for `view` because list-view filter rules are
// one of the three shapes it judges.
'validatePresetComparands',
// #9313 — the reference-integrity suite's entry dispatches for `view`;
// the suite then runs only its two list-view field members
// (`validateSearchableFields` / `validateSortableFields`) on the
// per-write snapshot — see `runtime-gate.view-writes.test.ts`.
'validateReferenceIntegrity',
// #29309 — a form section naming an unknown field or field group;
// advisory, against the same `objects` context.
'validateFormLayout',
// #25650 — a form open to anonymous intake declaring a file field;
// the snapshot's `objects` context carries the field types it reads.
'validatePublicFormFileFields',
// #28005 — a thank-you panel naming a field the engine does not
// generate; the same `objects` context carries the types it reads.
'validateThankYouRecordFields',
'validateVisibilityPredicates',
'validatePredicatePathRefs',
]);
});
// ── fires: the four defects the card names, at the door they bypassed ──
it('REFUSES a predicate that does not parse as CEL', () => {
const { errors } = gateView(runtimeView("record.status === 'open'"));
const f = errors.find((e) => e.rule === 'visibility-predicate-syntax');
expect(
f,
`\`===\` is not CEL. Before #7220 this exact body saved clean through Studio and then failed `
+ `OPEN in the console — the element renders unconditionally (#5149).`,
).toBeDefined();
// The 422 envelope's four keys: the caller turns `errors` into
// `err.issues` verbatim, so a finding without them is a refusal an author
// cannot act on.
expect(f!.severity).toBe('error');
expect(f!.path).toBe('views[0].form.sections[0].fields[0]');
expect(f!.where.length).toBeGreaterThan(0);
expect(f!.message).toMatch(/not valid CEL/);
expect(f!.hint).toMatch(/==/);
});
it('REFUSES a bare identifier no binding root resolves', () => {
const { errors } = gateView(runtimeView("status == 'open'"));
const f = errors.find((e) => e.rule === 'visibility-bare-identifier');
expect(f, '`status` instead of `record.status` resolves nowhere on any layer').toBeDefined();
expect(f!.severity).toBe('error');
expect(f!.path).toBe('views[0].form.sections[0].fields[0]');
expect(f!.hint).toMatch(/record\.status/);
});
it('REFUSES a predicate that overruns the CEL parse budget', () => {
const { errors } = gateView(runtimeView(overBudget));
const f = errors.find((e) => e.rule === 'visibility-predicate-over-budget');
expect(f, 'same refusal as a syntax fault, different edit (#7217)').toBeDefined();
expect(f!.severity).toBe('error');
});
it('REFUSES a predicate calling a function the CEL environment does not register', () => {
// #13594 — the arm that used to walk through. The shape is a method call on
// `current_user`: it PARSES, so the syntax arm has nothing to say, and
// `current_user` is a declared root, so the bare-ref arm cannot reach the
// call. Before the ruling this reached a tenant's runtime and faulted
// fail-CLOSED on every surface.
//
// RE-POINTED, not deleted (batch #147 item 5, letter A): the example used to
// be `current_user.can(object, verb)` from objectui#4421, and `can` is a
// registered receiver method now. `canApprove` carries the same shape and is
// still invented; the case below is the other half, and the two together are
// what says the gate narrowed by exactly one name.
const { errors } = gateView(runtimeView('current_user.canApprove(object, verb)'));
const f = errors.find((e) => e.rule === 'visibility-predicate-unknown-function');
expect(f, 'the publish door must refuse an unresolvable call, not just the validator').toBeDefined();
expect(f!.severity).toBe('error');
expect(f!.path).toBe('views[0].form.sections[0].fields[0]');
expect(f!.message).toMatch(/`canApprove`/);
expect(f!.message).toMatch(/found no matching overload/);
});
it('ACCEPTS `current_user.can(object, verb)` — objectui#4421, registered and evaluable now', () => {
// The predicate the whole #13594 arm was built around. It is no longer an
// unresolvable call, and the gate must say so: a publish door that kept
// refusing it would block the capability this platform now ships, and one
// that accepted it while nothing could evaluate it was the defect. Both ends
// moved together — `@objectstack/formula` registers `can` receiver-only and
// answers it from `EvalContext.permissions`.
const { errors } = gateView(runtimeView('current_user.can(object, verb)'));
expect(errors.map((e) => e.rule)).not.toContain('visibility-predicate-unknown-function');
});
it('ACCEPTS a predicate whose functions all resolve — the control for the arm above', () => {
// Same door, same shape, a registered function. Without this the test above
// would still pass if the arm had started refusing every call.
const { errors } = gateView(runtimeView("upper(record.name) == 'X'"));
expect(errors.map((e) => e.rule)).not.toContain('visibility-predicate-unknown-function');
});
it('REFUSES a predicate path the target schema does not declare', () => {
const { errors } = gateView(schemaBoundForm("data.tpye == 'text'"));
const f = errors.find((e) => e.rule === 'predicate-path-unresolved');
expect(
f,
'this is the rule whose SOLO wiring #7214 reverted — it is here because its siblings are',
).toBeDefined();
expect(f!.severity).toBe('error');
expect(f!.path).toBe('views[0].form.sections[0].fields[0].visibleWhen');
expect(f!.message).toMatch(/data\.tpye/);
});
it('REFUSES a schema key written without its binding root', () => {
const { errors } = gateView(schemaBoundForm("type == 'text'"));
expect(errors.map((e) => e.rule)).toContain('predicate-path-unrooted');
});
it('REFUSES a path on the RIGHT of `==` — which resolves cleanly and is broken anyway', () => {
// #7659, and the measurement that justifies the id existing: `data.type` and
// `data.label` are both keys of `FieldSchema`, so the rule directly above is
// silent here BY CONSTRUCTION. The renderer resolves only the left side and
// parses the right as a literal, so this compares against the string
// "data.label" and is false on every row.
const { errors } = gateView(schemaBoundForm('data.type == data.label'));
const f = errors.find((e) => e.rule === 'predicate-rhs-path-shaped');
expect(f, 'the right-hand position never evaluates a path').toBeDefined();
expect(f!.severity).toBe('error');
expect(
errors.map((e) => e.rule),
"#7214's check has nothing to say here — that silence is why this rule exists",
).not.toContain('predicate-path-unresolved');
});
it('sends a BARE unquoted word down the advisory channel, not the refusal one', () => {
// The second severity the same id carries. `== active` is compared as the
// literal string "active" today — very likely what the author meant — so
// this rule does not refuse the write over metadata that renders correctly.
//
// #7696: it is now the ONLY thing the author hears about that token. This
// pin used to record the opposite — `visibility-bare-identifier` refusing
// the same write and prescribing `<root>.active` — and the pair it pinned
// was a contradiction, not a division of labour: the rooted spelling it
// asked for is a path on the RIGHT, which this same gate refuses at `error`
// (the test below measures it). So the root-prescribing rules stand down
// for this position and the advisory carries both readings.
const result = gateView(schemaBoundForm('data.type == active'));
const f = result.advisories.find((a) => a.rule === 'predicate-rhs-path-shaped');
expect(f, 'the subset boundary must still reach the author').toBeDefined();
expect(f!.severity).toBe('warning');
expect(result.errors.map((e) => e.rule)).not.toContain('predicate-rhs-path-shaped');
expect(
result.errors.map((e) => e.rule),
'one token, one prescription — the write is no longer blocked by a rule asking for a '
+ 'spelling this gate refuses (#7696)',
).toEqual([]);
// The merged message must state BOTH readings and must not prescribe the
// in-place rooted spelling, which is the thing the next test refuses.
expect(f!.hint).toMatch(/'active'/);
expect(f!.hint).toMatch(/data\.active == /);
expect(f!.hint).toMatch(/Do NOT simply add the root in place/);
});
it('does not prescribe a fix it would itself refuse (#7696)', () => {
// The accept bar the old pair failed. `visibility-bare-identifier` told the
// author to root the word in place; both rootings of that exact predicate
// are a dotted chain on the RIGHT, and the gate refuses them at `error`.
for (const root of ['data', 'record']) {
const { errors } = gateView(schemaBoundForm(`data.type == ${root}.active`));
expect(
errors.map((e) => e.rule),
`\`== ${root}.active\` is the spelling the old error asked for`,
).toContain('predicate-rhs-path-shaped');
}
});
it('still REFUSES the same bare word on the LEFT, and on a runtime surface', () => {
// The scanner proves it can see before any silence is believed. The
// stand-down is per-IDENTIFIER and per-SURFACE, so three neighbours of the
// reconciled case keep their refusal unchanged.
expect(
gateView(schemaBoundForm('status == active')).errors.map((e) => e.rule),
'a bare word on the LEFT is a genuine dropped root, whatever sits on the right',
).toContain('visibility-bare-identifier');
expect(
gateView(schemaBoundForm('data.name == active && active')).errors.map((e) => e.rule),
'the word also occurs outside a right-hand slot — not a literal position',
).toContain('visibility-bare-identifier');
expect(
gateView(runtimeView('record.status == active')).errors.map((e) => e.rule),
'a runtime surface goes to real CEL, where a path on the right is legal and a bare word '
+ 'there really is a dropped root — nothing about it was reconciled',
).toContain('visibility-bare-identifier');
});
it('reports a MISLAYERED root through the advisory channel, not a refusal', () => {
// The one family member that is `warning` on every surface, so it must not
// 422 — and must not be silent either. #4717's `advisories` channel (the
// ruling's sequencing precondition) is what makes the second half true: it
// rides back on the 2xx `saveMetaItem` response, so the Studio / MCP author
// this gate exists for can actually read it. That channel landing is why
// this move was allowed to happen at all rather than running rules and
// discarding their verdicts (#4463's own shape, one notch quieter).
const result = gateView(runtimeView("data.status == 'open'"));
expect(result.errors).toEqual([]);
const f = result.advisories.find((a) => a.rule === 'visibility-root-mislayered');
expect(f, 'a wrong-layer paste must still reach the author').toBeDefined();
expect(f!.severity).toBe('warning');
});
// ── stays quiet ───────────────────────────────────────────────────────
it('a valid view still publishes, with the rules having RUN', () => {
const result = gateView(runtimeView("record.status == 'open'"));
expect(result.errors, JSON.stringify(result.errors)).toEqual([]);
expect(result.advisories, JSON.stringify(result.advisories)).toEqual([]);
// "clean" and "nothing ran" must stay distinguishable.
expect(result.rulesRun).toEqual([
'validateStackExpressions', // #24798 — its bulk `confirmText` pass alone, clean here
'validatePresetComparands', // #8793 — dispatched for `view`, clean here
'validateReferenceIntegrity', // #9313 — its two list-view field members, clean here
'validateFormLayout', // #29309 — a form's field and group references, clean here
'validatePublicFormFileFields', // #25650 — a public form's file fields, clean here
'validateThankYouRecordFields', // #28005 — a thank-you panel's named fields, clean here
'validateVisibilityPredicates',
'validatePredicatePathRefs',
]);
});
it('does not blame a `view` write for a pre-existing violation elsewhere', () => {
// The D4 subtraction, on the newly gated type: a stored object carrying a
// broken predicate is not this write's to answer for.
const result = runRuntimeAuthoringRules({
type: 'view',
item: runtimeView("record.status == 'open'"),
context: {
objects: [
{ name: 'account', fields: { name: { type: 'text', visibleWhen: 'broken ===' } } },
],
},
});
expect(result.errors).toEqual([]);
});
// ── the family property the ruling is about ───────────────────────────
it('the runtime door and `os build` reach the SAME verdict on every family input', () => {
// The asymmetry #7220 exists to prevent, pinned as a property rather than a
// count: for every input below, the finding set at the runtime gate is
// IDENTICAL — id, severity and path — to the finding set the two rule
// functions produce on the CLI. So there is no input on which one member of
// the family fires at the door and another does not, and no input on which
// the door and `os build` disagree about the same predicate.
//
// Asserted by set equality, not by "both are non-empty": a half-wired wall
// is precisely the state where both sides are non-empty and disagree.
const corpus = [
runtimeView("record.status === 'open'"), // syntax
runtimeView("status == 'open'"), // bare identifier
runtimeView("data.status == 'open'"), // mislayered root
runtimeView(overBudget), // over budget
runtimeView("record.status == 'open'"), // clean
schemaBoundForm("data.tpye == 'text'"), // unresolvable path
schemaBoundForm("type == 'text'"), // unrooted schema key
schemaBoundForm("data.type == 'text'"), // resolvable path
schemaBoundForm('data.type == active'), // bare word on the RIGHT (#7696)
];
const fingerprints = (fs: readonly AuthoringFinding[]) =>
fs.map((f) => `${f.severity}:${f.rule}@${f.path}`).sort();
let sawError = false;
let sawAdvisory = false;
for (const item of corpus) {
const gate = gateView(item);
sawError ||= gate.errors.length > 0;
sawAdvisory ||= gate.advisories.length > 0;
const stack = { views: [item] };
const cli = [...validateVisibilityPredicates(stack), ...validatePredicatePathRefs(stack)];
expect(
fingerprints([...gate.errors, ...gate.advisories]),
`the runtime gate and os build disagree about ${JSON.stringify(item)} — one family member `
+ `is enforced at a door the others are not, which is the partial-enforcement surface `
+ `#7220 was filed to prevent`,
).toEqual(fingerprints(cli));
}
// Non-vacuous: the corpus really does exercise both halves of the verdict.
expect(sawError, 'the corpus must contain a refusal').toBe(true);
expect(sawAdvisory, 'the corpus must contain an advisory').toBe(true);
});
});
// ─────────────────────────────────────────────────────────────────────
// #7815 — the layer the gate judges a schema-bound form at.
//
// A separate block, added at the end rather than woven into the family suite
// above (#7576 serialization): nothing in that suite is touched.
// ─────────────────────────────────────────────────────────────────────
describe('the publish gate judges a schema-bound form at its own layer (#7815)', () => {
it('a correctly `data.`-rooted form is SILENT — no advisory, no refusal', () => {
// The finding. `authoring-rules.ts` calls `validateVisibilityPredicates(stack)`
// with no options, so every view was judged at the `'runtime'` default and
// this exact body — correct metadata — came back with an advisory telling
// its author to write `record.`, on a surface that binds no `record` at all.
// Nothing went red then and nothing goes red now; the difference is only
// what the author is told, which is the whole harm of the class.
const result = gateView(schemaBoundForm("data.type == 'text'"));
expect(result.errors, JSON.stringify(result.errors)).toEqual([]);
expect(result.advisories, JSON.stringify(result.advisories)).toEqual([]);
// "clean" and "nothing ran" must stay distinguishable.
expect(result.rulesRun).toEqual([
'validateStackExpressions', // #24798 — its bulk `confirmText` pass alone, clean here
'validatePresetComparands', // #8793 — dispatched for `view`, clean here
'validateReferenceIntegrity', // #9313 — its two list-view field members, clean here
'validateFormLayout', // #29309 — a form's field and group references, clean here
'validatePublicFormFileFields', // #25650 — a public form's file fields, clean here
'validateThankYouRecordFields', // #28005 — a thank-you panel's named fields, clean here
'validateVisibilityPredicates',
'validatePredicatePathRefs',
]);
});
it('the runtime view one fixture-line away still draws it — the rule is live', () => {
// The negative control. Standing an advisory down and going blind look
// identical from the inside, so the case above is only worth its ink beside
// one that still fires: same predicate root, same gate, opposite verdict,
// decided by the `data:` source alone.
const f = gateView(runtimeView("data.status == 'open'"))
.advisories.find((a) => a.rule === 'visibility-root-mislayered');
expect(f, 'a wrong-layer paste on a RUNTIME view is still a wrong-layer paste').toBeDefined();
expect(f!.severity).toBe('warning');
});
it('a `record.`-rooted form now draws the advisory the OTHER way', () => {
// ADR-0089 D3's second direction, unreachable at this door until now: told
// `'runtime'`, the rule forbids `data.` and has nothing to say about
// `record.`, so a form predicate that can never match published in silence.
// Not new behaviour — the rule's existing metadata arm, finally addressed.
const result = gateView(schemaBoundForm("record.type == 'text'"));
expect(result.errors, 'still advisory-only: acceptance is untouched').toEqual([]);
const f = result.advisories.find((a) => a.rule === 'visibility-root-mislayered');
expect(f, 'a predicate that never matches must reach the author').toBeDefined();
expect(f!.severity).toBe('warning');
expect(f!.hint).toMatch(/data/);
});
it('prescribes the root the surface actually binds when it REFUSES', () => {
// The second half of the finding: the layer default also chose the root
// quoted inside `visibility-bare-identifier`'s hint, so the loudest finding
// on this surface — the one that BLOCKS the publish — told the author to
// write `record.status` on a form that binds `data`. Same id, same
// severity, same input: only the prescription moved.
const f = gateView(schemaBoundForm('status == active'))
.errors.find((e) => e.rule === 'visibility-bare-identifier');
expect(f, 'a bare word on the LEFT is still refused').toBeDefined();
expect(f!.severity).toBe('error');
expect(f!.hint).toContain('`data.status`');
expect(f!.hint).not.toContain('`record.status`');
});
it('moves NO finding across the error/advisory boundary', () => {
// The acceptance guarantee this card is bounded by, as a property over the
// schema-bound half of the family corpus: the derivation may only ever
// change which ADVISORIES are emitted. Asserted as exact error sets — each
// one is what the `'runtime'` reading produced on the same input — so a
// later edit to the layer plumbing that promoted or demoted anything goes
// red here rather than at a tenant's publish door.
const cases: Array<[string, string[]]> = [
["data.type == 'text'", []],
["record.type == 'text'", []],
['data.type == active', []],
['status == active', ['visibility-bare-identifier']],
['data.name == active && active', ['visibility-bare-identifier']],
['active == data.type', ['predicate-rhs-path-shaped', 'visibility-bare-identifier']],
["data.tpye == 'text'", ['predicate-path-unresolved']],
["type == 'text'", ['predicate-path-unrooted']],
['data.type == data.label', ['predicate-rhs-path-shaped']],
["country === 'USA'", ['visibility-predicate-syntax']],
];
for (const [predicate, expected] of cases) {
expect(
gateView(schemaBoundForm(predicate)).errors.map((e) => e.rule).sort(),
`the refusal set for \`${predicate}\` changed — the #7815 layer derivation is `
+ `advisory-only by construction, so anything moving here is a scope breach`,
).toEqual([...expected].sort());
}
});
});
// ─────────────────────────────────────────────────────────────────────
// #7529 — dashboard widget dataset bindings at the runtime publish door.
//
// A separate block, added at the end rather than woven into the suites above
// (#7576 serialization): nothing in them is touched.
//
// The card: a dashboard widget bound to a dataset that names nothing answered
// 200 on both save and publish — not because a validator was missing (the
// card's own root-cause lead, falsified by measurement), but because
// `validateWidgetBindings` provably catches this body and `dashboard` was not
// a runtime-gated type, so the gate returned empty before building a snapshot.
// Ruled 2026-08-12 (option B): a DRAFT may hold a forward reference;
// publishing refuses with the key path named. Ruled 2026-08-15: `surfaces` is
// per-RULE, so the flip puts the rule's error ids on the door as one "this
// board cannot render" reference-integrity class — pinned below as reachable,
// not merely declared. That class was SIX ids until #15463 demoted
// `chart-field-unknown` to `warning` (the pinned renderer refuses those three
// `chartConfig` binding keys outright, so the board renders correctly either
// way); it is FIVE now, and the demoted id is pinned on the advisory channel
// immediately after, so leaving the accept-set is a measured departure rather
// than an absence.
// ─────────────────────────────────────────────────────────────────────
/** A resolution universe with one real object and one real dataset. */
const dashObjects = [
{
name: 'orders',
fields: [
{ name: 'amount', type: 'number' },
{ name: 'status', type: 'text' },
{ name: 'region', type: 'text' },
],
},
];
const ordersDataset = {
name: 'orders_ds',
object: 'orders',
dimensions: [{ name: 'status', field: 'status' }, { name: 'region', field: 'region' }],
measures: [
{ name: 'order_count', aggregate: 'count' },
{ name: 'sum_amount', field: 'amount', aggregate: 'sum' },
],
};
const dashContext = { objects: dashObjects, datasets: [ordersDataset] };
const dashboard = (widgets: unknown[], extra: Record<string, unknown> = {}) => ({
name: 'ops_board',
label: 'Ops Board',
widgets,
...extra,
});
/** A widget every check passes: real dataset, real dimension, real measure. */
const cleanWidget = (over: Record<string, unknown> = {}) => ({
id: 'w1',
type: 'bar',
dataset: 'orders_ds',
dimensions: ['status'],
values: ['order_count'],
chartConfig: { xAxis: { field: 'status' }, yAxis: [{ field: 'order_count' }] },
...over,
});
const gateDashboard = (item: unknown, context: object = dashContext) =>
runRuntimeAuthoringRules({ type: 'dashboard', item, context });
describe('dashboard widget dataset bindings at the runtime publish gate (#7529)', () => {
it('dispatches `dashboard` writes to validateWidgetBindings, from the shared table', () => {
expect(runtimeGatedTypes()).toContain('dashboard');
expect(stackKeyForType('dashboard')).toBe('dashboards');
expect(runtimeAuthoringRulesFor('dashboard').map((r) => r.name)).toEqual([
'validateWidgetBindings',
// #8793 — bare preset names in widget-filter ordering comparands are
// judged at the same door (no resolution context needed).
'validatePresetComparands',
]);
});
it("REFUSES the card's body — a dataset binding that names nothing", () => {
const { errors } = gateDashboard(
dashboard([cleanWidget({ dataset: 'no_such_dataset_xyz' })]),
);
const f = errors.find((e) => e.rule === 'widget-dataset-unknown');
expect(
f,
`the exact body #7529 measured sailing through save AND publish must now be refused at ` +
`publish — the rule always caught it; the door just never ran the rule.`,
).toBeDefined();
// The 422 envelope's four keys (#4463 D3), including the ruling's own
// requirement: the offending key path is NAMED.
expect(f!.severity).toBe('error');
expect(f!.path).toBe('dashboards[0].widgets[0]');
expect(f!.where).toContain('ops_board');
expect(f!.message).toMatch(/no_such_dataset_xyz/);
expect(f!.hint.length).toBeGreaterThan(10);
});
it('publishes a fully legitimate multi-widget board clean, with the rule having RUN', () => {
// The 0-phantom half of the differential the snapshot widening exists for.
const legit = dashboard([
cleanWidget(),
cleanWidget({
id: 'w2',
type: 'donut',
dimensions: ['region'],
chartConfig: { series: [{ name: 'order_count' }] },
}),
cleanWidget({ id: 'w3', type: 'metric', dimensions: [], values: ['sum_amount'], chartConfig: undefined }),
]);
const result = gateDashboard(legit);
expect(result.errors, JSON.stringify(result.errors)).toEqual([]);
expect(result.advisories, JSON.stringify(result.advisories)).toEqual([]);
// "clean" and "nothing ran" must stay distinguishable.
expect(result.rulesRun).toEqual(['validateWidgetBindings', 'validatePresetComparands']);
});
it('the `datasets` snapshot key is LOAD-BEARING: without it the same board is refused', () => {
// The 3-phantom / 0-phantom measurement, pinned as a test. This is the
// reverse verification in its inverted direction: ablating the context key
// produces MORE errors, not fewer — every legitimate widget reads as
// dangling, which is why flipping the rule without widening the snapshot
// would have 422'd every legitimate dashboard publish in the product.
const legit = dashboard([
cleanWidget(),
cleanWidget({
id: 'w2',
type: 'donut',
dimensions: ['region'],
chartConfig: { series: [{ name: 'order_count' }] },
}),
cleanWidget({ id: 'w3', type: 'metric', dimensions: [], values: ['sum_amount'], chartConfig: undefined }),
]);
const withoutDatasets = gateDashboard(legit, { objects: dashObjects });
expect(
withoutDatasets.errors.filter((e) => e.rule === 'widget-dataset-unknown'),
`a per-write snapshot with no dataset universe cannot tell a dangling binding from a real ` +
`one, so it invents a refusal per widget — the false-422 shape #8309 measured as 38-vs-4 ` +
`for permissions, here as 3 phantom errors on a 3-widget board`,
).toHaveLength(3);
// And the true positive survives the widened snapshot (the fix does not
// buy silence): the dangling board still yields exactly its one error.
const dangling = gateDashboard(dashboard([cleanWidget({ dataset: 'no_such_dataset_xyz' })]));
expect(dangling.errors).toHaveLength(1);
});
it('ALL SIX error ids are reachable at the door — the class the 2026-08-15 ruling accepted', () => {
// `surfaces` is per-rule, so the flip enforces the rule's whole error set,
// not just `widget-dataset-unknown`. The ruling accepted the class as one
// coherent "this board cannot render" set — this test makes that
// acceptance REACHABLE rather than declared, and its exact error sets keep
// the boundary honest: a case gaining or losing an id is a scope change
// that must go through this line rather than around it.
//
// [#15463] It went through this line: the set was SIX until
// `chart-field-unknown` dropped to `warning`. Its case moves to the
// advisory test below rather than being deleted — an id that leaves the
// accept-set must still be shown to REACH the door, or "no longer gating"
// and "no longer running" become indistinguishable here.
const cases: Array<[string, unknown, string[]]> = [
[
'dangling dataset',
dashboard([cleanWidget({ dataset: 'no_such_dataset_xyz' })]),
['widget-dataset-unknown'],
],
[
'unknown dimension',
dashboard([cleanWidget({ dimensions: ['statuss'] })]),
['widget-dimension-unknown'],
],
[
'unknown measure',
dashboard([cleanWidget({ values: ['no_such_measure'], chartConfig: { xAxis: { field: 'status' } } })]),
['widget-measure-unknown'],
],
[
'legacy analytics shape as the only (dead) data wiring',
dashboard([{ id: 'w9', type: 'bar', categoryField: 'status' }]),
// The legacy-only widget also binds no dataset, so the required-binding
// arm of `widget-dataset-unknown` fires beside the legacy error.
['widget-dataset-unknown', 'widget-legacy-analytics-unrenderable'],
],
[
'dashboard filter targeting a field the bound object lacks',
dashboard([cleanWidget()], { dateRange: { field: 'close_date' } }),
['dashboard-filter-field-unknown'],
],
[
// [#27445] The sixth id joins through the same per-rule `surfaces`: a
// binding key the runtime never reads leaves the widget counting rows
// the author scoped out, so it is refused at the door with the five.
'filterBindings key naming no declared dashboard filter',
dashboard([cleanWidget({ filterBindings: { no_such_filter: false } })]),
['dashboard-filter-binding-unknown'],
],
];
const seen = new Set<string>();
for (const [label, item, expected] of cases) {
const { errors } = gateDashboard(item);
expect(
errors.map((e) => e.rule).sort(),
`error set changed for case "${label}"`,
).toEqual([...expected].sort());
for (const e of errors) seen.add(e.rule);
}
// Non-vacuous, and the ruling's whole accept-set as #15463 left it plus
// #27445's id: exactly the six. `chart-field-unknown` is deliberately absent.
expect([...seen].sort()).toEqual([
'dashboard-filter-binding-unknown',
'dashboard-filter-field-unknown',
'widget-dataset-unknown',
'widget-dimension-unknown',
'widget-legacy-analytics-unrenderable',
'widget-measure-unknown',
]);
expect(seen.has('chart-field-unknown')).toBe(false);
});
it('[#27445] a binding to a DECLARED filter passes the door; a misspelled key is refused at its path', () => {
const declared = { globalFilters: [{ name: 'region', field: 'region', type: 'select' }] };
const ok = gateDashboard(dashboard([cleanWidget({ filterBindings: { region: false } })], declared));
expect(ok.errors, JSON.stringify(ok.errors)).toEqual([]);
const typo = gateDashboard(dashboard([cleanWidget({ filterBindings: { regoin: false } })], declared));
expect(typo.errors.map((e) => e.rule)).toEqual(['dashboard-filter-binding-unknown']);
expect(typo.errors[0].path).toBe('dashboards[0].widgets[0].filterBindings.regoin');
expect(typo.errors[0].message).toContain('(declared: region)');
expect(typo.errors[0].hint).toContain('Did you mean "region"?');
});
it('the demoted `chart-field-unknown` still RUNS at the door — on the advisory channel (#15463)', () => {
// The other half of the accept-set narrowing: the exact body that used to
// 422 now publishes, and the finding reaches the author on the 2xx response
// instead. Pinned as one case so "demoted" cannot decay into "dropped".
const board = dashboard([cleanWidget({ chartConfig: { xAxis: { field: 'not_a_dim' } } })]);
const result = gateDashboard(board);
expect(result.errors, JSON.stringify(result.errors)).toEqual([]);
const f = result.advisories.find((a) => a.rule === 'chart-field-unknown');
expect(f, 'the advisory must still reach the author').toBeDefined();
expect(f!.severity).toBe('warning');
expect(f!.path).toBe('dashboards[0].widgets[0]');
expect(f!.message).toMatch(/not_a_dim/);
// The message names the refusal, not a query that never runs. [#22161]
// The one-line verdict says the key is ignored; HOW the renderer strips
// it is `os explain chart-field-unknown`.
expect(f!.message).toContain('is ignored anyway');
expect(f!.message).not.toContain('will not contain');
// And the rule genuinely ran, rather than the door skipping the type.
expect(result.rulesRun).toContain('validateWidgetBindings');
});
it('warning-tier ids ride the ADVISORY channel and never block (#4463 P1)', () => {
// A `table` widget selecting only count measures with no dimensions draws