Repository navigation
Expand file tree
/
Copy pathobject.test.ts
More file actions
3238 lines (2970 loc) · 138 KB
/
Copy pathobject.test.ts
File metadata and controls
3238 lines (2970 loc) · 138 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
import { describe, it, expect, vi, afterEach } from 'vitest';
// Fixtures below are AUTHORED objects — what a developer writes before the
// schema applies its defaults — so they are annotated with `ServiceObject`
// (`z.input`), not `ServiceObject` (`z.infer`, defaults already materialised).
// Under `z.infer` every fixture owes `isSystem`, `datasource`, `searchable`,
// `activities`, … and the annotation stops being a contract check at all. This
// only became visible when tsconfig.test.json put these files in front of tsc
// (#5286).
import { ObjectSchema, ObjectCapabilities, IndexSchema, ObjectFieldGroupSchema, ObjectExternalBindingSchema, ObjectAccessConfigSchema, LifecycleSchema, TenancyConfigSchema, isTenancyDisabled, isPublicSharingEnabled, resolveCrudAffordances, type ServiceObject } from './object.zod';
import { resolveInjectedSystemColumns } from './injected-system-columns';
import { RETIRED_KEY_UPGRADE_GUIDE_SENTENCE } from '../shared/protocol-upgrade-guide';
import { projectPublishedJsonSchema } from '../../scripts/lib/refinement-projection';
import { collectDroppedRefinements } from '../../scripts/lib/dropped-refinements';
import { Field } from './field.zod';
import { defineStack } from '../stack.zod';
import { isMaskedOnReadFieldType } from './masked-field-types';
import { resolveFieldHistory } from './field-history-default';
import { CONTROLLED_BY_PARENT_MASTER_INVALID, type ControlledByParentMasterShape } from './controlled-by-parent-master';
import type { StateMachineValidation } from './validation.zod';
describe('ObjectCapabilities', () => {
it('should apply default values correctly', () => {
const result = ObjectCapabilities.parse({});
expect(result.trackHistory).toBe(false);
expect(result.searchable).toBe(true);
expect(result.apiEnabled).toBe(true);
expect(result.files).toBe(false);
// feeds/activities are opt-OUT capabilities (#2707): default on, consumers
// gate on explicit `false` only — same posture as clone.
expect(result.feeds).toBe(true);
expect(result.activities).toBe(true);
expect(result.clone).toBe(true);
// The record-reader approval tier is opt-IN (#8652: default OFF, the
// downstream project opts in): an absent flag grants nothing.
expect(result.approvalsVisibleToReaders).toBe(false);
// [#36290] Field-change values are on unless turned off, and the flag has
// NO default: a parsed body never materializes it, so a built artifact or
// a stored definition can always tell an authored `false` from silence.
expect('fieldHistory' in result).toBe(false);
expect(ObjectCapabilities.parse({ fieldHistory: false }).fieldHistory).toBe(false);
});
it('should accept custom capability values', () => {
const capabilities = {
trackHistory: true,
searchable: false,
apiEnabled: true,
files: true,
feeds: true,
activities: false,
clone: true,
approvalsVisibleToReaders: true,
};
const result = ObjectCapabilities.parse(capabilities);
expect(result).toEqual(capabilities);
});
it('approvalsVisibleToReaders is a boolean an object declares in its enable block', () => {
// The authorable surface: the key is recognised on the object itself, not
// only on the bare block…
const declared = ObjectSchema.safeParse({
name: 'exam_sheet',
label: 'Exam Sheet',
fields: { title: { type: 'text', label: 'Title' } },
enable: { approvalsVisibleToReaders: true },
});
expect(declared.success).toBe(true);
expect(declared.success ? declared.data.enable?.approvalsVisibleToReaders : undefined).toBe(true);
// …and it takes a boolean only: a truthy string is refused, never read as on.
const wrongType = ObjectCapabilities.safeParse({ approvalsVisibleToReaders: 'yes' });
expect(wrongType.success).toBe(false);
expect(wrongType.success ? undefined : wrongType.error.issues[0]?.code).toBe('invalid_type');
});
// #2377/#3207 (ADR-0049): `trash`/`mru` parsed-but-did-nothing for years —
// the retired keys must fail loudly with the upgrade prescription, not strip
// silently (#1535; pattern of the tenancy tombstones, #2763).
it('rejects the retired trash/mru flags with upgrade guidance', () => {
for (const key of ['trash', 'mru'] as const) {
const result = ObjectCapabilities.safeParse({ [key]: true });
expect(result.success).toBe(false);
const message = result.success ? '' : result.error.issues.map((i) => i.message).join('\n');
expect(message).toContain(`\`${key}\``);
expect(message, 'the migration command is the durable reference').not.toMatch(/#\d{3,5}/);
// The prescription names the source rewrite the #3207 conversion used to
// perform; the conversion aged out with the 16.x kits (#25767), so the house
// sentence says so and links the guide instead of naming `--from 16`.
expect(message).toContain('This edit left `os migrate meta` with the protocol-16.x conversions');
expect(message).not.toContain('os migrate meta --from 16');
}
// `trash` additionally points at the recycle bin that shipped after the
// flag was retired (ADR-0148), which has no flag to set (#31629; it used
// to say soft delete was parked, which the bin made untrue).
const trash = ObjectCapabilities.safeParse({ trash: false });
expect(trash.success).toBe(false);
const trashMsg = trash.success ? '' : trash.error.issues.map((i) => i.message).join('\n');
expect(trashMsg).toContain('The recycle bin that shipped later (ADR-0148) has no flag');
expect(trashMsg, 'the prescription carries ADR ids and the migration command, never a tracker id')
.not.toMatch(/#\d{3,5}/);
});
// `enable.trash` and `versioning` both promised history, so both refusals
// say where field history lives now. It is the model `resolveFieldHistory`
// enforces (values on by default, `enable.fieldHistory: false` for the
// object, a field's own `fieldHistory: false`, a media or structured-JSON
// field opting in with `fieldHistory: true`), never `trackHistory`: on a
// field that only opts a media or JSON type in and `false` turns nothing off.
describe('retired history-promising keys prescribe the field-history model that runs', () => {
const trashMessage = (): string => {
const r = ObjectCapabilities.safeParse({ trash: false });
expect(r.success).toBe(false);
return r.success ? '' : r.error.issues.map((i) => i.message).join('\n');
};
const versioningMessage = (): string => {
try {
ObjectSchema.create({
name: 'demo',
fields: { status: { type: 'text' } },
versioning: { enabled: true },
} as Record<string, unknown> as Parameters<typeof ObjectSchema.create>[0]);
} catch (e) {
return (e as Error).message;
}
throw new Error('`versioning` was not refused');
};
for (const [key, read] of [['enable.trash', trashMessage], ['versioning', versioningMessage]] as const) {
it(`${key}: values show by default, and the two off switches are named`, () => {
const message = read();
expect(message).toContain(
'Field history is on by default: a changed field\'s old → new values show on the record activity timeline',
);
expect(message, 'the default-off types are named with their opt-in').toContain(
'except a media or structured-JSON field, which opts in with `fieldHistory: true`.',
);
expect(message).toContain('`enable.fieldHistory: false` turns them off for the object');
expect(message).toContain('a field opts out with its own `fieldHistory: false`');
expect(message).toMatch(/For retention, (use )?a (data lifecycle policy \(`lifecycle`\)|`lifecycle` policy)/);
});
it(`${key}: never sends the author to \`trackHistory\``, () => {
expect(read()).not.toContain('trackHistory');
});
}
it('the prescription agrees with resolveFieldHistory', () => {
const text = { type: 'text' } as const;
expect(resolveFieldHistory(text, {}), 'values show by default').toBe(true);
expect(resolveFieldHistory(text, { enable: { fieldHistory: false } }), 'object off switch').toBe(false);
expect(resolveFieldHistory({ ...text, fieldHistory: false }, {}), 'field off switch').toBe(false);
expect(resolveFieldHistory({ ...text, trackHistory: false }, {}), 'trackHistory: false is no off switch').toBe(true);
const json = { type: 'json' } as const;
expect(resolveFieldHistory(json, {}), 'a structured-JSON field is off by default').toBe(false);
expect(resolveFieldHistory({ ...json, fieldHistory: true }, {}), 'fieldHistory: true opts it in').toBe(true);
const image = { type: 'image' } as const;
expect(resolveFieldHistory(image, {}), 'a media field is off by default').toBe(false);
expect(resolveFieldHistory({ ...image, fieldHistory: true }, {}), 'fieldHistory: true opts it in').toBe(true);
});
});
it('rejects unknown capability keys instead of stripping them', () => {
const result = ObjectCapabilities.safeParse({ feedEnabled: true });
expect(result.success).toBe(false);
});
// ── #6805 — the map folded into the shared `strictObject` template ────────
// `strictCapabilitiesError` was a hand-written `$ZodErrorMap`, so
// `CAPABILITIES_RETIRED_KEY_GUIDANCE` registered in no registry and nothing
// judged it. Acceptance did not move (every case above is unchanged); these
// pin the assembly the template brings.
const capabilityRejection = (body: Record<string, unknown>): string => {
const result = ObjectCapabilities.safeParse(body);
expect(result.success).toBe(false);
return result.success ? '' : result.error.issues.map((i) => i.message).join('\n');
};
it.each([
['searchible', 'searchable'],
['trackHistroy', 'trackHistory'],
['clon', 'clone'],
['feed', 'feeds'],
])('a near-miss `%s` now gets the rename channel, not just "not an `enable` capability flag"', (written, canonical) => {
const message = capabilityRejection({ [written]: true });
expect(message).toContain(`\`${written}\` → \`${canonical}\``);
expect(message).not.toContain('is not an `enable` capability flag');
});
it('a key beyond edit distance is still named, with no misleading suggestion', () => {
const message = capabilityRejection({ feedEnabled: true });
expect(message).toContain('`feedEnabled`');
expect(message).not.toContain('Did you mean');
});
it('emission order: which key is wrong → the fix → the history, last', () => {
const message = capabilityRejection({ trash: false, searchible: true });
const preamble = 'Unrecognized key(s) on `enable`:';
const fix = '`enable.trash` was removed';
const history = 'every flag carries an enforcement contract';
expect(message.startsWith(preamble)).toBe(true);
expect(message.indexOf(fix)).toBeGreaterThan(message.indexOf(preamble));
expect(message.indexOf(history)).toBeGreaterThan(message.indexOf(fix));
expect(message.trimEnd().endsWith(`${history}.`)).toBe(true);
expect(message.split(history)).toHaveLength(2);
});
it('the tombstone text survives the fold byte-for-byte', () => {
expect(capabilityRejection({ mru: true })).toContain(
'`enable.mru` was removed from @objectstack/spec in the 16.x line ('
+ 'ADR-0049) — Most-Recently-Used tracking was never implemented; no reader '
+ 'existed, so the flag changed nothing.',
);
});
});
describe('LifecycleSchema (ADR-0057)', () => {
it('accepts the ADR §3.2 telemetry rotation shape', () => {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: { maxAge: '14d' },
storage: { strategy: 'rotation', shards: 14, unit: 'day' },
reclaim: true,
});
expect(result.success).toBe(true);
});
it('accepts the ADR §3.2 audit archive-then-delete shape', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
archive: { after: '90d', to: 'datalake', keep: '7y' },
});
expect(result.success).toBe(true);
});
it('accepts the ADR §3.2 transient ttl shape', () => {
const result = LifecycleSchema.safeParse({
class: 'transient',
ttl: { field: 'created_at', expireAfter: '7d' },
});
expect(result.success).toBe(true);
});
it('accepts a bare record class (permanent, no policies)', () => {
expect(LifecycleSchema.safeParse({ class: 'record' }).success).toBe(true);
});
it('rejects a non-record class with no bounding policy (§3.5 enforce-or-remove)', () => {
for (const cls of ['audit', 'telemetry', 'transient', 'event'] as const) {
const result = LifecycleSchema.safeParse({ class: cls });
expect(result.success).toBe(false);
}
});
it('rejects retention/ttl/storage/archive on a record class', () => {
const result = LifecycleSchema.safeParse({
class: 'record',
retention: { maxAge: '30d' },
});
expect(result.success).toBe(false);
});
it('rejects an archive window that does not start where the hot window ends', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
archive: { after: '30d', to: 'datalake' },
});
expect(result.success).toBe(false);
});
// [commit 5649efbf9] The retention + ttl + archive triple. Since commit
// 530c1df65 the Archiver selects rows by the ttl cutoff whenever `ttl` is
// declared, so a triple whose ttl diverges from the age bound leaves
// `retention.maxAge` declared but enforced by nothing — refused at parse
// time unless the ttl restates the age bound (same clock, same window).
describe('retention + ttl + archive triple — refused unless the ttl restates the age bound', () => {
const messagesOf = (result: ReturnType<typeof LifecycleSchema.safeParse>) =>
result.success ? '' : result.error.issues.map((i) => i.message).join('\n');
it('still accepts the ttl + archive pair, whose ttl cutoff picks the rows to archive (no retention)', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
ttl: { field: 'expires_at', expireAfter: '90d' },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(true);
});
it('accepts the triple when the ttl restates the age bound exactly (created_at, equal windows)', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
ttl: { field: 'created_at', expireAfter: '90d' },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(true);
});
it("rejects the issue's own triple — ttl on a different clock AND window — naming both bounds and the runtime truth", () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
ttl: { field: 'expires_at', expireAfter: '30d' },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(false);
const msg = messagesOf(result);
// Named values on both sides of the divergence …
expect(msg).toContain("lifecycle.ttl ('30d' after 'expires_at')");
expect(msg).toContain("retention.maxAge ('90d' after created_at)");
// … and the runtime truth since commit 530c1df65: the ttl cutoff selects, so the
// age bound is the one left inert (not "moves rows by age alone").
expect(msg).toContain('the Archiver moves rows by the ttl cutoff when ttl is declared');
expect(msg).toContain('no longer bounds the hot store');
});
it('rejects a diverging window even on the same clock (created_at, 30d vs 90d)', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
ttl: { field: 'created_at', expireAfter: '30d' },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(false);
expect(messagesOf(result)).toContain("lifecycle.ttl ('30d' after 'created_at')");
});
it('rejects a diverging clock even with equal windows (expires_at, 90d = 90d)', () => {
// Equal durations do NOT make the age bound enforced: a row whose
// `expires_at` sits in the future stays hot past `retention.maxAge`.
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d' },
ttl: { field: 'expires_at', expireAfter: '90d' },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(false);
expect(messagesOf(result)).toContain("lifecycle.ttl ('90d' after 'expires_at')");
});
});
it('rejects malformed duration literals', () => {
for (const bad of ['14', 'd14', '14 days', '2mo', '-3d', '1.5d']) {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: { maxAge: bad },
});
expect(result.success).toBe(false);
}
});
it('accepts retention.onlyWhen with scalar and $in predicates (mixed tables, where only terminal rows age out)', () => {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: {
maxAge: '30d',
onlyWhen: { status: { $in: ['completed', 'failed'] }, archived: true },
},
});
expect(result.success).toBe(true);
});
it('rejects onlyWhen operators other than $in and empty $in lists', () => {
for (const bad of [
{ status: { $nin: ['paused'] } }, // unsupported operator
{ status: { $in: [] } }, // empty list matches nothing — surely a mistake
{ status: { $in: ['a'], extra: 1 } }, // strict object: no extra keys
]) {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: { maxAge: '30d', onlyWhen: bad },
});
expect(result.success).toBe(false);
}
});
it('accepts ttl.onlyWhen with the canonical null predicate — so rows whose value is absent are spared', () => {
// The exact declaration this card unblocks (#7826 writes it on sys_session).
const result = LifecycleSchema.safeParse({
class: 'transient',
ttl: { field: 'expires_at', expireAfter: '1d', onlyWhen: { revoked_at: { $null: true } } },
});
expect(result.success).toBe(true);
});
it('accepts the null predicate on retention.onlyWhen too — one shared value union', () => {
// The two blocks are declared mirrors; the union is one schema on purpose,
// so the absence member cannot exist on one side and not the other.
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: { maxAge: '30d', onlyWhen: { processed_at: { $null: true }, archived: { $null: false } } },
});
expect(result.success).toBe(true);
});
it('rejects malformed null predicates on ttl.onlyWhen (non-boolean, extra keys, raw null)', () => {
for (const bad of [
{ revoked_at: { $null: 'yes' } }, // $null is z.boolean(), matching FieldOperatorsSchema
{ revoked_at: { $null: true, extra: 1 } }, // strict object: no extra keys
{ revoked_at: null }, // raw null is NOT the predicate — write {$null: true}
{ revoked_at: { $nin: [null] } }, // unsupported operator, unchanged by commit 801296050
]) {
const result = LifecycleSchema.safeParse({
class: 'transient',
ttl: { field: 'expires_at', expireAfter: '1d', onlyWhen: bad },
});
expect(result.success, `should reject ${JSON.stringify(bad)}`).toBe(false);
}
});
it('rejects ttl row-filter aliases (filter/where/when) with the onlyWhen prescription', () => {
for (const alias of ['filter', 'where', 'when'] as const) {
const result = LifecycleSchema.safeParse({
class: 'transient',
ttl: { field: 'expires_at', expireAfter: '1d', [alias]: { revoked_at: { $null: true } } },
});
expect(result.success).toBe(false);
const message = result.success ? '' : result.error.issues.map((i) => i.message).join('\n');
expect(message).toContain('onlyWhen');
}
});
it('rejects ttl.onlyWhen combined with rotation storage (shard DROPs ignore filters)', () => {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
ttl: { field: 'created_at', expireAfter: '14d', onlyWhen: { status: 'done' } },
storage: { strategy: 'rotation', shards: 14, unit: 'day' },
});
expect(result.success).toBe(false);
});
it('rejects ttl.onlyWhen combined with archive (archive takes over; the ttl sweep never runs)', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
ttl: { field: 'expires_at', expireAfter: '90d', onlyWhen: { revoked_at: { $null: true } } },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(false);
});
it('rejects onlyWhen combined with rotation storage (shard DROPs ignore filters)', () => {
const result = LifecycleSchema.safeParse({
class: 'telemetry',
retention: { maxAge: '14d', onlyWhen: { status: 'done' } },
storage: { strategy: 'rotation', shards: 14, unit: 'day' },
});
expect(result.success).toBe(false);
});
it('rejects onlyWhen combined with archive (the Archiver moves rows by age alone)', () => {
const result = LifecycleSchema.safeParse({
class: 'audit',
retention: { maxAge: '90d', onlyWhen: { status: 'done' } },
archive: { after: '90d', to: 'datalake' },
});
expect(result.success).toBe(false);
});
it('is accepted as an object-level property by ObjectSchema.create', () => {
const obj = ObjectSchema.create({
name: 'my_trace',
fields: {},
lifecycle: {
class: 'telemetry',
retention: { maxAge: '14d' },
},
});
expect(obj.lifecycle?.class).toBe('telemetry');
expect(obj.lifecycle?.retention?.maxAge).toBe('14d');
});
it('objects without a lifecycle block stay back-compatible (undefined = record semantics)', () => {
const obj = ObjectSchema.create({ name: 'plain_object', fields: {} });
expect(obj.lifecycle).toBeUndefined();
});
});
describe('IndexSchema', () => {
it('should accept basic index definition', () => {
const index = {
fields: ['email'],
};
expect(() => IndexSchema.parse(index)).not.toThrow();
});
it('should accept index with all properties', () => {
const index = {
name: 'idx_email_status',
fields: ['email', 'status'],
unique: 'global',
};
expect(() => IndexSchema.parse(index)).not.toThrow();
});
it('should accept composite index', () => {
const index = {
fields: ['tenant_id', 'created_at', 'status'],
unique: false,
};
expect(() => IndexSchema.parse(index)).not.toThrow();
});
it('should reject index without fields', () => {
expect(() => IndexSchema.parse({})).toThrow();
});
});
/**
* `indexes[].type` / `indexes[].partial` retirement (#5248, #4943, ADR-0049).
*
* Both were authorable with zero DDL consumers. `IndexSchema` is not
* `.strict()`, so a plain delete would have Zod strip an authored value in
* silence — swapping one no-op for another (#3726 / #3733, the ADR-0104
* class). The tombstone is what makes the removal audible, so these tests pin
* the PRESCRIPTION, not merely the rejection.
*/
describe('IndexSchema retired keys', () => {
// #25767: both tombstones were 16.x retirement kits and aged out (ADR-0087
// D2 = A). The index shape is strict, so each key is refused as an unknown
// key and the refusal's trailing sentence names the protocol upgrade guide,
// which carries the two prescriptions from here. Still never a silent strip.
it('REFUSES `type` as a strict unknown key, pointing at the upgrade guide', () => {
expect(() => IndexSchema.parse({ fields: ['tags'], type: 'gin' }))
.toThrow(/Unrecognized key\(s\) on this index: `type`[\s\S]*https:\/\/objectstack\.ai\/docs\/protocol-upgrade/);
});
it('REFUSES `partial` the same way', () => {
expect(() => IndexSchema.parse({ fields: ['name'], partial: "state = 'active'" }))
.toThrow(/Unrecognized key\(s\) on this index: `partial`[\s\S]*https:\/\/objectstack\.ai\/docs\/protocol-upgrade/);
});
it('no longer names a migrate step — the conversion that carried these aged out with its kit', () => {
for (const bad of [{ fields: ['a'], type: 'btree' }, { fields: ['a'], partial: 'x' }]) {
expect(() => IndexSchema.parse(bad)).not.toThrow(/os migrate meta --from/);
expect(() => IndexSchema.parse(bad)).toThrow();
}
});
it('the live keys are untouched — the retirement is surgical', () => {
const parsed = IndexSchema.parse({
name: 'idx_invoice_no',
fields: ['invoice_no'],
unique: 'organization',
});
expect(parsed).toEqual({ name: 'idx_invoice_no', fields: ['invoice_no'], unique: 'organization' });
});
it('no longer materializes a phantom `btree` into every parsed index', () => {
// The louder half of the defect: `type` carried `.default('btree')`, so an
// access-method knob nothing has ever read appeared in the parse output of
// every index of every object (it was pinned in service-realtime's
// sys_presence test, on an object that never declared it).
const parsed = IndexSchema.parse({ fields: ['email'] });
expect(parsed).not.toHaveProperty('type');
expect(parsed).not.toHaveProperty('partial');
expect(parsed).toEqual({ fields: ['email'], unique: false });
});
it('rejects the retired keys through a whole object too, not just the sub-schema', () => {
expect(() => ObjectSchema.parse({
name: 'crm_invoice',
label: 'Invoice',
fields: { name: { type: 'text', label: 'Name' } },
indexes: [{ fields: ['name'], partial: "state = 'active'" }],
})).toThrow(/Unrecognized key\(s\) on this index: `partial`/);
});
});
describe('ObjectSchema', () => {
describe('Basic Object Properties', () => {
it('should accept minimal valid object', () => {
const validObject: ServiceObject = {
name: 'account',
fields: {},
};
const result = ObjectSchema.safeParse(validObject);
expect(result.success).toBe(true);
});
it('should enforce snake_case for object name', () => {
const validNames = ['account', 'project_task', 'user_profile', '_system'];
validNames.forEach(name => {
expect(() => ObjectSchema.parse({ name, fields: {} })).not.toThrow();
});
const invalidNames = ['Account', 'project-task', 'UserProfile', '123object'];
invalidNames.forEach(name => {
expect(() => ObjectSchema.parse({ name, fields: {} })).toThrow();
});
});
it('should apply default values', () => {
const object = {
name: 'test_object',
fields: {},
};
const result = ObjectSchema.parse(object);
expect(result.datasource).toBe('default');
expect(result.isSystem).toBe(false);
});
});
describe('Object with Fields', () => {
it('should accept object with multiple fields', () => {
const objectWithFields: ServiceObject = {
name: 'contact',
label: 'Contact',
pluralLabel: 'Contacts',
fields: {
first_name: {
label: 'First Name',
type: 'text',
required: true,
maxLength: 50,
},
last_name: {
label: 'Last Name',
type: 'text',
required: true,
maxLength: 50,
},
email: {
label: 'Email',
type: 'email',
unique: true,
},
phone: {
label: 'Phone',
type: 'phone',
},
},
};
expect(() => ObjectSchema.parse(objectWithFields)).not.toThrow();
});
it('should enforce snake_case for field names', () => {
// Valid snake_case field names
const validFieldNames = ['first_name', 'last_name', 'email', 'company_name', 'annual_revenue', '_system_id'];
validFieldNames.forEach(fieldName => {
const obj = {
name: 'test_object',
fields: {
[fieldName]: {
type: 'text' as const,
label: 'Test Field',
},
},
};
expect(() => ObjectSchema.parse(obj)).not.toThrow();
});
});
it('should reject PascalCase field names', () => {
const invalidObject = {
name: 'lead',
fields: {
FirstName: {
type: 'text' as const,
label: '名',
},
},
};
expect(() => ObjectSchema.parse(invalidObject)).toThrow();
expect(() => ObjectSchema.parse(invalidObject)).toThrow(/Field names must be lowercase snake_case/);
});
it('should reject camelCase field names', () => {
const invalidObject = {
name: 'lead',
fields: {
firstName: {
type: 'text' as const,
label: 'First Name',
},
},
};
expect(() => ObjectSchema.parse(invalidObject)).toThrow();
expect(() => ObjectSchema.parse(invalidObject)).toThrow(/Field names must be lowercase snake_case/);
});
it('should reject kebab-case field names', () => {
const invalidObject = {
name: 'lead',
fields: {
'first-name': {
type: 'text' as const,
label: 'First Name',
},
},
};
expect(() => ObjectSchema.parse(invalidObject)).toThrow();
expect(() => ObjectSchema.parse(invalidObject)).toThrow(/Field names must be lowercase snake_case/);
});
it('should reject field names with spaces', () => {
const invalidObject = {
name: 'lead',
fields: {
'first name': {
type: 'text' as const,
label: 'First Name',
},
},
};
expect(() => ObjectSchema.parse(invalidObject)).toThrow();
expect(() => ObjectSchema.parse(invalidObject)).toThrow(/Field names must be lowercase snake_case/);
});
it('should reject field names starting with numbers', () => {
const invalidObject = {
name: 'lead',
fields: {
'123field': {
type: 'text' as const,
label: 'Field',
},
},
};
expect(() => ObjectSchema.parse(invalidObject)).toThrow();
expect(() => ObjectSchema.parse(invalidObject)).toThrow(/Field names must be lowercase snake_case/);
});
it('should reject mixed-case field names like in AI-generated objects', () => {
// This is the exact problem from the issue
const aiGeneratedObject = {
name: 'lead',
label: '线索',
fields: {
FirstName: {
type: 'text' as const,
label: '名',
maxLength: 40,
},
LastName: {
type: 'text' as const,
label: '姓',
required: true,
maxLength: 80,
},
Company: {
type: 'text' as const,
label: '公司',
required: true,
maxLength: 255,
},
},
};
expect(() => ObjectSchema.parse(aiGeneratedObject)).toThrow();
expect(() => ObjectSchema.parse(aiGeneratedObject)).toThrow(/Field names must be lowercase snake_case/);
});
});
describe('Object Metadata', () => {
it('should accept object with full metadata', () => {
const fullObject: ServiceObject = {
name: 'opportunity',
label: 'Opportunity',
pluralLabel: 'Opportunities',
description: 'Sales opportunities tracking',
icon: 'target',
datasource: 'salesforce',
isSystem: false,
nameField: 'opportunity_name',
fields: {
opportunity_name: {
label: 'Opportunity Name',
type: 'text',
},
},
};
expect(() => ObjectSchema.parse(fullObject)).not.toThrow();
});
});
describe('Object with Indexes', () => {
it('should accept object with indexes', () => {
const objectWithIndexes: ServiceObject = {
name: 'user',
fields: {
email: {
label: 'Email',
type: 'email',
},
username: {
label: 'Username',
type: 'text',
},
},
indexes: [
{
name: 'idx_email',
fields: ['email'],
unique: 'global',
},
{
name: 'idx_username',
fields: ['username'],
unique: 'global',
},
{
fields: ['email', 'username'],
},
],
};
expect(() => ObjectSchema.parse(objectWithIndexes)).not.toThrow();
});
});
describe('Object Capabilities', () => {
it('should accept object with custom capabilities', () => {
const objectWithCapabilities: ServiceObject = {
name: 'case',
fields: {},
enable: {
trackHistory: true,
searchable: true,
apiEnabled: true,
files: true,
feeds: true,
},
};
expect(() => ObjectSchema.parse(objectWithCapabilities)).not.toThrow();
});
it('should merge default capabilities with custom values', () => {
const object = {
name: 'task',
fields: {},
enable: {
trackHistory: true,
files: true,
},
};
const result = ObjectSchema.parse(object);
expect(result.enable?.trackHistory).toBe(true);
expect(result.enable?.files).toBe(true);
expect(result.enable?.searchable).toBe(true); // default
expect(result.enable?.apiEnabled).toBe(true); // default
});
});
describe('Complete Real-World Examples', () => {
it('should accept CRM Account object', () => {
const accountObject: ServiceObject = {
name: 'account',
label: 'Account',
pluralLabel: 'Accounts',
description: 'Companies and organizations',
icon: 'building-2',
nameField: 'account_name',
fields: {
account_name: {
label: 'Account Name',
type: 'text',
required: true,
maxLength: 255,
},
account_number: {
label: 'Account Number',
type: 'text',
unique: true,
externalId: true,
},
website: {
label: 'Website',
type: 'url',
},
industry: {
label: 'Industry',
type: 'select',
options: [
{ label: 'Technology', value: 'tech' },
{ label: 'Finance', value: 'finance' },
{ label: 'Healthcare', value: 'healthcare' },
],
},
annual_revenue: {
label: 'Annual Revenue',
type: 'currency',
precision: 18,
},
owner_id: {
label: 'Account Owner',
type: 'lookup',
reference: 'user',
},
},
indexes: [
{
name: 'idx_account_number',
fields: ['account_number'],
unique: 'global',
},
],
enable: {
trackHistory: true,
searchable: true,
apiEnabled: true,
files: true,
feeds: true,
},
};
expect(() => ObjectSchema.parse(accountObject)).not.toThrow();
});
it('should accept Task object with parent relationship', () => {
const taskObject: ServiceObject = {
name: 'task',
label: 'Task',
pluralLabel: 'Tasks',
icon: 'check-square',
nameField: 'subject',
fields: {
subject: {
label: 'Subject',
type: 'text',
required: true,
},
status: {
label: 'Status',
type: 'select',
options: [
{ label: 'Not Started', value: 'not_started', default: true },
{ label: 'In Progress', value: 'in_progress' },
{ label: 'Completed', value: 'completed' },
],
},
priority: {
label: 'Priority',
type: 'select',
options: [
{ label: 'Low', value: 'low', color: '#00FF00' },
{ label: 'Medium', value: 'medium', color: '#FFA500', default: true },
{ label: 'High', value: 'high', color: '#FF0000' },
],
},
environment_id: {
label: 'Project',
type: 'master_detail',
reference: 'project',
deleteBehavior: 'cascade',
},
assigned_to: {
label: 'Assigned To',
type: 'lookup',
reference: 'user',
},
due_date: {
label: 'Due Date',
type: 'date',
},
completed_at: {
label: 'Completed At',
type: 'datetime',
},
},
enable: {
trackHistory: false,
searchable: true,
apiEnabled: true,
files: false,
feeds: false,
},
};
expect(() => ObjectSchema.parse(taskObject)).not.toThrow();
});
// ADR-0020: record state machines are no longer a standalone
// `object.stateMachines` map. They converge onto a single
// `state_machine` validation rule on the object — a flat
// field + transitions table enforced on the write path.
it('should validate an object with a state_machine validation rule', () => {
const objectWithState = {
name: 'leave_request',
fields: {
status: { type: 'text' },
},