Repository navigation
Expand file tree
/
Copy pathdata-model-rules.ts
More file actions
955 lines (895 loc) · 47.8 KB
/
Copy pathdata-model-rules.ts
File metadata and controls
955 lines (895 loc) · 47.8 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Data-model best-practice lint rules.
*
* These rules encode the relationship / master-detail / roll-up conventions the
* platform ships (see the objectstack-data and objectstack-ui skills, ADR-0035).
* They run over the normalized object set and flag anti-patterns that an
* author — human OR an AI generator — commonly produces. They are intentionally
* heuristic: structural problems are `error`, likely-wrong choices are
* `warning`, and "you probably want this" nudges are `suggestion`. None of them
* block on a judgement call.
*
* The same rules double as the automated rubric for the metadata-generation
* eval (see `score.ts`): a generated stack scores well exactly when it is
* schema-valid AND lint-clean here.
*/
import { BOOLEAN_VALUE_TYPES, NUMERIC_VALUE_TYPES, referenceCarrierOf } from '@objectstack/spec/data';
export type Severity = 'error' | 'warning' | 'suggestion';
export interface LintIssue {
severity: Severity;
rule: string;
message: string;
path: string;
fix?: string;
}
/**
* A {@link LintIssue} that also states the HUMAN-READABLE location, for rules
* that are adapted into `AuthoringFinding` (`packages/lint/src/authoring-rules.ts`).
*
* `AuthoringFinding` declares two location slots with different jobs — `where`
* ("human-readable location", e.g. `object "leave_request"`) and `path` ("config
* path", e.g. `objects[3].sharingModel`) — and every CLI command renders the
* first as the line's prefix: `os validate` prints
* `• ${where}: ${message}` and then `rule: ${rule} at ${path}`.
*
* `LintIssue` carries only the positional `path`, so the three ADR-0120
* uniqueness rules' registry adapters had nothing else to map and set
* `where: f.path`. Measured on `origin/main`: an author saw
* `• objects[44].indexes[1]: "sys_account" declares index … at objects[44].indexes[1]`
* — the same positional string twice, and an index into the MERGED object array
* that appears in no file the author wrote (44 objects from
* `@objectstack/platform-objects` plus one from `@objectstack/metadata-core`).
* No information was lost — the object's name is in the message — but the
* location slot said nothing the `at` clause did not already say, and every
* other rule in the table spells it `object "sys_account"`.
*
* Stating `where` at the PRODUCER rather than reconstructing it in the adapter
* is deliberate: only the rule still holds the object it walked. Making it
* REQUIRED here (rather than adding `where?` to `LintIssue` and writing
* `f.where ?? f.path` at the adapter) is the same discipline — a consumer-side
* fallback would let the next rule ship the positional spelling again, silently.
*
* `path` is unchanged and stays positional AT THE RULE LEVEL: it is the slot
* that is SUPPOSED to be a config path, `os validate` prints it after `at`
* (where the index resolves against the author's own config file), and the
* runtime gate's `fingerprint` reads `where` and `path` together (making
* `where` more specific cannot merge two findings that were distinct).
*
* [commit def0d3e63] On the runtime gate's WIRE surface (`RuntimeAuthoringIssue.path`,
* the 422 `issues[]` / 2xx `advisories`), the top-level collection index of a
* collection-resident finding is rewritten to the entry's NAME
* (`objects[417].sharingModel` → `objects.acme_invoice.sharingModel`) after
* the differential — a runtime caller has no array to resolve `417` against;
* that index numbers the gate's private per-write snapshot. The rewrite lives
* in `runtime-gate.ts` (`nameKeyFindingPath`); rules keep emitting positional
* paths and need no awareness of it.
*/
export interface LocatedLintIssue extends LintIssue {
/** Human-readable location, e.g. `object "sys_account" · index 'uniq_org_email'`. */
where: string;
}
/** `object "sys_account"` — the spelling the rest of the authoring table uses. */
function objectWhere(obj: any): string {
return `object "${obj?.name}"`;
}
/**
* `object "sys_account" · index 'uniq_org_email'`.
*
* A declared index's `name` is optional, so an unnamed one is identified by the
* columns the author actually wrote (`· index [provider_id, account_id]`) — searchable
* in their source, which a bare ordinal is not. The ordinal is the last resort
* for an index that has neither, and is scoped to the named object rather than
* to the merged stack array.
*/
function indexWhere(obj: any, idx: any, j: number, cols: readonly string[]): string {
const named = typeof idx?.name === 'string' && idx.name.trim() ? `'${idx.name.trim()}'` : '';
const label = named || (cols.length > 0 ? `[${cols.join(', ')}]` : `#${j}`);
return `${objectWhere(obj)} · index ${label}`;
}
/** `object "sys_account" · field 'email'` — the field-scoped form of the above. */
function fieldWhere(obj: any, fieldName: string): string {
return `${objectWhere(obj)} · field '${fieldName}'`;
}
// ─── Heuristics ─────────────────────────────────────────────────────
const RELATIONSHIP_TYPES = new Set(['lookup', 'master_detail']);
const NUMERIC_TYPES = new Set([
'number', 'currency', 'integer', 'decimal', 'percent', 'float', 'double',
]);
const OPTION_FIELD_TYPES = new Set(['select', 'multiselect', 'radio', 'enum']);
/**
* Does a `min` / `max` roll-up over a child field of `childFieldType` produce
* an answer that fits the column a `summary` field is stored in?
*
* This is the roll-up door's OWN predicate, and it is deliberately NOT
* `isAggregateCompatibleWithFieldType`
* (`packages/spec/src/data/aggregate-field-type-compatibility.ts`). The two
* answer different questions about the same pair:
*
* - That table asks **"can every backend give one answer"** — and for
* `min` / `max` it ACCEPTS the temporal class on purpose, because there
* they "return a value of the field's OWN type (#15768)". A `DatasetMeasure`
* hands that answer straight to the caller, so a temporal answer is fine.
* - This rule asks **"does that answer fit the column this roll-up is
* STORED into"**. A roll-up's answer is not returned, it is persisted in
* the `summary` field, whose value contract is `z.number().finite()`
* (`valueSchemaFor`, ADR-0104 D1) because `summary` is a member of
* `NUMERIC_VALUE_TYPES`.
*
* So this predicate is the analytics table's `min` / `max` row NARROWED by
* exactly the temporal class. Reusing that table here would accept
* `max(child.shipped_at)` — the very declaration this rule exists to refuse —
* and the gate would be green because it never fires. ⛔ Do not "simplify"
* the two into one call; `data-model-rules.summary-rollup.test.ts` pins the
* disagreement.
*
* Membership is READ from the spec's own value classes rather than typed out
* here, and from these two specifically:
*
* - `NUMERIC_VALUE_TYPES` is the set that DEFINES the acceptance criterion —
* it is the very membership `valueSchemaFor` consults to answer
* `z.number().finite()`. A type joining that class changes the `summary`
* value contract and this door with it, in one edit.
* - `BOOLEAN_VALUE_TYPES` is admitted on the authority of maintainer ruling
* #11152: booleans aggregate as NUMBERS on every backend with no
* per-aggregate exception, pinned by the spec's own `AGGREGATION_CASES`
* (`min(flag)=0`, `max(flag)=1`, enrolled on six backends) and implemented
* by `driver-sql`'s `int` cast on Postgres (#11635). The answer is a
* number, so it fits.
*
* ⛔ Deliberately NOT read: `NON_TEXT_STORED_VALUE_TYPES`. It is defined by a
* third question — "may a text operator be aimed at this column" (#14079) —
* and it is no longer even coextensive with these two classes: #15683's ruling
* added `date` / `datetime` / `time` to it on 2026-09-05, and a temporal child
* field is the very declaration this rule exists to refuse, so reading it here
* would now widen this door by exactly the class the rule guards. Composing the
* union states why each half is in, so a future member of that set cannot widen
* this door as a side effect either.
*/
function summaryRollupAnswerFitsColumn(childFieldType: string): boolean {
return NUMERIC_VALUE_TYPES.has(childFieldType) || BOOLEAN_VALUE_TYPES.has(childFieldType);
}
/**
* Field names that give an object a title FACE, for R9
* (`object/missing-name-field`).
*
* DIVERGES from spec's `NAME_ISH_EXACT`
* (`packages/spec/src/data/display-name.ts`) by exactly one entry: `code`. That
* difference is INTENTIONAL — the maintainer ruled on 2026-08-10 (#6734) to
* keep both sets as they are and write the gap down in both places rather than
* converge them. The two sets answer different questions:
*
* - R9 asks the LOOSER **"will records be anonymous?"** — is there anything
* here a human could read instead of a raw id? A `code` clears that bar, so
* it counts as a title face and is listed below.
* - ADR-0079 derivation (`resolveDisplayField`) asks **"what IS the title?"**
* — which field to PICK as the primary. A `code` is an identifier, not a
* title, so spec deliberately omits it from tier 1 (name-ish exact) and
* tier 2 (name-ish affix). A `code`-only object can still be derived at
* tier 3 ("first title-eligible field by declaration order") — by a
* different rule and a different priority, so the two are not equivalent
* even where they agree on the outcome.
*
* Nothing user-visible turns on the gap: R9 is `severity: 'suggestion'` and
* ADR-0079's `Record #<id>` floor means no object ships without a title either
* way. Do not "fix" either set into the other without a ruling that supersedes
* the one above.
*/
const NAME_LIKE_FIELDS = ['name', 'title', 'subject', 'label', 'full_name', 'display_name', 'code'];
/** Child object names that read as line-items / composition (entered with the parent). */
const LINE_ITEM_RE = /_(line|lines|line_item|line_items|item|items|detail|details|entry|entries)$/;
/** Child object names that read as associations (comments/audit/activity — NOT line items). */
const ASSOCIATION_TOKENS = [
'comment', 'attachment', 'note', 'log', 'audit', 'activity', 'activities',
'history', 'event', 'reaction', 'like', 'mention', 'notification', 'message',
];
function isLineItemName(name: string): boolean {
return LINE_ITEM_RE.test(name);
}
function isAssociationName(name: string): boolean {
const lc = name.toLowerCase();
return ASSOCIATION_TOKENS.some((t) => lc === t || lc.endsWith(`_${t}`) || lc.endsWith(`_${t}s`));
}
interface FieldEntry {
name: string;
def: any;
}
function fieldEntries(fields: any): FieldEntry[] {
if (!fields) return [];
if (Array.isArray(fields)) {
return fields.filter((f) => f && f.name != null).map((f) => ({ name: String(f.name), def: f }));
}
return Object.entries<any>(fields).map(([name, def]) => ({ name, def }));
}
/**
* The `reference` target a relationship field points at.
*
* `reference` is the only spelling `FieldSchema` declares; `reference_to` (like
* `referenceTo` / `relatedTo` / `target`) is a rejected alias the strict error
* map renames for the author, so a field carrying it does not parse (#5017,
* #11567 — "one key, one answer, on both doors").
*
* The DELIBERATE narrowing here mirrors `refOf` in
* `packages/lint/src/validate-security-posture.ts`, which was narrowed to
* canonical-only on purpose and records the reasoning. It applies with more
* force in THIS file, because these rules exist to tell an author their
* metadata is wrong: `lintDataModel` runs over a schema-parsed stack
* (`@objectstack/lint` is "pure `(stack) => Finding[]` … an in-memory,
* schema-parsed stack object"), where a rejected alias cannot appear — and on
* any pre-parse path the schema already names the real defect (the alias key)
* rather than R1 guessing past it. Tolerating the alias made
* `relationship/missing-reference` report a valid target for a field that has
* none: the one component whose job is to catch the misspelling was the one
* accepting it.
*
* The narrowing is now a REFUSAL rather than a quiet `undefined` (#13053): a
* `reference` present in a shape no reader can read throws, because a rule whose
* job is to tell an author their metadata is wrong must not be the component
* that reads the wrong metadata as absent. The predicate is the spec's single
* carrier accessor, so this file, `validate-security-posture.ts` and the runtime
* cannot drift into three answers.
*/
function refOf(def: any): string | undefined {
return referenceCarrierOf({ reference: def?.reference }, 'data-model-rules refOf');
}
// ─── R2 under controlled_by_parent ──────────────────────────────────
/** The rule id R2 reports under, on both tiers. */
export const RELATIONSHIP_MASTER_DETAIL_REQUIRED = 'relationship/master-detail-required';
/** The rule id R3 reports under (`master_detail` without `deleteBehavior`). */
export const RELATIONSHIP_DELETE_BEHAVIOR = 'relationship/delete-behavior';
/** The rule id R13 reports under (a `min`/`max` roll-up over a non-numeric child). */
export const ROLLUP_NON_NUMERIC_AGGREGAND = 'rollup/non-numeric-aggregand';
/**
* [#22161] The consequence every `controlled_by_parent` arm of R2 ends with —
* one wording, so the three shapes cannot drift. Why such a record is
* readable by nobody, and why `readonly` / `system` skip the required check,
* is the `relationship/master-detail-required` explanation (`os explain`).
*/
const CBP_ORPHAN_CONSEQUENCE =
'a controlled_by_parent detail saved without its master is readable by nobody';
/**
* R2's `error` tier — a `master_detail` reference on a
* `sharingModel: 'controlled_by_parent'` object in one of the three shapes that
* leave the security gate as the only thing refusing a detail record saved
* without its master:
*
* 1. `required` absent (or `false`);
* 2. `required: true` + `readonly: true`;
* 3. `required: true` + `system: true`.
*
* Why these three. A `controlled_by_parent` detail derives ALL of its record
* access from the master its `master_detail` reference names (ADR-0055: such an
* object "must declare exactly one required `master_detail` field"). Record
* validation (`validateRecord`, `@objectstack/objectql`) never checks a field
* that is not `required`, and skips `readonly` / `system` fields before its
* required check is reached — so on all three shapes an insert that omits the
* master FK is refused by `assertControlledByParentWrite` (plugin-security) and
* by nothing else. A record that lands without its master anyway is readable by
* nobody: the derived read filter `masterFK IN (accessible master ids)` never
* matches null, and every later by-id write is refused.
*
* Why `error` here and `warning` elsewhere. This is the criterion
* `validate-security-posture.ts` states at its head — an `error` rule mirrors a
* hard runtime enforcement point and moves the failure from runtime-deny to an
* author-time fix. Under `controlled_by_parent` the security gate's refusal
* stands behind every one of these shapes; outside it nothing at runtime refuses
* a non-required `master_detail`, so there it stays a likely-wrong choice at
* `warning`, unchanged. Maintainer ruling of 2026-08-16, Direction 1, scheduled
* for the v18 boundary — the card that carries it verbatim is #9139 (the thread
* the ruling was recorded on no longer resolves on the board); the runtime half
* of that ruling is untouched
* (the security gate's fallbacks stay, so metadata already at rest keeps
* loading and is still guarded).
*
* Scope — EVERY `master_detail` field of a `controlled_by_parent` object, not
* only the one the runtime resolves as the master: that is the scope the
* builder half of the same ruling already enforces (`ObjectSchema.create()`
* forces `required: true` on every `master_detail` reference under
* `controlled_by_parent` and refuses an explicit `required: false` —
* `forceCbpMasterDetailRequired` in `packages/spec/src/data/object.zod.ts`).
* The spec parse refuses, at every door that parses, every shape that leaves
* the object without exactly one writable required master (`ObjectSchema`'s
* `controlledByParentMasterRefusal`: a missing `required` since ruling B,
* `readonly` / `system` on the one master since #25092, ruling 6328204856
* route A, shape `master-not-writable`). What only this rule reports is a
* shape on a second, non-required `master_detail` beside the master.
*
* ⚠ Reach: `lintDataModel` is `os lint`'s sweep and the metadata-generation
* rubric (`score.ts`), and nothing else — it is not an `AUTHORING_RULES` entry
* (`authoring-rule-wiring.test.ts` → `DIRECT_CALL_RATCHET`), so `os build`,
* `os validate` and the metadata save door do not run it; they meet the spec
* parse's refusal above instead. The `error` moves `os lint`'s exit code and
* the rubric's `valid`, not a publish verdict.
*
* One finding per field, located at the first defect it names; the `fix`
* names every edit the field needs.
*
* ⛔ Keep this above the first `export function`: `authoring-rule-wiring.test.ts`
* reads an exported rule's body as the source text up to the next `export`, so
* an `error`-emitting helper placed below one of the three registered advisory
* rules above `lintDataModel` is read as that rule emitting `error`.
*/
function cbpMasterReferenceFinding(
objectName: string,
fieldName: string,
fieldPath: string,
parent: string,
def: any,
): LintIssue | undefined {
const missingRequired = def.required !== true;
const flags = (['readonly', 'system'] as const).filter((flag) => def[flag] === true);
if (!missingRequired && flags.length === 0) return undefined;
const subject = `master_detail "${objectName}.${fieldName}" → ${parent}`;
// [#22161] One verdict per shape, ending in the one shared consequence; the
// derivation (why the record is unreadable, why the flags skip the check)
// is `os explain` text.
const message = missingRequired
? flags.length === 0
? `${subject} must be required: ${CBP_ORPHAN_CONSEQUENCE}`
: `${subject} must be required and not marked ${flags.join(' or ')}: ${CBP_ORPHAN_CONSEQUENCE}`
: `${subject} is marked ${flags.join(' and ')}, which skips its required check: ` +
CBP_ORPHAN_CONSEQUENCE;
return {
severity: 'error',
rule: RELATIONSHIP_MASTER_DETAIL_REQUIRED,
message,
path: `${fieldPath}.${missingRequired ? 'required' : flags[0]}`,
fix: [
...(missingRequired ? ['required: true'] : []),
...flags.map((flag) => `drop ${flag}: true`),
].join(', '),
};
}
// ─── Uniqueness declarations (ADR-0120) ─────────────────────────────
export const UNIQUE_DOUBLE_DECLARATION = 'unique/double-declaration';
export const UNIQUE_UNSCOPED_DECLARED_INDEX = 'unique/unscoped-declared-index';
export const UNIQUE_LEGACY_ORGANIZATION_COMPOSITE = 'unique/legacy-organization-composite';
/**
* The organization column, as an AUTHOR would have spelled it.
*
* `organization_id` is kernel-injected at registration, not authored — which is
* exactly why an author who typed it into an index's `fields` was hand-writing
* the per-organization composite the vocabulary now has a word for (ADR-0120
* S6). An object may declare a different column via `tenancy.tenantField`; that
* spelling is honored here for the same reason.
*/
function authoredTenantColumn(obj: any): string {
const declared = obj?.tenancy?.tenantField;
return typeof declared === 'string' && declared.trim() ? declared.trim() : 'organization_id';
}
/** Is `unique` declared at all? Mirrors `isUniqueDeclared` in @objectstack/spec/data. */
function uniqueDeclared(u: unknown): boolean {
return u === true || u === 'global' || u === 'organization';
}
/**
* Which boundary does a FIELD-level `unique` ask for? Bare `true` is the
* positional synonym of `'organization'` (#3696, ADR-0120 D1 — valid
* indefinitely).
*/
function fieldUniqueScope(u: unknown): 'organization' | 'global' {
return u === 'global' ? 'global' : 'organization';
}
/**
* Which boundary does a DECLARED-index `unique` ask for? `'organization'` asks
* for the NULL-safe organization key part to be prepended at registration
* (ADR-0120 D1/D3); `'global'` is the verbatim column list. Bare `true` — the
* positional spelling of `'global'`, refused since protocol 18 (#5082) — still
* reads as `'global'` here, because this rule also runs over the unparsed
* stack `os lint` sees, where R11 reports the spelling itself.
*/
function indexUniqueScope(u: unknown): 'organization' | 'global' {
return u === 'organization' ? 'organization' : 'global';
}
/**
* R11 (ADR-0120 D5a) — a declared index carries bare `unique: true`: the one
* spelling whose scope is unstated.
*
* Positional intent is the #4986 trap: an author writes
* `indexes: [{ fields: ['name'], unique: true }]` on an organization-scoped
* object, intends "unique per organization", and silently gets
* installation-wide. This rule fires on the SPELLING alone — deliberately no
* tenancy or posture inference (`organization_id` is kernel-injected at
* registration, not authored, so an authoring-time guess would be wrong half
* the time; that dead end is documented on #4698). Both replacement words are
* checkable at authoring time, which is what makes this the first gate in the
* #4986 saga that can actually run here.
*
* Protocol 18 (#5082, ADR-0120 D7): an ERROR. 17.x warned; the spelling is
* now refused, and this rule is one of its two refusal channels. The other is
* the schema itself — `IndexSchema.unique` refuses bare `true` with the same
* prescription, at every door that parses (`os validate` / `os build`,
* `ObjectSchema.create`, the runtime save door). This rule is what refuses it
* where nothing parses: `os lint` is the cheap pre-flight and runs every rule
* over the NORMALIZED, unparsed stack.
*
* Concrete harm: #8323 measured the cross-tenant 409-vs-201 oracle end to end.
*
* Wiring: one AUTHORING_RULES entry on all three commands (a gating rule must
* run on all three). `lintDataModel` no longer calls it — the registry entry
* is what reports it under `os lint`, so each command reports each finding
* exactly once.
*/
export function lintUnscopedDeclaredIndexes(objects: any[]): LocatedLintIssue[] {
const issues: LocatedLintIssue[] = [];
if (!Array.isArray(objects) || objects.length === 0) return issues;
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
if (!obj?.name) continue;
const declaredIndexes = Array.isArray(obj.indexes) ? obj.indexes : [];
for (let j = 0; j < declaredIndexes.length; j++) {
const idx = declaredIndexes[j];
if (idx?.unique !== true) continue; // fires on the bare spelling only
const colList: string[] = Array.isArray(idx?.fields)
? idx.fields.filter((f: unknown) => typeof f === 'string')
: [];
const cols = colList.join(', ');
const indexLabel = typeof idx?.name === 'string' && idx.name.trim() ? ` '${idx.name.trim()}'` : '';
issues.push({
severity: 'error',
rule: UNIQUE_UNSCOPED_DECLARED_INDEX,
where: indexWhere(obj, idx, j, colList),
// [#22161] One verdict; the two refusal channels and the stored-row
// conversion are `os explain` text.
message:
`"${obj.name}" index${indexLabel} [${cols}] has bare \`unique: true\`, an unstated scope protocol 18 ` +
`refuses (ADR-0120): it built the index installation-wide`,
path: `objects[${i}].indexes[${j}]`,
// [#22161] One remedy line. What `'organization'` makes the driver
// build, and the `os migrate meta` route for existing sources (the
// house sentence), are `os explain` text.
fix:
"State the scope: `unique: 'global'` (installation-wide — the exact index bare `true` built) or " +
"`unique: 'organization'` (one holder per organization).",
});
}
}
return issues;
}
/**
* R10 (ADR-0120 D5b) — the same single column carries BOTH a field-level
* `unique` and a declared single-column unique index (#3991), judged in the
* scope vocabulary. Each side states (or positionally implies) a boundary —
* field: `true`/`'organization'` = per-organization, `'global'` =
* installation-wide; declared index: `'global'` (or bare `true`, its
* deprecated spelling) = installation-wide, `'organization'` =
* per-organization — giving four quadrants:
*
* - Different scopes (field per-organization × index `'global'`, or field
* `'global'` × index `'organization'`): CONTRADICTION. The installation-wide
* index is physically stricter and wins; the per-organization constraint
* can never be tripped. One declared intent is silently dead.
* - Same scope (both per-organization, or both installation-wide):
* REDUNDANCY — the same index declared twice.
*
* Tenancy is deliberately NOT inferred here — the quadrants are judged from
* the two spellings alone, which is exactly what the vocabulary buys
* (pre-ADR-0120, the contradiction quadrant could only be described
* conditionally on unknowable tenancy).
*
* A composite declared index (`['organization_id', 'email']`) stays exempt:
* it is the legacy hand-written organization spelling and agrees with the
* field-level default (its `'organization'` respelling nudge is ADR-0120 D5c,
* a separate wave).
*
* Advisory. The resulting stack is well-defined — the cost is an intent that
* never takes effect, not a broken artifact — so this never fails a build.
*/
export function lintUniqueDeclarations(objects: any[]): LocatedLintIssue[] {
const issues: LocatedLintIssue[] = [];
if (!Array.isArray(objects) || objects.length === 0) return issues;
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
if (!obj?.name) continue;
const declaredIndexes = Array.isArray(obj.indexes) ? obj.indexes : [];
if (declaredIndexes.length === 0) continue;
// Columns covered by a declared SINGLE-column unique index. A composite
// (`['organization_id', 'email']`) is the legacy hand-written organization
// spelling — it agrees with the field-level default rather than fighting it.
const singleColumnUniqueIndexes = new Map<string, any>();
for (const idx of declaredIndexes) {
if (!uniqueDeclared(idx?.unique)) continue;
const cols = Array.isArray(idx?.fields) ? idx.fields.filter((f: unknown) => typeof f === 'string') : [];
if (cols.length !== 1) continue;
if (!singleColumnUniqueIndexes.has(cols[0])) singleColumnUniqueIndexes.set(cols[0], idx);
}
if (singleColumnUniqueIndexes.size === 0) continue;
for (const { name, def } of fieldEntries(obj.fields)) {
if (!uniqueDeclared(def?.unique)) continue;
const idx = singleColumnUniqueIndexes.get(name);
if (!idx) continue;
const fScope = fieldUniqueScope(def.unique);
const iScope = indexUniqueScope(idx.unique);
const indexLabel = typeof idx?.name === 'string' && idx.name.trim() ? ` '${idx.name.trim()}'` : '';
const fieldSpelling = `\`unique: ${typeof def.unique === 'string' ? `'${def.unique}'` : def.unique}\``;
const indexSpelling = `\`unique: ${typeof idx.unique === 'string' ? `'${idx.unique}'` : idx.unique}\``;
// [#22161] One verdict per quadrant; the scope matrix itself is
// `os explain` text.
let message: string;
let fix: string;
if (fScope === iScope) {
// Same scope on both sides — the same index declared twice.
const boundary = fScope === 'global' ? 'installation-wide' : 'per-organization';
message =
`"${obj.name}.${name}" field ${fieldSpelling} and index${indexLabel} ${indexSpelling} both ask ` +
`for ${boundary} uniqueness: the same index declared twice`;
fix =
fScope === 'global'
? `Keep ONE spelling of installation-wide uniqueness: \`unique: 'global'\` on '${name}', or the declared index — not both.`
: `Keep ONE spelling of per-organization uniqueness: \`unique: 'organization'\` on '${name}' (preferred), or the declared index — not both.`;
} else {
// Different scopes — the installation-wide side is physically stricter
// and wins; the per-organization intent is dead on arrival.
message =
`"${obj.name}.${name}" field ${fieldSpelling} and index${indexLabel} ${indexSpelling} CONTRADICT: ` +
`the installation-wide one wins, so the per-organization intent is silently dead`;
// [#22161] One remedy line; where each spelling may live is
// `os explain` text.
fix =
"Pick ONE scope and say it once: keep `unique: 'global'` and drop the per-organization side, or set " +
"`unique: 'organization'` and drop the installation-wide one.";
}
issues.push({
severity: 'warning',
rule: UNIQUE_DOUBLE_DECLARATION,
// More specific than `path` on purpose: this rule's finding is about ONE
// column, but its `path` has always been the whole object (`objects[i]`)
// because the defect straddles `fields.<name>.unique` and an entry of
// `indexes`. `where` can name the column without picking one of the two.
where: fieldWhere(obj, name),
message,
path: `objects[${i}]`,
fix,
});
}
}
return issues;
}
/**
* R12 (ADR-0120 D5c) — a declared unique index whose column list CONTAINS the
* organization column: the hand-written per-organization composite (S6),
* predating the vocabulary that can now say so.
*
* Why this is worth a nudge rather than left alone. The legacy spelling
* `{ fields: ['organization_id', 'name'], unique: 'global' }` (bare `true`
* before protocol 18 — the conversion respells it, zero drift) says "per
* organization" to a reader and materializes as a plain composite — and SQL
* UNIQUE is NULL-distinct, so on every row where the organization column is
* NULL it enforces **nothing** (#5030, measured). A 17.x single-organization
* deployment wrote *every* row that way; since ADR-0131 D9 a new row carries its
* organization wherever the organization object is registered, so there the gap
* now admits that residue (a composition that registers no organization object
* still writes NULL-organization rows). The `'organization'`
* respelling is what closes the hole: the driver makes the LISTED organization
* column NULL-safe in place (`COALESCE(organization_id, '__global__')`), so the
* NULL rows become one bucket that is unique among themselves.
*
* **Advisory, and deliberately no auto-fix.** ADR-0120 D5c is explicit that the
* legacy spelling stays valid and unmigrated forever if untouched — zero forced
* drift. Opting in is a real physical tightening that goes through the D4
* ceremony (a `recreate_index` gated by the duplicate pre-flight probe), because
* the rows the void constraint admitted may still be there. Fixing this on the
* author's behalf would schedule that migration without asking.
*
* Not fired for `unique: 'organization'` — that IS the respelling — nor for a
* unique declared on the organization column ALONE, which is not a composite and
* has no per-organization reading to recover.
*/
export function lintLegacyOrganizationComposites(objects: any[]): LocatedLintIssue[] {
const issues: LocatedLintIssue[] = [];
if (!Array.isArray(objects) || objects.length === 0) return issues;
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
if (!obj?.name) continue;
const tenantColumn = authoredTenantColumn(obj);
const declaredIndexes = Array.isArray(obj.indexes) ? obj.indexes : [];
for (let j = 0; j < declaredIndexes.length; j++) {
const idx = declaredIndexes[j];
// Already the target spelling, or not a unique at all.
if (!uniqueDeclared(idx?.unique) || idx.unique === 'organization') continue;
const cols = Array.isArray(idx?.fields)
? idx.fields.filter((f: unknown) => typeof f === 'string')
: [];
if (cols.length < 2) continue; // a lone organization column is not a composite
if (!cols.includes(tenantColumn)) continue;
const indexLabel = typeof idx?.name === 'string' && idx.name.trim() ? ` '${idx.name.trim()}'` : '';
issues.push({
severity: 'warning',
rule: UNIQUE_LEGACY_ORGANIZATION_COMPOSITE,
where: indexWhere(obj, idx, j, cols),
// [#22161] One verdict; what the composite is, and what the
// respelling costs, is `os explain` text.
message:
`"${obj.name}" index${indexLabel} [${cols.join(', ')}] lists the organization column, and SQL ` +
`UNIQUE is NULL-distinct: on every row whose '${tenantColumn}' is NULL it enforces nothing`,
path: `objects[${i}].indexes[${j}]`,
// [#22161] One remedy line; what the respelling builds, what the
// probe reports and why leaving it is valid are `os explain` text.
fix:
"Respell it `unique: 'organization'` and keep `fields` exactly as they are; opting in is a " +
'`recreate_index` gated by the duplicate pre-flight probe (ADR-0120 D4).',
});
}
}
return issues;
}
// ─── Rule engine ────────────────────────────────────────────────────
/**
* Lint the relationship / data-modeling conventions across the full object set.
* Pure and deterministic — safe to call from both the `lint` command and the
* metadata-generation scorer.
*/
export function lintDataModel(objects: any[]): LintIssue[] {
// R10/R12 live in their own exported functions so `os validate`/`os build`
// can run those rules without pulling in the whole best-practice sweep
// (#3991, ADR-0120 D5b/D5c) — here `os lint` picks both up. R11 is not
// called here since it became an error at protocol 18 (#5082): a gating
// rule runs on all three commands through its own registry entry, which is
// what reports it under `os lint`, exactly once.
const issues: LintIssue[] = [
...lintUniqueDeclarations(objects),
...lintLegacyOrganizationComposites(objects),
];
if (!Array.isArray(objects) || objects.length === 0) return issues;
// Index: object name → the object, for resolving a roll-up's child object.
const objectsByName: Record<string, any> = {};
for (const o of objects) {
if (o?.name && !(o.name in objectsByName)) objectsByName[o.name] = o;
}
// Index: parent object name → child relationships pointing at it.
const childrenByParent: Record<string, Array<{ child: any; fieldName: string; def: any }>> = {};
for (const child of objects) {
if (!child?.name) continue;
for (const { name: fieldName, def } of fieldEntries(child.fields)) {
if (!RELATIONSHIP_TYPES.has(def?.type)) continue;
const parent = refOf(def);
if (!parent) continue;
(childrenByParent[parent] ||= []).push({ child, fieldName, def });
}
}
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
if (!obj?.name) continue;
const objPath = `objects[${i}]`;
const fields = fieldEntries(obj.fields);
// R9 — object should have a derivable display/primary field.
//
// `nameField` is ADR-0079's canonical primary-title pointer, so an object
// that declares one HAS a title face. `titleFormat` is deliberately NOT one:
// the same ADR retires it (it is a render-only template the server can
// neither return nor query), `validate-record-title.ts` reports every
// declaration of it as `title-format-retired` and steers the author to
// `nameField`, and the shared spec predicate `objectTitleCompleteness`
// (packages/spec/src/data/display-name.ts) never reads it either.
//
// Reading `titleFormat` while ignoring `nameField` made this rule
// contradict its own package (#6108): an author who followed the platform's
// own migration advice earned a "records will display as raw IDs"
// suggestion, while one who kept the retired key did not. The name-like
// derivation is unchanged.
//
// A third limb, `!!obj.primaryField`, was REMOVED here in #6326. That key
// is declared nowhere in `packages/spec`: measured on 17.0.0-rc.5,
// `ObjectSchema.safeParse` reports `unrecognized_keys: ['primaryField']`
// and `ObjectSchema.create()` rejects it outright, so the limb could never
// be true for an object the spec accepts — a #4984-family dead branch that
// nonetheless read as a title face here, in `validate-semantic-roles` and
// in the objectstack-data skill doc. The maintainer ruled remove, not
// declare: `nameField` is ADR-0079's one canonical title pointer and a
// second parallel pointer contradicts "one Zod source per metadata type"
// (Prime Directive #7). Do not reintroduce it as a tolerated alias — a
// consumer-side `??` for a key the producer rejects is exactly the second
// de-facto contract Prime Directive #12 bans.
const hasNameField =
!!obj.nameField ||
fields.some((f) => NAME_LIKE_FIELDS.includes(f.name));
if (fields.length > 0 && !hasNameField) {
issues.push({
severity: 'suggestion',
rule: 'object/missing-name-field',
message: `Object "${obj.name}" has no nameField and no name-like field — records will display as raw IDs`,
path: `${objPath}.fields`,
// [#22161] One remedy line; why `titleFormat` does not count is
// `title-format-retired`'s `os explain` text.
fix:
"Set `nameField` (ADR-0079), never `titleFormat` (`os explain title-format-retired`); a composite title " +
"to import/sort/search by is a text field with an `expression` (a text formula is display-only).",
});
}
for (const { name: fieldName, def } of fields) {
if (!def || typeof def !== 'object') continue;
const fieldPath = `${objPath}.fields.${fieldName}`;
const type = def.type;
// R8 — option fields need options (or an options source).
//
// A `picklist` reference IS an options source: the field takes its
// options from the shared list it names (`data/picklist.zod.ts`), the
// same reading `FIELD_CHOICE_WITHOUT_OPTIONS` in the spec's
// functional-completeness rules makes. And the fix names the two
// sources as ALTERNATIVES: `FieldSchema` refuses `options` declared
// beside `picklist`, so a fix that said "add options" to a
// picklist-bound field would prescribe the schema's own refusal.
if (OPTION_FIELD_TYPES.has(type)) {
const hasOptions =
(Array.isArray(def.options) && def.options.length > 0) ||
(typeof def.picklist === 'string' && def.picklist !== '') ||
!!def.optionsFrom || !!def.dataSource || !!refOf(def);
if (!hasOptions) {
issues.push({
severity: 'warning',
rule: 'field/select-missing-options',
message: `${type} field "${obj.name}.${fieldName}" has no options`,
path: `${fieldPath}.options`,
fix:
"Give the field ONE options source: inline `options: [{ label: '…', value: '…' }]` or " +
"`picklist: '<name>'` naming a shared list — never both: `options` beside `picklist` is refused.",
});
}
}
// R13 — a `min`/`max` roll-up must aggregate a child field whose ANSWER
// fits the column the roll-up is stored into.
//
// `FieldSchema.summaryOperations` admits `min`/`max` over ANY child
// field, and `aggregateSummaryValue` (objectql) returns the driver's
// answer verbatim — only an empty-set fallback stands between the
// backend and the stored value. So an ordinary "latest shipment"
// roll-up, `max` over a `datetime` child field, computes an INSTANT into
// a field whose value contract says finite number. Nothing between
// author and driver correlated the two, so it is refused here, at
// authoring time, at `error` (Prime Directive #12: reject at authoring,
// never tolerate in a consumer).
//
// Scoped to `min`/`max` deliberately: `count` ignores the field
// entirely, and `sum`/`avg` over a non-numeric child is a different
// shape, whose accept set the analytics table's own rows already
// EXCLUDE. Measured on this tree, nothing consults that table on the
// roll-up door (or anywhere else), so that is an open gap, not a
// refusal this rule may lean on — and widening here to cover it would
// be a second account of a pair the table already rules on.
if (type === 'summary') {
const ops = def.summaryOperations;
const fn = ops?.function;
const childName = ops?.object;
const childFieldName = ops?.field;
if (
(fn === 'min' || fn === 'max') &&
typeof childName === 'string' && childName !== '' &&
typeof childFieldName === 'string' && childFieldName !== ''
) {
// SILENCE, never a guess, on anything this pass cannot resolve: a
// child object contributed by another package, a partially-loaded
// stack, or a field name that resolves to no declaration. The spec's
// own aggregate table states the tier — "a consumer that cannot
// resolve a field's type … must NOT call the predicate with a guess;
// 'cannot answer, do not block' is the consumer's tier". A refusal
// fired on an unresolvable model would redden an app for metadata
// this pass simply never saw.
const child = objectsByName[childName];
const childField = child
? fieldEntries(child.fields).find((f) => f.name === childFieldName)
: undefined;
const childType = childField?.def?.type;
if (typeof childType === 'string' && !summaryRollupAnswerFitsColumn(childType)) {
issues.push({
severity: 'error',
rule: ROLLUP_NON_NUMERIC_AGGREGAND,
// [#22161] One verdict; the value contract and why the two
// aggregate tables differ is `os explain` text.
message:
`summary field "${obj.name}.${fieldName}" rolls up ` +
`${fn}(${childName}.${childFieldName}), a ${childType} field: ${fn} answers in the ` +
`child field's own type, but a summary field stores a finite number`,
path: `${fieldPath}.summaryOperations.field`,
// [#22161] One remedy line; why min/max over those answer with a
// number and `count` reads no value is `os explain` text.
fix:
`Aggregate a numeric or boolean child field, or use function: 'count'; a roll-up cannot ` +
`store a ${childType}, so declare a ${childType} field and maintain it from a flow.`,
});
}
}
}
if (!RELATIONSHIP_TYPES.has(type)) continue;
const parent = refOf(def);
// R1 — relationship fields must declare a reference target.
if (!parent) {
issues.push({
severity: 'error',
rule: 'relationship/missing-reference',
message: `${type} field "${obj.name}.${fieldName}" is missing a reference target`,
path: `${fieldPath}.reference`,
});
continue;
}
if (type === 'master_detail') {
// R2 — master-detail children should require their parent.
//
// Two tiers, one rule id. On a `controlled_by_parent` object the master
// reference is what the object's whole record access is derived through,
// so an unsafe shape there is refused at `error`
// (`cbpMasterReferenceFinding`); everywhere else a non-required
// `master_detail` is a likely-wrong choice and stays a `warning`,
// byte-for-byte as before.
if (obj.sharingModel === 'controlled_by_parent') {
const finding = cbpMasterReferenceFinding(obj.name, fieldName, fieldPath, parent, def);
if (finding) issues.push(finding);
} else if (def.required !== true) {
issues.push({
severity: 'warning',
rule: RELATIONSHIP_MASTER_DETAIL_REQUIRED,
message: `master_detail "${obj.name}.${fieldName}" → ${parent} should be required (a detail record cannot exist without its master)`,
path: `${fieldPath}.required`,
fix: 'required: true',
});
}
// R3 — be explicit about cascade behaviour.
if (def.deleteBehavior === undefined) {
issues.push({
severity: 'suggestion',
rule: RELATIONSHIP_DELETE_BEHAVIOR,
// [#22161] One verdict; why `set_null` is not a choice here and
// what to use when children must survive is `os explain` text.
message: `master_detail "${obj.name}.${fieldName}" → ${parent} should declare deleteBehavior (cascade/restrict): left unset, deleting the master deletes its details`,
path: `${fieldPath}.deleteBehavior`,
fix: "deleteBehavior: 'cascade'",
});
}
// R5 — line-item children are usually entered inline with the parent.
if (isLineItemName(obj.name) && def.inlineEdit !== true) {
issues.push({
severity: 'suggestion',
rule: 'relationship/line-items-inline-edit',
message: `"${obj.name}" looks like line items of ${parent}; consider inlineEdit: true on "${fieldName}" so it is entered inline within the ${parent} form`,
path: `${fieldPath}.inlineEdit`,
fix: 'inlineEdit: true',
});
}
}
// R4 — a line-item-shaped child should usually be master_detail, not lookup.
if (type === 'lookup' && isLineItemName(obj.name)) {
issues.push({
severity: 'suggestion',
rule: 'relationship/line-item-should-be-master-detail',
message: `"${obj.name}" looks like line items of ${parent} but uses lookup; master_detail gives ownership + cascade + roll-ups`,
path: `${fieldPath}.type`,
fix: "type: 'master_detail'",
});
}
// R6 — associations should NOT be inlined into the parent's entry form.
if (def.inlineEdit === true && isAssociationName(obj.name)) {
issues.push({
severity: 'warning',
rule: 'relationship/association-inline-edit',
message: `"${obj.name}" is an association (comments/audit/activity), not line items — inlineEdit clutters the ${parent} entry form; surface it as a detail-page related list instead`,
path: `${fieldPath}.inlineEdit`,
fix: 'remove inlineEdit (use relatedList on the detail page)',
});
}
}
// R7 — a parent of master_detail children with numeric fields should roll one up.
const children = childrenByParent[obj.name] || [];
const summaryChildObjects = new Set(
fields
.filter((f) => f.def?.type === 'summary')
.map((f) => f.def?.summaryOperations?.object || refOf(f.def))
.filter(Boolean),
);
const seenSuggestedChild = new Set<string>();
for (const { child, def } of children) {
if (def?.type !== 'master_detail') continue;
if (!child?.name || seenSuggestedChild.has(child.name)) continue;
if (summaryChildObjects.has(child.name)) continue;
// Only nudge when the child actually has something worth aggregating.
const numericChildField = fieldEntries(child.fields).find((f) => NUMERIC_TYPES.has(f.def?.type));
if (!numericChildField) continue;
seenSuggestedChild.add(child.name);
issues.push({
severity: 'suggestion',
rule: 'rollup/missing-summary',
message: `"${obj.name}" owns "${child.name}" (master_detail) with numeric field "${numericChildField.name}" but has no roll-up summary; consider a summary field (count/sum) on ${obj.name}`,
path: `${objPath}.fields`,
fix: `summary field aggregating ${child.name}.${numericChildField.name}`,
});
}
}
return issues;
}