Repository navigation
Expand file tree
/
Copy pathplugin.ts
More file actions
3829 lines (3663 loc) · 194 KB
/
Copy pathplugin.ts
File metadata and controls
3829 lines (3663 loc) · 194 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 { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js';
import { assembleMetadataProtocol } from '@objectstack/metadata-protocol';
import { isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core';
import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol';
import { Plugin, PluginContext } from '@objectstack/core';
import { resolveArtifactPackageOrder, artifactPackageId, readDeploymentOrgScopingEntitlement } from '@objectstack/core';
// [ADR-0130 D4] The residual rule's decision half — which top-level items of a
// multi-package stack no body declares, and the id they take. See
// `unclaimedTopLevelObjects` below.
import { unclaimedTopLevel } from '@objectstack/metadata';
import { applyConversionsToStoredItem } from '@objectstack/spec';
import { StorageNameMapping } from '@objectstack/spec/system';
import { applyProtection } from '@objectstack/spec/shared';
// [#21777] The ONE "is this schema the remote's?" predicate, shared with `ObjectQL.syncSchemas`.
import { isFederatedObject } from './federated-object.js';
// [#22070] The builtin audit stamps are wrapped like a bound hook but registered in code.
import { wrapDeclarativeHook } from './hook-wrappers.js';
import { LifecycleService } from './lifecycle/lifecycle-service.js';
import { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js';
import type { DanglingReferenceAuditOptions } from './integrity/dangling-reference-audit.js';
import {
GLOBAL_ACTION_OBJECT_KEY,
runActionGovernanceInventory,
standaloneActionOwnerKey,
} from './action-governance.js';
// [ADR-0126 §8] The packaged-action activation ledger's durable store. The
// engine holds the projection; this plugin is what attaches the store and
// hydrates it once the deployment has finished registering objects.
import {
ObjectStoreActionActivationStore,
ACTION_ACTIVATION_TABLE,
type ActionActivationStoreEngine,
} from './action-activation.js';
import type { IMetadataService } from '@objectstack/spec/contracts';
import type { ServiceObject } from '@objectstack/spec/data';
import {
collectManifestPicklistExtensions,
collectManifestPicklistNames,
collectManifestPicklistReferences,
describeUnresolvedPicklistReferences,
} from './picklist-resolution.js';
// [ADR-0048 N.3] The security catalog's one-holder envelope, raised here by the
// cold-boot check (see `refuseEnvironmentHeldSecurityCatalogNames`).
import { SecurityCatalogNameConflictError, findEnvironmentHeldSecurityCatalogNames } from './registry.js';
// [ADR-0029 D3] The registry's own refusal of a second owner — read, never
// re-derived, when a residual object's name is already owned.
import { ObjectOwnershipConflictError, collectManifestBoundActions, collectManifestObjectNames, describeBoundActionCollision, describeUnboundActionTargets, FIND_BOUND_ACTION_COLLISIONS, type BoundActionCollision } from './registry.js';
export type { Plugin, PluginContext };
/**
* Protocol extension for DB-based metadata hydration.
* `loadMetaFromDb` is implemented by ObjectStackProtocolImplementation but
* is NOT (yet) part of the canonical ObjectStackProtocol wire-contract in
* `@objectstack/spec`, since it is a server-side bootstrap concern only.
*/
interface ProtocolWithDbRestore {
loadMetaFromDb(): Promise<{
loaded: number;
errors: number;
invalid?: number;
/**
* [#5897, ADR-0110 D3] True when the `sys_metadata` read itself failed for
* a reason that is NOT "the table has not been provisioned yet" — i.e. the
* row set never arrived, so `loaded: 0` is an outage rather than an empty
* store. `restoreMetadataFromDb` branches on it to tell the two apart.
*
* Optional, like `invalid` above and for the same reason: this interface is
* structural, matched by {@link hasLoadMetaFromDb} against whatever object
* happens to be registered as `protocol`. A shim that predates the field
* keeps type-checking and is simply read as "not an outage" — the same
* verdict it could express before.
*/
storeUnavailable?: boolean;
}>;
}
/** Type guard — checks whether the service exposes `loadMetaFromDb`. */
function hasLoadMetaFromDb(service: unknown): service is ProtocolWithDbRestore {
return (
typeof service === 'object' &&
service !== null &&
typeof (service as Record<string, unknown>)['loadMetaFromDb'] === 'function'
);
}
/**
* The OBJECTS of a multi-package stack's residual, and the id they are owned
* by — the residual rule's own answer (ADR-0130 D4), read through
* `unclaimedTopLevel` (`@objectstack/metadata`), the one copy both boot doors
* and `os validate` read. ⛔ Never re-derived here: which top-level items are
* residual and which id they take is that function's decision, and a second
* derivation would let this door and the metadata door disagree about it.
*
* Why the engine needs them: the `manifest` service registers the BODIES of a
* stack that carries `packages[]` and never its top level, while the metadata
* door registers the residual under the stack's `manifest.id` and the boot
* says every door reports that id as their owner. Without this, a residual
* object was listed by `GET /meta/object` and answered `404` on
* `/data/<name>`, through both boot doors.
*
* @returns `undefined` when the stack has no residual object — every stack
* without `packages[]`, and every normally composed one.
*/
function unclaimedTopLevelObjects(
stack: unknown,
): { ownerId: string | undefined; ownerVersion: string | undefined; objects: ServiceObject[] } | undefined {
const residual = unclaimedTopLevel(stack);
if (!residual) return undefined;
const objects = residual.items
.filter((entry) => entry.type === 'object')
.map((entry) => entry.item as ServiceObject);
return objects.length > 0
? { ownerId: residual.ownerId, ownerVersion: residual.ownerVersion, objects }
: undefined;
}
/**
* Options for ObjectQLPlugin.
*
* `environmentId` declares that this kernel serves ONE environment. It is a
* topology declaration, not a row filter. ADR-0005 (revised 2026-05) gave every
* environment its own physical database, so `protocol.saveMetaItem` stamps no
* `environment_id` column on new sys_metadata rows and `protocol.loadMetaFromDb`
* constrains on none — the isolation key that survived is `organization_id`.
* The column is deprecated on the metadata tables and new writes leave it NULL;
* `SysMetadataObject.environment_id` and `DatabaseLoaderOptions.environmentId`
* both carry that note, and `DatabaseLoader`'s own pin test asserts the write
* does not set it.
*
* What setting it still decides is topology: this kernel skips the boot-time
* `sys_metadata` hydration unless `hydrateMetadataFromDb` opts back in, skips
* bridging the process-wide SchemaRegistry into the metadata service (that
* registry is shared, so the bridge would leak sibling environments' objects),
* and does not provision the metadata-storage platform objects locally. Leave
* undefined in single-kernel / self-hosted mode.
*/
export interface ObjectQLPluginOptions {
/** Optional pre-built engine. When absent, one is lazily created in init. */
ql?: ObjectQL;
/** Passed to `new ObjectQL(...)` when `ql` is not supplied. */
hostContext?: Record<string, any>;
/**
* Declare that this kernel serves one environment. Topology only — it does
* not scope sys_metadata rows by an `environment_id` column. See the
* interface docblock above.
*/
environmentId?: string;
/**
* [#6710] Which authoring channel this kernel's metadata writes arrive on —
* the explicit expression of ADR-0005's "package author's own bootstrap
* channel".
*
* **Leave unset on every kernel that serves `PUT /api/v1/meta/*` to end
* users.** The default `'environment'` runs the #4463 runtime authoring
* rules (the shared `AUTHORING_RULES` that `os validate` / `os lint`
* run), which for a Studio tenant or an MCP/AI author is the ONLY
* author-time gate — there is no `os lint` for a `sys_metadata` overlay row.
*
* Set `'package-author'` ONLY on the genuine control-plane assembly. Before
* #6710 this was inferred from `environmentId === undefined`, which is a row
* -scoping key and not a topology signal: the CLI's host-config assembler
* leaves it undefined too, so the flagship showcase's own boot shape ran the
* gate on nothing. Omitting this option now means MORE enforcement, never
* less — which is the whole point of declaring it rather than deducing it.
*/
authoringChannel?: MetadataAuthoringChannel;
/**
* [#9380] Does this boot arm the `kernel:ready` platform-table repair
* migrations (#5839 / #8629 / #8686)?
*
* Same lesson as `authoringChannel` right above: the gate used to be deduced
* from `environmentId === undefined`, which is a row-scoping key and not a
* topology signal — the standalone stack stamps `'env_local'`, so the three
* migrations never armed on a self-hosted boot at all. Forwarded verbatim to
* `assembleMetadataProtocol`; see
* `AssembleMetadataProtocolOptions.runPlatformMigrations` for the two facts
* that make it false. Omitted ⇒ the historical deduction, unchanged.
*/
runPlatformMigrations?: boolean;
/**
* Override the kernel's default plugin-start timeout for this plugin.
* Defaults to 120000 (120s). Schema sync to a remote SQL backend
* (Neon/Postgres/Turso) is latency-bound — the SQL driver currently
* does NOT support `batchSchemaSync`, so it issues one round-trip per
* registered object × twice (Phase 1 + Phase 3 in `start()`). On a
* cold remote DB with N tables this can blow past the kernel's
* default 30s easily, even though everything is healthy.
*/
startupTimeout?: number;
/**
* Skip both `syncRegisteredSchemas()` calls inside `start()` and
* assume DDL is managed out-of-band (e.g. an `apps/cloud/scripts/migrate.ts`
* run before deploy that connects directly to the database and creates
* all `sys_*` + custom tables once — that script lives in the separate
* `objectstack-ai/cloud` repo and is NOT a path in this one).
*
* Use this on cold-start-sensitive runtimes (Cloudflare Containers,
* Lambda) where the platform's inbound-request budget is shorter than
* a fresh remote-DB schema sync. The plugin still hydrates the
* SchemaRegistry from `sys_metadata` (Phase 2), so custom user
* objects come up — they just aren't re-DDL'd on every cold boot.
*
* Falls back to `process.env.OS_SKIP_SCHEMA_SYNC === '1'` when the
* option is unset, so containers can flip it via their env without a
* code change.
*
* The resolved value also governs the other boot-time DDL in the kernel:
* plugins that provision their own system tables at `kernel:ready`
* (`plugin-audit`, `service-messaging`) read it from the engine and skip
* that provisioning too. A runtime publish's `syncObjectSchema` is not
* gated: the flag's scope is the boot.
*/
skipSchemaSync?: boolean;
/**
* Hydrate the SchemaRegistry from this kernel's local `sys_metadata`
* even when `environmentId` is set.
*
* By default Phase-2 hydration in `start()` is gated on
* `environmentId === undefined`, because the original multi-environment
* model assumed project kernels source metadata from a remote artifact /
* control-plane proxy and have NO local `sys_metadata` to read. That is
* NOT true for an isolated, proxy-free project kernel that persists its
* OWN `sys_metadata` locally (e.g. the cloud single-env tenant runtime on
* Turso): objects CREATED AT RUNTIME there — not present in the boot
* artifact manifest — would otherwise never re-enter the registry after a
* restart, so `registry.getObject(name)` returns nothing for them and any
* registry consumer (the unknown-`$select` guard, hooks, relationships)
* silently degrades.
*
* Set this ONLY when the kernel's registry is per-instance isolated AND
* `sys_metadata` lives on the kernel's own local driver (no control-plane
* proxy) — hydrating a proxied kernel would read the wrong database.
* Safe to leave unset: hydration tolerates a missing table.
*/
hydrateMetadataFromDb?: boolean;
/**
* ADR-0076 Step 2 (#2462): when `false`, this plugin SKIPS its built-in
* protocol assembly (the `protocol` service, the metadata-storage platform
* objects, and the lightweight `analytics` fallback) — mount
* `createMetadataProtocolPlugin()` from `@objectstack/metadata-protocol`
* alongside to own them instead. Protocol CONSUMERS stay here either way
* (DB hydration + authored hook/action rebind resolve `protocol` lazily).
* Defaults to `true` (built-in assembly, fully backward compatible).
*/
registerProtocol?: boolean;
/**
* ADR-0057 LifecycleService tuning. Lifecycle enforcement is a platform
* primitive and defaults ON — objects without a `lifecycle` declaration are
* never touched, so a kernel with no declarations sees zero deletes. Set
* `enabled: false` (or env `OS_LIFECYCLE_DISABLED=1`) to disable the
* periodic sweep entirely; the `lifecycle` service stays registered so
* tooling can still run `sweep()` explicitly.
*
* `referenceAudit` tunes the #4551 read-only dangling-reference audit that
* rides this same clock. It writes nothing; `enabled: false` drops the leg.
*/
lifecycle?: {
enabled?: boolean;
sweepIntervalMs?: number;
initialDelayMs?: number;
referenceAudit?: Omit<DanglingReferenceAuditOptions, 'signal'> & { enabled?: boolean };
};
}
/**
* [#22984] The engine-instance property under which {@link ObjectQLPlugin}
* publishes the `skipSchemaSync` value it resolved (the option, else
* `OS_SKIP_SCHEMA_SYNC === '1'`).
*
* This plugin's boot sync is not the only boot-time DDL in a composed kernel:
* `plugin-audit` and `service-messaging` provision their system tables from a
* `kernel:ready` hook through `syncObjectSchema`. They read this value so a
* deployment that declared its DDL managed out-of-band gets no table created
* behind its back, and they read the value resolved HERE rather than the
* environment a second time, so the option and the env var cannot disagree
* between the engine's boot and theirs.
*
* `syncObjectSchema` itself does not consult it: that method is also how a
* runtime publish gives a new object its table, and the flag's declared scope
* is the boot.
*
* Deliberately an undeclared own property of the engine instance, not a member
* of `ObjectQL` or of the `IDataEngine` contract, so it adds no name to any
* declared surface. Readers probe it (`=== true`); an engine nothing published
* it on reads as "not set". Both readers pin it against this producer by
* booting the real plugin in their own plugin tests.
*/
const SKIP_SCHEMA_SYNC_ENGINE_KEY = 'skipSchemaSync';
/**
* [#23649] The kernel-bus event {@link ObjectQLPlugin.start} triggers once per
* boot, with the live engine as its one argument, at the last moment a routing
* decision can still be made for free: every boot-registered driver has been
* adopted (`driver.*` services) and connected (`ObjectQL.init()`), and nothing
* has been schema-synced, hydrated from `sys_metadata`, read or written yet.
*
* It exists for the stack's `datasourceMapping` (ADR-0062 D2 (d), #4462). A
* mapping rule is routing, not a hint: from the moment it is installed, every
* object it matches resolves to the named datasource and never falls back to
* the default store. Installed any later than this (it used to be installed in
* `AppPlugin.start()`, after this plugin's schema sync and after the auth
* plugin wrote the Default Organization), the rules re-route platform objects
* whose tables and rows already sit in the default store, and the boot reports
* ready over two stores. The app plugin subscribes in its `init()`: it installs
* the rules and connects every datasource they route a registered object to,
* so the first DDL and every boot write land where the mapping routes them.
*
* After driver adoption on purpose, never in Phase 1: the engine makes its
* first registered driver the default, so a datasource connected before a
* stack plugin's `driver.*` service is adopted would take the default slot
* from it and move every unbound object with it. A handler's throw propagates
* and fails the boot (a mapped datasource that cannot connect has no fallback).
*
* Not in `IPluginLifecycleEvents`: the bus is open to custom names, and this
* one has one emitter (here) and one subscriber (`AppPlugin`).
*/
export const OBJECTQL_DRIVERS_READY_HOOK = 'objectql:drivers-ready';
export class ObjectQLPlugin implements Plugin {
name = 'com.objectstack.engine.objectql';
type = 'objectql' as const;
version = '1.0.0';
/**
* Services init() UNCONDITIONALLY registers (ADR-0116, #4131) — lets the
* kernel name this plugin when a consumer requires one of them before it
* initializes. `protocol`/`objects`/`analytics` are deliberately absent:
* they are option-gated (`registerProtocol`) and may be owned by
* MetadataProtocolPlugin instead.
*/
providesServices = ['objectql', 'data', 'manifest', 'lifecycle'];
/**
* Schema sync to remote SQL DBs is latency-bound (one round-trip per
* table × 2 phases). Default to 120s instead of the kernel's 30s so
* cold Neon/Turso starts don't get killed mid-sync.
*/
startupTimeout = 120_000;
private ql: ObjectQL | undefined;
private hostContext?: Record<string, any>;
private environmentId?: string;
/**
* [#6710] Declared authoring channel, forwarded to the ONE protocol
* assembly. `undefined` here is not "unknown" — `assembleMetadataProtocol`
* resolves it to `'environment'`, the gated channel.
*/
private authoringChannel?: MetadataAuthoringChannel;
/**
* [#9380] Declared arming of the `kernel:ready` platform-table repair
* migrations, forwarded to the ONE protocol assembly. `undefined` here is
* not "off" — it means "not declared", and the assembly resolves it to the
* historical `environmentId === undefined` deduction. The legacy positional
* `(ObjectQL, hostContext)` constructor returns before any option is read,
* so it lands here undefined and keeps that deduction too.
*/
private runPlatformMigrations?: boolean;
private skipSchemaSync = false;
/** Serializes reload-time schema syncs so overlapping reloads can't race DDL. */
private reloadSchemaSync: Promise<void> = Promise.resolve();
private hydrateMetadataFromDb = false;
private registerProtocol = true;
/**
* Armed at the end of `start()` (AFTER the one-shot
* {@link bridgeObjectsToMetadataService}, where that runs). From that
* point on, every manifest registered through the `manifest` service
* bridges its own objects into the metadata service incrementally — the
* one-shot bridge never runs again, so late registrations (marketplace
* install / rehydrate on `kernel:ready`) would otherwise stay invisible
* to every IMetadataService consumer. Armed on ALL kernels, including
* project-scoped ones (`environmentId` set — `os dev` boots as
* 'env_local'): unlike the one-shot registry-wide bridge, a per-manifest
* bridge cannot leak sibling-project objects, and gating it would turn
* the fix off in marketplace install-local's primary home.
*/
private bridgeLateManifests = false;
/**
* [#24182] For each package the late bridge bridged as an EXTENDER, the
* names of the objects whose copy it rewrote: copies stamped with another
* package's id (the owner's), re-registered with the merged body that
* carries this package's extension. Read and cleared by
* {@link restoreExtendedObjectCopies} when the package is withdrawn, the one
* moment the registry no longer says which objects it extended.
*/
private readonly extendedObjectCopies = new Map<string, Set<string>>();
/**
* Set at `kernel:ready`, once the boot audit has found every picklist a
* field names: from then on an artifact registered through the `manifest`
* service is judged before it registers (AGENTS.md, startup registry reads:
* seal the vocabulary, then judge).
*/
private picklistVocabularySealed = false;
/**
* [#24400] Set at `kernel:ready` beside {@link picklistVocabularySealed},
* once the boot audit has found the target object of every bound top-level
* action: from then on a late artifact's bound actions are judged before it
* registers.
*/
private boundActionTargetsSealed = false;
/** Unsubscribe handles for metadata-event subscriptions (ADR-0008 PR-7). */
private metadataUnsubscribes: Array<() => void> = [];
/** ADR-0057 lifecycle enforcement (Reaper/Rotator/Archiver). */
private lifecycleService: LifecycleService | undefined;
private lifecycleOptions: ObjectQLPluginOptions['lifecycle'];
constructor(qlOrOptions?: ObjectQL | ObjectQLPluginOptions, hostContext?: Record<string, any>) {
// Back-compat: legacy callers passed `(ObjectQL, hostContext)` positionally.
if (qlOrOptions instanceof ObjectQL) {
this.ql = qlOrOptions;
this.hostContext = hostContext;
return;
}
// New signature: options bag.
const opts = (qlOrOptions as ObjectQLPluginOptions | undefined) ?? {};
if (opts.ql) {
this.ql = opts.ql;
}
this.hostContext = opts.hostContext ?? hostContext;
this.environmentId = opts.environmentId;
this.authoringChannel = opts.authoringChannel;
this.runPlatformMigrations = opts.runPlatformMigrations;
if (typeof opts.startupTimeout === 'number' && opts.startupTimeout > 0) {
this.startupTimeout = opts.startupTimeout;
}
this.skipSchemaSync =
typeof opts.skipSchemaSync === 'boolean'
? opts.skipSchemaSync
: process.env.OS_SKIP_SCHEMA_SYNC === '1';
this.hydrateMetadataFromDb = opts.hydrateMetadataFromDb === true;
this.registerProtocol = opts.registerProtocol !== false;
this.lifecycleOptions = opts.lifecycle;
}
/**
* [ADR-0131 D7] The objects the deployment declares platform-global, as this
* plugin installed them at `start()` — compared at `kernel:ready` by
* {@link assertDeploymentPlatformGlobalObjectsUnchanged}.
*/
private installedPlatformGlobalObjects: ReadonlySet<string> = new Set<string>();
/**
* [ADR-0131 D7 — the #12699 declaration made total] Read the deployment's
* `OrgScopingEntitlement.platformGlobalObjects` off the mounted `org-scoping`
* service and install it as the injected-columns plan's input: every object
* it names gets NO organization column on this deployment, so Layer 0 and
* the driver agree by having nothing to scope.
*
* ## Why here, at the top of `start()` (ADR-0116)
*
* Every `init()` has completed by now — the Phase 1/2 split — and the
* provider declares `org-scoping` in `providesServices`, i.e. registers it
* unconditionally in its `init()`. So the declaration read here is final for
* this boot, and no table exists yet: the first schema sync is below. The
* plan is ALSO computed at registration, inside each registrant's `init()`,
* and the provider cannot be ordered ahead of those (it hard-depends on this
* plugin), so the registry re-plans every object already registered
* (`SchemaRegistry.setDeploymentPlatformGlobalObjects`).
*
* Fail closed, through the one reader (`readDeploymentOrgScopingEntitlement`,
* `@objectstack/core`): no service or an absent key installs nothing and
* every plan is byte-identical; a junk key is refused loudly and installs
* nothing, so no object loses its column.
*/
private installDeploymentPlatformGlobalObjects(ctx: PluginContext): void {
if (!this.ql) return;
const reading = this.readDeploymentPlatformGlobalObjects(ctx);
this.installedPlatformGlobalObjects = reading;
if (reading.size === 0) return;
const { replanned, keptAuthoredColumn } =
this.ql.registry.setDeploymentPlatformGlobalObjects(reading);
const objects = [...reading].sort();
ctx.logger.info(
`[ObjectQLPlugin] deployment declares ${objects.length} platform-global object(s) — no ` +
'organization column on THIS deployment (ADR-0131 D7); each is governed by object permission, ' +
'not by the organization wall',
{ objects, replannedAtStart: replanned },
);
if (keptAuthoredColumn.length > 0) {
ctx.logger.warn(
`[ObjectQLPlugin] deployment declares ${keptAuthoredColumn.join(', ')} platform-global, but the ` +
'object DECLARES its own organization_id: that column is the author\'s, not the platform\'s, so it ' +
'stays and the organization wall keeps scoping it. Remove the authored organization_id field to ' +
'make the declaration take effect, or drop the object from the declaration.',
{ objects: keptAuthoredColumn },
);
}
}
/** The validated `platformGlobalObjects` reading; warns for a refused key. */
private readDeploymentPlatformGlobalObjects(ctx: PluginContext): ReadonlySet<string> {
let service: unknown;
try {
service = ctx.getService('org-scoping');
} catch {
service = undefined;
}
const reading = readDeploymentOrgScopingEntitlement(service);
for (const refusal of reading.refused) {
if (refusal.key !== 'platformGlobalObjects') continue;
ctx.logger.warn(
`[ObjectQLPlugin] org-scoping entitlement key 'platformGlobalObjects' REFUSED — ${refusal.problem}`,
{ key: refusal.key, declared: refusal.value },
);
}
return reading.platformGlobalObjects;
}
/**
* [ADR-0131 D7] At `kernel:ready`, refuse the boot when the `org-scoping`
* service now declares a different platform-global set than the one the
* columns were planned from at `start()`. That only happens when a provider
* registers `org-scoping` outside its `init()` (or swaps it), which ADR-0116
* gives no ordering for: the objects it names were provisioned WITH the
* column, and serving on would advertise a declaration the deployment does
* not honour. Reads the service without warning — a junk key was warned
* about at `start()` and reads as the same empty set.
*/
private assertDeploymentPlatformGlobalObjectsUnchanged(ctx: PluginContext): void {
let service: unknown;
try {
service = ctx.getService('org-scoping');
} catch {
service = undefined;
}
const now = readDeploymentOrgScopingEntitlement(service).platformGlobalObjects;
const before = this.installedPlatformGlobalObjects;
const same = now.size === before.size && [...now].every((name) => before.has(name));
if (same) return;
throw new Error(
'[ObjectQLPlugin] the org-scoping service\'s platformGlobalObjects declaration changed after the engine ' +
`planned the columns at start() (planned: [${[...before].sort().join(', ')}]; now: ` +
`[${[...now].sort().join(', ')}]). The objects it names were provisioned with an organization column. ` +
"Register 'org-scoping' in the provider's init() and declare it in its providesServices (ADR-0116), " +
'so every plugin start() — this engine\'s schema sync included — reads the final declaration.',
);
}
/**
* Arm the protocol-driven rebinds. Shared by both assembly modes: called with
* the in-house shim when `registerProtocol` is on, and lazily from `start()`
* against whatever registered `protocol` (MetadataProtocolPlugin) otherwise.
*
* Two independent subscriptions, each guarded on its own — a protocol
* implementation that offers one seam and not the other must still get the
* one it has:
*
* 1. `onMetadataMutation` (#2588, #2605) — this plugin's OWN authored
* hook/action rebind.
* 2. `onMetaItemPublished` (#10219) — the kernel-wide `metadata:reloaded`
* announce for the per-item publish door. See
* {@link announcePerItemPublish}.
*/
private subscribeMetadataRebind(ctx: PluginContext, protocol: unknown): void {
if (typeof (protocol as any)?.onMetadataMutation === 'function') {
const unsubscribe = (protocol as any).onMetadataMutation(
(evt: { type: string; name: string; state: string }) => {
if (evt?.state === 'draft') return;
// The metadata service's copy of a runtime-authored object follows
// the registry the moment the authoring door lands. See
// {@link followRuntimeObjectCopy}.
if (evt?.type === 'object') this.followRuntimeObjectCopy(ctx, evt);
if (evt?.type === 'hook') {
void this.resyncAuthoredHooks(ctx).catch((e: any) => {
ctx.logger.warn('[ObjectQLPlugin] authored-hook rebind after mutation failed', {
hook: evt.name,
error: e?.message,
});
});
} else if (evt?.type === 'action' || evt?.type === 'object') {
// `object` rows carry embedded `actions[]`, so an object edit can
// add/remove an authored action too — re-sync on both.
void this.resyncAuthoredActions(ctx).catch((e: any) => {
ctx.logger.warn('[ObjectQLPlugin] authored-action rebind after mutation failed', {
item: evt.name,
error: e?.message,
});
});
}
},
);
this.metadataUnsubscribes.push(unsubscribe);
}
if (typeof (protocol as any)?.onMetaItemPublished === 'function') {
const unsubscribe = (protocol as any).onMetaItemPublished(
(evt: { type: string; name: string }) => this.announcePerItemPublish(ctx, evt),
);
this.metadataUnsubscribes.push(unsubscribe);
}
}
/**
* [#10219] Announce `metadata:reloaded` after a PER-ITEM publish
* (`POST /api/v1/meta/:type/:name/publish`), so every boot-cached consumer
* re-syncs without a restart.
*
* This is the missing third announcer of an event that had two: the metadata
* plugin's dev-artifact watcher, and the runtime dispatcher after
* `POST /packages/:id/publish-drafts` (#2576). Publishing one item at a time
* — what an AI author and the item-level Studio doors do — fired neither, so
* the load-bearing subscriber never ran: `service-automation`'s
* `resyncFlowsFromProtocol` binds record- and schedule-triggered flows off
* this event, and a flow published per item stayed `state='active'` and
* completely inert until the kernel was rebuilt. Same silence for authored
* hooks/actions of other packages, declared connectors and translations.
*
* The plugin is where the announce belongs because the protocol holds no
* kernel: it notifies, and this — holding `ctx` — triggers. That is the same
* division the dispatcher's `announceKernelEvent` makes for the batch door.
*
* `changed` uses the `'{type}/{name}'` spelling the batch announce emits, so
* a subscriber reading the payload cannot tell the two doors apart.
*
* Best-effort and never rethrown: the item is already published and durable,
* so a subscriber failure must not turn a landed publish into an error. It is
* reported at `warn` — the loss is an in-memory re-sync, AGENTS.md's own
* worked example of a FUNCTIONAL degradation, and the sibling announcers log
* it at exactly this level.
*/
private async announcePerItemPublish(
ctx: PluginContext,
evt: { type: string; name: string },
): Promise<void> {
try {
await ctx.trigger('metadata:reloaded', { changed: [`${evt.type}/${evt.name}`] });
} catch (e: any) {
ctx.logger.warn(
'[ObjectQLPlugin] the post-publish `metadata:reloaded` announce failed — the item IS published, but '
+ 'boot-cached consumers keep the pre-publish view until this process restarts (a newly published '
+ 'record-triggered flow does not bind its trigger and will not fire). Nothing retries this announce; '
+ 're-publishing the item is idempotent.',
{ item: `${evt.type}/${evt.name}`, error: e?.message ?? String(e) },
);
}
}
init = async (ctx: PluginContext) => {
if (!this.ql) {
// Pass kernel logger to engine to avoid creating a separate logger instance
const hostCtx = { ...this.hostContext, logger: ctx.logger };
this.ql = new ObjectQL(hostCtx);
}
// [#22984] Publish the resolved opt-out where boot-time provisioning
// plugins read it — see SKIP_SCHEMA_SYNC_ENGINE_KEY.
(this.ql as unknown as Record<string, unknown>)[SKIP_SCHEMA_SYNC_ENGINE_KEY] = this.skipSchemaSync;
// [ADR-0139 D2] The engine composes a `ReadableIds` leaf from the
// registered `security` service. Handed over as a SOURCE in the engine's
// slot (`SECURITY_SERVICE_SOURCE_SLOT`, not public surface), read at use and
// never here: at this plugin's init the service is not registered yet on
// any composition that ships it (plugin-security registers it in its own
// start()), so a lookup here would record a verdict the same boot
// contradicts. The engine answers every state but a usable service
// `$in: []` (fail closed); a throw — the in-repo kernels' answer for a
// name nothing registered — is one of them.
(this.ql as unknown as Record<symbol, unknown>)[SECURITY_SERVICE_SOURCE_SLOT] = () => ctx.getService('security');
// Register as provider for Core Kernel Services
ctx.registerService('objectql', this.ql);
ctx.registerService('data', this.ql); // ObjectQL implements IDataEngine
// Register manifest service for direct app/package registration.
// Plugins call ctx.getService('manifest').register(manifestData)
// instead of the legacy ctx.registerService('app.<id>', manifestData) convention.
const ql = this.ql;
ctx.registerService('manifest', {
// [ADR-0130 D4/D5] The load path reads BOTH artifact shapes and registers
// the packages inside one artifact in dependency-TOPOLOGICAL order.
//
// `resolveArtifactPackageOrder` is the whole of that decision: it reads
// `packages` when present and falls back to the caller's own object as a
// single-element list when absent (D4), and it orders through
// `resolvePluginOrder` — the platform's ONE topological sorter (ADR-0116).
// ⛔ Nothing here may re-derive either the entry shape or the ordering; a
// second copy of either is the drift both records exist about.
//
// Registration of ALL packages completes before ANY bridging begins. The
// bridge resolves objects out of the registry, and an artifact's later
// packages contribute extensions onto the earlier ones' objects — so a
// register/bridge interleave would bridge a body that the very next
// package is about to change. For the single-package artifact this is the
// same one register followed by the same one bridge as before (D7).
//
// [#23972] `options.source` is where every package in this artifact came
// from, stamped on each registry row (`InstalledPackageSchema.source`).
// Absent means `'code'`, the deployment's own code (`registerApp`'s
// default); the marketplace install-local plugin states `'marketplace'`.
register: (registeredArtifact: any, options?: { source?: 'code' | 'marketplace' }) => {
// ADR-0087 D2 at the registration door, for an artifact that carries
// `packages[]`: its bodies are strictly parsed by the ordering below
// BEFORE `registerApp` could convert each one, so a bundle handed here
// as authored (a marketplace install, a hosted kernel's own loader)
// converts once as a whole first — the window is the artifact's, read
// off its own declared range, and every body replays under it. A
// single-body payload converts at `registerApp` (the body door) and is
// handed through untouched here; a bundle an artifact door already
// converted comes back by reference. See `ObjectQL.convertPackageBodyForward`.
const artifact = Array.isArray(registeredArtifact?.packages)
? ql.convertPackageBodyForward(registeredArtifact)
: registeredArtifact;
const ordered = resolveArtifactPackageOrder(artifact) as any[];
// [ADR-0130 D4] The objects of the stack's RESIDUAL — top-level objects
// no package body declares — as the residual rule answers it. See
// {@link unclaimedTopLevelObjects}.
const residual = unclaimedTopLevelObjects(artifact);
if (ordered.length === 0 && residual === undefined) {
// An artifact that declared `packages: []` registers nothing. Said out
// loud rather than returning quietly: "the install did nothing" is not
// a state anyone should have to infer from an absence.
ctx.logger.warn(
'Artifact declared an empty `packages: []` — nothing was registered. A '
+ 'single-package artifact omits the key entirely and carries `manifest` '
+ '(ADR-0130 D4).',
);
return Promise.resolve();
}
// [ADR-0130 D1] The artifact's own package list, handed to every
// install in it. This is the whole of how the install gate learns
// "same artifact": co-ownership is proven by joint delivery, and this
// load path is the only place that holds the delivery. ⛔ No owner field
// on the manifest (D8) and nothing persisted — the claim cannot outlive,
// or drift from, the artifact that IS the claim.
//
// A single-`manifest` artifact yields a one-element list whose only
// member is the installing package itself, which the gate excludes
// anyway: that path stays bit-identical (D7).
const scope = {
packageIds: ordered
.map((m) => artifactPackageId(m))
.filter((id): id is string => id !== undefined),
};
// Once the boot has sealed the picklist vocabulary (`kernel:ready`,
// below), an artifact arriving later is judged BEFORE anything of it
// registers: every field it brings that names a picklist must resolve
// against the registry or against a list the artifact itself declares.
// A refused install registers nothing.
if (this.picklistVocabularySealed) {
const declared = new Set<string>();
for (const manifest of ordered) for (const name of collectManifestPicklistNames(manifest)) declared.add(name);
const known = (name: string) => declared.has(name) || ql.registry.resolvePicklistOptions(name) !== undefined;
const unresolved = ordered
.flatMap((manifest) => collectManifestPicklistReferences(manifest, artifactPackageId(manifest)))
.filter((ref) => !known(ref.picklist));
const orphans = ordered
.flatMap((manifest) => collectManifestPicklistExtensions(manifest, artifactPackageId(manifest)))
.filter((ext) => !known(ext.picklist));
const refusal = describeUnresolvedPicklistReferences(unresolved, orphans);
if (refusal) throw refusal;
}
// [#24400] The same seal for bound top-level actions: once the boot has
// judged every target (`kernel:ready`, below), an artifact arriving
// later must bind its actions to an object the registry holds or one
// the artifact itself declares. A refused install registers nothing.
if (this.boundActionTargetsSealed) {
const declared = new Set<string>(residual?.objects.map((o) => o.name) ?? []);
for (const manifest of ordered) for (const name of collectManifestObjectNames(manifest)) declared.add(name);
const unbound = ordered
.flatMap((manifest) => collectManifestBoundActions(manifest, artifactPackageId(manifest)))
.filter((bound) => !declared.has(bound.objectName) && ql.registry.getObject(bound.objectName) === undefined);
const refusal = describeUnboundActionTargets(unbound);
if (refusal) throw refusal;
}
for (const manifest of ordered) {
ql.registerApp(manifest, scope, options?.source);
ctx.logger.debug('Manifest registered via manifest service', {
id: manifest.id || manifest.name
});
}
// [ADR-0130 D4] The residual's objects, AFTER every body — the order
// the metadata door registers the same stack in — under the id the
// residual rule names, through the registry verb a body's own objects
// take (`registerApp` step 2). There is no package record for that id:
// the residual is not a package, and when the id names one of the
// bodies (a composed stack keeps one member's manifest) that body's
// record must not be replaced.
if (residual) this.registerUnclaimedTopLevelObjects(ctx, residual, ordered);
// [#24472] The boot reported every same-name pair it found
// (`kernel:ready`, below); an artifact arriving later is judged once it
// has registered, for the pairs naming one of its packages on either
// side. Reported, never refused — nothing above is undone.
if (this.boundActionTargetsSealed) {
const arrived = new Set(scope.packageIds);
if (residual?.ownerId !== undefined) arrived.add(residual.ownerId);
this.reportBoundActionCollisions(ctx, ql.registry[FIND_BOUND_ACTION_COLLISIONS](arrived));
}
// Manifests registered AFTER start() (marketplace install / ledger
// rehydrate arrive on `kernel:ready` or an HTTP request) land in the
// SchemaRegistry only — the one-shot startup bridge already ran — so
// bridge every registered package's objects into the metadata service now.
// No-op until start() arms it, so boot-time registrations keep the
// single startup bridge. The promise never rejects; async callers
// (marketplace install) await it so metadata reads right after
// install are deterministic, sync callers may ignore it. The residual's
// owner is bridged with them, so a late artifact's residual objects
// reach the metadata door as well as the data door.
const bridged = residual?.ownerId !== undefined && !scope.packageIds.includes(residual.ownerId)
? [...ordered, { id: residual.ownerId }]
: ordered;
return this.bridgeArtifactObjectsToMetadataService(ctx, bridged);
},
// [#24182] The withdrawal counterpart of the bridge's extender rewrite:
// a door that withdrew a package from the registry calls this so the
// copies of OTHER packages' objects that the package's extensions
// rewrote serve the registry's definition again. Never rejects. See
// {@link restoreExtendedObjectCopies}.
restoreExtendedObjectCopies: (packageId: string): Promise<void> =>
this.restoreExtendedObjectCopies(ctx, packageId),
});
ctx.logger.info('ObjectQL engine registered', {
services: ['objectql', 'data', 'manifest'],
});
if (this.registerProtocol) {
// ADR-0076 Step 2 PR-C: the ONE assembly lives in
// @objectstack/metadata-protocol — this built-in mode is the
// single-kernel convenience mount of the same code path the
// MetadataProtocolPlugin uses (identical objects/protocol/analytics).
// [#6710] `authoringChannel` rides the same seam as `environmentId`, and
// an undefined one resolves to `'environment'` (gated) inside the
// assembly — including on the legacy positional `(ObjectQL, hostContext)`
// constructor path, which returns before any option is read.
const protocolShim = assembleMetadataProtocol(ctx, this.ql, this.environmentId, {
authoringChannel: this.authoringChannel,
// [#9380] Rides the same seam, for the same reason: an undeclared value
// resolves to the historical `environmentId === undefined` deduction
// inside the assembly, so this mount and the delegated
// MetadataProtocolPlugin cannot disagree about when the migrations arm.
runPlatformMigrations: this.runPlatformMigrations,
});
this.subscribeMetadataRebind(ctx, protocolShim);
} else {
ctx.logger.info('registerProtocol=false — protocol assembly delegated to MetadataProtocolPlugin (ADR-0076 Step 2)');
}
// ADR-0057: the platform-owned LifecycleService. Registered from the
// engine plugin (not an opt-in capability) so every kernel that has data
// also has lifecycle enforcement — a declared retention that drives no
// sweeper is dead surface (ADR-0049).
this.lifecycleService = new LifecycleService({
getEngine: () => this.ql,
logger: ctx.logger,
// P4 governance: overrides/quotas resolve from the 'lifecycle'
// settings namespace when a SettingsService is present. Lazy per
// sweep — plugin registration order doesn't matter.
getSettings: () => {
try {
return ctx.getService('settings') as never;
} catch {
return undefined;
}
},
...this.lifecycleOptions,
});
ctx.registerService('lifecycle', this.lifecycleService);
}
start = async (ctx: PluginContext) => {
ctx.logger.info('ObjectQL engine starting...');
// [ADR-0131 D7] FIRST: the deployment's platform-global declaration is the
// injected-columns plan's input, so it is installed before anything below
// registers another object or creates a table.
this.installDeploymentPlatformGlobalObjects(ctx);
// Delegated-assembly mode (ADR-0076 Step 2): the protocol was registered
// by MetadataProtocolPlugin during init — arm the authored hook/action
// rebind against it now that all inits ran. Graceful when absent.
if (!this.registerProtocol) {
try {
this.subscribeMetadataRebind(ctx, ctx.getService('protocol'));
} catch { /* no protocol registered — rebind not armed */ }
}
// Sync from external metadata service (e.g. MetadataPlugin) if available
try {
const metadataService = ctx.getService<IMetadataService>('metadata');
if (metadataService && typeof metadataService.loadMany === 'function' && this.ql) {
await this.loadMetadataFromService(metadataService, ctx);
}
// ── ADR-0008 PR-7: subscribe to object metadata events so the
// SchemaRegistry cache is invalidated on edits (Studio HMR).
// The metadata service bubbles repo events through its own
// `subscribe(type, cb)` API (PR-6 bridge), so we don't talk
// to the repo directly here — this keeps ObjectQL decoupled
// from the storage backend.
if (metadataService && typeof metadataService.subscribe === 'function' && this.ql) {
this.subscribeToMetadataEvents(metadataService, ctx);
}
} catch (e: any) {
ctx.logger.debug('No external metadata service to sync from');
}
// ── Runtime-authored hook bind (#2588) ───────────────────────────────
// Hooks authored in the Studio live as `sys_metadata` rows, which the
// metadata service's loadMany() above does NOT surface on env-scoped
// kernels (no DatabaseLoader there) — so the boot bind never sees them
// and their bodies never run, even after a restart. Re-bind from the
// rows themselves:
// • at `kernel:ready` — cold-boot coverage, once every plugin has
// registered its packages (so the artifact filter can classify);
// • on `metadata:reloaded` — publish-while-running coverage (the
// runtime dispatcher announces after publishPackageDrafts, #2576),
// mirroring service-automation's flow re-sync.
// Idempotent: the bind fully replaces the 'metadata-service' package
// set, so edited hooks re-bind and deleted hooks tear down.
ctx.hook('kernel:ready', async () => {
// [ADR-0131 D7] The declaration the columns were planned from must still
// be the deployment's: a provider that registered `org-scoping` after
// this plugin's start() was never read, so its objects were provisioned
// WITH the column. Refused here, by name, rather than served.
this.assertDeploymentPlatformGlobalObjectsUnchanged(ctx);
// A field naming a picklist no package declares fails the boot, naming
// the field and the package — never served as a select with nothing to
// choose — and so does an extension of such a list, whose values would
// otherwise go nowhere. Judged HERE because every package has registered by now, so
// "not declared" is final; a list a later package declares would
// otherwise read as missing (AGENTS.md, startup registry reads). From
// here on the vocabulary is sealed and each late artifact is judged as
// it arrives (the `manifest` service above).
const unresolvedPicklists = describeUnresolvedPicklistReferences(
this.ql?.registry.findUnresolvedPicklistReferences() ?? [],
this.ql?.registry.findOrphanPicklistExtensions() ?? [],
);
if (unresolvedPicklists) throw unresolvedPicklists;
this.picklistVocabularySealed = true;
// [#24400] A top-level action bound by `objectName` to an object no
// package registers fails the boot, naming the action, its package and
// the object — never registered and listed nowhere. Judged here for the
// picklist reason: every package has registered, so "no such object"
// is final, and either registration order has had its turn. From here
// on each late artifact is judged as it arrives (the `manifest` service).
const unboundActions = describeUnboundActionTargets(this.ql?.registry.findUnboundActionTargets() ?? []);
if (unboundActions) throw unboundActions;
this.boundActionTargetsSealed = true;
// [#24472] A bound action named like one its target already lists, with
// a different declaration, is warned once per pair, naming the object,
// the action and both packages — judged here for the same reason, and
// reported, never refused: the object keeps serving its own (rung 1)
// and the boot goes on. Each late artifact is judged as it arrives.
this.reportBoundActionCollisions(ctx, this.ql?.registry[FIND_BOUND_ACTION_COLLISIONS]() ?? []);
// #7737 — FIRST, before anything that might read data: bind every
// declared federated object to its remote table now that every
// plugin's `start()` (including the declared-datasource auto-connect
// in `AppPlugin.start()`) has run. See
// {@link reconcileFederatedBindings}.
await this.reconcileFederatedBindings(ctx);
await this.resyncAuthoredHooks(ctx);
await this.resyncAuthoredActions(ctx);
// [ADR-0126 §8] Apply the packaged-ACTION activation ledger to the
// registry that re-sync just finalized.
//
// Ordering is load-bearing, and for the same reason the inventory below
// runs here: after `resyncAuthoredActions` the set of dispatchable
// actions is final for this boot, so the audit line names the actions
// this process will actually refuse. Running at `kernel:ready` (not in
// `start()`) is what lets the ledger's own object — registered by
// whichever composition uses it, and schema-synced by its own start —
// exist before the table is read.
await this.hydrateActionActivations(ctx);
// [ADR-0110 D5] Governance inventory — AFTER the authored-action
// re-sync, so the registry it audits is final for this boot. It lived
// in AppPlugin first, which is registered conditionally; on the `os
// dev` path it never ran, so the checklist that justifies D3's hard
// refusal was never printed where an upgrade most needs it. The
// engine owns the map being audited; the engine plugin reports on it.
await this.runGovernanceInventory(ctx);
// ADR-0057 P4: surface the lifecycle governance namespace in Settings
// (overrides / quotas / growth alerts) when a SettingsService exists.
try {
const settings = ctx.getService('settings') as { registerManifest?: (m: unknown) => void };
settings?.registerManifest?.(lifecycleSettingsManifest);
} catch {
// No settings service — governance stays at declared defaults.
}
});
// ADR-0104 / #3438: name the value-shape gates still open on THIS
// deployment, and the command that closes each. Deliberately on
// `kernel:bootstrapped` rather than `kernel:ready`: the answer depends on
// the storage service's OWN ready handler, which registers `sys_migration`
// and may attest a store it just created. Racing it inside `kernel:ready`
// would tell a brand-new deployment its gates are open moments after they
// were closed.
ctx.hook('kernel:bootstrapped', async () => {
await this.ql?.announceOpenMigrationGates();
});
ctx.hook('metadata:reloaded', async (payload?: unknown) => {
await this.resyncAuthoredHooks(ctx);
await this.resyncAuthoredActions(ctx);
// [ADR-0126 §8] Re-attempt the ledger attach — a no-op once attached.
// A reload is exactly when an object that was not registered at
// `kernel:ready` becomes visible, so this is what keeps that earlier