Repository navigation
Expand file tree
/
Copy pathprotocol-save.ts
More file actions
3477 lines (3408 loc) · 214 KB
/
Copy pathprotocol-save.ts
File metadata and controls
3477 lines (3408 loc) · 214 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) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#29985 codemod] The "Save refusals, saveMetaItem, saveConflict,
* migrateStoredMetadata" facet of `ObjectStackProtocolImplementation`: the
* bodies of `metaTypeNamespaceExists`, `viewContainerNameCollisionRefusal`,
* `saveMetaItem`, `saveMetaItemUnaudited`, `migrateStoredMetadata` moved out of
* `protocol.ts` whole (split by #29998 and #30687).
*
* A MOVE, not a redesign. `ProtocolSaveFacet` is a stateless facet over the host
* (ruling 6624345766): each static method below is the body of the class
* member of the same name as `packages/metadata-protocol/scripts/host-split.mjs`
* moves one (ruling E, item E1), with `this.<member>` read as `host.<member>`
* and nothing else changed. The facet holds no state: the fields stay on the
* class, and a body reaches them through the host (`protocol-host.ts`).
*
* The class keeps every member as a one-line delegation. A public member
* keeps its docblock there, which the published `.d.ts` prints; a private
* member's docblock moved here with its body (docblock ownership).
*
* What a body reads from elsewhere, it imports from where `protocol.ts`
* imports it. Nothing re-exports this module, so the published surface does
* not move.
*/
import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api';
import { stampHtmlPageRequires } from './runtime-authoring-gate.js';
import { SysMetadataRepository, actionCustomizationHoldersOf, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js';
import { boundObjectOf } from '@objectstack/metadata/stored-item-package';
import { ConflictError, itemDiscriminator, readLegacyOrganizationRows } from '@objectstack/metadata-core';
import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name';
import { authoringClientOf } from './draft-changes.js';
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';
import { isAggregatedViewContainer } from '@objectstack/spec/ui';
import {
TRANSLATED_ECHO_NOTICE_ID,
restoreTranslatedEchoes,
translatedEchoNotices,
} from './protocol-translated-echo.js';
import { PROTOCOL_VERSION, stripReadDecorations } from '@objectstack/spec/kernel';
import { collectDecisionModeReview } from './stored-migration.js';
import type {
StoredFlowCanonicalization,
StoredMigrationNotice,
StoredMigrationReport,
StoredMigrationRow,
StoredMigrationTodo,
} from './stored-migration.js';
import { droppedWithheldKeyNotices } from './protocol-credential-carry-forward.js';
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js';
import { flowVerdictBody } from './protocol-flow-save-replay.js';
import { withParsedStoredActions } from './protocol-stored-action-parse.js';
import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js';
import { withNullMasterRowCounts } from './protocol-destructive-null-master.js';
import { withStillShownBy } from './destructive-still-shown-by.js';
import { canonicalMetaType, canonicalizeMetaRequestType, resolveOverlaySchema } from './protocol-meta-type-schema.js';
import {
permissionSetOwnerBindingRefusal,
protectionBlockRefusal,
runtimeHookWithoutBodyRefusal,
withoutProtectionBlock,
} from './protocol-authoring-refusals.js';
import { zodIssuesToMetadataIssues } from './protocol-metadata-issues.js';
import {
graftFoldedFormSections,
graftNormalizedOperators,
normalizeViewMetadata,
projectStorableViewBody,
withDeclaredPageTypeDefault,
} from './protocol-view-normalization.js';
import { isShippedViewItem, stripDerivedProvenance } from './protocol-package-bindings.js';
import { mutationEventMemberOfBody } from './protocol-bundle-members.js';
import { mutationEventPackage, projectorEventPackage } from './protocol-mutation-package.js';
import { clientFacingFailureText } from './protocol-client-failures.js';
import {
destructiveChangeRemedy,
detectDestructiveObjectChanges,
specValidationFindings,
} from './protocol-write-face.js';
import { isNonCanonicalStoredType } from './protocol-stored-overlay-types.js';
import type { SaveMetaItemRequest } from './protocol-door-requests.js';
import { withRefusalAudit } from './protocol-refusal-audit.js';
import { captureStoredExpressionChange, fillStoredExpressionChange } from './protocol-stored-expression-fill.js';
import { reportObjectRegistryRefusal } from './protocol-registry-hydration.js';
import type { MutationProjectionOutcome } from './protocol-mutation-events.js';
import type { ProtocolHost } from './protocol-host.js';
import type { ObjectStackProtocolImplementation } from './protocol.js';
import { saveRegistryQuestion } from './registry-question.js';
import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js';
import { rowHeldBaseAddressOf, servedAddressJudgment } from './protocol-meta-item-face.js';
import { overlayMemberValue } from './migrations/overlay-index.js';
import { packagelessContentPackage, shippingPackageIds } from './protocol-environment-rows.js';
import type { StoredOverlayRow } from './item-lock.js';
import { installedManifestsOfEngine } from './installed-manifests.js';
import { packageScopedRefusalOf } from './protocol-meta-item-reads.js';
import { pairsOf } from '@objectstack/metadata-core';
import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js';
export class ProtocolSaveFacet {
/**
* Does `sys_metadata` already carry a row under this type key?
*
* Reached ONLY from {@link refuseUnmintableMetaType} after the static
* verdict has fired, so it costs nothing on the ordinary save path. Not
* scoped by name, org or state on purpose: the question is whether the
* NAMESPACE exists, and a residue row is exactly as real in a draft or in
* another org's overlay as it is here.
*
* An UNPROVISIONED store counts as "no" and the refusal stands — a
* deployment whose `sys_metadata` table does not exist yet has no residue to
* protect, and is the state in which this card's own defect (minting the
* first row of a namespace nothing serves) is at its most reachable. Any
* OTHER read failure propagates as `503 SERVICE_UNAVAILABLE`
* ({@link rethrowUnlessMetadataStoreUnprovisioned}): inventing "no rows"
* from an outage would answer `400 '<type>' is not a metadata type` — an
* existence claim about the store, stated while the store was unreachable —
* for a write that may be perfectly legal (AGENTS.md "Absence must be loud",
* #5186).
*/
static async metaTypeNamespaceExists(host: Pick<ProtocolHost, 'findEnvironmentRow' | 'rethrowUnlessMetadataStoreUnprovisioned'>, type: string): Promise<boolean> {
try {
// [#21908, ADR-0096 D5] The explicit system opt-in: an existence
// probe of the platform store, never a read on a caller's behalf.
const row = await host.findEnvironmentRow('sys_metadata', { where: { type }, context: { isSystem: true } });
return row != null;
} catch (error) {
host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
return false;
}
}
/**
* [#21639] The save door's ONE collision predicate for a view container:
* a container is refused when its save name, or any name its expansion
* produces, is a name already served from elsewhere — the family's rule,
* which replaces its two one-shape checks (#21558's own expansion,
* #21620's sibling of the same object) and adds the shapes they left open.
*
* Both read doors give a name with a stored row of its own that row
* (#21510's one predicate, {@link namesWithOwnStoredRow}), and fill a
* row-less name with an expansion, the last one read winning within a
* package's slot and on a by-name read that names no package
* ({@link servedViewExpansion}). So a container whose ROW name is
* served from elsewhere hides that view on both doors and, being no view
* itself, leaves no read answering a view under the name; a container
* whose EXPANSION takes such a name replaces that view on both doors with
* no word to anyone (ADR-0126: no silent override). Neither is ever what
* the author meant, so both are refused here, at authoring (Prime
* Directive 12), and the readers keep their one predicate: ⛔ no second
* own-row test and no precedence rule in the readers.
*
* "Elsewhere" is triage's two sources, judged by the readers' own pieces,
* never a copy of them:
* - another stored container's expansion, in the caller's selection,
* whatever that container's object: the rows
* {@link readActiveOverlayRows} selects (the environment's) with no
* package filter, parsed by
* {@link storedOverlayEntries} and expanded by
* {@link expandStoredViewContainers} with each row's own package
* binding. The row stored under the save name is left out: it is the
* row this save replaces, so a container's own re-save is never its
* own sibling;
* - a view item a package ships ({@link lookupArtifactItem}, the
* registry's artifact read, which never answers a tenant-authored
* row, holding a view item: {@link isShippedViewItem}), except the
* views of the shipped container this row overlays
* by its own name ({@link overlaidShippedContainerViewNames}): ADR-0005
* keys an overlay by its own name, so an overlay of a package's
* container stands in for that container and its views.
* A name the container's OWN expansion produces is a third source for its
* save name only: as the row of that name it would hide its own view.
*
* Every name the container would serve is its expansion as the readers
* place it, {@link expandRuntimeViewContainer} with the request's package
* binding (the binding the row is stored under), so every member kind,
* the expander's de-duplication and #21334's own-name arm on another
* package's object are judged where the readers put them. The body judged
* is the one the author sent, with the door's own `name` stamp applied
* first (a body with no `name` is judged under the save name), BEFORE
* {@link normalizeViewMetadata}'s identity patch: a `form`-only container
* under a registered view item's name would otherwise take that item's
* `viewKind` and reach the schema as a malformed view item.
*
* What still saves: a view item (`viewKind` set), which is not a
* container and under any of these names is that name's sanctioned
* override; a container under its object's name, or under any name of
* its own, whose expansion collides with nothing; an overlay of a
* package's own container; #21334's own-name arm. Rows already stored in a refused shape keep
* their bytes and are served as before; a new save of one, a re-save
* included, is refused until its body stops colliding, and the re-savers
* that write through this door (`migrateStoredMetadata`,
* `duplicatePackage`) record that refusal as the row's failure.
*
* `VALIDATION_ERROR` / 400, the envelope of the name check it sits beside
* (`savedItemNameRefusal`). The message names the other owner (the stored
* container, the shipping package, or the container's own expansion) and
* gives the family's prescription: add the view as a member of the
* container that owns the name, or save a view item under the name. ⛔ It
* never prescribes a save under a name another stored row holds: an
* author (or an AI) following such an arm literally would replace that
* row and drop the very views this refusal keeps serving. Runtime words
* carry no tracker number.
*/
static async viewContainerNameCollisionRefusal(host: Pick<ProtocolHost, 'expandRuntimeViewContainer' | 'expandStoredViewContainers' | 'lookupArtifactItem' | 'overlaidShippedContainerViewNames' | 'readActiveOverlayRows' | 'rethrowUnlessMetadataStoreUnprovisioned' | 'storedOverlayEntries'>, type: string,
item: unknown,
saveName: string,
packageId: string | null | undefined,): Promise<(Error & { code: 'VALIDATION_ERROR'; status: 400 }) | undefined> {
if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'view') return undefined;
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
const body = item as Record<string, unknown>;
const stamped = body.name ? body : { ...body, name: saveName };
if (!isAggregatedViewContainer(stamped)) return undefined;
const served = host.expandRuntimeViewContainer(type, stamped, { packageId });
let records: any[] = [];
try {
// [ADR-0131 D6] A save lands environment-wide, so its siblings are
// the environment-wide rows.
records = await host.readActiveOverlayRows({ type });
} catch (error) {
// [#5532] The readers' rule: only an unprovisioned store means "no
// rows". Any other failure is not answered as "no sibling".
host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
}
const siblings = host.expandStoredViewContainers(
type,
host.storedOverlayEntries({ type }, records).filter((entry) => entry.name !== saveName),
);
const siblingServing = (name: string) => siblings.find(({ item: expanded }) => expanded.name === name);
const overlaid = host.overlaidShippedContainerViewNames(type, stamped, packageId);
const shippedServing = (name: string): Record<string, unknown> | undefined => {
if (overlaid.has(name)) return undefined;
const artifact = host.lookupArtifactItem(type, name) as Record<string, unknown> | undefined;
if (!artifact || !isShippedViewItem(artifact)) return undefined;
return typeof artifact._packageId === 'string' && artifact._packageId !== '' ? artifact : undefined;
};
const refusal = (text: string) => {
const err = new Error(`Invalid view container: ${text}`) as Error & { code: 'VALIDATION_ERROR'; status: 400 };
err.code = 'VALIDATION_ERROR';
err.status = 400;
return err;
};
const kindOn = (view: Record<string, unknown>) => `${String(view.viewKind)} view on '${String(view.object)}'`;
const viewItem = (name: string) => `a view item (name, object, viewKind and config) under '${name}'`;
const asMemberOf = (container: string) =>
`Add the view as a member of the container '${container}' (its list, listViews, form or formViews)`;
const ofItsOwn = 'the container under a name of its own that no package ships and no stored container expands';
// ⛔ Every message names the owner, then gives the prescription, and
// only then explains: a 4xx message crosses the REST boundary bounded
// at 500 characters by truncating its TAIL (`CLIENT_MESSAGE_MAX`), so
// the explanation is the half an author can lose and still act.
//
// The save name: the row this container would be.
const rowHides = 'this container would be that row, so';
const sibling = siblingServing(saveName);
if (sibling) {
return refusal(
`it is saved under '${saveName}', which is a name the stored container '${sibling.container.name}' `
+ `expands (its ${kindOn(sibling.item)}). ${asMemberOf(sibling.container.name)}, or save `
+ `${viewItem(saveName)}. An expanded view fills only a name that has no stored row of its own, and `
+ `${rowHides} that view would no longer be served and no read would answer a view under '${saveName}'.`,
);
}
const shipped = shippedServing(saveName);
if (shipped) {
return refusal(
`it is saved under '${saveName}', which is the name of the ${kindOn(shipped)} the package `
+ `'${String(shipped._packageId)}' ships. Save ${viewItem(saveName)} to override the packaged view, or `
+ `save ${ofItsOwn}. A stored row under a packaged view's name takes that view's place, and ${rowHides} `
+ `the packaged view would no longer be served and no read would answer a view under '${saveName}'.`,
);
}
const own = served.find((expanded) => expanded.name === saveName);
if (own) {
const object = String(own.object);
const objectRow = records.find((record) => record?.name === object && record?.name !== saveName);
const firstArm = objectRow === undefined
? `Save the container under its object's name, '${object}'`
: isAggregatedViewContainer(host.storedOverlayEntries({ type }, [objectRow])[0]?.data)
? asMemberOf(object)
: `Save ${ofItsOwn}`;
return refusal(
`it is saved under '${saveName}', which is a name its own expansion produces (its ${kindOn(own)}). `
+ `${firstArm}, or save ${viewItem(saveName)}. An expanded view fills only a name that has no stored `
+ `row of its own, and ${rowHides} no read would answer a view under '${saveName}'.`,
);
}
// Every name its expansion produces: the views this container would serve.
for (const view of served) {
const name = String(view.name);
const taken = `its ${kindOn(view)} would be served as '${name}'`;
const other = siblingServing(name);
if (other) {
return refusal(
`${taken}, a name the stored container '${other.container.name}' already expands. `
+ `${asMemberOf(other.container.name)}, or save ${viewItem(name)}. Saved under '${saveName}', this `
+ `container and that one would both serve '${name}': the one read last would replace the other's `
+ `view on both doors, and nothing would say why.`,
);
}
const packaged = shippedServing(name);
if (packaged) {
return refusal(
`${taken}, the name of the ${String(packaged.viewKind)} view the package `
+ `'${String(packaged._packageId)}' ships. Save ${viewItem(name)} to override the packaged view, or `
+ `give the member a key of its own that no package ships and no stored container expands. Saved `
+ `under '${saveName}', this container's view would replace the packaged view on both doors, and `
+ `nothing would say why.`,
);
}
}
return undefined;
}
/** The body of `ObjectStackProtocolImplementation#saveMetaItem`; the method's docblock there is its contract. */
static async saveMetaItem(host: Pick<ProtocolHost, 'recordMetadataAudit' | 'saveMetaItemUnaudited'>, request: SaveMetaItemRequest): Promise<{
state: "draft" | "active";
message: string;
advisories?: {
rule: string;
path: string;
where: string;
message: string;
hint: string;
severity: "error" | "info" | "warning";
}[] | undefined;
projectionApplied?: MutationProjectionOutcome | undefined;
success: boolean;
version: string;
seq: number;
}> {
// [#28355] A refusal that carries no row of its own leaves its `denied` row here.
return withRefusalAudit((entry) => host.recordMetadataAudit(entry), {
operation: 'save', type: request.type, name: request.name, actor: request.actor,
source: request.source ?? 'protocol.saveMetaItem',
}, () => host.saveMetaItemUnaudited(request));
}
/** [#28355] The body of {@link saveMetaItem} before its refusal audit; that method's docblock is the contract. */
static async saveMetaItemUnaudited(host: Pick<ProtocolHost, 'anonymousElevatedFlowRefusal' | 'applyRegistryWriteThrough' | 'assertLockAllowsWrite' | 'assertRuntimeAuthoringRules' | 'authoredLockFamily' | 'authoringChannel' | 'carryForwardRedactedCredentials' | 'classifyObjectContribution' | 'codeOnlyCreateError' | 'codeOnlyOverrideError' | 'credentialChannelFor' | 'declinesStoredRow' | 'defaultRecordPageSaveRefusal' | 'emitMetaItemPublished' | 'emitMetadataMutation' | 'engine' | 'ensureObjectStorage' | 'ensureOverlayIndex' | 'envWritableTypes' | 'externalBindingSaveRefusal' | 'flowCanonicalizeFallbackWarned' | 'flowSaveReplaysRetired' | 'foldObjectExtendersFromRegistry' | 'getMetaItems' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'isWritablePackage' | 'namedBaseOverlayWriteRefusal' | 'objectExtensionItemRefusal' | 'objectNamespaceObjectNameClash' | 'objectNamespacePrefixViolation' | 'objectRegistrationRefusal' | 'overlayPackageMismatchError' | 'overrideWriteVerdict' | 'packagelessAddress' | 'packagelessDraftAddress' | 'packagelessOverlayWriteRefusal' | 'permissionSetNameCollisionRefusal' | 'readItemActiveRows' | 'readMetaItem' | 'receiptVersion' | 'recordMetadataAudit' | 'refuseOrganizationScopedWrite' | 'refusePackagedBaseOverride' | 'refuseUngrammaticalMetaItemName' | 'refuseUnmintableMetaType' | 'registryAllowsOverlay' | 'resolveFlowCanonicalizer' | 'resolveSduiManifest' | 'restoreInjectedColumnEchoes' | 'restoreTranslatedObjectEchoes' | 'restoredCredentialPathsFor' | 'rethrowUnlessMetadataStoreUnprovisioned' | 'runAuthoringGate' | 'runMutationProjector' | 'saveConflict' | 'saveWriteBinding' | 'seedExternalIdSaveRefusal' | 'shippedArtifactsOf' | 'storableViewFallbackWarned' | 'storedParentForToken' | 'stripServedObjectColumns' | 'tenantAuthoredWriteRefusal' | 'uninstalledNamedBaseRefusal' | 'unknownDatasourceSaveRefusal' | 'unknownGrantObjectSaveRefusal' | 'unknownPicklistBindingSaveRefusal' | 'viewContainerNameCollisionRefusal'>, request: SaveMetaItemRequest) {
// [ADR-0131 D6] FIRST, before every other gate and every read: an
// organization-scoped write is refused for every type, draft or
// publish. See {@link organizationScopedWriteRefusal}.
host.refuseOrganizationScopedWrite(
`Metadata item '${request.type}/${request.name}'`, request,
);
// [commit fd6bdf89f] The ADR-0112 envelope this refusal always owed. Every OTHER
// refusal in this method declares `code` AND `status`
// (`NOT_OVERRIDABLE`/403, `NOT_CREATABLE`/403, `ITEM_LOCKED`/403,
// `OBJECT_OVERLAY_PACKAGE_MISMATCH`/422, the org-scope and
// destructive-change refusals, the parent-version conflict/409); this
// one declared neither, and an undeclared throw is withheld by
// {@link clientFacingFailureText} (a positive list keyed on 4xx
// `status`) and rendered `500 INTERNAL_ERROR` by `handleRouteError` —
// a SERVER FAULT for what is purely the caller's mistake, telling the
// author less than the producer knew and inviting a pointless retry.
//
// MEASURED reachable from the wire — this is an AUTHORING refusal, not
// a programming-error guard. `PUT /api/v1/meta/:type/:name` unwraps the
// `{ item }` / `{ metadata }` envelope shapes before calling here, so
// `{"item": null}` and `{"metadata": null}` arrive as `item: null` and
// land exactly here (measured end to end against a live server: both
// answered `500 INTERNAL_ERROR` before this change). ⚠️ A missing,
// empty or literal-`null` BODY does NOT reach this guard: the route
// folds it to `{}`, which is truthy, and the per-type Zod parse below
// refuses it with `422 INVALID_METADATA` — so this guard's whole
// reachable population is the explicitly-null envelope.
//
// `INVALID_REQUEST`/400 rather than the `INVALID_METADATA`/422 the
// sibling refusals use, and NEITHER mints a code: both are already
// registered to this package in the ADR-0112 ledger (D3). The 422
// sites all describe a body that EXISTS and failed the per-type parse,
// and every one carries structured `issues`; here there is no body to
// validate and no issues to report, so a 422 would misdescribe the
// failure and break that convention. The structural twin is
// {@link rollbackMetaItem}'s own opening guard — same class, same
// position, a malformed REQUEST ENVELOPE rather than an off-spec
// document — which is `INVALID_REQUEST`/400.
if (!request.item) {
const err: any = new Error(
`saveMetaItem requires an 'item' body for '${request.type}/${request.name}'. `
+ `Send the metadata document as the request body, or wrap it as {"item": {...}} / {"metadata": {...}}. `
+ `An explicitly null item is refused rather than persisted as an empty document.`,
);
err.code = 'INVALID_REQUEST';
err.status = 400;
throw err;
}
// [#24395] The authoring surface the draft save stamps on every key
// path it changes: a value outside the closed set is refused here,
// before any read or write, with the request-envelope refusal above —
// never stamped as `api`, which would record a caller's mistake as
// a fact about who wrote the draft. The HTTP doors never send
// `copilot` or `mcp` (`metaSaveRequestOptions`); an in-process tool may.
if (request.surface !== undefined && !MetadataAuthoringSurfaceSchema.safeParse(request.surface).success) {
const err: any = new Error(
`saveMetaItem 'surface' must be one of copilot, mcp, studio or api for '${request.type}/${request.name}'; `
+ `got ${JSON.stringify(request.surface)}. Omit it for a save that is none of the copilot, an MCP client or Studio (recorded as api).`,
);
err.code = 'INVALID_REQUEST';
err.status = 400;
throw err;
}
// [#27176] The OAuth client an `mcp` save names, stated only by the
// MCP build door: refused beside any other surface (a client is the
// MCP door's attribution, never a label another caller borrows) and
// refused malformed, both before anything is read or written.
if (request.client !== undefined
&& (request.surface !== 'mcp' || authoringClientOf(request.client) === undefined)) {
const err: any = new Error(
request.surface !== 'mcp'
? `saveMetaItem 'client' is stated only with surface 'mcp' for '${request.type}/${request.name}'; `
+ `got surface ${JSON.stringify(request.surface ?? null)}. Only the MCP build door names the OAuth client it verified.`
: `saveMetaItem 'client' must be { id, name? } with a non-empty id and, when present, a non-empty name `
+ `for '${request.type}/${request.name}'.`,
);
err.code = 'INVALID_REQUEST';
err.status = 400;
throw err;
}
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}.
request = canonicalizeMetaRequestType(request);
// [commit 311433f6b] The item-name grammar verdict — static, request-only, so it
// runs before the store-backed type probe below. Closes the measured
// slash bypass: a slash-bearing name used to skip the #8421 refusal
// entirely. See {@link refuseUngrammaticalMetaItemName}.
host.refuseUngrammaticalMetaItemName(request);
// [#8421] …and the second verdict, on the door that MINTS. Kept here
// rather than inside the fold above because it is not answerable from
// the request alone — see {@link refuseUnmintableMetaType} for the
// scoping, its exemption, and the measurements behind it.
await host.refuseUnmintableMetaType(request);
// What the history row, the audit row and the watch event record as the
// origin of this write. Defaults to this method — the ordinary Studio /
// REST / SDK save. The only caller that overrides it is
// {@link migrateStoredMetadata} (`'migrate-stored'`), so an operator
// reading a diff can tell a canonicalization pass from an author's edit
// (#4327). NOT request-derived: the REST layer builds this request field
// by field and never forwards a client-supplied `source`, so provenance
// stays something the server states, not something a caller claims.
const writeSource = request.source ?? 'protocol.saveMetaItem';
// Drop OUR OWN read decorations before anything reads the body (#4326).
// The write path persists verbatim by design for every type but `view`
// (ADR-0005 appendix (c), the "Addendum — 2026-05-16 (c)"), and a view
// is gated on this same body before it is projected, so
// the standard Studio round-trip — GET (decorated) → edit → PUT the whole
// body — would otherwise bake a read-time verdict into the row, its
// checksum, and every history diff. See {@link stripReadDecorations} for
// why this is a silent strip and which underscore keys are NOT touched.
// Placed first so the destructive-change diff, the schema gate, the
// authoring gate and the persisted body all see the same document.
request.item = stripReadDecorations(request.item);
// [#16702] …and the three DERIVED protection keys, for the same reason
// one beat later. `metadata-read-decorations.ts` deliberately does NOT
// strip `_provenance` from a SERVED document (a served body must keep
// its provenance on re-parse), so the very same round-trip echoed
// `_packageId` / `_packageVersion` / `_provenance: 'package'` straight
// back into the tenant's own row — and for every non-`object` type the
// hydrated row's own bytes then decided it was a code artifact, closing
// the tenant out of their own item with `NOT_OVERRIDABLE` forever. The
// read side recomputes all three from the artifact on every read
// ({@link mergeArtifactProtection}), so nothing is lost by not storing
// them. See {@link DERIVED_PROVENANCE_KEYS} for why `_lock*` is NOT in
// the set. Placed alongside the decoration strip so the
// destructive-change diff, the schema gate, the authoring gate and the
// persisted body all still see one document.
//
// [#20761, ADR-0126 §2] …except for a FLOW, which is asked the one
// authoring rule FIRST, while the body still carries the stamps the
// caller sent: a flow no managed package loaded, sent with stamps that
// would classify it as code-shipped, is refused loudly rather than
// stripped silently, and a flow the loader's set holds is a locked
// base. [#20863] The base this save names rides along, because the
// rule refuses one no installed package holds — a binding the
// platform could never honour. A tenant row's own stamps echoed on a
// round trip pass and are stripped below as for every type. Every
// other type is untouched — {@link tenantAuthoredWriteRefusal}
// answers `null` for it.
//
// Asked of AUTHORING writes only. The two server-stated rewrites of
// rows this store already holds — {@link migrateStoredMetadata}
// (`source: 'migrate-stored'`, the only caller that states a source)
// and {@link duplicatePackage} (`writeFace: 'package-duplicate'`) —
// are no caller's claim about anything: a row stored before the
// #16702 strip may still carry stale stamps, and rewriting it keeps
// the silent strip it always had rather than failing the rewrite.
// [ADR-0146 D2, ruling A on #28390] The override write gate — on every
// save, whatever its source, and ahead of the flow-only sealed check
// below, so a declared or same-named item meets its own named
// refusal rather than a regime sentence: only the base's paired
// `<base>.custom` declares an override; a dependent's same-named item
// is refused (rename, or for the pair declare-or-rename); `overrides`
// on a dependent, on a package outside the closure or on a type with
// no override channel is refused. An admitted declaration is the
// pair's own row: the sealed refusal does not apply to it, and the
// store is told a runtime-only write (both below).
//
// A refused DECLARATION throws here. An undeclared same name throws
// just before the store is asked (below), after every refusal this
// door already answered for that write, so no existing refusal's code
// or status changes (a view container's name collision keeps its
// 400, a lock its ITEM_LOCKED).
//
// [ADR-0146 D11] …and AHEAD of it, the package-less write onto a
// packaged item, closed: an authoring save naming no package, of an
// item a code package ships, on one of the five overlay types, whose
// row `os migrate packageless-overlays` would move (#28576 ruling 2:
// every row it leaves keeps this write), is refused naming the base's
// paired `.custom` and the ceremony
// ({@link packagelessOverlayWriteRefusal}). Ahead of the gate so the
// writer reads that fix, not the gate's "a row bound to no package
// carries `overrides`… rename" for the body Setup sends as it read
// it. Every other type's packaged item is sealed further down
// ({@link refusePackagedBaseOverride}). Registry reads first: the
// close's one store read (the item's rows) happens only for a name
// one read-only package ships with an ensurable pair, so #5706's lock
// gate stays the first store reader of every other name. The
// server-stated rewrites (`source` set, `package-duplicate`) name the
// row they rewrite and are not asked.
//
// This retires the migration window's allowance (a package-less save
// landing on a pair row the ceremony moved kept that row's
// declaration): such a save is this refusal now.
//
// [#28905, ADR-0146 D1, D11] …and the save NAMING the read-only base
// itself (`?package=<base>`, draft or active), of an item of one of the
// five overlay types it ships: refused with the same fix, the pair
// ({@link namedBaseOverlayWriteRefusal}; registry reads only). Before
// it, such a save landed an undeclared row bound to the base, served
// in place of the base's document and never seen by the ceremony.
if (request.source === undefined && request.writeFace !== 'package-duplicate') {
const closed = await host.packagelessOverlayWriteRefusal({
type: request.type,
name: request.name,
packageId: request.packageId,
state: request.mode === 'draft' ? 'draft' : 'active',
item: request.item,
}, 'save');
if (closed) throw closed;
const namedBase = host.namedBaseOverlayWriteRefusal({
type: request.type,
name: request.name,
packageId: request.packageId,
item: request.item,
}, 'save');
if (namedBase) throw namedBase;
}
const overrideVerdict = host.overrideWriteVerdict(request);
if (overrideVerdict.verdict === 'refuse' && overrideVerdict.rule !== 'undeclared_same_name') {
throw overrideWriteRefusalError(overrideVerdict);
}
const declaredOverride = overrideVerdict.verdict === 'admit';
if (request.source === undefined && request.writeFace !== 'package-duplicate') {
const authored = await host.tenantAuthoredWriteRefusal({
type: request.type,
name: request.name,
item: request.item,
...(request.packageId ? { packageId: request.packageId } : {}),
});
if (authored) throw authored;
// [#26708] …and the named-base rule for EVERY type, draft or
// active: a base the save names must be an installed package. A
// flow was asked it just above, at its own position; the second
// ask answers the same. See {@link uninstalledNamedBaseRefusal}.
const unbound = host.uninstalledNamedBaseRefusal(request);
if (unbound) throw unbound;
}
request.item = stripDerivedProvenance(request.item);
// [#6562] …and OUR OWN injected system columns, for the same reason and
// at the same moment. `governServedItem` now serves the EFFECTIVE object
// schema, so the very same Studio round-trip would otherwise persist
// `created_at` / `owner_id` / `organization_id` / … into a body whose
// author declared none of them — turning the platform's own columns into
// a phantom customization in `sys_metadata`, in the checksum, in every
// history diff, and in the layered read's `overlay` layer. Placed
// alongside the decoration strip so the destructive-change diff, the
// schema gate, the authoring gate and the persisted body all still see
// one document. See {@link stripServedSystemColumns} for why this is a
// separate strip from the decoration list and not another entry in it.
//
// [#29673] …and, one beat BEFORE that strip, the read's TRANSLATION
// of an injected column taken back off: a label the `/meta` read served
// in the caller's language through the built-in table is put back to
// the platform's own text, so the column is the platform's definition
// again and comes off with the rest. Pure — no read, so it runs before
// the refusals. The author's own slots are compared with the stored
// row later, beside the credential carry-forward that reads the same
// row. See {@link restoreInjectedColumnEchoes}.
request.item = host.restoreInjectedColumnEchoes(request);
request.item = host.stripServedObjectColumns(request.type, request.item);
// Per-item lifecycle (ADR-0005 §"Drafts"). Default is `'publish'`
// (legacy semantics — save goes straight live) to keep callers
// that predate the draft/publish split working. Studio's
// designer surface opts into staged drafts by sending
// `?mode=draft`; the `POST /publish` endpoint then promotes it.
const mode: 'draft' | 'publish' = request.mode === 'draft' ? 'draft' : 'publish';
// ADR-0005 (extended — two-tier model): project-kernel customization is
// gated by per-item provenance, not just the type-level flag.
//
// • Item exists as a packaged artifact → require `allowEnvironmentOverlay`
// (writing here would overlay code-shipped behaviour; gated for
// security on executable types like hook/trigger/validation).
// • Item does NOT exist as an artifact → require `allowRuntimeCreate`
// OR `allowEnvironmentOverlay`. This lets users author brand-new hooks /
// validations / triggers without unlocking the artifact-shadowing
// capability. Returns `not_creatable` (vs `not_overridable`) so
// the UI can present a tailored message.
const overlayAllowed = host.isOverlayAllowed(request.type);
const runtimeCreateAllowed = host.isRuntimeCreateAllowed(request.type);
// #5086 — CODE-ONLY TYPES ARE REFUSED ON EVERY KERNEL, not only on
// project-scoped ones. A type whose registry entry sets BOTH
// `allowRuntimeCreate: false` AND `allowEnvironmentOverlay: false` declares
// that it has **no runtime write channel at all** — today `job`
// (#4509: `handler` resolves only through the compiled bundle's
// function table, so a runtime-created job could never be scheduled)
// and `agent` (ADR-0063 §2: platform-owned, per-org forks withdrawn).
//
// The rest of this block stays behind `environmentId !== undefined`
// because ADR-0005 §"Whitelist enforcement" deliberately keeps the
// *overlay* whitelist off single-kernel deployments ("keep their
// existing behaviour"). That sentence predates `allowRuntimeCreate`
// and speaks only of the overlay list — it never granted a topology
// the right to author a type the registry declares code-only. And the
// premise the carve-out rests on ("this kernel is the package
// author's own bootstrap channel") is simply not true for the CLI's
// lightweight assembler: a host config with instantiated plugins
// (`isHostConfig` → `shouldBootWithLibrary === false`) boots
// `new ObjectQLPlugin()` with NO environmentId, so the flagship
// showcase — a self-hosted app server whose `PUT /api/v1/meta/*` is
// an END-USER surface — ran with this entire gate disengaged. Keying
// authorization off a row-scoping key is what made a type-level
// declaration depend on deployment topology; the declaration decides
// it here instead.
//
// [#22220] "The rest of this block" no longer stays behind it either:
// the package door below now asks on every topology too — see its
// call site for why that moves no acceptance set.
//
// `isOverlayAllowed` still consults `OS_METADATA_WRITABLE`, so the
// documented operator escape hatch stays the ONE door: unlocking a
// type there unlocks it here too — [ADR-0131 D6] for a NEW item only.
// An item a managed package ships is sealed, so for it this refusal
// reads the registry alone ({@link isSealedManagedItem}'s type half):
// with the hatch open or shut it is refused here, by the same sentence,
// instead of being carried past this gate to be refused by the package
// door in another one. `deleteMetaItem` is deliberately NOT gated the
// same way — removing a code-only row that predates this refusal is
// repair, and must stay possible.
//
// [#6960] THAT CARVE-OUT NOW NAMES BOTH TIERS, because as written it
// covered only the CODE-ONLY one (`allowRuntimeCreate: false` AND
// `allowEnvironmentOverlay: false`, i.e. the `if` immediately below) while
// the identical argument had grown a second population: an
// ARTIFACT-BACKED item of a type that kept `allowRuntimeCreate: true`
// and had its `allowEnvironmentOverlay` ROLLED BACK to `false` (commit
// ee58392e1 — `permission` / `position` / `page` / `app` / `dataset` /
// `book`). Its loader still merges the overlay at read time
// (`supportsOverlay: true`, untouched by the rollback), so a row
// authored before the rollback keeps shaping the effective body while
// the ordinary "Reset to package default" answered 403 — repair
// reachable only through the operator hatch. The maintainer ruled on
// 2026-08-10 that the delete side moves for that tier too: the
// removal restores the code-declared state, is strictly narrowing,
// and cannot widen anything.
//
// ⛔ THE ASYMMETRY IS DELIBERATE AND DELETE-ONLY. This gate and the
// artifact-backed refusal below it are UNCHANGED: create and update
// on such an item stay refused exactly as today. Do not "restore
// symmetry" in either direction — symmetrizing towards delete re-opens
// the write door commit ee58392e1 closed, symmetrizing towards save re-traps the
// repair. And the relaxation is keyed on `supportsOverlay`, not on
// `allowEnvironmentOverlay`, so it stops at the tier boundary: `object`
// (`supportsOverlay: false`, its overlay a contributor LAYER per
// ADR-0029 D9) keeps refusing both verbs, which is D9.6's declared
// cost and is pinned. See {@link deleteMetaItem}.
if (!runtimeCreateAllowed) {
const shipped = host.isArtifactBacked(request.type, request.name);
const channel = shipped
? host.registryAllowsOverlay(request.type)
: overlayAllowed;
if (!channel) {
throw shipped
? host.codeOnlyOverrideError(request.type, request.name)
: host.codeOnlyCreateError(request.type);
}
}
// [#8184] THE PACKAGE DOOR — the refusal of a write onto an item a
// code package ships, on a type with no per-org overlay channel.
// The verdict and its full record live in
// {@link refusePackagedBaseOverride}: [#20679] lifted out of this
// method UNCHANGED, so a second write door onto the same artifact
// asks this exact predicate and gets this exact emitter through
// {@link packagedBaseRefusal}, rather than a copy that agrees with
// this one only until either of them moves.
//
// [#22220] ON EVERY TOPOLOGY, and HERE: ahead of every check below
// that judges the request's body or the store. It used to sit behind
// `environmentId !== undefined`, on the ground that a host-config
// kernel meets the same predicate one layer down, at the repository
// write (`SysMetadataRepository.assertAllowed`, the first statement
// of `repo.put`). It does, but `repo.put` is this method's LAST act,
// so on that kernel every refusal in between answered first. Measured
// on a host-config boot: a publish of a packaged `object` whose body
// the runtime authoring gate refuses answered `422 INVALID_METADATA`
// where an environment kernel answered `403 NOT_OVERRIDABLE` for the
// same request, and a body the spec-conformance parse refuses did the
// same in draft and publish mode. The author was told to repair
// findings that no write through this door could ever land, and was
// refused for the basic reason only after repairing them. The same
// window held the ADR-0029 D9.9 package mismatch, the destructive
// diff, the layered-envelope and save-name refusals, the flow
// conversion conflict, the stored-hook body refusal and the domain
// plugins' authoring gates; #21694 had taught the `_lock` gate below
// to defer to this door by hand. Asked once, here, the door answers
// before all of them — one request, one refusal, on both kernels —
// and none of them has to learn to defer to it.
//
// ⛔ NO ACCEPTANCE SET MOVES. This predicate is the repository's
// (the registry's `allowEnvironmentOverlay` — [ADR-0131 D6] never the
// `OS_METADATA_WRITABLE` hatch for an item a managed package ships —
// and a named read-only base through the one `isWritablePackage`),
// and `repo.put` refuses every write it refuses, on every topology —
// so a request refused here was refused before, and only which
// refusal its author reads has changed: the same code and status on
// both kernels, and this door's sentence on both. The repository's
// check stays the store-level backstop for the doors that reach `put`
// without passing here (draft promotion, restore, revert). Nor does
// this retire a single-kernel carve-out: ADR-0005 §"Whitelist
// enforcement" kept such deployments "any type writable", but the
// repository has refused these writes on them all along; the door
// only answers first.
//
// [#23577] Every write over a sealed name reads one sentence: the
// first-write pin (`If-None-Match: *`) declares no create, so the door
// advises neither a create nor an edit.
// [ADR-0146 D2] An admitted declared override (see the gate above) is
// the pair's own row: the sealed refusal judges the base's managed
// item, so it does not apply to it.
if (!declaredOverride) host.refusePackagedBaseOverride(request);
// ADR-0010 L3 — per-item lock. Artifact `_lock` (or persisted
// overlay `_lock`) blocks save independent of the L1 type-level
// flag. Records the denial in `sys_metadata_audit` before
// throwing so refused attempts are visible in compliance reports.
//
// [#21694] On EVERY topology — it used to sit inside the package
// door's `environmentId` block, so a host-config kernel never asked
// it (see {@link lockWriteRefusal}). Its rank is unchanged and is the
// same on every kernel: BELOW the package door. #21694 kept that rank
// on a host-config kernel by asking {@link packagedBaseRefusal} here,
// because that kernel's door then answered only at the repository
// write; [#22220] the door above now throws on every kernel whenever
// it refuses, so that question always answered "no refusal" here and
// is gone. One request, one refusal code, on both kernels — the
// `_lock` gate never pre-empts `NOT_OVERRIDABLE` on either topology.
{
const lockErr = await host.assertLockAllowsWrite({
type: request.type,
name: request.name,
// [#21761] The save's address carries its package, as the read's does.
...(request.packageId ? { packageId: request.packageId } : {}),
operation: 'save',
...(request.actor ? { actor: request.actor } : {}),
source: writeSource,
});
if (lockErr) throw lockErr;
}
// [#23165, ADR-0048] THE WRITE ADDRESS of a direct save that names no
// package: the item's own package when its active rows are bound to
// exactly one ({@link packagelessAddress}). It used to be the
// package-unbound row, always, so a save of a package's item minted a
// second row beside the package's and answered `200` while the item
// read kept serving the package's row. The draft save already resolved
// its address this way (#11087, `SysMetadataRepository.resolveWriteHead`).
//
// Resolved ONCE, here, and from here on the save IS a save naming that
// package: every gate below that asks about the row this save writes
// (the D9.9 object check, the stored lock family, the runtime
// authoring gate, ADR-0070 D1's writable-base check, the lock parent,
// the credential carry-forward, `repo.put`, the registry write-through
// and the receipt) reads the same `packageId`, so no two of them can
// judge different rows. A package that is read-only answers here what
// `?package=` naming it answers.
//
// Below the authorization refusals on purpose: the code-only refusal,
// the package door and the `_lock` gate judge the item, not its row,
// and they answer before this store read, as #22220 ordered.
//
// Asked of a publish-mode AUTHORING save whose `packageId` is absent or
// `null`, the two spellings of "no package" the request contract
// states. Not asked of: a save that names a package (ADR-0048, its
// address is its own); a draft save, whose binding the repository
// resolves (#11087); the server-stated rewrites of a row this store
// already holds (`source` set: the stored-metadata migration and the
// stored flow-credential move, which pass `null` for the
// package-unbound row they read and rewrite; `package-duplicate`,
// which always names its target), the same two the authoring rules
// above exempt.
//
// Several bindings is a name more than one package holds, and a save
// naming none of them is refused, not guessed.
// [#23514] Whether the CALLER named a package, read before the address
// below may name one for it: the D9.9 refusal's prescription differs.
const namedNoPackage = request.packageId == null;
if (
mode === 'publish'
&& request.packageId == null
&& request.source === undefined
&& request.writeFace !== 'package-duplicate'
) {
const writeType = PLURAL_TO_SINGULAR[request.type] ?? request.type;
const address = await host.packagelessAddress(
writeType, request.name, itemDiscriminator(writeType, request.item),
);
// [ADR-0150 D4, ruling 6902014292] An action is keyed
// `(package, objectName, name)`: when every package that holds the
// name binds it to an object other than the one this body binds,
// no package holds this item, so the save writes the
// environment's own row on this object and every package's item
// stays where it is ({@link packagelessActionKeyedAddress}).
const keyed = await packagelessActionKeyedAddress(
host, writeType, request.name, request.item, address,
);
const environmentOwnAction = keyed === 'environment';
// [#32605, epic ruling 6781691009] A name a disabled package also
// holds is written where the read naming no package serves it
// ({@link servedPackagelessSaveAddress}): never the disabled
// package's row, never a new package-unbound row beside an
// enabled holder, and a refusal names only the served holders.
// [ADR-0150 D4] For an action some holder binds to another object,
// judged over the holders at the body's object first. When no
// holder there is disabled, that judgment declines, and the
// name's own judgment answers as it does for every other save: a
// disabled holder on another object is never a served holder, so
// the one enabled holder on the body's object takes the write.
const member = itemDiscriminator(writeType, request.item);
const served = environmentOwnAction
? undefined
: (keyed !== undefined
? await servedPackagelessSaveAddress(host, writeType, request.name, member, keyed, true)
: undefined)
?? await servedPackagelessSaveAddress(host, writeType, request.name, member, address);
if (environmentOwnAction) {
// The package-unbound row: `packageId` stays empty.
} else if (served !== undefined) {
if (served.packageId !== null) request = { ...request, packageId: served.packageId };
} else if (address.candidates.length > 1) {
// [#34681] …where the read naming no package serves the
// row-held base, the save writes the base's row
// ({@link packagelessRowHeldBaseAddress}); otherwise refused
// naming every package the rows are bound to.
const base = await packagelessRowHeldBaseAddress(host, writeType, request.name, member);
if (base === undefined) throw packagelessAddressAmbiguityRefusal('save', request.type, request.name, address.candidates);
request = { ...request, packageId: base };
} else {
// [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the
// read naming no package counts ({@link packagelessHolderRefusal}):
// two or more enabled holders are refused naming them, and a name
// only disabled packages hold is refused naming none, never
// written at one row's package or as a new package-unbound row.
const holderRefusal = packagelessHolderRefusal(
host, 'save', request.type, writeType, request.name, itemDiscriminator(writeType, request.item), address,
);
if (holderRefusal) throw holderRefusal;
// [#35524] …and a named non-canonical member only a dependent
// holds, where the read naming no package takes the row-held
// base's address: the base's row, as the save naming the base
// writes it ({@link packagelessRowHeldBaseAddress}), never the
// dependent's row the read does not serve there.
const base = address.candidates.length === 1
? await packagelessRowHeldBaseAddress(host, writeType, request.name, member)
: undefined;
const resolved = base ?? address.packageId;
if (resolved !== null) request = { ...request, packageId: resolved };
}
}
const singularType = PLURAL_TO_SINGULAR[request.type] ?? request.type;
// [#23712] The draft a draft save naming no package writes
// ({@link packagelessDraftAddress}): the repository resolves its
// binding (#11087), so `packageId` stays empty, but the address is
// read here for the two gates below that judge the row it lands in.
// Read once, for the same authoring saves the publish-mode address
// above is resolved for.
// [ADR-0150 D4] …asked of the body this save writes, so an action
// draft the environment owns is judged as the package-unbound draft
// the repository writes it as.
let draftAddress = mode === 'draft'
&& request.packageId == null
&& request.source === undefined
&& request.writeFace !== 'package-duplicate'
? await host.packagelessDraftAddress(
singularType, request.name, itemDiscriminator(singularType, request.item), request.item,
)
: undefined;
// [#34681] An item whose active rows are bound to two or more packages
// where the read naming no package serves the row-held base: the
// draft save writes the base's draft, as the save naming that base
// does ({@link packagelessRowHeldBaseAddress}). Otherwise the
// ambiguous address is left to the repository's `409`, as before.
// `followedBase` keeps the base for the two rules below that judge a
// draft save's inherited package (the named-base rule and the late
// override re-judgment): the base is judged exactly as the save
// naming it is, an id no installed package has refused `422`.
// [#35524] …and the same where the active rows at the member are bound
// to the one dependent whose addition the read naming no package does
// not serve (it takes the base's address there): the base's draft,
// also over a stored package-unbound draft there (epic ruling
// 6781691009, contract review S2 option (b)). The named base is passed
// down, so the repository's orphan-draft adoption (a save naming no
// package) does not run: the package-unbound draft stays untouched, as
// the save naming the base leaves it, and the draft the next bare
// draft read, publish and discard reach is the one written here.
let followedBase: string | undefined;
if (draftAddress !== undefined && (draftAddress.kind === 'ambiguous' || draftAddressFollowsRowHeldBase(draftAddress))) {
const base = await packagelessRowHeldBaseAddress(
host, singularType, request.name, itemDiscriminator(singularType, request.item),
);
if (base !== undefined) {
request = { ...request, packageId: base };
draftAddress = undefined;
followedBase = base;
}
}
// [ADR-0150 D4] The environment's own action draft is one slot per
// name, and its per-item publish writes the one package-unbound row:
// a holder's customization stored in either is refused, never moved
// ({@link environmentActionDraftSlotRefusal}).
if (draftAddress !== undefined && draftAddress.kind !== 'ambiguous' && draftAddress.key === null && draftAddress.into === null) {
const slotRefusal = await environmentActionDraftSlotRefusal(
host, singularType, request.name, itemDiscriminator(singularType, request.item), request.item,
);
if (slotRefusal) throw slotRefusal;
}
// [ADR-0150 D3/D5, red line 2, ruling A] The draft save naming no
// package answers the holders as the publish-mode save above does
// ({@link packagelessHolderRefusal}), judged over the item's active rows
// and its drafts: the draft address alone took the one package with a
// row, or a new package-unbound draft. An ambiguous draft address is
// left to the repository's `409`, as before.
if (draftAddress !== undefined && draftAddress.kind !== 'ambiguous') {
const member = itemDiscriminator(singularType, request.item);
const active = await host.packagelessAddress(singularType, request.name, member, 'active');
const holderRefusal = packagelessHolderRefusal(host, 'save', request.type, singularType, request.name, member, {
candidates: [...new Set([...active.candidates, ...draftAddress.drafts.candidates])],
unbound: active.unbound || draftAddress.drafts.unbound,
});
if (holderRefusal) throw holderRefusal;
}
// [#26921] THE NAMED-BASE RULE for the binding a save naming no
// package INHERITS: the package its address gives (the resolved
// `packageId` above for a publish-mode save; the draft address's
// package for a draft save) must be installed too. Rows bound to an id
// no installed package has were stored before the save door refused
// naming one, and this save kept extending them. Refused, naming the
// id and the way out, ⛔ never re-homed package-less in silence: that
// would move the item without a word. Not asked of a save that names a
// package (asked above as named) nor of the server-stated rewrites,
// which resolve no address. An ambiguous draft address is left to the
// repository's `409`, as before. See {@link uninstalledNamedBaseRefusal}.
if (namedNoPackage && request.source === undefined && request.writeFace !== 'package-duplicate') {
const inherited = mode === 'draft'
? followedBase ?? (draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into : null)
: request.packageId ?? null;
const unboundInherited = host.uninstalledNamedBaseRefusal(
{ type: singularType, name: request.name, packageId: inherited },
{ inherited: true },
);
if (unboundInherited) throw unboundInherited;
}
// [ADR-0029 D9.9 / #6995] The refusal that is about REPRESENTABILITY
// rather than authorization: an `object` overlay bound to a package
// that does not own the object. See
// {@link overlayPackageMismatchError} for why one object name can
// carry at most one overlay layer while `sys_metadata` can hold two
// rows for it.
//
// AT THE PRODUCER, deliberately. Before D9 this row reached
// `registerObject`, which threw `already owned by package "…"` into
// `applyObjectRegistryMutation`'s best-effort `console.warn` — and
// `saveMetaItem` still returned a SUCCESS RECEIPT for a write the
// runtime had discarded (#6995, the silent write-side divergence).
// The receipt and the registry now agree because the write never
// happens: this precedes `ensureOverlayIndex` and every `put`.
//
// [#23514] The same holds for an object its package-less definition
// owns (the `'sys_metadata'` sentinel): a save naming a package beside
// it is refused here, with the move-into-a-package prescription
// ({@link unboundOwnerPackageRefusal}).
//