Repository navigation
Expand file tree
/
Copy pathprotocol-package-commits.ts
More file actions
2419 lines (2373 loc) · 147 KB
/
Copy pathprotocol-package-commits.ts
File metadata and controls
2419 lines (2373 loc) · 147 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 "Package revert, duplicate, import, orphans, commits,
* revertCommit, rollback" facet of `ObjectStackProtocolImplementation`: the
* bodies of `revertStoredPackage`, `duplicatePackage`,
* `importUnmanagedPackage`, `reassignOrphanedMetadata`, `listCommits`,
* `readRevertableCommit`, `revertCommit`, `rollbackToPackageCommit`,
* `rollbackMetaItem`, `rollbackMetaItemUnaudited` moved out of `protocol.ts`
* whole (split by #29998 and #30687).
*
* A MOVE, not a redesign. `ProtocolPackageCommitsFacet` 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 { ImportUnmanagedPackageRequestSchema } from '@objectstack/spec/api';
import type {
ImportUnmanagedPackageRequest,
InstallPackageRequest,
} from '@objectstack/spec/api';
import { packageScopedRowWhere } from './sys-metadata-repository.js';
import { overlayMemberWhere } from './migrations/overlay-index.js';
import type { SysMetadataRepository } from './sys-metadata-repository.js';
import { ConflictError, assertProtocolCompat } from '@objectstack/metadata-core';
import { isPlatformRecordRow } from '@objectstack/metadata';
import {
planUnmanagedImport,
UNMANAGED_SEED_TYPE,
unmanagedInstallPostureRefusal,
unmanagedInstallRenameRefusal,
type UnmanagedImportRenameRefusal,
} from './package-unmanaged-install.js';
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import {
DEFAULT_METADATA_TYPE_REGISTRY,
ManifestSchema,
deriveNamespaceFromPackageId,
manifestIdRefusal,
} from '@objectstack/spec/kernel';
import { planNamespaceRename } from './package-namespace-rename.js';
import {
BatchRowHealError,
canJudgeBatchObjects,
isBatchObjectType,
judgeBatchObjectRegistrations,
readActiveBatchRow,
registerAdmittedBatchRows,
settleBatchObjectRows,
syncAdmittedBatchStorage,
undoBatchRowWrite,
undoOutcomeForLog,
type BatchObjectRow,
type WrittenBatchRow,
} from './batch-object-registration.js';
import { extensionFieldSuffixRefusalError, judgeExtensionFieldSuffix } from './protocol-extension-field-suffix.js';
import { customizationPairManifestRefusal } from './protocol-customization-package.js';
import {
canonicalMetaType,
canonicalizeMetaRequestType,
overlaySchemaDeclaredKey,
} from './protocol-meta-type-schema.js';
import { permissionSetOwnerBindingRefusal } from './protocol-authoring-refusals.js';
import { zodIssuesToMetadataIssues } from './protocol-metadata-issues.js';
import {
bundleMemberDiscriminator,
memberOption,
mutationEventMember,
resolveBundleMemberSelector,
type CommitPlanItem,
} from './protocol-bundle-members.js';
import { mutationEventPackage, projectorEventPackage } from './protocol-mutation-package.js';
import { captureStoredExpressionChange, fillStoredExpressionChange, type StoredExpressionFillCapture } from './protocol-stored-expression-fill.js';
import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js';
import { compareAuditInstants, isoFromValidDate } from './protocol-version-tokens.js';
import {
clientFacingFailureCode,
clientFacingFailureText,
declaresClientRefusal,
metadataIssueHeadline,
} from './protocol-client-failures.js';
import { isNonCanonicalStoredType } from './protocol-stored-overlay-types.js';
import type { RollbackMetaItemRequest } from './protocol-door-requests.js';
import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js';
import { packagelessHolderRefusal } from './protocol-save.js';
import { withRefusalAudit } from './protocol-refusal-audit.js';
import type { ProtocolHost } from './protocol-host.js';
import type { ImportUnmanagedPackageAnswer, InstallPackageStoredRowHook, StoredPackageRow } from './protocol-package-install.js';
/**
* [#30319] The grant keys of a stored permission set's `objects` map: what a
* copy of that row holds because the source does (the save request's
* `inheritedGrantObjects`). The same derivation as the permission-set clone
* door's `inheritedGrantObjectsOf` (`@objectstack/runtime`, which depends on
* this package, so it is restated, not imported).
*/
/**
* [#33563] What `revertCommit` says, in an item's `failed[]` entry, when the
* mutation projector (ADR-0094) failed after the item's row write: the derived
* read-model still holds the state the revert moved away from. The projector's
* own text is driver-shaped and stays on the operator's log line
* (`runMutationProjector` warns it), never on the answer.
*/
const REVERT_PROJECTION_NOT_APPLIED =
'its mutation projector failed, so the record derived from it still holds the state before the revert';
function storedGrantObjectKeys(stored: unknown): string[] {
const objects = stored && typeof stored === 'object' ? (stored as { objects?: unknown }).objects : undefined;
return objects && typeof objects === 'object' && !Array.isArray(objects) ? Object.keys(objects) : [];
}
export class ProtocolPackageCommitsFacet {
/** The body of `ObjectStackProtocolImplementation#revertStoredPackage`; the method's docblock there is its contract. */
static async revertStoredPackage(host: Pick<ProtocolHost, 'discardDraftInItsScope' | 'ensureOverlayIndex' | 'findEnvironmentRows' | 'getOverlayRepo' | 'refuseOrganizationScopedWrite' | 'rethrowUnlessMetadataStoreUnprovisioned'>, request: {
packageId: string;
actor?: string;
}): Promise<{
stored: boolean;
discarded: Array<{ type: string; name: string }>;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped revert is refused.
host.refuseOrganizationScopedWrite(
`Package '${request.packageId}'`, request,
);
await host.ensureOverlayIndex();
let drafts: Awaited<ReturnType<SysMetadataRepository['listDrafts']>>;
let publishedRows: unknown[];
try {
drafts = await host.getOverlayRepo().listDrafts({ packageId: request.packageId });
// [#21911] The explicit system opt-in — see findServedOverlayRow.
publishedRows = (await host.findEnvironmentRows('sys_metadata', {
where: packageScopedRowWhere('active', { packageId: request.packageId }),
limit: 1,
context: { isSystem: true },
})) as unknown[];
} catch (error) {
host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata');
return { stored: false, discarded: [] };
}
if (drafts.length === 0 && publishedRows.length === 0) return { stored: false, discarded: [] };
if (publishedRows.length === 0) {
const err = new Error(
`Package '${request.packageId}' has never been published, so there is no published version to `
+ 'revert to. Publish the package first, or discard its drafts to drop them.',
) as Error & { code?: string; status?: number };
err.code = 'RESOURCE_CONFLICT';
err.status = 409;
throw err;
}
const discarded: Array<{ type: string; name: string }> = [];
for (const d of drafts) {
await host.discardDraftInItsScope(d, request.actor);
discarded.push({ type: d.type, name: d.name });
}
return { stored: true, discarded };
}
/** The body of `ObjectStackProtocolImplementation#duplicatePackage`; the method's docblock there is its contract. */
static async duplicatePackage(host: Pick<ProtocolHost, 'applyRegistryWriteThrough' | 'classifyObjectContribution' | 'convertStoredItem' | 'engine' | 'ensureObjectStorage' | 'findEnvironmentRow' | 'findEnvironmentRows' | 'getOverlayRepo' | 'installPackage' | 'isArtifactBacked' | 'objectRegistrationRefusal' | 'overlayPackageMismatchError' | 'refuseOrganizationScopedWrite' | 'resolveFlowCanonicalizer' | 'restoreArtifactRegistryView' | 'saveMetaItem'>, request: {
sourcePackageId: string;
targetPackageId: string;
targetName?: string;
targetNamespace?: string;
actor?: string;
}): Promise<{
success: boolean;
copiedCount: number;
failedCount: number;
targetPackageId: string;
copied: Array<{ type: string; name: string }>;
failed: Array<{ type: string; name: string; error: string }>;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped duplicate is refused.
host.refuseOrganizationScopedWrite(
`Package '${request.targetPackageId}'`, request,
);
// [#19417] ⭐ THE TARGET ID IS PARSED BEFORE ANYTHING IS MINTED — same
// declaration, same surfaced sentence, one key over.
//
// This door builds `dupManifest` with `id: request.targetPackageId` and
// writes it through {@link installPackage}, so the gate there already
// covers the WRITE. It does not cover this method, for two reasons that
// are both about where the refusal lands:
//
// ① a refusal of the `installPackage` call below is rethrown before
// any item is copied, so it would not be lost — but it names
// `manifest.id`, the key of a manifest this door builds, never the
// `targetPackageId` the caller wrote (the closing paragraph below);
// ② the refusal has to precede the MUTATIONS, and the manifest write
// is not the first of them. #14451 already established the position
// for this door's other precondition: `duplicatePackage` mints the
// target package record ahead of its copy loop, so a refusal any
// later leaves the empty shell behind.
//
// The key named is `targetPackageId`, because that is the authoring
// path the caller actually wrote — `manifestIdRefusal` takes the key so
// one declaration can name itself correctly at every door.
const declaredTargetId = ManifestSchema.shape.id.safeParse(request.targetPackageId);
if (!declaredTargetId.success) {
throw Object.assign(
new Error(manifestIdRefusal('targetPackageId', request.targetPackageId)),
{ statusCode: 400 },
);
}
const registry: any = (host.engine as any).registry;
const srcPkg = registry?.getPackage?.(request.sourcePackageId);
// [#19417] ⭐ ONE ASSUMPTION, ONE IMPLEMENTATION. Both namespaces were
// derived here by a RAW `id.split('.').pop()`, while
// {@link installPackage} derives the very same default with the spec
// helper `deriveNamespaceFromPackageId` — which sanitises to the
// namespace charset, truncates to 20 and answers `null` when nothing
// valid comes out. The raw copy did none of that, and `targetNs` is not
// a label: it is spliced into every copied OBJECT name as
// `${targetNs}_${short}`, and an object name is
// `/^[a-z_][a-z0-9_]*$/` (`packages/spec/src/data/object.zod.ts`).
//
// So the Studio's own default duplicate id — `<sourceId>-copy`, the
// value both objectui duplicate dialogs prefill — derived the namespace
// `leave-copy` and minted object names `leave-copy_ticket`, which the
// object declaration refuses. The helper answers `leave_copy`. The
// source side is the same rule read backwards: the prefix these rows
// actually carry is the one `installPackage` stamped, i.e. the helper's,
// so matching them with the raw split found nothing and the copy landed
// under the SOURCE's names — the collision the re-namespacing exists to
// prevent.
//
// [#19577] ⭐ AN EXPLICIT `targetNamespace` STILL WINS OVER THE DEFAULT,
// BUT IT IS PARSED, NOT TAKEN RAW. Whichever branch answered, the value
// becomes the copy's `manifest.namespace` AND the prefix of every copied
// object name, so both branches pass ONE parse before anything is
// minted — `ManifestSchema.shape.namespace`, the declaration itself,
// never a hand-copied regex. An explicit value was the more reachable
// hole of the two: it is pure caller input, and `targetNamespace:
// 'my-ns'` minted `my-ns_ticket`, a name the object declaration refuses.
//
// ⛔ A refused explicit value is REFUSED, never sanitised the way the
// derivation sanitises an id: it is what the caller wrote, and a copy
// quietly landing under a namespace nobody wrote is the silent rewrite
// this door exists not to perform.
//
// The sentence is the DECLARATION's, surfaced — the discipline the id
// gate above follows — and this door adds only the key it read and the
// value that arrived. The throw carries `statusCode: 400` and no `code`,
// exactly like the id refusal above, so an HTTP boundary answers the
// status-derived `VALIDATION_ERROR` on both branches (`resolveThrownHttpError`).
const sourceNs: string =
(srcPkg?.manifest?.namespace as string) ?? (deriveNamespaceFromPackageId(request.sourcePackageId) ?? '');
const explicitNs = request.targetNamespace;
const targetNs: string | null = explicitNs ?? deriveNamespaceFromPackageId(request.targetPackageId);
// `?? ''` because the declaration is `.optional()`: an ABSENT value
// passes it, and a derivation that produced nothing must not.
const declaredTargetNs = ManifestSchema.shape.namespace.safeParse(targetNs ?? '');
if (targetNs == null || !declaredTargetNs.success) {
const rule = declaredTargetNs.error?.issues[0]?.message ?? 'See `manifest.namespace`';
throw Object.assign(
new Error(
explicitNs != null
? `Invalid package namespace '${String(explicitNs)}' on \`targetNamespace\`. ${rule}. `
+ 'It becomes the copy\'s `manifest.namespace` and the prefix of every copied object name.'
// Reachable only for an id the pattern admits but the
// namespace charset cannot carry (a single-letter final
// segment) — never a copy renamed with an empty prefix.
: `Cannot derive a package namespace from '${request.targetPackageId}'. `
+ `Pass \`targetNamespace\` explicitly. ${rule}.`,
),
{ statusCode: 400 },
);
}
// [ADR-0146 D3] A copy into a paired customization package id must carry
// what the pair's ensure door writes — the base's pair namespace and the
// dependency on the base — judged on the record this verb WOULD install,
// before a row is read. `installPackage` asks the same predicate of the
// record it is handed; asking here as well covers a source with no
// registered manifest, whose copy mints no record for that gate to judge
// and would otherwise land items under a pair id no package holds.
const pairRefusal = customizationPairManifestRefusal(
{ id: request.targetPackageId, namespace: targetNs, dependencies: srcPkg?.manifest?.dependencies },
(id) => registry?.getPackage?.(id),
);
if (pairRefusal !== undefined) throw Object.assign(new Error(pairRefusal), { statusCode: 400 });
// [ADR-0131 D6] The source's ENVIRONMENT rows — the ones every `/meta`
// read serves. A legacy organization-scoped row is served by none of
// them and waits for the promotion ceremony (ADR-0131 C7); copying it
// would write its body environment-wide under the new package, a
// promotion this verb has no business performing, and — beside the
// environment row of the same item — land two bodies on one target key.
const where: Record<string, unknown> = {
package_id: request.sourcePackageId,
state: 'active',
};
// [#21911] The explicit system opt-in — see findServedOverlayRow.
const rows = (await host.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } })) as any[];
// [#30794] ⭐ ONE RENAME ENGINE, TWO CALLERS. Every rule that names the
// copy — the object renames and the refusal of a claimed name, the
// whole-identifier free-text rewrite, a view item following its
// object, a name rewritten whole at an object-reference property, a
// record entry's `name` following its key, a permission set's field
// rules following the renamed objects, and the refusal of every
// collision those rewrites meet — lives in `package-namespace-rename.ts`,
// which the unmanaged import's `targetNamespace` calls too. This door
// hands it the source's rows, parsed; an unparseable row is left to the
// copy loop, which reports it at its own name.
const rename = planNamespaceRename({
sourcePackageId: request.sourcePackageId,
sourceNamespace: sourceNs,
targetNamespace: targetNs,
items: rows.map((row) => {
let body: unknown;
try {
body = typeof row?.metadata === 'string' ? JSON.parse(row.metadata) : row?.metadata;
} catch {
body = undefined;
}
return { type: row?.type, name: row?.name, body };
}),
retryVerb: 'duplicate',
// [#35157] The source base stays installed beside its duplicate.
sourceStaysInstalled: true,
});
// [ADR-0146 D10, #28564] ⭐ THE `__c` RESERVATION, JUDGED AGAINST THE
// TARGET, before the copy's first mutation (the package record below):
// every object the copy would write is the target's own object, so a
// copy of a `.custom` pair's objects into a plain id carries their
// `__c` fields into a package that may not declare one. Refused whole,
// with the save door's judge and envelope (`VALIDATION_ERROR` / 400),
// so no half-copied app is left behind; a copy into a pair id writes
// the pair's own objects, which are not judged. An unparseable row is
// left to the copy loop, which reports it. See
// {@link judgeExtensionFieldSuffix}.
{
const copiedObjects: Record<string, unknown> = {};
for (const row of rows) {
if (row?.type !== 'object' || typeof row.name !== 'string') continue;
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
} catch {
continue;
}
if (body && typeof body === 'object' && !Array.isArray(body)) {
copiedObjects[row.name] = { ...(body as Record<string, unknown>), name: rename.copyName(row.type, row.name) };
}
}
const suffixRefusals = judgeExtensionFieldSuffix({ packageId: request.targetPackageId, objects: copiedObjects });
if (suffixRefusals.length > 0) throw extensionFieldSuffixRefusalError(suffixRefusals);
}
if (srcPkg?.manifest && typeof registry?.installPackage === 'function') {
try {
// Route through installPackage (not a bare registry write) so the
// duplicated base ALSO lands in sys_packages — otherwise the copy
// would vanish from GET /packages on the next restart (#2532).
// Spread-then-strip: the source may carry `scope` (e.g. 'project'
// on a code package) — copying it would brand the duplicate as
// read-only in every writability heuristic, when the whole point
// of a duplicate is a WRITABLE base. The copy is scope-less.
const dupManifest: Record<string, unknown> = {
...srcPkg.manifest,
id: request.targetPackageId,
name: request.targetName ?? `${srcPkg.manifest.name ?? request.sourcePackageId} (copy)`,
namespace: targetNs,
};
delete dupManifest.scope;
await host.installPackage({ manifest: dupManifest } as InstallPackageRequest);
} catch (e: any) {
// [#24041] ⭐ A REFUSED PACKAGE RECORD REFUSES THE DUPLICATE —
// the refusal itself, rethrown unchanged, before any item is
// copied (ruling B, claim amendment 6227008947).
//
// This catch used to drop it and copy anyway. A refused install
// leaves no registry record and no `sys_packages` row, so the
// copy's items were live, bound to an id no package record
// holds, absent from `GET /packages`. After a namespace conflict
// they also sat inside a namespace another package owns — the
// very state ADR-0048 Phase 1's install-time gate in
// `SchemaRegistry.installPackage` exists to refuse. The sibling
// verb {@link importUnmanagedPackage} states the rule this door
// now keeps: "There is no half-copied app."
//
// Nothing needs undoing: this call is the duplicate's FIRST
// mutation (everything above it reads), and a refused install
// leaves nothing behind — the registry judges before it writes,
// and a failed persist undoes the registry write before it
// throws (#21243). So the door answers the refusal's own status:
// `422 NAMESPACE_CONFLICT` with the registry's remedy (choose
// another namespace), or the primitive's `500` for a store fault.
//
// Logged once, because neither the primitive nor the HTTP door
// logs it. A store fault's driver text rides only on the error's
// `cause`, which no answer quotes, so the error itself is handed
// to the log for that one; a client refusal's sentence is
// already the whole story.
console.warn(
`[protocol.duplicatePackage] refused: the package record for '${request.targetPackageId}' `
+ `(copy of '${request.sourcePackageId}') was not installed, so nothing was copied: `
+ `${typeof e?.code === 'string' ? `${e.code}: ` : ''}${e?.message ?? e}`,
...(declaresClientRefusal(e) ? [] : [e]),
);
throw e;
}
}
const copied: Array<{ type: string; name: string }> = [];
const failed: Array<{ type: string; name: string; error: string }> = [];
// [#32369] The object rows this copy wrote, judged as one unit once the
// loop is done (see the settle below the loop).
const writtenObjects: Array<WrittenBatchRow & { source: { type: string; name: string } }> = [];
const judging = canJudgeBatchObjects(host);
// Resolved once for the whole copy: every flow row in this package needs
// the same engine, and a package with fifty flows should not walk the
// service table fifty times.
const canonicalizeFlow = host.resolveFlowCanonicalizer();
for (const row of rows) {
const refusal = row?.type === 'object' ? rename.objectRefusal(row.name) : undefined;
if (refusal !== undefined) {
failed.push({ type: row.type, name: row.name, error: refusal });
continue;
}
const newName = rename.copyName(row.type, row.name);
const rawType = String(row.type);
const singular = PLURAL_TO_SINGULAR[rawType] ?? rawType;
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : (row.metadata ?? {});
} catch {
failed.push({ type: row.type, name: row.name, error: 'unparseable metadata' });
continue;
}
// Canonicalize the source row before re-saving (#3903): the copy is
// a NEW write and must pass today's schema gate, so a legacy shape
// the chain owns is lifted rather than failing the copy —
// duplication never mints new rows in a pre-protocol dialect.
//
// For `flow` that guarantee was false until #4498: `convertStoredItem`
// returns flows untouched, and `FlowNodeSchema.config` is an open
// `z.record`, so a pre-17 body (`delete_record` with `config.filters`)
// sailed through `saveMetaItem` and landed verbatim in a brand-new
// row. ADR-0087 justifies the whole stored-metadata design on new
// writes being canonical — "a strictly shrinking concern" — and this
// was the one live producer contradicting it.
let item: any;
if (singular === 'flow') {
if (!canonicalizeFlow) {
// No engine in this process (control-plane / metadata-only
// host). Copy the source body as-is — the honest behaviour,
// and no worse than the source row already is — rather than
// failing a duplication that has nothing to do with flows.
// `os migrate meta --stored --apply` is the finish line for
// both rows, and it reports what it could not canonicalize.
item = body;
} else {
try {
const result = canonicalizeFlow(String(row.name ?? ''), body);
item = result.storable;
} catch (e: any) {
// `FlowSchema` is strict (#4001) and the region validator
// hard-fails: this source row cannot register at all, so
// the copy would be broken the same way. Report it.
failed.push({
type: row.type,
name: row.name,
error: `the flow does not canonicalize: ${e?.message ?? String(e)}`,
});
continue;
}
}
} else {
try {
item = host.convertStoredItem(rawType, body);
} catch (e: any) {
// A tombstoned key throws here (ADR-0087 D2) — a genuine
// contract violation in the source, not a parse failure.
failed.push({
type: row.type,
name: row.name,
error: `the source item does not convert: ${e?.message ?? String(e)}`,
});
continue;
}
}
// The engine names the copy: every renamed name rewritten, `name`
// set to `newName`, a permission set's field rules following the
// renamed objects — or the collision that refuses the item, before
// anything is written for it.
const outcome = rename.rewrite(row.type, row.name, item);
if ('refusal' in outcome) {
failed.push({ type: row.type, name: row.name, error: outcome.refusal });
continue;
}
const rewritten: any = outcome.item;
if (rewritten && typeof rewritten === 'object' && !Array.isArray(rewritten)) {
// [ADR-0086 D3] A permission set that declares its SOURCE
// package as its owner is copied declaring the target, the
// package the copy is saved into: the save door refuses a
// `packageId` that disagrees with that binding
// ({@link permissionSetOwnerBindingRefusal}), and the copy's
// owner is the target. Any other declared value is left as
// stored, so a source row that already disagreed with its own
// binding is reported in `failed[]` with the door's remedy.
if (singular === 'permission' && rewritten.packageId === request.sourcePackageId) {
rewritten.packageId = request.targetPackageId;
}
}
try {
// [#32369] The copy's own address before it writes there: what an
// undo puts back if the registry refuses the row (a duplicate
// again writes over its earlier copy).
const before = judging && isBatchObjectType(singular)
? await readActiveBatchRow(host, { type: singular, name: newName, packageId: request.targetPackageId })
: null;
await host.saveMetaItem({
type: row.type,
name: newName,
item: rewritten,
mode: 'publish',
packageId: request.targetPackageId,
// [commit 82cb6e849] Which door the refusal below will be prescribing
// a remedy FOR. Stated by the server, never by the caller —
// `duplicatePackage`'s own request type has no such field,
// exactly as `source` is server-stated one gate down. The
// Phase 3a-destructive gate reaches this call on the
// duplicate-AGAIN workflow, and its `?force=true` default
// would name a parameter this door does not accept.
writeFace: 'package-duplicate',
// [#30319] A copied permission set's grants are the SOURCE
// row's, so the unknown-object refusal does not judge the
// keys that row holds as stored — the clone door's rule
// (#30255) for this door's copy. A platform set may grant on
// an optional plugin's object this deployment does not
// install (`sys_comment`, `@objectstack/plugin-audit`).
// Derived from the stored row, never from the request; a key
// the rewrite above renamed is not the source's, and is judged.
...(singular === 'permission' ? { inheritedGrantObjects: storedGrantObjectKeys(body) } : {}),
...(request.actor ? { actor: request.actor } : {}),
});
// [#32369] Read back BEFORE the row is answered copied: a read
// that fails lands the row in `failed[]` alone (the `catch`
// below), never in both lists.
if (judging && isBatchObjectType(singular)) {
const stored = await readActiveBatchRow(host, { type: singular, name: newName, packageId: request.targetPackageId });
const address = {
type: singular, name: newName, packageId: request.targetPackageId,
prevVersion: before?.version ?? null,
// The stamp this copy wrote: an undo of a row it created locks on it.
writtenHash: stored?.hash ?? null,
};
writtenObjects.push({
type: singular, name: newName, body: stored?.body ?? rewritten, packageId: request.targetPackageId,
source: { type: row.type, name: row.name },
undo: () => undoBatchRowWrite(host, address, {
...(request.actor ? { actor: request.actor } : {}),
source: 'protocol.duplicatePackage',
message: `undo the copy of ${row.type}/${row.name}: the registry refuses it (ADR-0144 D2 and D6)`,
}),
});
}
copied.push({ type: row.type, name: newName });
} catch (e: any) {
// [#8333 · P10] `failed[].error` is copy-response DATA.
// Measured on `origin/main` by failing the `sys_metadata`
// insert under `saveMetaItem`: the field carried `SQLITE_ERROR:
// no such table: sys_metadata` verbatim.
//
// This `try` wraps exactly one call, and `saveMetaItem`'s
// authored refusals all declare 4xx — the spec rejection is
// `422 INVALID_METADATA` (measured: the whole "Unrecognized
// key(s) on this view container … Wrap it: `defineView({ … })`"
// prescription comes through unchanged), the author-time gate
// likewise 422, the org/overridability refusals 403. Nothing an
// author needs is blanked.
//
// ⛔ The two sibling `failed[]` pushes ABOVE this one (`the flow
// does not canonicalize` / `the source item does not convert`)
// are deliberately untouched: they interpolate authored
// schema-validation text, not driver text, and #8333 records
// them as examined-and-left.
failed.push({
type: row.type, name: row.name,
error: clientFacingFailureText(e, 'copy failed'),
});
console.warn(
`[protocol.duplicatePackage] copy failed for ${row.type}/${row.name} → `
+ `'${request.targetPackageId}': ${e?.message ?? e}`,
);
}
}
// [#32369, ADR-0144 D2 and D6] The copied objects as ONE unit, after the
// copy's own registrations: a row whose pair the registry refuses — at
// its registration (D6's roll-up door, only logged at the write-through)
// or once the whole copy is in (the follow door, which no registration
// asks) — is taken back out of the copy, its address put back as it was,
// and reported here in `failed[]` with the registry's own refusal, never
// in `copied[]`. Judged after the loop, not per row, so a row whose pair
// a later sibling of this copy completes is copied (#29673). See
// `batch-object-registration.ts`.
for (const out of await settleBatchObjectRows(host, writtenObjects)) {
const at = copied.findIndex((c) => c.name === out.row.name && c.type === out.row.source.type);
if (at !== -1) copied.splice(at, 1);
const refusal = clientFacingFailureText(out.refusal, 'copy failed');
failed.push({
type: out.row.source.type,
name: out.row.source.name,
error: out.undoError === undefined
? refusal
: out.undoError instanceof BatchRowHealError
? `${refusal} The copy '${out.row.name}' was taken back, but the registry could not be put back `
+ `(${clientFacingFailureText(out.undoError.healError, 'heal failed')}) and may serve it until the server restarts.`
: `${refusal} The copy '${out.row.name}' could not be taken back `
+ `(${clientFacingFailureText(out.undoError, 'undo failed')}): it is stored although the registry refuses it; `
+ 'delete it, then copy the corrected source again.',
});
console.warn(
`[protocol.duplicatePackage] the copy of ${out.row.source.type}/${out.row.source.name} → `
+ `'${request.targetPackageId}' was refused by the registry and `
+ `${undoOutcomeForLog(out.undoError)}: `
+ `${out.refusal.message}`,
);
}
return {
success: failed.length === 0 && copied.length > 0,
copiedCount: copied.length,
failedCount: failed.length,
targetPackageId: request.targetPackageId,
copied,
failed,
};
}
/** The body of `ObjectStackProtocolImplementation#importUnmanagedPackage`; the method's docblock there is its contract. */
static async importUnmanagedPackage(host: Pick<ProtocolHost, 'applyRegistryWriteThrough' | 'classifyObjectContribution' | 'convertStoredItem' | 'engine' | 'ensureObjectStorage' | 'findEnvironmentRow' | 'installPackage' | 'isRuntimeCreateAllowed' | 'objectRegistrationRefusal' | 'overlayPackageMismatchError' | 'refuseOrganizationScopedWrite' | 'resolveFlowCanonicalizer' | 'rollBackUnmanagedImport' | 'saveMetaItem' | 'unmanagedImportCollisions'>, request: ImportUnmanagedPackageRequest & { actor?: string; seedData?: boolean },): Promise<ImportUnmanagedPackageAnswer> {
const rawSourceId = (request as { manifest?: { id?: unknown } } | undefined)?.manifest?.id;
const sourceLabel = typeof rawSourceId === 'string' && rawSourceId !== '' ? rawSourceId : '(unnamed)';
// 1. FIRST, as on every package write verb.
host.refuseOrganizationScopedWrite(`Package '${sourceLabel}'`, request);
// 2. The request, through its published declaration. The keys that
// are never a body's — the door's `actor`, the door's `seedData`
// (#30808: the installer asked for the sample data), and the
// organization the refusal above has already judged — are read off
// before the parse.
const { actor, seedData, organizationId: _scopeJudgedAbove, ...body } =
(request ?? {}) as ImportUnmanagedPackageRequest & { actor?: string; seedData?: boolean; organizationId?: unknown };
const declared = ImportUnmanagedPackageRequestSchema.safeParse(body);
if (!declared.success) {
const issues = zodIssuesToMetadataIssues(declared.error.issues);
throw Object.assign(
new Error(`Invalid unmanaged install request: ${metadataIssueHeadline(issues)}.`),
{ statusCode: 400, issues },
);
}
// 3. The deployment walls organizations: nothing is read or written.
const walled = unmanagedInstallPostureRefusal(sourceLabel);
if (walled) throw walled;
// 4. Everything the body alone can answer.
const plan = planUnmanagedImport(declared.data.manifest, {
...(declared.data.targetPackageId !== undefined ? { targetPackageId: declared.data.targetPackageId } : {}),
...(declared.data.targetName !== undefined ? { targetName: declared.data.targetName } : {}),
// [#30794] Rename-on-install: judged by the plan, applied by the
// duplicate's own engine (`package-namespace-rename.ts`).
...(declared.data.targetNamespace !== undefined ? { targetNamespace: declared.data.targetNamespace } : {}),
// [#30808] Each dataset as a `seed` item of the base: the receipt.
...(seedData === true ? { seedData: true } : {}),
// The save door's own predicate — registry-only, the hatch unread.
isRuntimeCreatable: (type) => host.isRuntimeCreateAllowed(type),
// The save door's own schema, asked which types declare the
// `protection` block the copy strips (ADR-0010 Phase 4.3).
protectionDeclarationOf: (type) => overlaySchemaDeclaredKey(type, 'protection'),
loadOrderOf: (type) =>
DEFAULT_METADATA_TYPE_REGISTRY.find((entry) => entry.type === type)?.loadOrder ?? Number.MAX_SAFE_INTEGER,
});
const { sourcePackageId, targetPackageId, namespace, rename } = plan;
// 5. The handshake `installPackage` asks too — asked here so a refusal
// precedes the base.
assertProtocolCompat(declared.data.manifest);
// 6. A NEW base, under a namespace nobody owns.
const registry: any = (host.engine as any).registry;
if (registry?.getPackage?.(targetPackageId) || (host.engine as any).manifests?.has?.(targetPackageId)) {
throw Object.assign(new Error(
`Package '${targetPackageId}' already exists. An unmanaged install of '${sourcePackageId}' writes into a `
+ 'NEW base, never into an existing one. Name another `targetPackageId`, or uninstall '
+ `'${targetPackageId}' first.`,
), { code: 'RESOURCE_CONFLICT', status: 409, details: { targetPackageId } });
}
const owners: unknown = registry?.getNamespaceOwners?.(namespace);
if (Array.isArray(owners) && owners.length > 0) {
const named = owners.map((o) => `'${String(o)}'`).join(', ');
throw Object.assign(new Error(
rename
// [#30794] The namespace the request named is someone else's.
? `The namespace '${namespace}' named by \`targetNamespace\` is already owned by ${named}, so the `
+ `unmanaged copy of '${sourcePackageId}' cannot take it. Name another \`targetNamespace\`, or `
+ 'uninstall that package first.'
: `The namespace '${namespace}' of package '${sourcePackageId}' is already owned by `
+ `${named}. The unmanaged copy keeps the source namespace, `
+ 'so it cannot sit beside a package that owns it — a managed install of this same package '
+ 'included. Uninstall that package first, keep the managed install, or install the copy '
+ 'under a namespace of its own with `targetNamespace`.',
), { code: 'RESOURCE_CONFLICT', status: 409, details: { namespace, owners } });
}
// 7. Today's protocol, item by item — the conversion a managed install
// applies to an artifact, so an older package imports as it installs.
// Converted under the name the package declares it, as the duplicate
// converts a source row; then, when the copy is renamed, rewritten by
// the duplicate's own engine — after the conversion, as the duplicate
// rewrites — every refusal it meets raised before the base exists.
const canonicalizeFlow = plan.items.some((i) => i.type === 'flow') ? host.resolveFlowCanonicalizer() : undefined;
const prepared: Array<{ type: string; name: string; item: unknown }> = [];
const unconvertible: string[] = [];
const unrenamable: UnmanagedImportRenameRefusal[] = [];
for (const planned of plan.items) {
const declaredName = planned.sourceName ?? planned.name;
let converted: unknown;
try {
if (planned.type !== 'flow') {
converted = host.convertStoredItem(planned.type, planned.body);
} else if (!canonicalizeFlow) {
// No engine in this process: the body as declared, exactly as
// `duplicatePackage` copies it; the save door still judges it.
converted = planned.body;
} else {
converted = canonicalizeFlow(declaredName, planned.body).storable;
}
} catch (e: any) {
unconvertible.push(`${planned.type} '${declaredName}': ${e?.message ?? String(e)}`);
continue;
}
// [#30808] A seed item's records are data: the plan already named
// its object as the copy names it, and the free-text rewrite below
// would turn any record value spelled like an object name.
if (rename === undefined || planned.type === UNMANAGED_SEED_TYPE) {
prepared.push({ type: planned.type, name: planned.name, item: converted });
continue;
}
const outcome = rename.rewrite(planned.type, declaredName, converted);
if ('refusal' in outcome) {
unrenamable.push({ type: planned.type, name: declaredName, reason: outcome.refusal });
continue;
}
prepared.push({ type: planned.type, name: planned.name, item: outcome.item });
}
if (unconvertible.length > 0) {
throw Object.assign(new Error(
`Package '${sourcePackageId}' cannot be installed unmanaged: ${unconvertible.length} item(s) do not convert `
+ `to this runtime's protocol — ${unconvertible.slice(0, 3).join('; ')}`
+ `${unconvertible.length > 3 ? ` (+${unconvertible.length - 3} more)` : ''}. Rebuild the package against `
+ 'this protocol, then install again.',
), { code: 'INVALID_METADATA', status: 422 });
}
if (unrenamable.length > 0) throw unmanagedInstallRenameRefusal(sourcePackageId, namespace, unrenamable);
// 8. Every name the copy would take, against the environment and the
// managed packages — the save door would refuse or overlay them.
const collisions = await host.unmanagedImportCollisions(plan.items);
if (collisions.length > 0) {
throw Object.assign(new Error(
`Package '${sourcePackageId}' cannot be installed unmanaged: ${collisions.length} of its names are already `
+ `taken — ${collisions.slice(0, 3).map((c) => `${c.type} '${c.name}' (${c.heldBy})`).join('; ')}`
+ `${collisions.length > 3 ? ` (+${collisions.length - 3} more)` : ''}. `
+ (rename
? `The copy takes every name the package declares, renamed into namespace '${namespace}', so remove `
+ 'or rename the items that hold them, or name another `targetNamespace`, then install again.'
: 'The copy keeps every name the package declares, so remove or rename the items that hold them, '
+ 'or install it under a namespace of its own with `targetNamespace`, then install again.'),
), { code: 'RESOURCE_CONFLICT', status: 409, details: { collisions } });
}
// The base. Not best-effort: a refusal here is the import's, and
// `installPackage` leaves nothing behind when it refuses.
// [#31530] The base row as its own write answered it, door-only beside
// the published request: the answer's `baseInstance`, so a caller that
// ties a record to the row instance never reads the row back.
let baseInstance: StoredPackageRow | undefined;
const onStoredRow = (row: StoredPackageRow): void => { baseInstance = row; };
await host.installPackage({ manifest: plan.baseManifest, onStoredRow } as InstallPackageRequest & InstallPackageStoredRowHook);
const copied: Array<{ type: string; name: string }> = [];
for (const item of prepared) {
try {
await host.saveMetaItem({
type: item.type,
name: item.name,
item: item.item,
mode: 'publish',
packageId: targetPackageId,
// Server-stated, as on every face: no body reaches this field.
writeFace: 'package-unmanaged-import',
// [#30319] No `inheritedGrantObjects`, deliberately: the
// package is the request's body, not a stored row, so its
// permission sets are new writes and every grant is judged.
...(actor ? { actor } : {}),
});
copied.push({ type: item.type, name: item.name });
} catch (e: any) {
throw await host.rollBackUnmanagedImport(e, {
sourcePackageId, targetPackageId, failed: item, copiedCount: copied.length, actor,
});
}
}
// [#32369, ADR-0144 D2 and D6] The copied objects as ONE unit, once all
// of them are in: a row whose pair the registry refuses — at its
// registration (D6's roll-up door, only logged at the write-through) or
// once the whole copy is in (the follow door, which no registration
// asks) — fails the import as a write refusal of that row does, and the
// same rollback removes the base, so nothing of the package remains
// stored unregistered. Judged after the loop, so a row whose pair a
// later item of the package completes installs (#29673). The rows that
// pass are registered again in package order, so a row the write-through
// refused only because its sibling was not in yet is served.
const objectRows: BatchObjectRow[] = [];
for (const item of canJudgeBatchObjects(host) ? prepared : []) {
const type = PLURAL_TO_SINGULAR[item.type] ?? item.type;
if (!isBatchObjectType(type)) continue;
const stored = await readActiveBatchRow(host, { type, name: item.name, packageId: targetPackageId });
objectRows.push({ type, name: item.name, body: stored?.body ?? item.item, packageId: targetPackageId });
}
const verdict = judgeBatchObjectRegistrations(host, objectRows);
const [refusedAt, refusal] = [...verdict.refused][0] ?? [];
if (refusedAt !== undefined && refusal !== undefined) {
const failedRow = objectRows[refusedAt]!;
throw await host.rollBackUnmanagedImport(refusal, {
sourcePackageId,
targetPackageId,
failed: prepared.find((p) => p.name === failedRow.name && (PLURAL_TO_SINGULAR[p.type] ?? p.type) === failedRow.type) ?? failedRow,
copiedCount: copied.length,
actor,
});
}
await registerAdmittedBatchRows(host, objectRows, verdict.order);
await syncAdmittedBatchStorage(host, objectRows, verdict.order);
return {
sourcePackageId,
...(plan.sourceVersion !== undefined ? { sourceVersion: plan.sourceVersion } : {}),
targetPackageId,
namespace,
// [#30794] The provenance of every renamed name.
...(rename !== undefined ? { sourceNamespace: plan.sourceNamespace } : {}),
copiedCount: copied.length,
copied,
// Planned before the base existed; every item was written, so every
// lock listed was dropped from a copy that now exists.
strippedLocks: plan.strippedLocks,
...(baseInstance !== undefined ? { baseInstance } : {}),
};
}
/** The body of `ObjectStackProtocolImplementation#reassignOrphanedMetadata`; the method's docblock there is its contract. */
static async reassignOrphanedMetadata(host: Pick<ProtocolHost, 'applyRegistryWriteThrough' | 'classifyObjectContribution' | 'engine' | 'findEnvironmentRows' | 'isArtifactBacked' | 'overlayPackageMismatchError' | 'refuseOrganizationScopedWrite' | 'releaseAdoptedObjectOwner' | 'storedOverlayEntries'>, request: {
targetPackageId: string;
actor?: string;
}): Promise<{
success: boolean;
reassignedCount: number;
reassigned: Array<{ type: string; name: string }>;
targetPackageId: string;
}> {
// [ADR-0131 D6] FIRST: an organization-scoped adoption is refused.
host.refuseOrganizationScopedWrite(
`Package '${request.targetPackageId}'`, request,
);
// The ENVIRONMENT's orphans: ADR-0070 D5 makes the environment the unit
// ("bulk-assign legacy orphans to a default base named for the
// environment"), and since ADR-0131 D6 every new orphan is
// environment-wide (`saveMetaItem` writes `organization_id = NULL`). A
// legacy organization-scoped row is left as it is stored — rebinding
// it would be an organization-scoped write; the promotion ceremony
// (ADR-0131 C7) carries it to the environment layer, where a later
// adoption sees it.
const where: Record<string, unknown> = {};
// [#21911] The explicit system opt-in — see findServedOverlayRow.
const rows = (await host.findEnvironmentRows('sys_metadata', { where, context: { isSystem: true } })) as any[];
const orphans = rows.filter(
(r) => (r?.package_id == null || r.package_id === '' || r.package_id === 'sys_metadata')
// [#23198] An overlay of an artifact item keeps its binding
// (ADR-0070); see the header. The type folds as the save's does.
&& !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name))
// [#37604] …nor the platform's own record: the package-less row
// the platform registers at every boot is no orphan an author
// left behind, and rebound it would become the target's item,
// mark and all (`isPlatformRecordRow`, `@objectstack/metadata`,
// the one reader the restore refusal and the overlay census ask).
&& !isPlatformRecordRow(r),
);
// [ADR-0029 D9.9, ADR-0086 D3, #28776] ⭐ THE OWNER JUDGES, in the save
// door's order (before the `__c` judge below), against the TARGET and
// before the first update: refused whole, each with its own envelope.
// The object arm skips the `'sys_metadata'` sentinel owner, the orphan's
// own registration this adoption hands over; see the header.
for (const row of orphans) {
if (row?.state !== 'active' || typeof row.name !== 'string') continue;
const type = canonicalMetaType(String(row.type));
if (type === 'object') {
const layer = host.classifyObjectContribution(row.name, request.targetPackageId);
if (layer.kind === 'mismatch' && layer.ownerPackageId !== 'sys_metadata') {
throw host.overlayPackageMismatchError(
row.name, request.targetPackageId, layer.ownerPackageId,
);
}
} else if (type === 'permission') {
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
} catch {
continue;
}
const ownerRefusal = permissionSetOwnerBindingRefusal(
type, body, row.name, request.targetPackageId, 'save',
);
if (ownerRefusal) throw ownerRefusal;
}
}
// [ADR-0146 D10, #28735] ⭐ THE `__c` RESERVATION, JUDGED AGAINST THE
// TARGET, before the first update below: each active object row this
// adoption rebinds becomes the target's own object. Refused whole, with
// the save door's judge and envelope; see the header. An unparseable
// row is left to the loop, as `duplicatePackage` leaves it.
{
const adoptedObjects: Record<string, unknown> = {};
for (const row of orphans) {
if (canonicalMetaType(String(row?.type)) !== 'object' || row.state !== 'active') continue;
if (typeof row.name !== 'string') continue;
let body: unknown;
try {
body = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
} catch {
continue;
}
if (body && typeof body === 'object' && !Array.isArray(body)) {
adoptedObjects[row.name] = { ...(body as Record<string, unknown>), name: row.name };
}
}
const suffixRefusals = judgeExtensionFieldSuffix({ packageId: request.targetPackageId, objects: adoptedObjects });
if (suffixRefusals.length > 0) throw extensionFieldSuffixRefusalError(suffixRefusals);
}
const reassigned: Array<{ type: string; name: string }> = [];
// [#12981] The refusal channel this loop used to lack entirely.
//
// The catch below is the card's defining shape, and this method is the
// sharpest instance of it in the file: a refused `update` was dropped
// whole -- not logged, not rethrown, not carried on the response -- and
// the return then reported `success: reassigned.length > 0`. So an
// adoption where 99 of 100 orphans were refused answered
// `{success: true, reassignedCount: 1}`, byte-identical in shape to a
// healthy run with one orphan to move, and the 99 stayed orphans with
// nothing anywhere recording that they had been tried. Nothing retries
// them and no later boot reconstructs the attempt.
//
// A COUNTER plus one report AFTER the loop, deliberately, and not a
// `console.error` inside the catch: AGENTS.md -> "Degradation log
// levels" says an operator-facing degradation is stated ONCE, at the
// first occurrence, not once per failed write -- and a refused
// `sys_metadata` write is refused for every row, so the per-row
// spelling would print one line per orphan in the environment. This is
// the same shape #12923's shared refusal accumulator takes at the other
// repaired seams of this family.
let refusedCount = 0;
let firstRefusal = '';
for (const row of orphans) {
try {
await host.engine.update(
'sys_metadata',
{ package_id: request.targetPackageId },
{ where: { id: row.id }, context: { isSystem: true } },
);
reassigned.push({ type: row.type, name: row.name });
} catch (e: any) {
// Control flow is UNCHANGED: a row that cannot be rebound must
// not abort the adoption of the rows that can. Only the
// silence changes.
refusedCount += 1;
if (firstRefusal === '') firstRefusal = e?.message ?? String(e);