-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathobject.zod.ts
More file actions
2846 lines (2736 loc) · 154 KB
/
Copy pathobject.zod.ts
File metadata and controls
2846 lines (2736 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { FieldSchema, UniqueScopeSchema } from './field.zod';
import { ValidationRuleSchema } from './validation.zod';
import { ActionSchema } from '../ui/action.zod';
import { ObjectListViewSchema } from '../ui/view.zod';
/**
* API Operations Enum
*/
import { ExpressionInputSchema, TemplateExpressionInputSchema, type Expression, type ExpressionInput } from '../shared/expression.zod';
import { lazySchema } from '../shared/lazy-schema';
import { MetadataProtectionFields } from '../kernel/metadata-protection.zod';
import { strictObject } from '../shared/strict-object';
import { ProtectionSchema } from '../shared/protection.zod';
import { retiredKey } from '../shared/retired-key';
export const ApiMethod = z.enum([
'get', 'list', // Read
'create', 'update', 'delete', // Write
'bulk', // Batch operations
]);
export type ApiMethod = z.input<typeof ApiMethod>;
/**
* The eight RETIRED legacy `apiMethods` values (#3543, P2 of #3391). Each is
* DERIVED from the six primitives by the spec's single derivation table
* (`API_METHOD_DERIVATION` in `api-derivation.ts`) — an author never declares
* them. A stored/authored legacy value is stripped at parse by
* {@link stripLegacyApiMethods} (canonicalize-and-warn, never a hard parse
* failure): real metadata does not upgrade in lockstep with the spec, so this
* tolerance is a PERMANENT compatibility layer, not a one-release transition.
*/
export const LEGACY_API_METHODS = [
'upsert', 'aggregate', 'history', 'search', 'restore', 'purge', 'import', 'export',
] as const;
export type LegacyApiMethod = (typeof LEGACY_API_METHODS)[number];
/**
* Tombstones for the retired legacy values — same doctrine as
* `CAPABILITIES_RETIRED_KEY_GUIDANCE` below: the strip warning must carry the
* FROM → TO prescription, because it is the one channel a consumer whose
* metadata still declares a legacy value is guaranteed to hit.
*/
export const LEGACY_API_METHOD_GUIDANCE: Record<LegacyApiMethod, string> = {
upsert: "declare ['create','update'] — `upsert` derives from create ∧ update",
aggregate: "declare ['list'] — `aggregate` derives from list",
history: "declare ['get'] with `enable.trackHistory: true` — `history` derives from get ∧ trackHistory",
search: "declare ['list'] (with `searchable` not false) — `search` derives from list ∧ searchable",
restore: "delete the value — `restore` never derives (`enable.trash` retired, #2377); it returns only with a real recycle bin (#3146, parked)",
purge: "delete the value — `purge` never derives (`enable.trash` retired, #2377)",
import: "declare ['create'] and/or ['update'] — `import` derives from create ∨ update (writeMode-precise at the gate)",
export: "declare ['list'] — `export` derives from list",
};
/**
* The canonical serialization order of the EFFECTIVE operation vocabulary —
* the declaration order of the pre-#3543 fourteen-value enum, preserved
* verbatim so the wire contract (405 `allowed` array, `/me/permissions`
* `apiOperations`) is byte-stable across the shrink.
*/
export const API_OPERATION_ORDER = [
'get', 'list', 'create', 'update', 'delete', 'upsert', 'bulk',
'aggregate', 'history', 'search', 'restore', 'purge', 'import', 'export',
] as const;
/**
* An effective API operation — the vocabulary of gates and wire serialization:
* the six authored primitives plus the eight derived verbs. Authors declare
* {@link ApiMethod}; servers derive and speak THIS (see `api-derivation.ts`).
*/
export type ApiOperation = (typeof API_OPERATION_ORDER)[number];
/**
* Zod schema for {@link ApiOperation} — response-side surfaces that carry an
* effective operation set (e.g. `EffectiveObjectPermissionSchema.apiOperations`)
* validate against THIS, never against the authored {@link ApiMethod} enum.
*/
export const ApiOperationSchema = z.enum(API_OPERATION_ORDER);
const LEGACY_API_METHOD_SET: ReadonlySet<string> = new Set(LEGACY_API_METHODS);
/** Distinct legacy combinations already warned about (bounded; parse is hot). */
const warnedLegacyApiMethods = new Set<string>();
/**
* Strip retired legacy values from an `apiMethods` whitelist before enum
* validation (#3543). Non-arrays pass through untouched (the schema reports
* them). Emits a single warning per distinct legacy combination — parse runs
* on hot paths and carries no object-name context; the registration-time
* diagnostic in objectql `registry.ts` adds the per-object view.
*
* The one behavioral cliff is called out loudly: a whitelist that becomes
* EMPTY after stripping is `[]` = deny-all under the three-state contract,
* so a pure-legacy whitelist (e.g. `['upsert']`) now closes the object's API
* entirely instead of widening it.
*/
export function stripLegacyApiMethods(
raw: unknown,
opts?: { warn?: (msg: string) => void },
): unknown {
if (!Array.isArray(raw)) return raw;
const legacy = [...new Set(raw.filter(
(v): v is LegacyApiMethod => typeof v === 'string' && LEGACY_API_METHOD_SET.has(v),
))];
if (legacy.length === 0) return raw;
const kept = raw.filter((v) => !(typeof v === 'string' && LEGACY_API_METHOD_SET.has(v)));
const key = `${[...legacy].sort().join(',')}${kept.length === 0 ? '|deny-all' : ''}`;
if (!warnedLegacyApiMethods.has(key)) {
warnedLegacyApiMethods.add(key);
const warn = opts?.warn ?? ((msg: string) => console.warn(msg));
warn(
`[spec] enable.apiMethods declares retired legacy value(s) [${legacy.join(', ')}] — ` +
`the ApiMethod enum is the six primitives get/list/create/update/delete/bulk (#3543). ` +
`Legacy values are stripped at parse; their semantics are DERIVED from the primitives:\n` +
legacy.map((v) => ` • \`${v}\`: ${LEGACY_API_METHOD_GUIDANCE[v]}`).join('\n') +
(kept.length === 0
? `\n ⚠ After stripping, this whitelist is EMPTY — \`[]\` means DENY-ALL (fully closed ` +
`API). Declare the underlying primitives if the object should stay reachable.`
: '') +
`\nCodemod: node scripts/codemod/apimethods-legacy-to-primitives.mjs`,
);
}
return kept;
}
/**
* Tombstones for RETIRED capability flags — same doctrine as the tenancy
* block and the top-level `UNKNOWN_KEY_GUIDANCE` map below: a retired
* key's rejection must carry the upgrade prescription, because the parse
* error is the one channel every consumer bumping `@objectstack/spec` is
* guaranteed to hit. Removed in the 16.x line (#2377, ADR-0049
* enforce-or-remove).
*/
const CAPABILITIES_RETIRED_KEY_GUIDANCE: Record<string, string> = {
trash:
'`enable.trash` was removed from @objectstack/spec in the 16.x line (#2377/#3207, ' +
'ADR-0049) — it never had a runtime consumer: every delete has always been a ' +
'hard delete, and a default-true flag promising a recycle bin was a false ' +
'affordance (authors wrote `trash: false` believing they were opting out of a ' +
'soft-delete that never ran). Delete the key. For recoverability use per-field ' +
'`trackHistory` (audit trail) or a `lifecycle` policy; soft delete is parked at ' +
'#3146 and, if built, returns as a live enforced flag (ADR-0049 prune-or-build). ' +
'Run `os migrate meta --from 16` to list the mechanical edits for existing sources; apply them by hand.',
mru:
'`enable.mru` was removed from @objectstack/spec in the 16.x line (#2377/#3207, ' +
'ADR-0049) — Most-Recently-Used tracking was never implemented; no reader ' +
'existed, so the flag changed nothing. Delete the key. If MRU tracking is ' +
'built it returns as a live enforced flag (ADR-0049 prune-or-build). ' +
'Run `os migrate meta --from 16` to list the mechanical edits for existing sources; apply them by hand.',
};
/**
* The standing history sentence for the `enable` block, emitted LAST on every
* rejection — the shared template's `history` slot.
*
* ## Why the slot, and why the fold waited for it (#6805)
*
* This block was the LAST hand-written `unrecognized_keys` map in this file.
* #6619 folded its sibling `strictTenancyError` into the shared `strictObject`
* template and left this one out for a reason it stated precisely: the map
* emitted NO trailing sentence while `strictUnknownKeyError` appends its
* `history` unconditionally (`${message} ${history}`). Measured again at #6805,
* that is a statement about the TEXT and not about the template — `enable` has
* a real history, it had simply never been written down. Writing it is the
* whole of what the fold needed.
*
* The reading of the slot is #6619's, unchanged: what it encodes is *position*
* — the one standing sentence that follows both fix channels (#5955 / #6416) —
* so the surface decides what belongs there, and background is as legitimate as
* literal history.
*
* The rejection itself is unchanged in kind: an unknown key — a retired
* `trash`/`mru` or a typo like `feedEnabled` — is a loud, *fixable* parse error
* instead of a silent strip (#1535), a retired key's error carries its upgrade
* prescription, and every other issue code defers to zod's default. What the
* fold changes is the *other* key: `searchible` now resolves to `searchable`
* through the template's rename channel instead of being told only that it "is
* not an `enable` capability flag", which named the problem and never the fix.
* And it is what puts this table under `alias-integrity.test.ts`, which no
* hand-rolled map has ever been judged by.
*
* ⚠️ `scripts/strictness-ledger.test.ts` used the `ObjectCapabilities` site
* below as its `z.object(…).strict()` fixture. #6805 moved it to
* `PerOperationRequiredPermissionsSchema` in this same file rather than
* deleting the assertion, exactly as that test's own note instructs.
*/
const CAPABILITIES_HISTORY =
'Until this shape was closed an unknown flag was dropped without a word — the object '
+ 'shipped as if the author had never written it (#1535); `enable` is a closed vocabulary '
+ 'in which every flag carries an enforcement contract (#2707).';
/**
* Capability Flags
* Defines what system features are enabled for this object.
*
* Modeled on industry standards (Salesforce "Allow Activities"/"Track Field
* History"/"Enable Feed Tracking", Dataverse table options). Each flag has a
* defined enforcement contract (#2707); a flag with no runtime consumer is a
* bug, not a reservation — see `@objectstack/spec/liveness/object.json`.
*
* Opt-out flags (`feeds`, `activities`, `clone`, `searchable`, `apiEnabled`)
* default to `true`: absent block/flag = enabled, and consumers gate on
* explicit `false` only. Opt-in flags (`trackHistory`, `files`) default to
* `false`.
*
* `.strict()`: unknown keys (incl. the retired `trash` / `mru`, #2377) are
* rejected with guidance, not stripped (#1535).
*
* Closed with the shared `strictObject` template since #6805 — see
* {@link CAPABILITIES_HISTORY} for why the fold waited on one sentence, and
* what changes (and does not) about the message.
*
* ⚠️ ORDER IS LOAD-BEARING here for the same reason it is at
* `ObjectSchemaBase` (#5593, ~1000 lines below): `strictObject` evaluates its
* options object at CONSTRUCTION — that is what lets `alias-integrity.test.ts`
* judge the table against the real `.shape` — so both
* `CAPABILITIES_RETIRED_KEY_GUIDANCE` and `CAPABILITIES_HISTORY` must be
* declared ABOVE this site. Moving either below it reintroduces the temporal
* dead zone as a module-init crash under `OS_EAGER_SCHEMAS=1` (how
* `build-schemas.ts` runs), which the test suite does not reach because tests
* import lazily.
*
* @example
* {
* trackHistory: true,
* searchable: true,
* apiEnabled: true,
* activities: false
* }
*/
export const ObjectCapabilities = strictObject({
surface: '`enable`',
history: CAPABILITIES_HISTORY,
guidance: CAPABILITIES_RETIRED_KEY_GUIDANCE,
}, {
/**
* History tracking (Audit Trail) master switch — opt-in.
*
* Contract: `true` surfaces the record History tab (audit-trail UI) in the
* console. Pair with per-field `trackHistory: true` to select which field
* diffs render as human-readable timeline summaries (ADR-0052 §5b). Audit
* *capture* into `sys_audit_log` is a compliance ledger and stays on
* regardless of this flag; retention is governed by data lifecycle
* (ADR-0057), not by hiding the UI.
*/
trackHistory: z.boolean().default(false).describe('Show the record History tab (audit-trail UI). Pair with per-field trackHistory to pick which field diffs are summarized; audit capture itself is always on for compliance'),
/** Enable global search indexing */
searchable: z.boolean().default(true).describe('Index records for global search'),
/** Enable REST/GraphQL API access */
apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),
/**
* API Supported Operations
* Granular control over API exposure — a whitelist over the SIX PRIMITIVES
* (#3391/#3543): `undefined` = unrestricted, `[]` = deny-all, a subset = the
* derived closure (see `api-derivation.ts`). Retired legacy values are
* stripped at parse by {@link stripLegacyApiMethods} (permanent tolerance
* for stored metadata); the cast below keeps the AUTHORING type at the six
* primitives so TS authors get the compile-time migration signal instead of
* the `unknown` input a raw `z.preprocess` would infer.
*/
apiMethods: (z.preprocess((raw) => stripLegacyApiMethods(raw), z.array(ApiMethod))
.optional() as unknown as z.ZodOptional<z.ZodType<ApiMethod[], ApiMethod[]>>)
.describe('Whitelist of allowed API operations (six primitives; undefined = all, [] = none)'),
/**
* Generic Attachments panel (Salesforce "Notes & Attachments" parity) —
* opt-in.
*
* Contract (#2727): `true` surfaces the record Attachments panel in the
* console (upload/list/download/delete over `sys_attachment` join rows)
* and permits `sys_attachment` rows to target this object; anything else
* rejects new attachments server-side (403 FILES_DISABLED, enforced at
* the engine hook seam by plugin-audit — opt-in means explicit).
* `Field.file` / `Field.image` column attachments are independent of
* this flag.
*/
files: z.boolean().default(false).describe('Generic record Attachments panel (sys_attachment). Opt-in: true surfaces the panel and permits attachments targeting this object; otherwise creation is rejected. Field.file/Field.image are independent'),
/**
* Social collaboration (Comments, Mentions, Feeds) — opt-out.
*
* Contract: default on. An explicit `false` hides the record feed UI and
* rejects new `sys_comment` rows targeting this object (403
* FEEDS_DISABLED, enforced at the engine hook seam by plugin-audit).
*/
feeds: z.boolean().default(true).describe('Record comments/collaboration feed. Default on; explicit false hides the feed UI and rejects new comments for this object'),
/**
* Activity timeline (sys_activity mirror of create/update/delete) — opt-out.
*
* Contract: default on. An explicit `false` stops plugin-audit from
* mirroring this object's CRUD into `sys_activity` (the record timeline)
* and hides the timeline merge in the console. The off-switch is also the
* per-object lever for activity-row growth (ADR-0057).
*/
activities: z.boolean().default(true).describe('Record activity timeline (sys_activity mirror of CRUD). Default on; explicit false stops mirroring and hides the timeline'),
/** Allow cloning records */
clone: z.boolean().default(true).describe('Allow record deep cloning'),
});
/**
* Schema for database indexes.
*
* The declaration surface is exactly what the driver materializes:
* `name` / `fields` / `unique` (ADR-0120 scope). Nothing else — see the
* retirement note below.
*
* @example
* {
* name: "idx_account_name",
* fields: ["name"],
* unique: true
* }
*
* ## `type` / `partial` were RETIRED at protocol 17 (#5248, #4943, ADR-0049)
*
* Both were authorable and had **zero** DDL consumers.
* `SqlDriver.syncDeclaredIndexes` builds every declared index through knex's
* `table.unique(fields, { indexName })` / `table.index(fields, name)`, and the
* differ's `DeclaredIndexInput` (`driver-sql/src/schema-drift.ts`) carries
* `name` / `fields` / `unique` / `nullSafeColumns` — neither key ever reached
* a `CREATE INDEX`. `type` was the louder of the two because it also carried
* `.default('btree')`, so it appeared in *every* parse output: a knob that had
* never influenced a single statement, rendered as live configuration. That is
* the exact shape ADR-0078 (no-silently-inert-metadata) and ADR-0049
* (enforce-or-remove) exist to delete.
*
* The maintainer chose **remove** over **enforce** (2026-08-06, #5248):
* enforcing would mean per-dialect algorithm mapping (`gin`/`gist` Postgres-only,
* `fulltext` MySQL-only), raw-SQL `CREATE INDEX … WHERE` (MySQL has no partial
* index at all), and a redesign of how `isSyncReproducibleIndex` excludes
* partial indexes from incremental sync — real design cost for a capability
* nothing has asked for. If a genuine need appears, it comes back enforce-first.
*
* Replacements: an index **method** is the driver/dialect's choice, not a
* declaration-surface concern. A **partial** index is built at the database
* layer (a runtime migration issuing `CREATE UNIQUE INDEX … WHERE`, the way
* `metadata-protocol`'s `ensureOverlayIndex` does for `sys_metadata`); drift
* detection's exemption for DB-authored partial indexes is unaffected —
* `isSyncReproducibleIndex` reads a boolean parsed out of the database's OWN
* DDL (`parseIndexDdl`), which never had anything to do with this string.
*
* ⚠️ The tombstones sit at the BOTTOM of the shape deliberately (#5606): the
* docs renderer prints only the first `INLINE_KEY_LIMIT` keys of an inline
* shape and has no `z.never()` branch, so a tombstone high in the shape prints
* as `any` and reads as a free-form slot.
*
* ## Closed at #4001 批 20 site 14 — the batch's held site, after its producer converged
*
* This shape was 批 20's ONE deliberately-open site. The console's embedded
* index editor (`objectui` → `metadata-admin/EmbeddedItemEditor.tsx`,
* `FALLBACK_SCHEMAS.index`) ships its own hand-copied JSON-Schema for this
* shape — the framework publishes none, because `index` is an embedded-only
* sub-type with no metadata type of its own — and that copy had drifted: it
* offered **`where`** for the partial predicate and **`brin`** in the
* algorithm enum, spliced its form output into `object.indexes[]`, and PUT
* the WHOLE object. Closing the shape while those controls rendered would
* have turned an admin's clean save into a 422 on a control the console
* itself drew (the #5114 class), so the strip was held until the producer
* was fixed (contract-first: the drift was in the copy, not here).
*
* objectui#4772 (#5247's fix) deleted both drifted controls — the fallback
* now offers exactly `name` / `fields` / `unique`, converged to this schema —
* so the hold's evidence is spent and the shape is `strictObject` like its
* thirteen siblings. `where` keeps a curated `guidance` entry rather than a
* rename suggestion: the predicate never reached any DDL under EITHER
* spelling (`syncDeclaredIndexes` consumes `name`/`fields`/`unique` only),
* and the replacement is a database-layer migration, not another key — a
* rename onto the retired `partial` tombstone would be the campaign's
* finding 7 (a suggestion pointing into a second rejection).
*/
export const IndexSchema = lazySchema(() => strictObject({
surface: 'this index',
history:
'Until #4001 批 20 closed this site (its held 14th, closed once objectui#4772 ' +
"converged the console's drifted index editor), an unknown key here was dropped " +
'silently: the index still parsed and registered, minus whatever the author ' +
'believed the key did.',
guidance: {
where:
'`where` has never been an index key in this protocol — it was the console ' +
"fallback editor's drifted spelling for a partial-index predicate (objectui#4772 " +
'removed the control), and no driver ever emitted a predicate under either ' +
'spelling. Delete the key. A partial index is built at the database layer, not ' +
'the declaration surface: issue `CREATE [UNIQUE] INDEX … WHERE <predicate>` from ' +
"a runtime migration (what `metadata-protocol`'s `ensureOverlayIndex` already " +
'does for `sys_metadata`).',
},
}, {
name: z.string().optional().describe('Index name (auto-generated if not provided)'),
fields: z.array(z.string()).describe('Fields included in the index'),
// Unique scope on a DECLARED index (ADR-0120 D1, amending #3696):
//
// - `'global'` — the VERBATIM contract: materialized over exactly the
// columns listed in `fields`, no organization column injected. Correct
// for genuinely installation-wide reservations (a DNS hostname, a
// reserved slug, an external provider id, every engine dedup key).
// - `'organization'` — one holder per organization: the driver prepends
// the organization key part to the listed columns at REGISTRATION,
// where tenancy is known (authoring-time inference is impossible —
// `organization_id` is kernel-injected, not authored). The key part is
// NULL-safe — `COALESCE(organization_id, '__global__')` (ADR-0120 D3,
// #5030): NULL-organization rows form one platform bucket instead of
// escaping the constraint under SQL's NULL-distinct semantics.
// Materialization lands with #5030's driver PR. On an object with no
// organization column it degrades to the listed columns alone,
// mirroring field-level behavior.
// - bare `true` — the DEPRECATED positional spelling of `'global'`
// (today's verbatim behavior, unchanged). It is the spelling whose
// meaning was encoded by position — the #4986 trap — so 17.x warns
// (lint `unique/unscoped-declared-index`) and protocol 18 rejects it
// with a prescriptive error (#5082). State the scope.
//
// The old advice "spell a per-tenant index as
// `fields: ['organization_id', 'code']`" survives as valid legacy input,
// but new code says `unique: 'organization'` — the hand-written composite
// is NOT NULL-safe (#5030).
unique: UniqueScopeSchema.optional().default(false).describe("Whether the index enforces uniqueness, and at which scope (ADR-0120). 'global' = materialized over exactly `fields`, no organization column injected — one holder across the whole installation; 'organization' = the driver prepends the NULL-safe organization key part (COALESCE(organization_id, '__global__')) at registration — one holder per organization; bare true = deprecated positional spelling of 'global' (warned in 17.x by lint unique/unscoped-declared-index, rejected at protocol 18, #5082) — state the scope. 'tenant'/'org' are rejected — the word is 'organization'"),
// ── Tombstones (ADR-0049 / ADR-0087) ─────────────────────────────────
// Kept LAST in the shape on purpose — see the #5606 note in the block
// comment above. `IndexSchema` is not `.strict()`, so a plain delete would
// make Zod strip an authored value silently, which is the same no-op these
// keys already were (#3726 / #3733, the ADR-0104 class). The tombstone
// makes the removal audible in the two channels an upgrading author
// actually reads: `tsc` (input type `never`) and the parse itself.
// `object-index-type-partial-removed` strips both from stored/authored
// sources on the protocol-17 migration.
type: retiredKey(
'`indexes[].type` was removed in @objectstack/spec 17.0.0 (#5248, ADR-0049) — no driver ever ' +
'read it. `SqlDriver.syncDeclaredIndexes` creates every declared index through knex\'s ' +
'`table.index()` / `table.unique()`, which cannot express an access method, so the value ' +
'changed no DDL; its `.default(\'btree\')` merely made an inert knob show up in every parse ' +
'output. Delete the key. The index method is the driver/dialect\'s decision (Postgres ' +
'defaults to B-tree; `gin`/`gist`/`fulltext` are dialect-specific and are chosen by a ' +
'database-layer migration when a workload actually needs one). ' +
'Run `os migrate meta --from 16` to list the mechanical edits for existing sources; apply them by hand.',
),
partial: retiredKey(
'`indexes[].partial` was removed in @objectstack/spec 17.0.0 (#5248, #4943, ADR-0049) — no ' +
'driver ever emitted the `WHERE` clause, so a declared partial index was materialized as a ' +
'FULL index and the predicate silently did nothing. Delete the key. Partial indexes are ' +
'built at the database layer, not the declaration surface: issue `CREATE [UNIQUE] INDEX … ' +
'WHERE <predicate>` from a runtime migration (this is what `metadata-protocol`\'s ' +
'`ensureOverlayIndex` already does for `sys_metadata`). Drift detection is unaffected — it ' +
'reads partiality back from the database\'s own DDL, never from this key. ' +
'Run `os migrate meta --from 16` to list the mechanical edits for existing sources; apply them by hand.',
),
}));
/**
* Tombstones for RETIRED tenancy keys — same doctrine as the top-level
* `UNKNOWN_KEY_GUIDANCE` map below: a retired key's rejection must carry the
* upgrade prescription, because the parse error is the one channel every
* consumer bumping `@objectstack/spec` is guaranteed to hit. Removed after
* spec 15.0 by owner decision #2763 (enforce-or-remove, ADR-0049; precedent
* ADR-0056 D8 — compliance-grade config must never merely look live).
*/
const TENANCY_RETIRED_KEY_GUIDANCE: Record<string, string> = {
strategy:
'`tenancy.strategy` was removed from @objectstack/spec after v15.0 (#2763) — it ' +
'never had a consumer. The platform has exactly two tenancy modes and neither is ' +
'object-level config: database-per-tenant isolation is an environment/deployment ' +
'choice (each environment carries its own database URL), and row-level isolation ' +
'is `tenancy.enabled` + `tenancy.tenantField`. Delete the key.',
crossTenantAccess:
'`tenancy.crossTenantAccess` was removed from @objectstack/spec after v15.0 (#2763) — it ' +
'never had a consumer; setting it granted nothing. Cross-tenant visibility is ' +
'governed by sharing rules / OWD (ADR-0056), `externalSharingModel` (ADR-0090 ' +
'D11), and the object access posture. Delete the key.',
};
/**
* The standing two-modes explainer, emitted LAST on every `tenancy` rejection.
*
* It occupies the template's `history` slot, which is the slot for exactly this
* — the one sentence of standing background that follows both fix channels
* (#5955 / #6416). It is background rather than history in the literal sense,
* and that is fine: the contract the slot encodes is *position*, and this
* sentence is the thing that must not sit in front of a key's own prescription.
* On the single-line renders several consumers use (`os validate`'s
* `• where: message`, CI logs) it used to bury each bullet behind ~160
* characters.
*/
const TENANCY_MODES_EXPLAINER =
'The two supported tenancy modes are: database-per-tenant = environment-level '
+ 'deployment (no object config); row-level isolation = `tenancy.enabled` + '
+ '`tenancy.tenantField`.';
/**
* Multi-Tenancy Configuration Schema
* Row-level tenant isolation for shared-database SaaS applications: the
* tenant field is injected on write and enforced on read (RLS predicate).
* Platform objects declare `enabled: false` to opt out of org row-scoping
* (environment-level objects). Database-per-tenant isolation is NOT object
* metadata — it is an environment/deployment choice.
*
* `.strict()`: unknown keys (incl. the retired `strategy` /
* `crossTenantAccess`, #2763) are rejected with guidance, not stripped (#1535).
*
* Closed with the shared `strictObject` template since #6619. The tombstone
* bullets and the trailing explainer are byte-for-byte what the hand-written
* `strictTenancyError` emitted; what the fold changes is the *other* key — a
* near-miss like `tenantfield` now resolves to `tenantField` through the
* template's rename channel instead of being told only that it "is not a
* `tenancy` key", which named the problem and never the fix. Folding it in is
* also what puts this table under `alias-integrity.test.ts`, which no
* hand-rolled map has ever been judged by.
*
* `tenantField` carries **no default** (#5315). It used to default to
* `'tenant_id'`, which no consumer could act on: the platform's tenant column
* is `organization_id` (kernel-injected; the same column `tenantPolicy()` in
* `security/rls.zod.ts` and the RLS predicates assume), and the SQL driver's
* `computeTenantField` honours a declared name only when the object actually
* has that field — so the materialized `'tenant_id'` merely sent it looking for
* a column that did not exist before falling back to `organization_id` anyway.
* A declaration nobody reads is exactly what ADR-0078 prohibits, and `tenant`
* is a word ADR-0120 §Terminology refuses for the authorable vocabulary
* (`organization` is the product's noun). Undeclared now stays `undefined` and
* the driver's fallback is the single source of truth.
*
* `organizationField` (#8707 / #8778, maintainer-ruled option A) is the
* STAMP-ONLY sibling: it answers "which column says who this row is ABOUT",
* where `tenantField` answers "what is this object WALLED by". For ordinary
* objects the two coincide and `organizationField` is never needed; for
* credential tables they deliberately do not — `sys_api_key` records the
* organization a key authenticates into under `active_organization_id`
* precisely so the credential table does NOT become org-walled (#8287). The
* key is consulted exclusively by audit stamping (plugin-audit's
* `resolveRecordOrganizationField`); no read path reads it, and that
* read-neutrality is pinned by tests beside each read path. ⛔ Scope-pinned by
* the #8778 ruling: this is ONE stamp-only declaration key, not the opening
* move of a general field-roles mechanism — a consumer other than audit
* stamping needs its own ruling before reading it.
*
* That pin is WIDENED **by name** by the maintainer ruling recorded on
* cloud#1395, 2026-08-17T03:18Z, accepting the decision-inbox recommendations
* in full — verbatim: 「新进卡六张 同意你的建议」. It is transcribed here so the
* widening is declared, not discovered (#10110):
*
* > Ruled: Option A — extend the #8778 ruling: `resolveRecordOrganizationField`
* > is promoted to a shared resolver used by all three platform-row writers
* > (approvals, automation runs, audit). A platform row's organization is the
* > SUBJECT record's organization; actor context is the fallback, never the
* > primary.
*
* The ruling sanctions exactly THREE consumers of this key, and no others:
*
* 1. **audit stamping** — plugin-audit's `resolveRecordOrganizationField`;
* the original #8778 consumer and, as of this annotation, still the only
* one wired up;
* 2. **`plugin-approvals`** — the approval-row writer;
* 3. **the automation-run recorder** — reached when
* `resolveRecordOrganizationField` is promoted to the shared platform-row
* resolver.
*
* Consumers 2 and 3 are sanctioned but not yet implemented: #10101 carries that
* behaviour change (this card is annotation-only and changes no accept/reject
* behaviour). Which is why the `.describe()` below still speaks of audit rows —
* it states what reads the key TODAY, and #10101 updates it as the readers
* actually land.
*
* ⛔ The refusal posture is UNCHANGED for a FOURTH consumer. Three named
* platform-row writers are still not a general field-roles mechanism: anything
* outside the list above needs its own maintainer ruling before reading this
* key, exactly as #8778 required.
*
* @example Shared database, platform-default tenant column (organization_id)
* {
* enabled: true
* }
*
* @example An object whose tenant column is genuinely not organization_id
* {
* enabled: true,
* tenantField: 'workspace_id'
* }
*
* @example An unwalled credential table whose audit rows still stamp the
* organization of the record they describe (sys_api_key, #8778)
* {
* enabled: false,
* organizationField: 'active_organization_id'
* }
*/
export const TenancyConfigSchema = lazySchema(() => strictObject({
surface: '`tenancy`',
history: TENANCY_MODES_EXPLAINER,
guidance: TENANCY_RETIRED_KEY_GUIDANCE,
}, {
enabled: z.boolean().describe('Enable multi-tenancy for this object'),
tenantField: z.string().optional().describe(
'Column this object is tenant-scoped by. Omit it unless the tenant column ' +
"genuinely is not the platform's: when undeclared the driver falls back to " +
'`organization_id`, the kernel-injected column the RLS predicates and ' +
'`tenantPolicy()` also assume. A declared name is honoured only when the ' +
'object really has that field — otherwise the same `organization_id` ' +
'fallback applies. No default is materialized here on purpose (#5315).',
),
organizationField: z.string().optional().describe(
'STAMP-ONLY (#8778): column carrying the organization a row is ABOUT, ' +
'consulted exclusively when audit rows are stamped. It does NOT ' +
'tenant-scope anything — no read path (`applyTenantScope`, ' +
'`injectTenantOnInsert`, `computeTenantLayer0Filter`) reads it, so ' +
'declaring it never walls the object and never hides rows. Declare it ' +
'only when the organization a row belongs to lives under a column that ' +
'deliberately is NOT the tenant column: `sys_api_key` is the shipped ' +
'example — a credential table that must stay unwalled (`enabled: false`) ' +
'while history/revocation audit rows stamp the organization of the key ' +
'they describe (`active_organization_id`). Ordinary tenant objects omit ' +
'it; their stamp column is resolved from `tenantField` / ' +
'`organization_id` already. Honoured only when the object really has ' +
'the field, like `tenantField`.',
),
}));
/**
* [ADR-0066] Platform-global posture: `tenancy.enabled === false` explicitly
* opts the object out of row-level org scoping, even when it carries an
* `organization_id` column (e.g. `sys_license` keeps an optional owner FK).
* Single source of truth for the registry (tenant-column injection), the
* ObjectQL engine (tenantId propagation into driver options), and drivers
* (native scoping) — previously each re-derived `tenancy?.enabled === false`
* independently and could drift (#3249).
*/
export function isTenancyDisabled(schema: unknown): boolean {
return (schema as { tenancy?: { enabled?: boolean } } | null | undefined)?.tenancy?.enabled === false;
}
/**
* [ADR-0066 D2] Secure-by-default object posture.
*
* Declares whether the object participates in blanket wildcard permission
* grants — a data-model posture like {@link TenancyConfigSchema}, NOT an
* assignment (it names no principal).
*
* - `public` (default) — covered by a permission set's `'*'` wildcard object
* grant; today's allow-by-default behaviour.
* - `private` — NOT covered by the `'*'` wildcard grant; access requires an
* EXPLICIT per-object grant (Salesforce "new object = no access until
* granted"). A `private` object is ALSO exempt from wildcard RLS
* (`tenant_isolation`, owner scoping): the posture-gated superuser bypass
* (`viewAllRecords`/`modifyAllRecords`) short-circuits RLS, so a platform
* admin — incl. one who is also an org admin whose `tenant_isolation` would
* otherwise narrow the result — sees all rows, while non-admins without an
* explicit grant see none.
*
* Pair with the object's `requiredPermissions` (D3) to additionally gate access
* on holding a capability.
*/
export const ObjectAccessConfigSchema = lazySchema(() => strictObject({
surface: "this object's `access` block",
history:
'Until #4001 these were dropped silently — the block still parsed, so an object the ' +
'author declared `private` shipped `public`: covered by every `\'*\'` wildcard grant, ' +
'with no signal that the posture had been discarded.',
aliases: {
visibility: 'default',
posture: 'default',
defaultAccess: 'default',
},
guidance: {
// Wrong-layer, not typos: both are real TOP-LEVEL object keys, and both
// are the neighbouring half of the same access story — so edit distance
// would never reach them and a bare rejection would read as "no such
// concept" when the concept exists one level up.
sharingModel:
'`sharingModel` is the object-wide default record visibility (OWD) and is a ' +
'TOP-LEVEL object key, not an `access` key — write it beside `access`, not inside ' +
'it. `access.default` decides wildcard-GRANT coverage; `sharingModel` decides ' +
'record visibility between users (ADR-0090).',
requiredPermissions:
'`requiredPermissions` is a TOP-LEVEL object key (ADR-0066 D3) — it gates access on ' +
'the caller HOLDING a capability, which is a different axis from `access.default` ' +
'(whether a wildcard grant covers this object at all). Pair them, side by side.',
},
}, {
default: z.enum(['public', 'private']).default('public')
.describe('Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).'),
}));
/**
* [ADR-0066 ⑤] Per-operation capability requirements for an object. Each key
* lists the capabilities a caller must hold for that operation CLASS; an absent
* key means that operation carries no capability gate. Lets an object be
* "read-open / write-gated" (Salesforce & Dataverse separate capability by
* operation) instead of the flat all-CRUD gate the `string[]` form applies.
* Operation→class mapping mirrors the CRUD permission bits: `transfer`/`restore`
* fold into `update`, `purge` into `delete`. `.strict()` so a mistyped key
* (e.g. `reads`) is rejected at author time rather than silently ignored.
*
* ⚠️ This site is `scripts/strictness-ledger.test.ts`'s fixture for the OLDER
* `z.object(…).strict()` spelling — the reading the ledger's AST walker has to
* keep making, and `packages/spec` is not the only tree it reads. The fixture
* has moved twice as the campaign converted its predecessors
* (`security/permission.zod.ts` → `TenancyConfigSchema` at #5593 →
* `ObjectCapabilities` at #6619 → here at #6805). If THIS one is ever
* converted, move the fixture again rather than deleting the assertion.
*/
export const PerOperationRequiredPermissionsSchema = z.object({
read: z.array(z.string()).optional().describe('Capabilities required to read (find/findOne/count/aggregate).'),
create: z.array(z.string()).optional().describe('Capabilities required to create (insert).'),
update: z.array(z.string()).optional().describe('Capabilities required to update (update/transfer/restore).'),
delete: z.array(z.string()).optional().describe('Capabilities required to delete (delete/purge).'),
}).strict();
/**
* [ADR-0066 D3/⑤] Object capability contract — either capabilities required for
* ALL operations (`string[]`, the original shape) or a per-operation map
* (narrows the gate by operation). See the field doc on `Object.requiredPermissions`.
*/
export const ObjectRequiredPermissionsSchema = z.union([
z.array(z.string()),
PerOperationRequiredPermissionsSchema,
]);
export type PerOperationRequiredPermissions = z.input<typeof PerOperationRequiredPermissionsSchema>;
export type ObjectRequiredPermissions = z.input<typeof ObjectRequiredPermissionsSchema>;
/**
* Data Lifecycle (ADR-0057)
*
* Declares how long an object's data lives and how its space is reclaimed —
* the axis validation/permissions never covered. Enforced at runtime by the
* platform-owned LifecycleService (`@objectstack/objectql`): Reaper (TTL/age
* batch delete), Rotator (time-shard + DROP oldest on SQLite, an age-based
* reap of the same window elsewhere), Archiver (cold-store
* copy then delete). A declared policy with no runtime consumer is a spec
* defect (ADR-0049 enforce-or-remove); the liveness gate requires every
* non-`record` class to declare `retention`, `ttl`, or rotation `storage`.
*/
/**
* Lifecycle class — what persistence contract the object's data carries.
*
* | class | contract |
* |-------------|-------------------------------------------------|
* | `record` | business truth — permanent, recoverable |
* | `audit` | compliance ledger — retain → archive → delete |
* | `telemetry` | high-frequency log — rotation, short retention |
* | `transient` | ephemeral state — TTL auto-expire |
* | `event` | event-bus messages — very short TTL |
*
* `record` is the back-compat default: an object with no `lifecycle` block
* behaves exactly as today (immortal data).
*/
export const LifecycleClassSchema = z.enum(['record', 'audit', 'telemetry', 'transient', 'event']);
/**
* Duration literal: `<n><unit>` where unit is h(ours), d(ays), w(eeks) or
* y(ears) — e.g. `'6h'`, `'14d'`, `'12w'`, `'7y'`. Parsed by
* `@objectstack/objectql` `parseLifecycleDuration`.
*/
export const LIFECYCLE_DURATION_REGEX = /^\d+(h|d|w|y)$/;
const lifecycleDuration = (what: string) =>
z.string().regex(LIFECYCLE_DURATION_REGEX, `${what} must be a duration literal like '6h', '14d', '12w' or '7y'`);
/**
* [#10165] The `onlyWhen` row-filter value union, shared by
* `retention.onlyWhen` and `ttl.onlyWhen` — ONE shape on purpose: the two
* blocks are mirrors (maintainer ruling 2026-08-20, option A: give `ttl` an
* `onlyWhen` mirroring `retention`'s), and the runtime enforces them through
* one code path (`LifecycleService.reap` spreads the filter into the
* candidate-read `where` identically for both policies), so two copied unions
* here could only ever drift apart.
*
* Members: per-field equality (string/number/boolean), `{$in: [...]}`
* (non-empty), and the platform's canonical null predicate `{$null: boolean}`
* — `$null` is declared `z.boolean()` to match `FieldOperatorsSchema`'s
* first-class query-layer declaration exactly, never a `true`-only literal
* that would mint a third dialect of the predicate. The absence member exists
* because interleaved terminal rows are often supersets of live rows (a
* `sys_session` tombstone stamps `revoked_at` and clears nothing), so the
* only property that distinguishes a live row is a value's ABSENCE.
* Dialect compile coverage: `driver-sql`'s
* `sql-driver-ttl-onlywhen-null-dialects.test.ts` (SQLite live, pg + mysql2
* compiled SQL).
*/
const lifecycleOnlyWhenSchema = z.record(
z.string(),
z.union([
z.string(),
z.number(),
z.boolean(),
z.object({ $in: z.array(z.union([z.string(), z.number()])).min(1) }).strict(),
z.object({ $null: z.boolean() }).strict(),
]),
);
export const LifecycleSchema = lazySchema(() => strictObject({
surface: "this object's `lifecycle` block",
history:
'Until #4001 these were dropped silently — the block still parsed, so a bounding ' +
'policy written one level too high left the object with NO policy at all. ADR-0057 ' +
"§3.5's own refine then passed, because the key it looks for was never there.",
aliases: { rotation: 'storage' },
guidance: {
// The dominant failure on this block is FLATTENING: every one of these is a
// real key of a real sub-block, written one level too high. Edit distance
// cannot help — the key is spelled correctly, it is just in the wrong
// object — and the §3.5 refine makes the mistake worse than inert: a
// flattened `maxAge` leaves `retention` absent, so a non-`record` class is
// then rejected as unbounded and the author is told about the wrong key.
maxAge:
'`maxAge` belongs to the retention block, one level down: ' +
"`retention: { maxAge: '30d' }`. Written here it is not read, and a non-`record` " +
'class with no `retention`/`ttl`/`storage` is rejected as unbounded (ADR-0057 §3.5).',
expireAfter:
'`expireAfter` belongs to the TTL block, one level down: ' +
"`ttl: { field: 'expires_at', expireAfter: '1d' }`.",
field:
'`field` belongs to the TTL block, one level down — it names the timestamp the TTL ' +
"is measured from: `ttl: { field: 'expires_at', expireAfter: '1d' }`.",
after:
'`after` belongs to the archive block, one level down: ' +
"`archive: { after: '7y', to: 'cold_store' }` — and ADR-0057 requires it to EQUAL " +
'`retention.maxAge`.',
to:
'`to` belongs to the archive block, one level down — it names the cold-storage ' +
"datasource: `archive: { after: '7y', to: 'cold_store' }`.",
keep:
'`keep` belongs to the archive block, one level down — it is how long COLD rows are ' +
'kept. The HOT window is `retention.maxAge`.',
strategy:
'`strategy` belongs to the storage block, one level down: ' +
"`storage: { strategy: 'rotation', shards: 7, unit: 'day' }`.",
shards:
'`shards` belongs to the storage block, one level down: ' +
"`storage: { strategy: 'rotation', shards: 7, unit: 'day' }`.",
unit:
'`unit` belongs to the storage block, one level down: ' +
"`storage: { strategy: 'rotation', shards: 7, unit: 'day' }`.",
},
}, {
class: LifecycleClassSchema.describe(
'Persistence contract: record (business truth, permanent) | audit (compliance ledger) | telemetry (high-freq log) | transient (ephemeral state) | event (bus messages).',
),
retention: strictObject({
surface: "this object's `lifecycle.retention` block",
history:
'Until #4001 these were dropped silently — the retention window still parsed, so a ' +
'row filter written under the wrong key reaped rows the author had meant to exempt.',
aliases: { filter: 'onlyWhen', where: 'onlyWhen', when: 'onlyWhen', age: 'maxAge' },
guidance: {
expireAfter:
'`expireAfter` is a `ttl` key, not a retention key. Retention reaps by AGE from ' +
'`created_at` (`maxAge`); TTL expires each row relative to a timestamp field you ' +
'name (`ttl.field`). Pick the one that matches how the rows die.',
keep:
'`keep` is an `archive` key — how long COLD rows survive. The hot window is ' +
'`retention.maxAge`.',
},
}, {
maxAge: lifecycleDuration('retention.maxAge').describe('Rows older than this (by created_at) are deleted by the Reaper — or archived first when `archive` is set.'),
onlyWhen: lifecycleOnlyWhenSchema.optional().describe(
'Row filter the retention applies to — per-field equality, {$in: [...]} or the null predicate {$null: true|false} (e.g. { status: { $in: ["completed", "failed"] } }). Rows OUTSIDE the filter are retained regardless of age: for tables that interleave live workflow state with terminal history (sys_automation_run). Incompatible with rotation storage and archive, which act on whole shards / age alone.',
),
}).optional().describe('Age-based retention window enforced by the LifecycleService Reaper.'),
ttl: strictObject({
surface: "this object's `lifecycle.ttl` block",
history:
'Until #4001 these were dropped silently — the TTL block still parsed, so rows the ' +
'author expected to auto-expire lived forever.',
aliases: { expiresAfter: 'expireAfter', after: 'expireAfter', timestampField: 'field', on: 'field', filter: 'onlyWhen', where: 'onlyWhen', when: 'onlyWhen' },
guidance: {
maxAge:
'`maxAge` is a `retention` key, not a TTL key. TTL measures from the timestamp ' +
'field named in `ttl.field`; retention measures AGE from `created_at`. For ' +
"age-based reaping write `retention: { maxAge: '30d' }` instead.",
},
}, {
field: z.string().describe('Timestamp field the TTL is measured from (e.g. created_at, expires_at).'),
expireAfter: lifecycleDuration('ttl.expireAfter').describe('Rows expire this long after `field` and are deleted by the Reaper.'),
onlyWhen: lifecycleOnlyWhenSchema.optional().describe(
'Row filter the TTL reap applies to — per-field equality, {$in: [...]} or the null predicate {$null: true|false} (e.g. { revoked_at: { $null: true } }). Rows OUTSIDE the filter are retained regardless of expiry: for tables that interleave live rows with terminal history a TTL keyed on the same timestamp would otherwise destroy (a sys_session audit tombstone backdates expires_at, so a naive TTL reaps tombstones first). Incompatible with rotation storage and archive, which act on whole shards / age alone.',
),
}).optional().describe('Per-row TTL auto-expiry (transient/event classes).'),
storage: strictObject({
surface: "this object's `lifecycle.storage` block",
history:
'Until #4001 these were dropped silently — the rotation block still parsed, so a ' +
'telemetry table declared as rotating kept every shard it ever cut.',
aliases: { count: 'shards', interval: 'unit', period: 'unit', granularity: 'unit' },
guidance: {
maxAge:
'`maxAge` is a `retention` key. Rotation takes its window from `shards` × `unit`, ' +
'not from an age you name — reclaimed by DROPping the oldest shard whole on SQLite, ' +
'by an equivalent age-based reap elsewhere. Set the window ' +
'with `shards`/`unit`, or use `retention` instead of rotation.',
},
}, {
strategy: z.literal('rotation').describe(
'Time-shard the table. The retained window (`shards` × `unit`) is the same on every ' +
'dialect; the reclamation is not — SQLite DROPs the oldest shard whole (O(1) reclaim), ' +
'other dialects reap that same window by age from `created_at`.',
),
shards: z.number().int().min(2).describe('Number of shards retained; total window = shards × unit.'),
unit: z.enum(['day', 'week', 'month']).describe('Time width of one shard.'),
}).optional().describe('Physical storage strategy for high-frequency telemetry (LifecycleService Rotator).'),
archive: strictObject({
surface: "this object's `lifecycle.archive` block",
history:
'Until #4001 these were dropped silently — the archive block still parsed, so audit ' +
'rows were reaped hot with no cold copy ever written.',
aliases: { datasource: 'to', target: 'to', destination: 'to', retain: 'keep' },
guidance: {
maxAge:
'`maxAge` is a `retention` key. The archive boundary is `archive.after`, and ' +
'ADR-0057 requires the two to be EQUAL — the hot window ends exactly where the ' +
'archive begins, so declare `retention.maxAge` and `archive.after` with the same value.',
},
}, {
after: lifecycleDuration('archive.after').describe('Rows older than this are copied to the archive datasource before hot deletion.'),
to: z.string().describe('Target datasource name for cold storage. When it is not registered, the Archiver skips (audit rows are then retained, never dropped unarchived).'),
keep: lifecycleDuration('archive.keep').optional().describe('How long archived rows are kept in cold storage (undefined = forever).'),
}).optional().describe('Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off.'),
reclaim: z.boolean().optional().describe('Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.'),
}).superRefine((lc, ctx) => {
// ADR-0057 §3.5: a non-`record` lifecycle class with no bounding policy is a
// false surface — the object would still grow forever. Enforce-or-remove.
if (lc.class !== 'record' && !lc.retention && !lc.ttl && !lc.storage) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.class '${lc.class}' requires at least one bounding policy: retention, ttl, or storage (rotation) — ADR-0057 §3.5`,
});
}
if (lc.class === 'record' && (lc.retention || lc.ttl || lc.storage || lc.archive)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.class 'record' is permanent business truth — retention/ttl/storage/archive policies are not allowed on it (ADR-0057 §3.1)`,
});
}
if (lc.archive && lc.retention && lc.archive.after !== lc.retention.maxAge) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.archive.after ('${lc.archive.after}') must equal retention.maxAge ('${lc.retention.maxAge}') — the hot window ends where the archive begins`,
});
}
if (lc.retention?.onlyWhen && lc.storage?.strategy === 'rotation') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.retention.onlyWhen cannot be combined with rotation storage — the Rotator DROPs whole shards and would destroy rows the filter protects',
});
}
if (lc.retention?.onlyWhen && lc.archive) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.retention.onlyWhen cannot be combined with archive — the Archiver moves rows by age alone and would archive rows the filter protects',
});
}
// [#10165] ttl.onlyWhen mirrors both of retention.onlyWhen's conflicts, from
// the Reaper's actual semantics rather than by symmetry alone:
// - rotation: the Rotator DROPs whole physical shards; a shard is dropped by
// age with no row read, so rows the filter protects go down with it.
// - archive: `reapObject` returns into `archiveObject` before the ttl reap
// ever runs, so with `archive` declared the filter guards a code path that
// is never executed (declared ≠ enforced) — while the Archiver itself
// copies and hot-deletes by `created_at` age alone.
if (lc.ttl?.onlyWhen && lc.storage?.strategy === 'rotation') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.ttl.onlyWhen cannot be combined with rotation storage — the Rotator DROPs whole shards and would destroy rows the filter protects',
});
}
if (lc.ttl?.onlyWhen && lc.archive) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.ttl.onlyWhen cannot be combined with archive — archive takes over the whole reap (the ttl sweep never runs) and the Archiver moves rows by age alone',
});
}
}));
/**
* Object Field Group Schema — MVP (data-layer protocol)
*
* Declares the set of logical field groups for an object. A group bundles
* related fields together for presentation in forms, detail pages, and
* editors (e.g., "Contact Info", "Billing", "System").
*
* Design rules (MVP):
* - Group **order** is the declaration order of this array — no `order` property.
* - Field → group mapping is derived automatically from `Field.group`
* matching `ObjectFieldGroup.key`; the **in-group display order** equals
* the traversal order of `ObjectSchema.fields`.
* - Fields whose `group` is unset (or references an undeclared key) are
* considered ungrouped and must be rendered by consumers in a default
* bucket after the declared groups, preserving their field declaration order.
* - Extension packages and runtime code use `Field.group` to assign fields
* to an existing group — no per-field order property is introduced at this
* layer.
*
* Migration operations supported by this MVP:
* - add / rename / delete / reorder groups (via the array)
* - assign an existing field to a group (via `Field.group`)
*
* Deferred (not part of MVP):