Repository navigation
Expand file tree
/
Copy pathregistry.ts
More file actions
8411 lines (7972 loc) · 424 KB
/
Copy pathregistry.ts
File metadata and controls
8411 lines (7972 loc) · 424 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 { ServiceObject, ObjectSchema, ObjectOwnership, provisionPrimary, resolveInjectedSystemColumns, resolveInjectedColumnProvenance as injectedColumnProvenance, isInjectedColumnDefinition, isTenancyDisabled, checkManagedApiMethodAffordances, LEGACY_API_METHODS, AUDIT_PROVENANCE_FIELDS, materializeTreeSelfReferences, BASE_FIELD_DISPLAY_WHITELIST, type ObjectExtensionParsed } from '@objectstack/spec/data';
// [#4513] The audit-family governance table, and [#6562] the injected-column
// DEFINITION tables it governs — see the re-exports below for why both live in a
// package `objectql` and `metadata-protocol` both depend on.
import {
AUDIT_FIELD_GOVERNANCE,
applyAuditFieldGovernance,
AUDIT_FIELD_DEFS,
TENANT_SCOPE_FIELD_DEF,
OWNER_FIELD_DEF,
OWNING_BUSINESS_UNIT_FIELD_DEF,
QUEUE_FIELD_DEF,
// [#7774] The i18n-bundle identity table and its value reader, sunk into
// metadata-core so this registry and the `/meta` list merge in
// `@objectstack/metadata-protocol` answer "what is this type's identity?"
// from one place. Re-exported below under its original name.
ITEM_KEY_DISCRIMINATORS,
readDiscriminatorValue as discriminatorValue,
// [commit fa5d137ab] The ADR-0029 D9.6 provenance pair, sunk into metadata-core for the
// same reason as the table above: `@objectstack/service-automation`'s flow
// precedence asks the same question ("does a code package ship this name?")
// and reached it by importing this package, which it does not declare — so
// the bundler inlined a copy of this implementation into ITS dist. Both names
// keep their original spelling here, and `isCodeArtifactBody` is re-exported
// below, so this package's public API is unchanged.
isCodeArtifactBody,
isTenantAuthored,
// [#16319] The field-`type` admission vocabulary — the predicate, the shared
// sentence and the discriminator name. It lives one package down for the
// ordinary reason: the reporting seam is `@objectstack/metadata-protocol`'s
// `loadMetaFromDb`, which THIS package depends on, so the reverse import is a
// cycle. See the module's own header.
describeUndeclarableFieldType,
findUndeclarableFieldType,
OBJECT_FIELD_TYPE_REFUSED_ERROR_NAME,
type ObjectFieldTypeRefusal,
type ObjectFieldTypeViolation,
// [ADR-0146 D10, second rule] The field-patch target check — the install
// door's and `os validate`'s judge, asked here so the fold names a patch it
// cannot apply by the same verdict those doors refuse it by.
fieldPatchTargetMisses,
type FieldPatchTargetMiss,
} from '@objectstack/metadata-core';
// [ADR-0029 D9.2a] `scalarOverridesPackagedBase` is the #8284 comparison, imported rather
// than re-spelled: the object FOLD asks the same question one layer down (has
// this scalar been authored away from the packaged default?), and the ruling
// required the same mechanism, not a second comparison shape.
import { SystemFieldName, scalarOverridesPackagedBase } from '@objectstack/spec/system';
import { resolveTenancyPosture, resolveSearchPinyinEnabled } from '@objectstack/types';
import { postureEnforcesWall } from '@objectstack/spec/security';
import { provisionSearchCompanion, SEARCH_COMPANION_FIELD } from './search-companion.js';
import { ObjectStackManifest, ManifestSchema, InstalledPackage, InstalledPackageSchema, InstalledPackageSourceSchema, type InstalledPackageSource, checkFieldCompleteness, customizationPackageId } from '@objectstack/spec/kernel';
import { DEFAULT_FLOW_FUNCTION_EFFECT } from '@objectstack/spec/automation';
import { AppSchema, ActionSchema } from '@objectstack/spec/ui';
import { applyProtection } from '@objectstack/spec/shared';
// [ADR-0130 D1] The ONE derivation of the key a package is installed under
// (`id || name`). The install gate's co-ownership set must name packages by the
// same string the artifact loader ordered them by, or a co-owner would be
// admitted — or refused — under a key nothing else in the path uses.
import { artifactPackageId, declaredDependencyIds, type SecurityCatalogType } from '@objectstack/core';
// One name, one holder for positions, permission sets and capabilities — the
// rule, the holders and the one place a declaration is read from (module doc).
import {
BUILT_IN_SECURITY_CATALOG_NAMES,
declaredSecurityCatalogNames,
describeSecurityCatalogHolder,
ENVIRONMENT_HELD_SECURITY_CATALOG_TYPES,
isSecurityCatalogType,
securityCatalogHolderKey,
securityCatalogTypeLabel,
type SecurityCatalogHolder,
} from './security-catalog-namespace.js';
// One default record page per object per deployment — the holders and the one
// place a manifest's default record pages are read from (module doc).
import {
declaredDefaultRecordPages,
misplacedDefaultPages,
type MisplacedDefaultPage,
defaultRecordPageHolderKey,
describeDefaultRecordPageHolder,
type DefaultRecordPageHolder,
} from './default-record-page.js';
import { defaultRecordPageObject, misplacedDefaultPageRefusal } from '@objectstack/spec/ui';
// [#14553] The ONE resolution of "does this nav group id exist?" and the ONE
// wording of the diagnostic when it does not. `os build` calls the same two
// (`checkNavContributionGroups`), so the compile-time door and this read-time
// fold cannot disagree about what a missing group is — the drift that would
// make the build's silence indistinguishable from the silence being fixed.
import {
findNavGroup as resolveNavGroup,
navContributionGroupDiagnostic,
formatNavContributionGroupDiagnostic,
type NavContributionGroupDiagnostic,
} from './nav-contribution-diagnostics.js';
// The shared-picklist judgments (merge, served shape, unknown-name refusal) —
// pure, so the registry and the engine plugin's load-time audit read one
// spelling of each. See the module header.
import {
collectPicklistReferences,
duplicatePicklistValueError,
findDuplicatePicklistValue,
mergePicklistOptions,
resolvePicklistFieldsOnto,
type PicklistContribution,
type PicklistOptionLike,
type PicklistReference,
} from './picklist-resolution.js';
import { standaloneActionOwnerKey, isObjectLessActionKey } from './action-governance.js';
import { recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js';
/**
* [#24400] A bound top-level action whose target object no package has
* registered — see {@link SchemaRegistry.findUnboundActionTargets}.
*/
export interface UnboundActionTarget {
/** The action's `name`. */
action: string;
/** The object its `objectName` names. */
objectName: string;
/** The package that ships the action. */
packageId: string | undefined;
}
/** The boot refusal's error: the `INVALID_METADATA` envelope (ADR-0112) the picklist refusal also answers. */
export interface UnboundActionTargetError extends Error {
code: 'INVALID_METADATA';
status: 422;
httpStatus: 422;
}
/**
* [#24400] The refusal for bound top-level actions whose target object no
* loaded package registers — every one of them, so an author fixes the set in
* one pass. `undefined` when there are none.
*
* Refused rather than dropped: such an action registers, is listed on no
* object, and no client renders it — the silent drop the extension guidance
* would otherwise lead an author into.
*/
export function describeUnboundActionTargets(
unbound: readonly UnboundActionTarget[],
): UnboundActionTargetError | undefined {
if (unbound.length === 0) return undefined;
const lines = unbound.map(
(u) => `action '${u.action}' (${u.packageId ? `package '${u.packageId}'` : 'a registration with no package'}) `
+ `is bound to object '${u.objectName}'`,
);
const err = new Error(
`${lines.length === 1 ? 'A top-level action is' : `${lines.length} top-level actions are`} bound by `
+ `\`objectName\` to an object that no loaded package registers: ${lines.join('; ')}. A bound action `
+ 'is attached to its object when the object is served, so with no such object it would be listed '
+ 'nowhere. Register the object (in the package or in one it depends on), or correct the '
+ '`objectName`.',
) as UnboundActionTargetError;
err.code = 'INVALID_METADATA';
err.status = 422;
err.httpStatus = 422;
return err;
}
/**
* [#25649] The refusal of a code package's `action` that does not satisfy
* `ActionSchema` — the `INVALID_METADATA` envelope (ADR-0112) the unbound-target
* refusal above answers, with `issues[]` locating each failure.
*/
interface PackageActionSchemaError extends Error {
code: 'INVALID_METADATA';
status: 422;
httpStatus: 422;
issues: Array<{ path: string; message: string; code: string }>;
}
/**
* [#25649] A code package's `action` item, as its `ActionSchema` parse — the
* body {@link SchemaRegistry.registerItem} stores — or the loud refusal of one
* that does not parse.
*
* Why the stored item has to BE the parse: `ActionSchema` is not only a judge,
* it is a producer. Its transform lowers `requiresMembershipReach` and
* `requiresFeature` into the CEL `visible` predicate and deletes the two keys,
* and nothing downstream reads either key raw — so an action stored as authored
* carries both gates declared and inert. A platform object's actions are parsed
* where they are authored (`ObjectSchema.create`), and a strict `defineStack`
* parses a stack's actions; a programmatic `registerApp`, a nested plugin's
* manifest, a `strict: false` stack or a raw plugin manifest reached this store
* with no parse at all, and {@link SchemaRegistry.attachBoundActions} served
* what it found. Parsing at this seam, once, means every reader — the bound
* attachment, the router's rung 2, `GET /meta/action` — holds the one parsed
* body, by reference.
*
* The parse is idempotent over its own output (a lowered action carries no
* `requiresFeature` left to lower), so an action a strict `defineStack` already
* parsed is stored deep-equal to what it arrived as. Besides the lowering, the
* parse fills the schema's defaults (`type`, `refreshAfter`, …), turns a
* CEL-string shorthand into its `{ dialect, source }` envelope, and refuses an
* undeclared key; the ADR-0010 envelope (`_packageId`, `_packageVersion`,
* `_provenance`, `_lock`) is declared on the schema and passes through.
*
* Refused rather than stored unparsed: an action that fails the parse would be
* served with whatever gates it declares never taking effect, and `defineStack`
* and `os validate` refuse the same declaration at authoring time.
*
* [#25744] The one parse for both places a code package declares an action:
* a standalone `action` item ({@link SchemaRegistry.registerItem}) and an
* object's own `actions` ({@link parsePackageObjectActions}, called by
* {@link SchemaRegistry.registerObject}). `owner` names the object an own
* action is declared on, so the refusal says which object and `issues[]`
* locates each failure inside its body.
*/
function parsePackageAction(
item: unknown,
name: string,
packageId: string,
owner?: { object: string; index: number },
): unknown {
const parsed = ActionSchema.safeParse(item);
if (parsed.success) return parsed.data;
// [#25744] An object's own action is located inside the object body it was
// declared in (`actions.<index>.<key>`), the path `ObjectSchema` reports.
const prefix = owner ? ['actions', String(owner.index)] : [];
const issues = parsed.error.issues.map((issue) => ({
path: [...prefix, ...issue.path.map(String)].join('.'),
message: issue.message,
code: issue.code,
}));
const subject = owner
? `Action '${name}' of object '${owner.object}' in package '${packageId}'`
: `Action '${name}' of package '${packageId}'`;
const err = new Error(
`${subject} does not satisfy the action contract (ActionSchema): `
+ issues.map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)).join('; ')
+ '. Every action a package ships is stored as its schema parse — the parse that lowers '
+ '`requiresFeature` and `requiresMembershipReach` into `visible` — so an action that does not parse '
+ 'is refused rather than served with its declared gates inert. Correct the declaration; `defineStack` '
+ 'and `os validate` report the same issues.',
) as PackageActionSchemaError;
err.code = 'INVALID_METADATA';
err.status = 422;
err.httpStatus = 422;
err.issues = issues;
throw err;
}
/**
* [#25744] A code package's object, its own `actions` stored as their
* `ActionSchema` parse ({@link parsePackageAction}) — or the loud refusal of
* the first one that does not parse.
*
* The object-path twin of {@link SchemaRegistry.registerItem}'s action parse.
* `ObjectSchema`'s `actions` is `ActionSchema[]`, so a platform object
* (`ObjectSchema.create`) and a strict `defineStack` already hand this method
* parsed actions, and the parse being idempotent over its own output stores
* them deep-equal to what arrived. A raw manifest, a `strict: false` stack or a
* programmatic `registerApp` reached the store with its objects' actions as
* written, so a declared `requiresFeature` / `requiresMembershipReach` was
* served raw, never lowered into `visible`.
*
* Returns `schema` by reference when it declares no `actions` array, and a
* shallow copy carrying the parsed array otherwise: the caller's body is
* never mutated.
*/
function parsePackageObjectActions(schema: ServiceObject, packageId: string): ServiceObject {
const actions = (schema as { actions?: unknown }).actions;
if (!Array.isArray(actions) || actions.length === 0) return schema;
const parsed = actions.map((action, index) => {
const declared = (action as { name?: unknown } | null | undefined)?.name;
const name = typeof declared === 'string' && declared !== '' ? declared : `#${index}`;
return parsePackageAction(action, name, packageId, { object: schema.name, index });
});
return { ...schema, actions: parsed } as ServiceObject;
}
/**
* [#24472] The key {@link SchemaRegistry}'s bound-action collision audit is
* carried under. A symbol, and ⛔ deliberately NOT re-exported from the package
* entry (`index.ts`, `core.ts`), so the audit is no NAMEABLE member of the
* registry's published face: only the ObjectQL plugin's boot and late-artifact
* reports reach it, importing the key from this module.
*/
export const FIND_BOUND_ACTION_COLLISIONS: unique symbol = Symbol('objectstack.objectql.findBoundActionCollisions');
/**
* [#24472] A bound top-level action that its target object does NOT list,
* because the object already lists a DIFFERENT declaration under the same
* name — see {@link FIND_BOUND_ACTION_COLLISIONS}.
*/
export interface BoundActionCollision {
/** The object both declarations are for. */
objectName: string;
/** The action name they share. */
action: string;
/** The package whose declaration the object serves — its owner, for the object's own action. */
servedPackageId: string | undefined;
/** The package whose bound declaration the object does not list. */
shadowedPackageId: string | undefined;
}
const describePackage = (packageId: string | undefined): string =>
packageId ? `package '${packageId}'` : 'a registration with no package';
/**
* [#24472] The author-visible warning for one {@link BoundActionCollision}.
* Reported, never refused: a refusal would be a narrowing, and the decision
* for this collision is to report it first.
*/
export function describeBoundActionCollision(collision: BoundActionCollision): string {
const { objectName, action, servedPackageId, shadowedPackageId } = collision;
return `Action '${action}' on object '${objectName}' is declared twice, and the two declarations differ: `
+ `${describePackage(servedPackageId)} declares the one the object serves, and `
+ `${describePackage(shadowedPackageId)} binds another by \`objectName\`, which the object does not list. `
+ `Both register their handler under the one key '${objectName}:${action}', so when both carry one, the `
+ 'handler that runs is whichever package registered last — not necessarily the declaration the object '
+ 'lists. Rename one of the two actions, or drop the duplicate declaration.';
}
/**
* Keys that say where an action declaration came from or where it sits, not
* what it declares: the registry's stamps (`_packageId`, `_provenance`, the
* `_lock` envelope…), the `protection` block those stamps translate, and
* `objectName`, which an object's own action leaves to its position.
*/
const isActionProvenanceKey = (key: string): boolean =>
key.startsWith('_') || key === 'protection' || key === 'objectName';
/**
* [#24472] Are two action declarations the SAME declaration — one carried
* twice (a same-stack merge's copy beside the top-level item, one declaration
* shipped by two packages, a copy re-bridged under another package's stamp)?
* Structural equality minus {@link isActionProvenanceKey} keys at the top
* level; a key set to `undefined` reads as absent, callables compare by
* reference, and past depth 32 the answer is "different" — the reported side.
*/
function sameActionDeclaration(a: unknown, b: unknown, depth = 0): boolean {
if (Object.is(a, b)) return true;
if (depth >= 32 || typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
if (Array.isArray(a)) {
const other = b as unknown[];
return a.length === other.length && a.every((item, i) => sameActionDeclaration(item, other[i], depth + 1));
}
const left = a as Record<string, unknown>;
const right = b as Record<string, unknown>;
const keysOf = (o: Record<string, unknown>) =>
Object.keys(o).filter((k) => o[k] !== undefined && (depth > 0 || !isActionProvenanceKey(k)));
const leftKeys = keysOf(left);
return leftKeys.length === keysOf(right).length
&& leftKeys.every((k) => right[k] !== undefined && sameActionDeclaration(left[k], right[k], depth + 1));
}
/** A manifest and its nested `plugins[]`, which register under its package (`registerPlugin`). */
function manifestAndNestedPlugins(manifest: any): any[] {
const plugins = Array.isArray(manifest?.plugins)
? manifest.plugins.filter((p: unknown) => p !== null && typeof p === 'object')
: [];
return [manifest, ...plugins];
}
/**
* [#24400] The bound top-level actions one manifest brings — its own
* `actions` and its nested plugins', each with the object it is bound to —
* read BEFORE the manifest registers, by the post-boot install door.
*/
export function collectManifestBoundActions(manifest: any, packageId: string | undefined): UnboundActionTarget[] {
const out: UnboundActionTarget[] = [];
for (const source of manifestAndNestedPlugins(manifest)) {
for (const action of Array.isArray(source?.actions) ? source.actions : []) {
if (!action || typeof action !== 'object' || typeof action.name !== 'string') continue;
const objectName = standaloneActionOwnerKey(action);
if (isObjectLessActionKey(objectName)) continue;
out.push({ action: action.name, objectName, packageId });
}
}
return out;
}
/** [#24400] The object names one manifest declares, nested plugins included, in either authored spelling. */
export function collectManifestObjectNames(manifest: any): string[] {
const names: string[] = [];
for (const source of manifestAndNestedPlugins(manifest)) {
const objects = source?.objects;
if (Array.isArray(objects)) {
for (const o of objects) if (typeof o?.name === 'string') names.push(o.name);
} else if (objects && typeof objects === 'object') {
names.push(...Object.keys(objects));
}
}
return names;
}
/**
* Stable sort by `order` (unset reads as `0`), by reference when no action
* sets one — the rule `defineStack()` applies to each object's merged actions
* (`sortActionsByOrder` in `@objectstack/spec`'s stack builder, which is
* internal there), applied here to the attached actions among themselves.
*/
function sortActionsByOrder<T extends { order?: number }>(actions: T[]): T[] {
if (!actions.some((a) => a?.order !== undefined)) return actions;
return actions.slice().sort((a, b) => (a?.order ?? 0) - (b?.order ?? 0));
}
/**
* Reserved namespaces that do not get FQN prefix applied.
* Objects in these namespaces keep their short names (e.g., "user" — short name IS the canonical key).
*/
export const RESERVED_NAMESPACES = new Set(['base', 'system']);
/**
* Default priorities for the three contributor kinds.
*
* [ADR-0029 D9.3] `DEFAULT_OVERLAY_PRIORITY` sits BETWEEN the owner and the
* extenders so a `getObjectContributors()` read lists the stack in layer
* order. It is ORDERING ONLY: {@link SchemaRegistry.resolveObject} selects its
* base layer by KIND, never by "highest priority wins" — extender priority is
* author-declared (`ext.priority ?? 200` in the `objectExtensions` loop), so a
* package could otherwise re-rank a tenant's overlay out of the base slot by
* declaring `priority: 140`. Declared numbers order PEERS; they must not be
* able to change WHICH LAYER IS THE BASE.
*/
export const DEFAULT_OWNER_PRIORITY = 100;
export const DEFAULT_OVERLAY_PRIORITY = 150;
export const DEFAULT_EXTENDER_PRIORITY = 200;
/**
* Contributor Record
* Tracks how a package contributes to an object.
*
* Three kinds (ADR-0029 D9):
*
* - `own` — the single owning package. Defines the base schema, the table and
* the namespace claim. Exactly one per object name, unconditionally
* ({@link SchemaRegistry.assertSingleOwnerPerObject}).
* - `overlay` — [D9.1] a TENANT customization layer over the owner's
* definition, hydrated from a `sys_metadata` row. It REPLACES the base layer
* at resolution time (D9.2) and owns nothing: it claims no namespace,
* decides no package membership, holds no table. That is why the
* single-owner assertion needs no "unless it is an overlay" clause — which
* matters beyond tidiness, since ADR-0028 D5/D6 rest on that sentence being
* unconditional. `ownership: 'overlay'` is LOADER-SET at the hydration seams
* and reachable from no authoring surface.
* - `extend` — additive contributions from other packages, folded on top of
* whichever layer is the base.
*/
export interface ObjectContributor {
// Optional (#12623): `registerObject`'s own `packageId` parameter is now
// optional, and this is the exact value it was called with — a bare
// `registerObject(schema)` call stores `undefined` here, matching the
// runtime behavior every call site without a tsc test-layer gate already
// exercised (JS does not enforce TS arity).
packageId: string | undefined;
namespace: string;
ownership: ObjectOwnership;
priority: number;
definition: ServiceObject;
}
/**
* Compute canonical registry key for an object.
*
* Under the current naming convention, object names are canonical identifiers
* and are used as-is (no namespace__ prefix). The namespace parameter is
* retained for backward compatibility but no longer affects the returned key.
*
* @param namespace - The package namespace (unused, kept for API compatibility)
* @param shortName - The object's name (already the canonical identifier)
* @returns The object name unchanged
*
* @example
* computeFQN('crm', 'account') // => 'account'
* computeFQN(undefined, 'task') // => 'task'
*/
export function computeFQN(_namespace: string | undefined, shortName: string): string {
return shortName;
}
/**
* Parse FQN back to namespace and short name.
*
* @param fqn - Object name (e.g., "account" or legacy "crm__account" for backward compat)
* @returns { namespace, shortName } - namespace is undefined for unprefixed names
*/
export function parseFQN(fqn: string): { namespace: string | undefined; shortName: string } {
const idx = fqn.indexOf('__');
if (idx === -1) {
return { namespace: undefined, shortName: fqn };
}
return {
namespace: fqn.slice(0, idx),
shortName: fqn.slice(idx + 2),
};
}
/**
* The three SCALAR props {@link mergeObjectDefinitions} resolves last-writer-wins
* — the exact set the #8284 ruling and ADR-0029 D9.2a both cover, and the same three
* {@link scalarOverridesPackagedBase} answers for.
*/
const OBJECT_FOLD_SCALAR_KEYS = ['label', 'pluralLabel', 'description'] as const;
type ObjectFoldScalarKey = (typeof OBJECT_FOLD_SCALAR_KEYS)[number];
/**
* [ADR-0146 D10, second rule] An object extension's per-field display patches:
* the slot `ObjectExtensionSchema.fieldPatches` declares, carried onto the
* extension def by the manifest loop (`engine.ts`) and applied by
* {@link mergeObjectDefinitions}. ⛔ No second shape: the type IS the spec's,
* and the keys applied are read from `BASE_FIELD_DISPLAY_WHITELIST`, so a
* widened whitelist widens what the merge applies too.
*/
type ObjectFieldPatches = NonNullable<ObjectExtensionParsed['fieldPatches']>;
/** An `extend` contributor's body: a partial object that may carry {@link ObjectFieldPatches}. */
type ObjectExtensionBody = Partial<ServiceObject> & { fieldPatches?: ObjectFieldPatches };
/** [#28835] One extension's `fields` as the fold merged them, with the package that declared them. */
type FoldedExtensionFields = { packageId: string | undefined; fields: unknown };
const isPlainRecord = (v: unknown): v is Record<string, unknown> =>
v !== null && typeof v === 'object' && !Array.isArray(v);
/**
* The address of one patched display key in a fold's D9.2a yield set
* ({@link SchemaRegistry.tenantPatchedDisplayKeys}): a field key, or one key of
* the option addressed by its stored value.
*/
function fieldPatchYieldKey(field: string, key: string, option?: string): string {
return option === undefined ? `${field}\u0000${key}` : `${field}\u0000options\u0000${option}\u0000${key}`;
}
/** A field of an object body's name-keyed `fields`, when it is a record. */
function recordFieldOf(body: unknown, name: string): Record<string, unknown> | undefined {
const fields = isPlainRecord(body) ? body.fields : undefined;
if (!isPlainRecord(fields) || !Object.prototype.hasOwnProperty.call(fields, name)) return undefined;
const field = fields[name];
return isPlainRecord(field) ? field : undefined;
}
/**
* [ADR-0146 D10, second rule] The fields a field patch reaches: the names the
* `own` contributor's declaration carries in the name-keyed `fields` the merge
* reads — "the target object's own fields", as `ObjectExtensionSchema.fieldPatches`
* publishes it. A field an extension adds is never one of them, whatever the
* priorities, and neither is an array-spelled entry: the merge, the patch and
* the miss report all read the record spelling, so they cannot disagree.
* The declaration is the one the registry stores, so the platform columns
* {@link applySystemFields} injects at registration (`created_at` and the
* rest) are among these names: the fold and the install door
* (`getObjectOwner`) admit a patch of one, while `os validate`, which judges
* the authored declaration, refuses it.
* `undefined` when no owner is registered — no opinion, as
* {@link SchemaRegistry.tenantPatchedDisplayKeys} has none there either.
*/
function ownFieldNamesOf(owner: unknown): ReadonlySet<string> | undefined {
if (owner === undefined) return undefined;
const fields = isPlainRecord(owner) ? owner.fields : undefined;
return new Set(isPlainRecord(fields) ? Object.keys(fields).filter((name) => isPlainRecord(fields[name])) : []);
}
/**
* [ADR-0146 D10, second rule; #28809] What a field patch is judged against in
* the fold: the owner's declaration (`owner`) with only the fields of
* `ownFields` the fold carries at that point in the record spelling
* (`carried`) — which fields a patch reaches is the owner's own, unchanged —
* each field AS THE OWNER DECLARES IT, never as an extension's `fields`
* redeclared it. The install door (`getObjectOwner(name).definition`) and
* `os validate` (the declared object) cannot see another package's extension,
* so the owner's own field and options are the one answer all three readers
* share: an option an extension adds by taking the field over through `fields`
* is not one a patch can name.
*/
function ownFieldsTarget(
owner: unknown,
ownFields: ReadonlySet<string>,
carried: (name: string) => boolean,
): Record<string, unknown> {
const fields: Record<string, unknown> = {};
for (const name of ownFields) {
const field = recordFieldOf(owner, name);
if (field && carried(name)) fields[name] = field;
}
return { ...(isPlainRecord(owner) ? owner : {}), fields };
}
/** The option of a field's own `options` whose stored `value` is `value`. */
function optionByValue(field: Record<string, unknown>, value: string): Record<string, unknown> | undefined {
const options = field.options;
if (!Array.isArray(options)) return undefined;
const found = options.find((o) => isPlainRecord(o) && o.value === value);
return isPlainRecord(found) ? found : undefined;
}
/**
* [ADR-0029 D9.2a] The scalar yield's comparison, asked of one display key of a
* field or of one of its options. It IS {@link scalarOverridesPackagedBase} —
* the one comparison behind every D9.2a yield, keyed by any attribute (its own
* docblock: the exported key union names the keys its callers ask about, and
* the implementation underneath reads any) — ⛔ never a second copy of it.
*/
function displayKeyOverridesPackagedBase(packaged: unknown, key: string, value: unknown): boolean {
return scalarOverridesPackagedBase(packaged, key as Parameters<typeof scalarOverridesPackagedBase>[1], value);
}
/**
* [ADR-0146 D10, second rule] One base field with an extension's patch applied:
* the whitelisted field keys, then each option the patch addresses by its
* stored `value`. A key the tenant authored on the fold's base yields
* (`tenantPatched`, ADR-0029 D9.2a). Returns `field` BY REFERENCE when nothing
* applies.
*
* A field bound to a picklist is left alone under `options`: the served options
* are the picklist's, written over the field after the fold
* ({@link SchemaRegistry.finishServedObject}), so an option label written here
* would never be served. The target check names that patch instead.
*/
function patchedField(
name: string,
field: Record<string, unknown>,
patch: ObjectFieldPatches[string],
tenantPatched: ReadonlySet<string> | undefined,
): Record<string, unknown> {
let next: Record<string, unknown> | undefined;
const patchKeys = patch as Record<string, unknown>;
for (const key of BASE_FIELD_DISPLAY_WHITELIST.field) {
const value = patchKeys[key];
if (value === undefined || tenantPatched?.has(fieldPatchYieldKey(name, key))) continue;
(next ??= { ...field })[key] = value;
}
const optionPatches = patch.options;
const options = field.options;
const picklistBound = typeof field.picklist === 'string' && field.picklist !== '';
if (optionPatches && Array.isArray(options) && !picklistBound) {
let patchedOptions: unknown[] | undefined;
options.forEach((option, index) => {
if (!isPlainRecord(option) || typeof option.value !== 'string') return;
if (!Object.prototype.hasOwnProperty.call(optionPatches, option.value)) return;
const optionPatch = optionPatches[option.value] as Record<string, unknown> | undefined;
if (!optionPatch) return;
let patchedOption: Record<string, unknown> | undefined;
for (const key of BASE_FIELD_DISPLAY_WHITELIST.option) {
const value = optionPatch[key];
if (value === undefined || tenantPatched?.has(fieldPatchYieldKey(name, key, option.value))) continue;
(patchedOption ??= { ...option })[key] = value;
}
if (patchedOption) (patchedOptions ??= [...options])[index] = patchedOption;
});
if (patchedOptions) (next ??= { ...field }).options = patchedOptions;
}
return next ?? field;
}
/**
* [ADR-0146 D10, second rule] `fields` with every patch of `patches` applied
* that names one of the owner's own fields (`ownFields`, {@link ownFieldNamesOf})
* present in `fields`. A patch naming any other field — one the object lacks,
* or one only an extension adds — is skipped here, and named by the fold
* ({@link SchemaRegistry.reportFieldPatchMisses}). Nothing applies when no
* owner is registered. Returns `fields` BY REFERENCE when nothing applies.
*
* [#28809] The fold hands this only the patches the judge admitted against the
* owner's declaration ({@link admittedFieldPatches}). An admitted option patch
* whose option an earlier layer left out (an extension's `fields`
* redeclaration, a tenant overlay base) finds no option here, so nothing of it
* applies; the fold names it after the merge, by the same judge asked of the
* merged fields.
*/
function applyFieldPatches(
fields: ServiceObject['fields'],
patches: ObjectFieldPatches,
tenantPatched: ReadonlySet<string> | undefined,
ownFields: ReadonlySet<string> | undefined,
): ServiceObject['fields'] {
if (!isPlainRecord(fields) || !ownFields) return fields;
let out: Record<string, unknown> | undefined;
for (const [name, patch] of Object.entries(patches)) {
if (!patch || !ownFields.has(name)) continue;
const field = recordFieldOf({ fields: out ?? fields }, name);
if (!field) continue;
const next = patchedField(name, field, patch, tenantPatched);
if (next !== field) (out ??= { ...fields })[name] = next;
}
return (out ?? fields) as ServiceObject['fields'];
}
/**
* [ADR-0146 D10, second rule; #28809] `patches` without what the judge missed
* against the owner's declaration: a missed field's whole patch, a missed
* option's entry under `options`. The fold applies exactly what the install
* door and `os validate` admit, and names exactly what they refuse. Returns
* `patches` BY REFERENCE when nothing was missed.
*/
function admittedFieldPatches(
patches: ObjectFieldPatches,
misses: readonly FieldPatchTargetMiss[],
): ObjectFieldPatches {
if (misses.length === 0) return patches;
const out: Record<string, ObjectFieldPatches[string]> = { ...patches };
for (const miss of misses) {
const patch = out[miss.field];
if (!patch) continue;
if (miss.option === undefined) {
delete out[miss.field];
continue;
}
if (!patch.options) continue;
const { [miss.option]: _missed, ...options } = patch.options;
out[miss.field] = { ...patch, options };
}
return out as ObjectFieldPatches;
}
/**
* [#28356] Which layer an object fold serves: `'served'`, what every read
* answers (the bound actions the registry serves, runtime-authored included),
* or `'code'`, the code-layer resolution {@link SchemaRegistry.getArtifactItem}
* answers (the code packages' bound actions alone).
*/
type ServedObjectLayer = 'served' | 'code';
/**
* Deep merge two ServiceObject definitions.
*
* The merge set is CLOSED and enumerable — this is NOT "every prop, later
* value wins":
* - `fields` and `indexes` are merged ADDITIVELY (`fields` keyed by name).
* - `validations` are merged BY NAME ({@link mergeValidationsByName},
* [ADR-0029 D9.2a, 2026-10-30 note]): rules of different names add, and a
* rule of a name already folded replaces it — with `tenantRules`, carrying
* the tenant's `message` and `active`, never the tenant's condition.
* - The three {@link OBJECT_FOLD_SCALAR_KEYS} (`label`, `pluralLabel`,
* `description`) are overridden last-writer-wins, subject to the
* `tenantAuthored` yield rule below.
* - `fieldPatches` [ADR-0146 D10, second rule] is APPLIED, never carried:
* after the merges above, each patch writes its `BASE_FIELD_DISPLAY_WHITELIST`
* keys onto the named field and its option labels onto the options whose
* stored `value` it names, each key yielding where `tenantPatched` says the
* tenant authored it — the same D9.2a rule as the scalars. A patch reaches
* the owner's own fields only (`ownFields`): one naming any other field,
* a field an extension adds included, is skipped here; the fold names it.
*
* **Every other top-level prop on `extension` is silently discarded.**
* `merged` starts as `{ ...base }` and nothing outside the list above is ever
* copied onto it — a caller that hands this function an extension body
* carrying an undeclared key, e.g. `tenancy: { enabled: false }`, gets a
* valid-but-inert no-op HERE: no error, no warning from this function, the
* base's existing value simply wins as if the extension had never named the
* key (issue #12680).
*
* Declarative authors never reach that silence, though: `ObjectExtensionSchema`
* (`packages/spec/src/data/object.zod.ts`) is `.strict()` — its shape is
* exactly `extend` / `fields` / `fieldPatches` / `label` / `pluralLabel` /
* `description` / `validations` / `indexes` / `priority`, so an `objectExtensions` entry
* naming `tenancy`, `permissions`, or any other key outside that list fails
* LOUDLY at authoring time with a prescription (#4001; the same rule is
* documented at `content/docs/data-modeling/object-extensions.mdx`). This
* function's discard is reachable only by a caller that bypasses that
* schema — a direct, programmatic `registry.registerObject(def, pkg,
* undefined, 'extend', …)` call, which is how this package's own pin
* (`registry-object-extension-nonenumerated-prop-discard.test.ts`) exercises
* the rule. Extender-writable `tenancy`/`permissions` would in any case be a
* separate, much bigger decision that has NOT been made.
*
* Unlike `tenancy`/`permissions`, this one is not blocked by schema:
* `_provenance` is a real top-level prop an `extend` contributor carries
* TODAY. Copying it through (as "later value
* wins" would) lets a third-party extender flip a tenant-authored object's
* `_provenance` to the extending package's — reaching, by a different route,
* the exact outcome ADR-0029 D9.3's priority-reranking guard exists to
* prevent. `registry-object-overlay-layer.test.ts` ("an extender declaring
* priority 140 does not become the base layer") fails if this merge set is
* widened to copy it through.
*
* [ADR-0029 D9.2a] …the SCALAR override above is conditional. `tenantAuthored` names
* the scalars the fold's BASE has authored away from the packaged owner's
* value; an extender yields on those. See
* {@link SchemaRegistry.tenantAuthoredScalars} for why the set is computed once
* over the base rather than re-derived from the running `merged`; `tenantRules`
* ({@link SchemaRegistry.tenantRuleSettings}) is computed once for the same reason.
*/
function mergeObjectDefinitions(
base: ServiceObject,
extension: ObjectExtensionBody,
tenantAuthored?: ReadonlySet<ObjectFoldScalarKey>,
tenantRules?: ReadonlyMap<string, TenantRuleSettings>,
tenantPatched?: ReadonlySet<string>,
ownFields?: ReadonlySet<string>,
): ServiceObject {
const merged = { ...base };
// Merge fields additively
if (extension.fields) {
merged.fields = { ...base.fields, ...extension.fields };
}
// [ADR-0029 D9.2a, 2026-10-30 note] Merge validations by name
if (extension.validations) {
merged.validations = mergeValidationsByName(
base.validations,
extension.validations,
tenantRules,
) as ServiceObject['validations'];
}
// Merge indexes additively
if (extension.indexes) {
merged.indexes = [...(base.indexes || []), ...extension.indexes];
}
// Override scalar props (last writer wins) — [ADR-0029 D9.2a] unless the base has been
// authored by the tenant, in which case the extender's packaged default yields.
const yields = (key: ObjectFoldScalarKey): boolean => tenantAuthored?.has(key) === true;
if (extension.label !== undefined && !yields('label')) merged.label = extension.label;
if (extension.pluralLabel !== undefined && !yields('pluralLabel')) {
merged.pluralLabel = extension.pluralLabel;
}
if (extension.description !== undefined && !yields('description')) {
merged.description = extension.description;
}
// [ADR-0146 D10, second rule] The extension's display patches of the
// owner's own fields (`ownFields`) — never of a field an extension adds,
// whatever the priorities, or the answer would depend on which extender the
// fold reached first — applied AFTER the additive merges, with each key
// yielding where the tenant authored it (`tenantPatched`, ADR-0029 D9.2a),
// as the scalars above yield. Two extenders patching one key resolve as the
// scalars do: the fold applies contributors in ascending `priority`, so the
// higher one is written last.
if (extension.fieldPatches) {
merged.fields = applyFieldPatches(merged.fields, extension.fieldPatches, tenantPatched, ownFields);
}
return merged;
}
/**
* [#8027] Key-order-insensitive JSON, for comparing two `indexes` entries, or
* two validation rules' keys, BY VALUE — see
* {@link SchemaRegistry.subtractExtenderContributions} and
* {@link changedPackagedRuleKeys}.
*
* Plain `JSON.stringify` would report the same rule as two different rules
* whenever the two copies were built by different code paths (a stored overlay
* row that went through `JSON.parse` vs the contributor's in-memory literal),
* which is exactly the pair being compared, so key order cannot be assumed.
* Arrays keep their order — an index's `fields` list is ordered and two
* spellings of it are genuinely two different indexes.
*/
function stableStringify(value: unknown): string {
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`;
}
/**
* [ADR-0029 D9.2a, 2026-10-30 note] What a tenant's same-named copy of a
* packaged validation rule may set: its sentence and its switch. Every other key
* a rule carries — `type`, `condition` and each variant's own predicate keys,
* `events`, `severity`, `priority`, and the editor keys — is the package's.
*/
type TenantRuleSettings = { message?: string; active?: boolean };
/** A rule's `name` when it has one; a rule without a string name has no identity to merge by and is always additive. */
function validationRuleName(rule: unknown): string | undefined {
const name = (rule as { name?: unknown } | null | undefined)?.name;
return typeof name === 'string' && name !== '' ? name : undefined;
}
/**
* The tenant settings a base layer's rules carry, keyed by rule name — the
* first copy of a name wins, so a stored row that predates the by-name fold
* (the tenant's reworded copy, then the extension's original appended after
* it) still answers with the tenant's sentence.
*/
function tenantRuleSettingsOf(rules: unknown): Map<string, TenantRuleSettings> {
const out = new Map<string, TenantRuleSettings>();
if (!Array.isArray(rules)) return out;
for (const rule of rules) {
const name = validationRuleName(rule);
if (name === undefined || out.has(name)) continue;
const { message, active } = rule as { message?: unknown; active?: unknown };
out.set(name, {
...(typeof message === 'string' ? { message } : {}),
...(typeof active === 'boolean' ? { active } : {}),
});
}
return out;
}
/** The packaged rule, carrying the tenant's sentence and switch where the tenant's copy sets them. */
function withTenantRuleSettings<R>(packaged: R, settings: TenantRuleSettings | undefined): R {
if (!settings || (settings.message === undefined && settings.active === undefined)) return packaged;
return { ...packaged, ...settings };
}
/**
* [ADR-0029 D9.2a, 2026-10-30 note] Merge `validations` BY NAME, the way
* `fields` merge by key: a later layer's rule replaces every earlier rule of its
* name and is appended in fold order, and a rule of a new name is added. With
* `tenantRules` (the fold's base is a tenant overlay), the rule carries the
* tenant's `message` and `active` for its name; its condition stays the
* later layer's.
*/
function mergeValidationsByName(
base: readonly unknown[] | undefined,
extension: readonly unknown[],
tenantRules: ReadonlyMap<string, TenantRuleSettings> | undefined,
): unknown[] {
const names = new Set<string>();
for (const rule of extension) {
const name = validationRuleName(rule);
if (name !== undefined) names.add(name);
}
const kept = (base ?? []).filter((rule) => {
const name = validationRuleName(rule);
return name === undefined || !names.has(name);
});
const added = extension.map((rule) => {
const name = validationRuleName(rule);
return name === undefined ? rule : withTenantRuleSettings(rule, tenantRules?.get(name));
});
return [...kept, ...added];
}
/** The value a rule's key has when the rule leaves it out — `BASE_VALIDATION_SHAPE`'s defaults. */
const VALIDATION_RULE_DEFAULTS: Readonly<Record<string, unknown>> = {
events: ['insert', 'update'],
priority: 100,
severity: 'error',
};
/**
* The keys on which a tenant's copy of a packaged rule differs from the
* package's, beyond the two it may set (`message`, `active`) and the loader's
* `_`-prefixed stamps. A key a rule leaves out is read at its schema default,
* so a stored copy whose parse stamped the defaults is not a change. Empty when
* the copy changes nothing but its sentence and its switch.
*/
function changedPackagedRuleKeys(copy: unknown, packaged: unknown): string[] {
const enforced = (rule: unknown): Record<string, unknown> => {
const out: Record<string, unknown> = { ...VALIDATION_RULE_DEFAULTS };
for (const [key, value] of Object.entries((rule ?? {}) as Record<string, unknown>)) {
if (key === 'message' || key === 'active' || key.startsWith('_') || value === undefined) continue;
out[key] = value;
}
return out;
};
const a = enforced(copy);
const b = enforced(packaged);
return [...new Set([...Object.keys(a), ...Object.keys(b)])]
.filter((key) => stableStringify(a[key]) !== stableStringify(b[key]))
.sort((x, y) => (x === 'type' ? -1 : y === 'type' ? 1 : x < y ? -1 : x > y ? 1 : 0));
}
/**
* Global Schema Registry
* Unified storage for all metadata types (Objects, Apps, Flows, Layouts, etc.)
*
* ## Namespace & Ownership Model
*
* Objects use a namespace-based FQN system:
* - `namespace`: Short identifier from package manifest (e.g., "crm", "todo")
* - `name`: canonical object name (e.g., "account", "sys_user")
* - Reserved namespaces (`base`, `system`) don't get prefixed
*
* Ownership modes:
* - `own`: One package owns the object (creates the table, defines base schema)
* - `extend`: Multiple packages can extend an object (add fields, merge by priority)
*
* ## Package vs App Distinction
* - **Package**: The unit of installation, stored under type 'package'.
* Each InstalledPackage wraps a ManifestSchema with lifecycle state.
* - **App**: A UI navigation shell (AppSchema), registered under type 'apps'.
* Apps are extracted from packages during registration.
* - A package may contain 0, 1, or many apps.
*/
export type RegistryLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
/** All valid {@link RegistryLogLevel} values — used to validate `OS_REGISTRY_LOG`. */
export const REGISTRY_LOG_LEVELS: readonly RegistryLogLevel[] = [
'debug', 'info', 'warn', 'error', 'silent',
];
/**
* Construction options for {@link SchemaRegistry}.
*/
export interface SchemaRegistryOptions {
/**
* Whether the host kernel runs in multi-tenant mode. The `organization_id`
* column itself is auto-injected regardless of this flag (lookup →
* sys_organization, on every registered object that doesn't already declare
* it, isn't `managedBy` an external subsystem, and hasn't opted out via
* `systemFields`/`tenancy.enabled:false`). When `true` the injected column
* is additionally INDEXED — single-tenant stacks skip the index since
* nothing ever filters by organization.
*
* Sourced from the `OS_MULTI_ORG_ENABLED` env var when not explicitly set —
* matches how the SecurityPlugin and CLI startup banner pick the mode.