-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathprotocol.ts
More file actions
6577 lines (6266 loc) · 311 KB
/
Copy pathprotocol.ts
File metadata and controls
6577 lines (6266 loc) · 311 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 { ObjectStackProtocol } from '@objectstack/spec/api';
import { IDataEngine } from '@objectstack/core';
import { readEnvWithDeprecation } from '@objectstack/types';
import type { MetadataHostEngine } from './host-engine.js';
import { SysMetadataRepository, type SysMetadataEngine } from './sys-metadata-repository.js';
import { ConflictError, assertProtocolCompat, type MetadataItem } from '@objectstack/metadata-core';
import type {
BatchUpdateRequest,
BatchUpdateResponse,
UpdateManyDataRequest,
DeleteManyDataRequest,
InstallPackageRequest,
InstallPackageResponse
} from '@objectstack/spec/api';
import type { MetadataCacheRequest, MetadataCacheResponse, ServiceInfo, ApiRoutes, WellKnownCapabilities } from '@objectstack/spec/api';
import { readServiceSelfInfo } from '@objectstack/spec/api';
import type { IFeedService } from '@objectstack/spec/contracts';
import { parseFilterAST, isFilterAST } from '@objectstack/spec/data';
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';
import { type FormView, isAggregatedViewContainer } from '@objectstack/spec/ui';
import { METADATA_FORM_REGISTRY } from '@objectstack/spec/system';
import { DEFAULT_METADATA_TYPE_REGISTRY, getMetadataTypeSchema, getMetadataTypeActions, getMetadataCreateSeed } from '@objectstack/spec/kernel';
import {
extractProtection,
evaluateLockForWrite,
evaluateLockForDelete,
resolveLockState,
type MetadataLock,
type MetadataProvenance,
} from '@objectstack/spec/kernel';
import { validateObjectNamespacePrefix, deriveNamespaceFromPackageId } from '@objectstack/spec/kernel';
import { z } from 'zod';
import {
computeMetadataDiagnostics,
computeViewReferenceDiagnostics,
decorateMetadataItem,
decorateMetadataItems,
type MetadataDiagnostics,
} from './metadata-diagnostics.js';
/**
* Canonical Zod schema per metadata type lives in
* `@objectstack/spec/kernel/metadata-type-schemas` and is exposed through
* {@link getMetadataTypeSchema}. Both save-time validation
* ({@link resolveOverlaySchema}) and the `/meta/types/:type` JSON Schema
* emitter consult that single source of truth, so adding a new
* metadata-type schema requires editing exactly one file (or calling
* `registerMetadataTypeSchema()` from a plugin).
*/
// (TYPE_TO_SCHEMA removed — use `getMetadataTypeSchema(type)` directly.)
/**
* Canonical {@link FormView} layout per metadata type. Sourced from the
* shared {@link METADATA_FORM_REGISTRY} in `@objectstack/spec/system` so
* the runtime form payload, the i18n extractor, and Studio all read from
* a single source of truth.
*
* Types without an entry render with the auto-generated single-section
* layout derived from their JSON Schema (acceptable for simple types).
*/
const TYPE_TO_FORM: Readonly<Record<string, FormView>> = METADATA_FORM_REGISTRY;
/**
* Convert a Zod schema to a JSON Schema, returning `undefined` if conversion
* fails (e.g. unsupported constructs). Cached per schema reference.
*/
const _jsonSchemaCache = new WeakMap<z.ZodTypeAny, Record<string, unknown> | null>();
function toJsonSchemaSafe(schema: z.ZodTypeAny): Record<string, unknown> | undefined {
const cached = _jsonSchemaCache.get(schema);
if (cached !== undefined) return cached ?? undefined;
try {
const result = z.toJSONSchema(schema, { unrepresentable: 'any' }) as Record<string, unknown>;
_jsonSchemaCache.set(schema, result);
return result;
} catch {
_jsonSchemaCache.set(schema, null);
return undefined;
}
}
/**
* Hand-crafted fallback JSON Schemas for metadata types whose Zod schema
* cannot be safely converted via `z.toJSONSchema()` (e.g. due to recursive
* references or non-representable constructs like `z.lazy()` chains).
*
* These mirror the shape consumed by the corresponding `*.form.ts` layouts,
* so the SchemaForm renderer can still produce a real form (instead of
* falling back to the raw JSON editor). All fields use lenient types
* (`string | object | array`) because the widget hint in the form layout
* is what actually drives the UI control selection — the JSON Schema is
* only used to (a) seed defaults and (b) report which property names exist.
*/
const HAND_CRAFTED_SCHEMAS: Record<string, Record<string, unknown>> = {
object: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
pluralLabel: { type: 'string' },
icon: { type: 'string' },
description: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
active: { type: 'boolean', default: true },
isSystem: { type: 'boolean', default: false },
abstract: { type: 'boolean', default: false },
datasource: { type: 'string' },
fields: {
// Canonical Object.fields is a name-keyed map
// (Record<string, FieldDefinition>) — insertion order is
// display order. The SchemaForm engine recognises
// `additionalProperties` as a Record and dispatches to
// the `record` form-field renderer (ADR-0007). The form
// layout in `object.form.ts` declares `type: 'record'`
// so the inner `additionalProperties` schema is used to
// shape each value.
type: 'object',
default: {},
additionalProperties: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
type: { type: 'string' },
required: { type: 'boolean', default: false },
unique: { type: 'boolean', default: false },
defaultValue: {},
description: { type: 'string' },
},
required: ['type'],
},
},
capabilities: { type: 'object', additionalProperties: true },
},
required: ['name'],
additionalProperties: true,
},
action: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
objectName: { type: 'string' },
icon: { type: 'string' },
type: { type: 'string', enum: ['url', 'flow', 'api', 'script'] },
variant: { type: 'string', enum: ['primary', 'secondary', 'danger', 'ghost', 'outline'] },
target: { type: 'string' },
method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
body: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
line: { type: 'string' },
},
},
},
params: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
type: { type: 'string' },
required: { type: 'boolean', default: false },
},
required: ['name'],
},
},
confirmText: { type: 'string' },
successMessage: { type: 'string' },
refreshAfter: { type: 'boolean', default: true },
locations: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
location: { type: 'string' },
},
},
},
component: { type: 'string' },
visible: { type: 'string' },
disabled: { type: 'string' },
shortcut: { type: 'string' },
bulkEnabled: { type: 'boolean', default: false },
aiExposed: { type: 'boolean', default: false },
recordIdParam: { type: 'string' },
recordIdField: { type: 'string' },
bodyShape: { type: 'string', enum: ['flat', 'nested'] },
},
required: ['name', 'label', 'type'],
additionalProperties: true,
},
// Validation rules live inside `object.validations[]`. The canonical
// ValidationRuleSchema is a discriminated union of 9 variants; the
// generic SchemaForm renderer treats unions as opaque JSON, so we
// ship a *flat* form-friendly schema covering the common base
// properties plus every variant-specific field as optional. Save-time
// validation is unaffected — the union schema is still authoritative
// at write time.
validation: {
type: 'object',
properties: {
// --- Base fields (all variants) ---
name: { type: 'string', description: 'Unique rule name (snake_case)' },
label: { type: 'string' },
description: { type: 'string' },
type: {
type: 'string',
enum: [
'script',
'unique',
'state_machine',
'format',
'cross_field',
'json',
'async',
'custom',
'conditional',
],
default: 'script',
description: 'Validation variant',
},
active: { type: 'boolean', default: true },
events: {
type: 'array',
items: { type: 'string', enum: ['insert', 'update', 'delete'] },
default: ['insert', 'update'],
},
priority: { type: 'number', default: 100, minimum: 0, maximum: 9999 },
severity: {
type: 'string',
enum: ['error', 'warning', 'info'],
default: 'error',
},
message: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
// --- Variant-specific (all optional, gated by `type`) ---
condition: {
type: 'string',
description: 'CEL predicate (type=script). True ⇒ validation fails.',
},
fields: {
type: 'array',
items: { type: 'string' },
description: 'Fields (type=unique / cross_field).',
},
scope: { type: 'string', description: 'CEL scope predicate (type=unique).' },
caseSensitive: { type: 'boolean', default: true },
field: { type: 'string', description: 'Single field (type=state_machine / format).' },
transitions: {
type: 'object',
additionalProperties: { type: 'array', items: { type: 'string' } },
description: 'Map { OldState: [AllowedNewStates] } (type=state_machine).',
},
regex: { type: 'string', description: 'Regex (type=format).' },
format: {
type: 'string',
enum: ['email', 'url', 'phone', 'json'],
description: 'Built-in format (type=format).',
},
url: { type: 'string', description: 'Endpoint URL (type=async).' },
handler: { type: 'string', description: 'Handler reference (type=custom).' },
when: { type: 'string', description: 'Outer condition (type=conditional).' },
},
required: ['name', 'type', 'message'],
additionalProperties: true,
},
};
/**
* Zod schemas used to validate overlay items before they are persisted into
* `sys_metadata` by {@link ObjectStackProtocolImplementation.saveMetaItem}.
*
* Single source of truth: the spec-side {@link getMetadataTypeSchema}
* registry (`@objectstack/spec/kernel/metadata-type-schemas`). Every
* metadata type whose payload should round-trip through Studio's
* generic editor maps to its canonical Zod schema there; this function
* is a plural→singular adapter on top of it.
*
* Validation policy:
* - `safeParse` is used so we can craft a 422 with structured `issues`.
* - We do NOT replace the persisted document with `parsed.data`; the
* original payload is stored verbatim so Studio-only auxiliary fields
* (e.g. `isPinned`, `isDefault`, `sortOrder`) survive the round-trip.
* - Types without a registered schema (the wiring-layer types
* `function`/`service`/`router`, and any plugin types that have not
* yet called `registerMetadataTypeSchema()`) fall through unvalidated.
*/
function resolveOverlaySchema(type: string, _item: unknown): z.ZodTypeAny | null {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
return getMetadataTypeSchema(singular) ?? null;
}
/**
* Guarantee a `view` body carries a top-level `name`.
*
* {@link ObjectStackProtocolImplementation.getMetaItems} only surfaces a
* sys_metadata overlay row when its parsed body has a top-level `name` (objects
* and dashboards include one; some view producers — notably loose `{ list }`
* fragments — do not, so the view is silently dropped from the object's view
* list and never appears as a tab). We stamp the save name here, at the single
* write chokepoint, without otherwise reshaping the document.
*
* Deliberately does NOT convert shape: both the `defineView` container form
* (`{ list, listViews, … }`) and the `{ name, object, viewKind, config }`
* record form are valid and the console consumes both — reshaping a container
* into a record risks producing an invalid record (e.g. a non-`<object>.<key>`
* name). Structural validity is enforced separately by the view metadata schema
* during the spec-validation step. No-op for non-view types and bodies that
* already carry a `name`.
*
* When `baseline` is provided (the registry entry this overlay will shadow),
* missing identity fields — `viewKind`, `object`, `label` — are inherited onto
* non-container bodies. A runtime personalization PUT (console column sort,
* inline edit, …) sends only the raw view config; persisting it verbatim makes
* the overlay replace the flattened package entry minus its identity, and the
* view silently drops out of every consumer that filters on
* `viewKind`/`object` (e.g. the switcher endpoint). See #2555. Container
* bodies are left untouched — `expandViewContainer` derives identity itself.
*/
export function normalizeViewMetadata(type: string, item: unknown, saveName: string, baseline?: unknown): unknown {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
if (singular !== 'view') return item;
if (!item || typeof item !== 'object' || Array.isArray(item)) return item;
const it = item as Record<string, unknown>;
const patch = viewIdentityPatch(it, baseline);
if (it.name && !patch) return it;
return { ...it, ...(it.name ? undefined : { name: saveName }), ...patch };
}
/**
* #2555 — compute the identity fields (`viewKind`, `object`, `label`) a view
* overlay is missing but the registry entry it shadows carries. The overlay's
* own fields always win. Returns `null` (nothing to inherit) for `defineView`
* container bodies — their identity is derived at expansion — and for
* absent/invalid baselines.
*/
function viewIdentityPatch(overlay: Record<string, unknown>, baseline: unknown): Record<string, unknown> | null {
if (!baseline || typeof baseline !== 'object' || Array.isArray(baseline)) return null;
if ('list' in overlay || 'listViews' in overlay || 'formViews' in overlay) return null;
const b = baseline as Record<string, unknown>;
const patch: Record<string, unknown> = {};
for (const key of ['viewKind', 'object', 'label'] as const) {
if (overlay[key] === undefined && b[key] !== undefined) patch[key] = b[key];
}
return Object.keys(patch).length > 0 ? patch : null;
}
/**
* ADR-0010 §3.3 — Overlay the artifact's metadata-protection envelope
* onto a returned item so artifact-level lock/packageId/provenance
* always wins over whatever was persisted in the `sys_metadata` overlay
* row. Returns `item` unchanged when no artifact baseline is available.
*
* The artifact's `_lock`, `_lockReason`, `_packageId`, `_packageVersion`,
* and `_provenance` are the source of truth — an overlay copy may
* pre-date the artifact's protection declaration and would otherwise
* mask it.
*/
function mergeArtifactProtection(item: unknown, artifactItem: unknown): unknown {
if (item === undefined || item === null) return item;
if (artifactItem === undefined || artifactItem === null) return item;
const a = artifactItem as Record<string, unknown>;
if (typeof a !== 'object') return item;
const out: Record<string, unknown> = { ...(item as Record<string, unknown>) };
if (a._lock !== undefined) out._lock = a._lock;
if (a._lockReason !== undefined) out._lockReason = a._lockReason;
if (a._lockDocsUrl !== undefined) out._lockDocsUrl = a._lockDocsUrl;
if (a._lockSource !== undefined) out._lockSource = a._lockSource;
if (a._packageId !== undefined) out._packageId = a._packageId;
if (a._packageVersion !== undefined) out._packageVersion = a._packageVersion;
if (a._provenance !== undefined) out._provenance = a._provenance;
return out;
}
/**
* Simple hash function for ETag generation (browser-compatible)
* Uses a basic hash algorithm instead of crypto.createHash
*/
function simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(16);
}
/**
* Thrown by `updateData` / `deleteData` when the caller supplies an
* `expectedVersion` that does not match the current record's `updated_at`.
*
* The HTTP layer maps this to `409 Conflict` with code `CONCURRENT_UPDATE`,
* and includes both the current server-side version and the current record
* payload so the client can render an informed conflict-resolution UI
* ("Reload latest" vs. "Overwrite anyway").
*
* NOTE: This is an *application-level* compare-and-set — not an atomic
* storage-layer CAS. There is a small TOCTOU window between the version
* check and the subsequent write. For the conflict frequency this targets
* (different users seconds-to-minutes apart in B2B record editing) this
* is more than adequate; a future revision can push the check into the
* driver's UPDATE statement (`WHERE id=? AND updated_at=?`) for true
* atomicity.
*/
export class ConcurrentUpdateError extends Error {
readonly code = 'CONCURRENT_UPDATE';
readonly status = 409;
readonly currentVersion: string | null;
readonly currentRecord: unknown;
constructor(opts: { currentVersion: string | null; currentRecord: unknown; message?: string }) {
super(opts.message ?? 'Record was modified by another user');
this.name = 'ConcurrentUpdateError';
this.currentVersion = opts.currentVersion;
this.currentRecord = opts.currentRecord;
}
}
/**
* Normalises a version token for comparison. Strips RFC-7232-style quotes
* (`"…"`) that an HTTP `If-Match` header may carry, trims whitespace, and
* returns null for empty / nullish input.
*/
function normaliseVersionToken(v: unknown): string | null {
if (v === null || v === undefined) return null;
const s = String(v).trim();
if (!s) return null;
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
}
return s;
}
// Lifecycle columns the engine always owns; the clone path drops them by NAME
// so the insert re-stamps fresh values instead of copying the source's. Mirrors
// record-validator's SKIP_FIELDS (system-injected, never author-supplied).
const CLONE_STRIP_FIELDS: readonly string[] = [
'id', 'created_at', 'created_by', 'updated_at', 'updated_by',
];
/**
* Service Configuration for Discovery
* Maps service names to their routes and plugin providers.
*
* `route: undefined` means the service has NO HTTP surface — discovery must
* not advertise a route for it (ADR-0076 D12, #2462: an advertised route
* with no mounted handler 404s and misleads consumers).
*/
const SERVICE_CONFIG: Record<string, { route?: string; plugin: string }> = {
auth: { route: '/api/v1/auth', plugin: 'plugin-auth' },
automation: { route: '/api/v1/automation', plugin: 'plugin-automation' },
cache: { route: '/api/v1/cache', plugin: 'plugin-redis' },
queue: { route: '/api/v1/queue', plugin: 'plugin-bullmq' },
job: { route: '/api/v1/jobs', plugin: 'job-scheduler' },
ui: { route: '/api/v1/ui', plugin: 'ui-plugin' },
workflow: { route: '/api/v1/workflow', plugin: 'plugin-workflow' },
// service-realtime is an in-process pub/sub bus; nothing mounts
// /api/v1/realtime, so no route is advertised (D12, #2462).
realtime: { plugin: 'service-realtime' },
notification: { route: '/api/v1/notifications', plugin: 'plugin-notifications' },
ai: { route: '/api/v1/ai', plugin: 'plugin-ai' },
i18n: { route: '/api/v1/i18n', plugin: 'service-i18n' },
graphql: { route: '/graphql', plugin: 'plugin-graphql' }, // GraphQL uses /graphql by convention (not versioned REST)
'file-storage': { route: '/api/v1/storage', plugin: 'plugin-storage' },
search: { route: '/api/v1/search', plugin: 'plugin-search' },
};
/**
* Phase 3a-references: hand-curated reference path registry.
*
* Maps a *target* metadata type to the list of *source* type+path tuples
* that may point at it. Used by {@link findReferencesToMeta} to scan all
* loaded metadata and surface "what depends on this?" before a user
* deletes or renames an artifact.
*
* Path syntax:
* - `'foo'` → item.foo
* - `'foo.bar'` → item.foo.bar
* - `'foo[]'` → each element of array item.foo
* - `'foo[].bar'` → bar of each element of array item.foo
* - `'foo{}'` → each value of Record item.foo
* - `'foo{}.bar'` → bar of each value of Record item.foo
*
* Coverage is intentionally narrow — covers the highest-value references
* for MVP. Add more entries as new editors are built.
*/
const REFERENCE_PATHS: Record<string, Array<{ fromType: string; paths: string[]; kind: string }>> = {
object: [
{ fromType: 'view', paths: ['object', 'objectName'], kind: 'view' },
{ fromType: 'dashboard', paths: ['widgets[].object', 'widgets[].objectName'], kind: 'dashboard widget' },
{ fromType: 'flow', paths: ['object', 'context.object', 'trigger.object', 'targetObject'], kind: 'flow' },
{ fromType: 'workflow', paths: ['object', 'targetObject'], kind: 'workflow' },
{ fromType: 'permission', paths: ['objects[].name', 'objects[].object'], kind: 'permission' },
{ fromType: 'app', paths: ['navItems[].objectName', 'navItems[].object', 'tabs[].objectName', 'tabs[].object'], kind: 'app nav' },
{ fromType: 'page', paths: ['object', 'objectName'], kind: 'page' },
{ fromType: 'report', paths: ['object', 'objectName'], kind: 'report' },
{ fromType: 'action', paths: ['object', 'objectName'], kind: 'action' },
{ fromType: 'validation', paths: ['object', 'objectName'], kind: 'validation' },
{ fromType: 'hook', paths: ['object', 'objectName'], kind: 'hook' },
{ fromType: 'object', paths: ['fields[].referenceTo', 'fields{}.referenceTo', 'fields{}.reference'], kind: 'field reference' },
],
view: [
{ fromType: 'dashboard', paths: ['widgets[].view', 'widgets[].viewName'], kind: 'dashboard widget' },
{ fromType: 'app', paths: ['navItems[].viewName', 'tabs[].viewName'], kind: 'app nav' },
{ fromType: 'page', paths: ['viewName'], kind: 'page' },
],
tool: [
{ fromType: 'agent', paths: ['tools[]', 'tools[].name'], kind: 'agent tool' },
],
skill: [
{ fromType: 'agent', paths: ['skills[]', 'skills[].name'], kind: 'agent skill' },
],
flow: [
{ fromType: 'app', paths: ['navItems[].flowName', 'tabs[].flowName'], kind: 'app nav' },
],
dashboard: [
{ fromType: 'app', paths: ['navItems[].dashboardName', 'tabs[].dashboardName'], kind: 'app nav' },
],
page: [
{ fromType: 'app', paths: ['navItems[].pageName', 'tabs[].pageName'], kind: 'app nav' },
],
};
/**
* Extract one or more string values from `item` at `path`. Supports
* `'a.b'` (nested object access) and `'a[].b'` (array element access).
* Returns an empty array if any segment is missing.
*/
function extractPathValues(item: unknown, path: string): string[] {
if (!item || typeof item !== 'object') return [];
const segments = path.split('.');
let current: unknown[] = [item];
for (const rawSeg of segments) {
let kind: 'value' | 'array' | 'record' = 'value';
let seg = rawSeg;
if (seg.endsWith('[]')) {
kind = 'array';
seg = seg.slice(0, -2);
} else if (seg.endsWith('{}')) {
kind = 'record';
seg = seg.slice(0, -2);
}
const next: unknown[] = [];
for (const node of current) {
if (!node || typeof node !== 'object') continue;
let value: unknown;
if (seg === '') {
value = node;
} else {
value = (node as Record<string, unknown>)[seg];
}
if (value === undefined || value === null) continue;
if (kind === 'array') {
if (Array.isArray(value)) {
for (const v of value) next.push(v);
}
} else if (kind === 'record') {
if (Array.isArray(value)) {
for (const v of value) next.push(v);
} else if (typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) next.push(v);
}
} else {
next.push(value);
}
}
current = next;
if (current.length === 0) return [];
}
// Coerce final values to strings, dropping non-string non-object leaves.
const out: string[] = [];
for (const v of current) {
if (typeof v === 'string' && v.length > 0) out.push(v);
else if (v && typeof v === 'object' && 'name' in (v as any) && typeof (v as any).name === 'string') {
out.push((v as any).name);
}
}
return out;
}
/**
* Phase 3a-destructive: detect changes between an existing object schema
* and an incoming overlay that would break runtime data — removed fields,
* field type narrowing, required toggled on without a default. Returned
* issues are surfaced as HTTP 409 `destructive_change` unless the caller
* sets `force: true`, letting the admin UI render a warning dialog before
* proceeding.
*
* Scope is intentionally narrow for MVP: covers the most common
* data-loss footguns for `object` and `field` types. Subsequent passes
* can layer in relationship changes, enum-value removals, etc.
*/
/**
* Shallow JSON diff used by `diffMetaItem`. Compares the top-level
* keys of `from` vs `to`; primitive value changes are reported as
* `changed`, nested objects/arrays that differ structurally are also
* reported as a single `changed` entry (deep structural diffs are out
* of scope — Studio renders the full bodies for a side-by-side view).
*/
function diffShallow(
from: Record<string, unknown>,
to: Record<string, unknown>,
): {
added: Array<{ path: string; value: unknown }>;
removed: Array<{ path: string; value: unknown }>;
changed: Array<{ path: string; from: unknown; to: unknown }>;
} {
const added: Array<{ path: string; value: unknown }> = [];
const removed: Array<{ path: string; value: unknown }> = [];
const changed: Array<{ path: string; from: unknown; to: unknown }> = [];
const fromKeys = new Set(Object.keys(from ?? {}));
const toKeys = new Set(Object.keys(to ?? {}));
for (const k of toKeys) {
if (!fromKeys.has(k)) {
added.push({ path: k, value: (to as any)[k] });
} else {
const a = (from as any)[k];
const b = (to as any)[k];
const aStr = JSON.stringify(a);
const bStr = JSON.stringify(b);
if (aStr !== bStr) {
changed.push({ path: k, from: a, to: b });
}
}
}
for (const k of fromKeys) {
if (!toKeys.has(k)) {
removed.push({ path: k, value: (from as any)[k] });
}
}
return { added, removed, changed };
}
function detectDestructiveObjectChanges(prev: any, next: any): Array<{
code: string;
field?: string;
message: string;
}> {
if (!prev || typeof prev !== 'object' || !next || typeof next !== 'object') return [];
const prevFields = (prev.fields && typeof prev.fields === 'object') ? prev.fields as Record<string, any> : {};
const nextFields = (next.fields && typeof next.fields === 'object') ? next.fields as Record<string, any> : {};
const issues: Array<{ code: string; field?: string; message: string }> = [];
// Removed fields — silently dropping a column is a data-loss event.
for (const fname of Object.keys(prevFields)) {
// Skip system fields — those are managed by applySystemFields and
// re-injected on every registerObject call; they will look "removed"
// in any user-supplied overlay.
if (prevFields[fname]?.system) continue;
if (!(fname in nextFields)) {
issues.push({
code: 'field_removed',
field: fname,
message: `Field '${fname}' removed — existing data in this column will become inaccessible.`,
});
}
}
// Field type changes — narrowing or incompatible conversions.
const TYPE_COMPATIBILITY: Record<string, Set<string>> = {
text: new Set(['textarea', 'markdown', 'html', 'code']),
number: new Set([]),
boolean: new Set([]),
date: new Set(['datetime']),
datetime: new Set(['date']),
};
for (const fname of Object.keys(nextFields)) {
const prevField = prevFields[fname];
const nextField = nextFields[fname];
if (!prevField) continue; // brand-new field — non-destructive
const prevType = prevField.type;
const nextType = nextField.type;
if (prevType && nextType && prevType !== nextType) {
const compatible = TYPE_COMPATIBILITY[prevType]?.has(nextType);
if (!compatible) {
issues.push({
code: 'field_type_change',
field: fname,
message: `Field '${fname}' type changed from '${prevType}' to '${nextType}' — existing values may not convert cleanly.`,
});
}
}
// required toggled on without a default — new inserts will start
// to fail validation, and any null rows already in the table will
// fail on next save.
if (!prevField.required && nextField.required && nextField.defaultValue === undefined) {
issues.push({
code: 'field_required_no_default',
field: fname,
message: `Field '${fname}' is now required but has no default value — existing rows with null values may fail validation.`,
});
}
}
return issues;
}
/**
* Result of projecting a published metadata body into its data-plane
* representation. `success:false` with an `error` is the surfaced-not-thrown
* failure contract — publishing the metadata itself always succeeds.
*/
export interface PublishMaterializeResult {
success: boolean;
inserted: number;
updated: number;
error?: string;
}
/**
* Publish-time materializer (ADR-0086 P2). Receives the just-published body
* plus the draft's package binding and org scope. Registered per metadata type
* via {@link ObjectStackProtocolImplementation.registerPublishMaterializer}.
*/
export type PublishMaterializer = (args: {
body: unknown;
packageId: string | null;
organizationId: string | null;
actor: string;
}) => Promise<PublishMaterializeResult>;
/**
* Uninstall-time data-plane cleanup (ADR-0086 D3, #2747). The exact mirror of
* {@link PublishMaterializer}: domain plugins own data-plane tables the
* protocol layer must not know the shape of (e.g. plugin-security's
* `sys_permission_set` and its binding tables), so they register a named
* cleanup here and {@link ObjectStackProtocolImplementation.deletePackage}
* invokes every cleanup with the uninstalled package id. Cleanups run
* best-effort — a failure is REPORTED on the uninstall response (`cleanups`),
* never thrown — but ghost grants are a security condition, so callers must
* surface a failed cleanup, not swallow it.
*/
export type UninstallCleanup = (args: {
packageId: string;
organizationId?: string;
actor?: string;
}) => Promise<{ success: boolean; removed: number; error?: string }>;
/** Per-cleanup outcome reported on the `deletePackage` response. */
export interface UninstallCleanupOutcome {
name: string;
success: boolean;
removed: number;
error?: string;
}
/**
* Post-persistence metadata-mutation notification (#2588). Emitted by
* `saveMetaItem` / `publishMetaItem` / `deleteMetaItem` AFTER the write
* landed. `type` is the singular metadata type name. Subscribe via
* {@link ObjectStackProtocolImplementation.onMetadataMutation}.
*/
export interface MetadataMutationEvent {
type: string;
name: string;
/** Resulting lifecycle state of the row the mutation produced. */
state: 'active' | 'draft' | 'deleted';
organizationId?: string | null;
}
/**
* Awaited per-type mutation projector (ADR-0094). Invoked AFTER a metadata
* mutation persists — `saveMetaItem` (draft AND active saves),
* `publishMetaItem`, `deleteMetaItem` — and AWAITED before the write returns,
* so a data-plane read-model derived from the metadata (e.g. `permission` →
* `sys_permission_set`) is already consistent when the caller's next read
* lands. This is what makes such a read-model a PURE projection: the
* projector is its only writer, and it runs in the same awaited operation as
* every metadata write, instead of a fire-and-forget subscriber a new write
* path might race or forget.
*
* Complements (does not replace) {@link MetadataMutationEvent} listeners,
* which stay fire-and-forget for cache-invalidation consumers.
*
* Best-effort: a projector failure is surfaced on the write's response
* (`projectionApplied: { success:false, error }`) and logged, never thrown —
* the metadata write itself already succeeded, and boot reconciliation heals
* the projection on next start.
*
* `body` carries the just-persisted item when the mutation has one in hand
* (save/publish); projectors that need the EFFECTIVE (layered) body should
* re-read it — a delete, for instance, may reveal the artifact baseline.
*/
export type MetadataMutationProjector = (
evt: MetadataMutationEvent & { body?: unknown },
) => Promise<void>;
/** Per-write outcome of the awaited mutation projector (ADR-0094). */
export interface MutationProjectionOutcome {
success: boolean;
error?: string;
}
/**
* Pre-persistence authoring gate (ADR-0094 addendum seam; #3050).
*
* Unlike the post-persist {@link MetadataMutationProjector} (best-effort,
* never thrown), an authoring gate runs BEFORE persistence and REJECTS the
* write by throwing — it is the seam for domain invariants that must hold on
* every runtime-authored body regardless of which HTTP surface produced it
* (e.g. plugin-security's OWD posture gate: an environment may only TIGHTEN
* a packaged object's `sharingModel`, and `externalSharingModel ≤
* sharingModel` per ADR-0090 D11).
*
* Invoked inside `saveMetaItem` for BOTH draft and publish-mode saves, after
* the ADR-0005 overlay/runtime-create authorization and the per-type spec
* validation — so `publishMetaItem` promotes an already-gated body and needs
* no second gate. Environment writes only: control-plane bootstrap writes
* (`environmentId === undefined`) are the package author's own channel and
* bypass the gate, mirroring the ADR-0005 gate above.
*/
export interface MetadataAuthoringGateContext {
/** Singular type name (e.g. `object`). */
type: string;
name: string;
/** Lifecycle the body is being saved into. */
state: 'draft' | 'active';
organizationId?: string;
/** The body being persisted. */
body: unknown;
/** True when a packaged artifact backs this name — the write is an env overlay of shipped metadata. */
isArtifactBacked: boolean;
/** The packaged (code-layer) baseline body when {@link isArtifactBacked}; the declaration an overlay customizes. */
declaredBody?: unknown;
}
export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise<void>;
export class ObjectStackProtocolImplementation implements ObjectStackProtocol {
private engine: MetadataHostEngine;
private getServicesRegistry?: () => Map<string, any>;
private getFeedService?: () => IFeedService | undefined;
/**
* Project scope applied to sys_metadata reads/writes. When undefined
* (single-kernel deployments), rows land in / come from the
* platform-global bucket (`environment_id IS NULL`). When set, every
* saveMetaItem insert/update and loadMetaFromDb query is filtered by
* `environment_id = environmentId`, so per-project kernels see only their own
* metadata even if several projects share the same physical database.
*/
private environmentId?: string;
/**
* Lazily-instantiated SysMetadataRepository per organization. Keyed by
* `${organizationId ?? '__env__'}`. Repositories are stateful — they
* carry the per-org `seqCounter` and watch subscribers — so we cache
* them rather than constructing one per call.
*/
private overlayRepos = new Map<string, SysMetadataRepository>();
/**
* Publish-time materializers keyed by singular metadata type (ADR-0086 P2).
* When a draft of a registered type is published, its body is projected
* into a data-plane representation the admin surface reads — e.g. a
* `permission` set is upserted into `sys_permission_set` with
* `managed_by:'package'`. Domain plugins own the projection (the generic
* protocol layer must not know `sys_permission_set`'s field shape), so they
* register here at init. Best-effort — a materializer failure is surfaced on
* the publish response, never thrown (publishing metadata always succeeds
* independently; the same contract as `seed` apply).
*/
private publishMaterializers = new Map<string, PublishMaterializer>();
/** [#2747] Named uninstall cleanups, run by {@link deletePackage}. */
private uninstallCleanups = new Map<string, UninstallCleanup>();
/**
* Awaited per-type mutation projectors (ADR-0094), keyed by singular
* metadata type. Unlike {@link publishMaterializers} (publish-only,
* package door) a projector runs on EVERY persisted mutation of its type
* — save, publish, delete — so a derived data-plane read-model can be a
* pure projection with no unsynchronized door. One per type; a second
* registration replaces the first (idempotent re-init).
*/
private mutationProjectors = new Map<string, MetadataMutationProjector>();
/**
* Pre-persistence authoring gates (#3050). One per type; a second
* registration replaces the first (idempotent re-init). Unlike
* projectors these THROW to reject the write — see
* {@link MetadataAuthoringGate}.
*/
private authoringGates = new Map<string, MetadataAuthoringGate>();
constructor(
engine: IDataEngine,
getServicesRegistry?: () => Map<string, any>,
getFeedService?: () => IFeedService | undefined,
environmentId?: string,
) {
this.engine = engine as MetadataHostEngine;
this.getServicesRegistry = getServicesRegistry;
this.getFeedService = getFeedService;
this.environmentId = environmentId;
}
/**
* Register a publish-time materializer for a metadata type (ADR-0086 P2).
* Called by domain plugins at init (e.g. plugin-security registers the
* `permission` → `sys_permission_set` projection). The singular type name is
* used — `permissions` and `permission` both resolve here. One materializer
* per type; a second registration replaces the first (idempotent re-init).
*/
registerPublishMaterializer(type: string, materializer: PublishMaterializer): void {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
this.publishMaterializers.set(singular, materializer);
}
/**
* Register a named uninstall-time data-plane cleanup (ADR-0086 D3, #2747).
* Called by domain plugins at init — e.g. plugin-security registers the
* cleanup that removes its package-owned `sys_permission_set` rows and
* their bindings when the owning package is uninstalled, so grants are
* revoked everywhere at once (no ghost grants). One cleanup per name; a
* second registration replaces the first (idempotent re-init).
*/
registerUninstallCleanup(name: string, cleanup: UninstallCleanup): void {
this.uninstallCleanups.set(name, cleanup);
}
/**
* Register the awaited mutation projector for a metadata type (ADR-0094).
* Called by the domain plugin that owns the derived read-model (e.g.
* plugin-security registers the `permission` → `sys_permission_set`
* projector). Singular or plural type names both resolve.
*/
registerMutationProjector(type: string, projector: MetadataMutationProjector): void {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
this.mutationProjectors.set(singular, projector);
}
/**
* Register the pre-persistence authoring gate for a metadata type
* (ADR-0094 addendum seam; #3050). Called by domain plugins at init —
* e.g. plugin-security registers the `object` OWD posture gate. The gate
* THROWS to reject the write. Singular or plural type names both resolve;
* one gate per type, a second registration replaces the first.
*/
registerAuthoringGate(type: string, gate: MetadataAuthoringGate): void {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
this.authoringGates.set(singular, gate);
}
/**
* Run the registered authoring gate for an about-to-persist body (#3050).
* No-op when no gate is registered for the type. A gate throw PROPAGATES
* (with its status/code) — that is the contract: the write is rejected
* before persistence. Resolves the artifact-backed flag and the packaged
* declaration body (the baseline an overlay customizes) for the gate.
*/
private async runAuthoringGate(evt: {
type: string; name: string; state: 'draft' | 'active'; organizationId?: string; body: unknown;
}): Promise<void> {
const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type;
const gate = this.authoringGates.get(singular);
if (!gate) return;
const artifactBacked = this.isArtifactBacked(evt.type, evt.name);
let declaredBody: unknown;
if (artifactBacked && typeof this.engine.registry?.getItem === 'function') {
const alt = PLURAL_TO_SINGULAR[evt.type] ?? SINGULAR_TO_PLURAL[evt.type];
declaredBody = this.engine.registry.getItem(evt.type, evt.name)
?? (alt ? this.engine.registry.getItem(alt, evt.name) : undefined);
}
await gate({
type: singular,
name: evt.name,
state: evt.state,
...(evt.organizationId ? { organizationId: evt.organizationId } : {}),
body: evt.body,
isArtifactBacked: artifactBacked,
...(declaredBody !== undefined ? { declaredBody } : {}),
});
}
/**
* Run the registered projector for a just-persisted mutation (ADR-0094).
* Returns `undefined` when no projector is registered for the type;
* otherwise a {@link MutationProjectionOutcome} that callers attach to
* the write's response as `projectionApplied`. Never throws.
*/
private async runMutationProjector(
evt: MetadataMutationEvent & { body?: unknown },
): Promise<MutationProjectionOutcome | undefined> {
const projector = this.mutationProjectors.get(evt.type);
if (!projector) return undefined;
try {
await projector(evt);
return { success: true };
} catch (e) {
const error = e instanceof Error ? e.message : String(e);
console.warn(
`[Protocol] mutation projector failed for ${evt.type}/${evt.name} (state=${evt.state}): ${error}`,
);