diff --git a/.changeset/32552-pair-row-removal-every-shipper.md b/.changeset/32552-pair-row-removal-every-shipper.md new file mode 100644 index 00000000000..75580103cd9 --- /dev/null +++ b/.changeset/32552-pair-row-removal-every-shipper.md @@ -0,0 +1,24 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a customization pair's row of a name two namespaces hold is judged against its own base, whichever package registered first — its removal, its commit revert and the boot census (ADR-0150 D4) + +Clause-②: yes (widening) — answers that refused or misreported the second-registered holder's declared override now admit or leave it, as they already did for the first. For a name two packages of two namespaces ship, each with its paired `.custom` holding a declared override (ADR-0146 D2), three answers depended on which package registered first, because each judged the pair's row against the one package the bare-name artifact lookup answers. Each is now judged against every package that ships the name. First-party callers in any of these positions: 0. +Metadata-protocol: none + +Every row below is the `widening` arm, is pinned in both registration orders in `@objectstack/objectql`'s `protocol-flow-custom-override.test.ts`, and keeps its one-holder answer (the one-holder CONTROL there): + +| Door | Second-registered holder B, before | Now | One holder (CONTROL) | +|:--|:--|:--|:--| +| `DELETE /meta/TYPE/NAME?package=.custom` (`deleteMetaItem`); pinned for a flow, and for an action in the list probe below | `403 NOT_OVERRIDABLE` "sealed against removal"; B's override stays | `200`: B's override row removed (runtime-only), A's untouched; afterwards every listed and execution-view entry of the name is its own package's | unchanged: `200`, removed | +| `revertCommit` of a commit into `.custom` (the restore limb; the per-item rollback shares the derivation); pinned for a flow | the item in `failed[]`, `NOT_OVERRIDABLE` "sealed against in-place edits"; nothing restored | restored, judged by the override write gate as the pair's declared override | unchanged: restored | +| boot census `[metadata_sealed_overlay_unserved]` (`loadMetaFromDb`), a flow or an action only | named B's live declared override as an unserved row to delete | not named | unchanged: the override not named | + +With one of the two holders disabled (ADR-0150 D3), the bare-name answer is still the first-registered holder, disabled or not, so the same three answers moved the same way whichever holder is disabled: each holder's pair removal and commit revert are admitted now, the disabled holder's pair included, and the census names neither override. A binding never moves with a reversible disable. Pinned in both registration orders with each holder disabled in turn, beside a one-holder disabled CONTROL (its removal and revert admitted, as before). + +Unchanged in both: a row of a package that is no shipper's pair keeps its removal `403` and is still named by the census. + +The census judges a row as the reads serve it (`declinesStoredRow`). The reads serve a second holder's declared override per shipper for a flow and an action only (#32613), so only those two types move here. A page, app, dataset, doc, book or mapping keeps the name's first-registered shipper in the census, as in the reads, until #33131 moves them: the second holder's override of such a name is still named, pinned for a mapping in both registration orders. + +No shipper is picked: the row judged is always the one its own `package_id` names, and the judgement asks only whether that package is a pair of SOME package that ships the name. A name one package ships answers exactly as before (the bare-name answer is read first and alone while it holds). diff --git a/packages/metadata-protocol/src/protocol-class-head.ts b/packages/metadata-protocol/src/protocol-class-head.ts index 3e80f8d1be5..600924b17d6 100644 --- a/packages/metadata-protocol/src/protocol-class-head.ts +++ b/packages/metadata-protocol/src/protocol-class-head.ts @@ -41,6 +41,7 @@ import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; import type { IObjectQLEngine, IPubSub } from '@objectstack/spec/contracts'; import { isPairOf } from '@objectstack/metadata-core'; import { installedManifestsOfEngine } from './installed-manifests.js'; +import { someShipperOf } from './protocol-environment-rows.js'; import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import type { ObjectExtensionRegistry } from './protocol-object-extension-item.js'; @@ -201,13 +202,17 @@ export class ProtocolClassHeadFacet { * caller's `artifactBacked` decides the intent, and the body writer is * {@link restoredBodyWriter}'s alone. */ - static restoreWriteFor(host: Pick, singularType: string, + static restoreWriteFor(host: Pick, singularType: string, name: string, binding: string | null, artifactBacked: boolean, source: string,): { intent: 'override-artifact' | 'runtime-only'; deriveRestoredBody: (historyBody: unknown) => Promise } { - const owner = artifactBacked ? host.packagedArtifactOwner({ type: singularType, name }) : undefined; - const pairRow = owner !== undefined && isPairOf(binding, owner, installedManifestsOfEngine(host.engine)); + // [ADR-0150 D4, #32552] The binding is judged against every package + // that ships the name ({@link someShipperOf}): each namespace's holder + // has its own pair, never only the shipper registered first. + const installed = installedManifestsOfEngine(host.engine); + const pairRow = artifactBacked && someShipperOf(host, singularType, name, + (owner) => owner !== undefined && isPairOf(binding, owner, installed)); const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !pairRow ? 'override-artifact' : 'runtime-only'; const writeRestored = host.restoredBodyWriter(singularType, name, binding, source); const deriveRestoredBody = pairRow diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 2470680636b..648b2ce535f 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -39,12 +39,13 @@ import { isMissingTableError } from '@objectstack/metadata/errors'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; import { isServedOverrideRowOf } from './served-override.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; +import { someShipperOf } from './protocol-environment-rows.js'; import type { ServedOverrideRow } from './served-override.js'; import { REFERENCE_SITES } from './reference-sites.js'; import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; import { hasMetadataRedactor, redactMetadataItem } from './metadata-redaction.js'; import { isPairRowRemoval } from './protocol-packaged-base-refusal.js'; -import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; +import { canonicalMetaType, canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { boundPackageOf } from './protocol-package-bindings.js'; import { remainingRowsPhrase } from './protocol-authoring-refusals.js'; import { memberOption, mutationEventMember, resolveBundleMemberSelector } from './protocol-bundle-members.js'; @@ -391,7 +392,7 @@ export class ProtocolDiffDeleteLoadFacet { } /** [#28355] The body of {@link deleteMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ + static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ success: boolean; message?: string; reset?: boolean; @@ -427,10 +428,13 @@ export class ProtocolDiffDeleteLoadFacet { // flow's armed) again. Admitted past the sealed-removal refusal and // told to the store as a runtime-only removal, as the declared save // is ({@link isPairRowRemoval}). - const pairRowRemoval = isPairRowRemoval( - request.type, host.packagedArtifactOwner({ type: request.type, name: request.name }), request.packageId, - installedManifestsOfEngine(host.engine), - ); + // [ADR-0150 D4, #32552] Judged against every package that ships the + // name ({@link someShipperOf}): two namespaces' items of one name each + // carry their own pair, so the pair named here is judged against its + // own base, never against whichever shipper registered first. + const installed = installedManifestsOfEngine(host.engine); + const pairRowRemoval = someShipperOf(host, request.type, request.name, + (base) => isPairRowRemoval(request.type, base, request.packageId, installed)); // Two-tier authorization for delete (mirrors saveMetaItem). // • Artifact-backed item → delete becomes a tombstone overlay, // requires `allowEnvironmentOverlay`… @@ -1105,7 +1109,7 @@ export class ProtocolDiffDeleteLoadFacet { } /** The body of `ObjectStackProtocolImplementation#loadMetaFromDb`; the method's docblock there is its contract. */ - static async loadMetaFromDb(host: Pick): Promise<{ loaded: number; errors: number; invalid: number; storeUnavailable: boolean }> { + static async loadMetaFromDb(host: Pick): Promise<{ loaded: number; errors: number; invalid: number; storeUnavailable: boolean }> { let loaded = 0; let errors = 0; let invalid = 0; @@ -1173,13 +1177,25 @@ export class ProtocolDiffDeleteLoadFacet { // would prescribe deleting the live customization. The // one predicate, on the row's `package_id` column. The // census only: what this loop loads is unchanged. + // + // [ADR-0150 D4, #32552] …judged as the reads judge it + // (`declinesStoredRow`): for a flow and an action + // against every package that ships the name + // ({@link someShipperOf}), so a second holder's + // served override is not named for deletion; for the + // six sealed types against the name's first-registered + // shipper alone, which is the only override the reads + // serve for them until #33131 moves them. + const servedOverrideOf = (base: string | undefined) => isServedOverrideRowOf( + record as ServedOverrideRow, base, installedManifestsOfEngine(host.engine), + ); + const recordName = String(record.name); + const perShipperType = ['flow', 'action'].includes(canonicalMetaType(normalizedType)); if ( - !host.isHostCodeDatasource(normalizedType, String(record.name)) - && !isServedOverrideRowOf( - record as ServedOverrideRow, - host.packagedArtifactOwner({ type: normalizedType, name: String(record.name) }), - installedManifestsOfEngine(host.engine), - ) + !host.isHostCodeDatasource(normalizedType, recordName) + && !(perShipperType + ? someShipperOf(host, normalizedType, recordName, servedOverrideOf) + : servedOverrideOf(host.packagedArtifactOwner({ type: normalizedType, name: recordName }))) ) { sealedOverlays.push({ type: normalizedType, name: String(record.name) }); } diff --git a/packages/metadata-protocol/src/protocol-environment-rows.ts b/packages/metadata-protocol/src/protocol-environment-rows.ts index 78fcd12721e..d38f85a350e 100644 --- a/packages/metadata-protocol/src/protocol-environment-rows.ts +++ b/packages/metadata-protocol/src/protocol-environment-rows.ts @@ -264,6 +264,33 @@ export function shippingPackageIds(shipped: readonly unknown[]): ReadonlySet boolean, +): boolean { + if (judge(host.packagedArtifactOwner({ type, name }))) return true; + return [...shippingPackageIds(host.shippedArtifactsOf(type, name))].some((shipper) => judge(shipper)); +} + /** * [ADR-0146 D11] The READ-ONLY code packages that ship a name, sorted: the * {@link shippingPackageIds} of `shipped` less every package diff --git a/packages/objectql/src/protocol-flow-custom-override.test.ts b/packages/objectql/src/protocol-flow-custom-override.test.ts index 5df93a9caab..30d387bf149 100644 --- a/packages/objectql/src/protocol-flow-custom-override.test.ts +++ b/packages/objectql/src/protocol-flow-custom-override.test.ts @@ -744,3 +744,315 @@ describe('[#30065] a declared .custom action override is the packaged action, at expect(refusal!.message).not.toMatch(/not yet available/); }); }); + +/** + * [#32552, ADR-0150 D4, epic #31527 red line 2] Two namespaces' packages each + * ship a flow of one name (the flow's one-holder rule is per namespace since + * #31696), and each package's paired `.custom` declares its own override. The + * removal `?package=.custom` removes B's override and leaves A's, whichever + * package registered first. + * + * The removal's pair-row verdict (`isPairRowRemoval`) read the base from the + * bare-name artifact lookup, which answers the first package registered: the + * second package's pair was judged against the first package, was no pair of + * it, and its removal was refused `403 NOT_OVERRIDABLE` "sealed against + * removal", so B's override could not be undone. It is judged against every + * package that ships the name now, as the served read judges the row. + * + * The same bare-name judgement, swept on the same class: a commit revert into + * the second holder's pair was refused `403 NOT_OVERRIDABLE` (`restoreWriteFor`, + * which the per-item rollback shares), and the boot census named the second + * holder's live override as an unserved row to delete. Each is judged against + * every shipper now (`someShipperOf`). + * + * After the second holder's override is removed, every entry the list and the + * execution view carry for the name is its own package's, a package-less row + * of the name stored beside them, for a flow and for an object-less action. + * + * CONTROLS: removing a stored row of a package that depends on both holders + * and is the pair of neither keeps the refusal it had, and the census still + * names such a row, in both orders; with one holder, the removal, the revert + * and the census answer as before. + */ +describe('[#32552] a pair\'s row of a name two namespaces hold is judged against its own base', () => { + const ALPHA = 'com.example.alpha'; + const BETA = 'com.example.beta'; + const STRANGER = 'com.example.stranger'; + /** An object-less action of one name, which two namespaces may each ship too. */ + const SHARED = 'shared_close'; + const sharedAction = (label: string, extra: Record = {}) => ({ + name: SHARED, label, type: 'script', body: { language: 'js', source: `return { ran: '${label}' };` }, ...extra, + }); + /** An import mapping of one name, a sealed type that keeps the first-registered holder's judgment until #33131. */ + const MAPPING = 'shared_feed'; + const sharedMapping = (ns: string, label: string, extra: Record = {}) => ({ + name: MAPPING, label, sourceFormat: 'csv', targetObject: `${ns}_task`, + fieldMapping: [{ source: 'Title', target: 'title' }], mode: 'insert', ...extra, + }); + const holderManifest = (id: string, ns: string, opts: { mapping?: boolean } = {}) => ({ + id, name: ns, version: '1.0.0', namespace: ns, type: 'app', + objects: [{ name: `${ns}_task`, label: 'Task', sharingModel: 'private', fields: { title: { name: 'title', label: 'title', type: 'text' } } }], + flows: [flowBody(`SHIPPED-${ns}`)], + actions: [sharedAction(`SHIPPED-${ns}`)], + ...(opts.mapping ? { mappings: [sharedMapping(ns, `SHIPPED-${ns}`)] } : {}), + }); + const nsOf = (id: string) => id.split('.').pop()!; + + /** The holders registered in `holders`' order, each with its pair and its pair's declared flow and action overrides. */ + async function bootHolders(holders: readonly string[], opts: { mapping?: boolean } = {}) { + const engine = new ObjectQL(); + const { driver, stores } = makeMemoryDriver(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(sysMetadataObject, 'test-package'); + for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + for (const id of holders) engine.registerApp(holderManifest(id, nsOf(id), opts)); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); + for (const base of holders) { + await (protocol as any).installPackage({ + manifest: { + id: `${base}.custom`, name: `${nsOf(base)}-custom`, version: '0.1.0', type: 'app', + namespace: `${nsOf(base)}_custom`, dependencies: { [base]: '^1' }, + }, + }); + } + // A package that depends on every holder and is the pair of none. + await (protocol as any).installPackage({ + manifest: { + id: STRANGER, name: 'stranger', version: '0.1.0', type: 'app', + dependencies: Object.fromEntries(holders.map((id) => [id, '*'])), + }, + }); + // Each holder's pair declares its own overrides, through the save door. + for (const base of holders) { + for (const [type, name, body] of [['flow', FLOW, flowBody], ['action', SHARED, sharedAction]] as const) { + await protocol.saveMetaItem({ + type, name, item: body(`OVERRIDE-${nsOf(base)}`, { overrides: { package: base, basedOn: '1.0.0' } }), + mode: 'draft', packageId: `${base}.custom`, + } as any); + await protocol.publishMetaItem({ type, name, packageId: `${base}.custom` } as any); + } + } + const active = () => Array.from(stores.get('sys_metadata')?.values() ?? []) + .filter((r) => r.type === 'flow' && r.name === FLOW && r.state === 'active') + .map((r) => r.package_id).sort(); + const labelAt = async (packageId: string) => (await read(protocol, packageId)).label; + return { engine, protocol, active, labelAt }; + } + const bootTwo = (first: string) => bootHolders(first === ALPHA ? [ALPHA, BETA] : [BETA, ALPHA]); + + for (const first of [ALPHA, BETA]) { + for (const target of [ALPHA, BETA]) { + const other = target === ALPHA ? BETA : ALPHA; + it(`${nsOf(first)} registered first: ?package=${nsOf(target)}.custom removes ${nsOf(target)}'s override, never ${nsOf(other)}'s`, async () => { + const { protocol, active, labelAt } = await bootTwo(first); + expect(active()).toEqual([`${ALPHA}.custom`, `${BETA}.custom`]); + expect(await labelAt(target)).toBe(`OVERRIDE-${nsOf(target)}`); + + const removed: any = await protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: `${target}.custom` } as any); + + expect(removed.success).toBe(true); + expect(active()).toEqual([`${other}.custom`]); + expect(await labelAt(target)).toBe(`SHIPPED-${nsOf(target)}`); + expect(await labelAt(other)).toBe(`OVERRIDE-${nsOf(other)}`); + }); + } + + it(`CONTROL, ${nsOf(first)} registered first: removing a row of a package that is neither holder's pair keeps its refusal`, async () => { + const { engine, protocol, active } = await bootTwo(first); + // Laid down by the store's own write, as before the save gate. + await engine.insert('sys_metadata', { + type: 'flow', name: FLOW, organization_id: null, package_id: STRANGER, + metadata: JSON.stringify(flowBody('STRANGER', { overrides: { package: ALPHA, basedOn: '1.0.0' } })), state: 'active', version: 1, + }, { context: { isSystem: true } }); + await expect(protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: STRANGER } as any)) + .rejects.toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(active()).toEqual([`${ALPHA}.custom`, `${BETA}.custom`, STRANGER]); + }); + + it(`${nsOf(first)} registered first: each holder's commit into its own pair reverts`, async () => { + for (const target of [ALPHA, BETA]) { + const { protocol, labelAt } = await bootTwo(first); + await protocol.saveMetaItem({ + type: 'flow', name: FLOW, item: flowBody('EDITED', { overrides: { package: target, basedOn: '1.0.0' } }), + mode: 'draft', packageId: `${target}.custom`, + } as any); + const commit: any = await protocol.publishPackageDrafts({ packageId: `${target}.custom` } as any); + expect(commit.commitId, nsOf(target)).toBeDefined(); + expect(await labelAt(target)).toBe('EDITED'); + + const reverted: any = await (protocol as any).revertCommit({ commitId: commit.commitId, packageId: `${target}.custom` }); + + expect({ target: nsOf(target), success: reverted.success, failed: reverted.failed ?? [] }) + .toEqual({ target: nsOf(target), success: true, failed: [] }); + expect(await labelAt(target)).toBe(`OVERRIDE-${nsOf(target)}`); + } + }); + + it(`${nsOf(first)} registered first: the boot census names no holder's declared override as unserved, and still names a stranger's row`, async () => { + const { engine, protocol } = await bootTwo(first); + const census = async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + await (protocol as any).loadMetaFromDb(); + return warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('metadata_sealed_overlay_unserved')); + } finally { + warn.mockRestore(); + } + }; + expect(await census()).toEqual([]); + // CONTROL: a row of a package that is neither holder's pair is named. + await engine.insert('sys_metadata', { + type: 'flow', name: FLOW, organization_id: null, package_id: STRANGER, + metadata: JSON.stringify(flowBody('STRANGER', { overrides: { package: ALPHA, basedOn: '1.0.0' } })), state: 'active', version: 1, + }, { context: { isSystem: true } }); + const named = await census(); + expect(named).toHaveLength(1); + expect(named[0]).toContain(`flow×1 (${FLOW})`); + }); + + // [#32552 review s1] The census judges a row as the reads serve it. The + // reads serve a second holder's declared override per shipper for a flow + // and an action only (#32613); the six sealed types keep the name's + // first-registered shipper until #33131, so the second holder's mapping + // override is unserved and the census still names it. + it(`CONTROL, ${nsOf(first)} registered first: a sealed type's census keeps the first-registered holder's judgment (a mapping)`, async () => { + const { engine, protocol } = await bootHolders(first === ALPHA ? [ALPHA, BETA] : [BETA, ALPHA], { mapping: true }); + for (const base of [ALPHA, BETA]) { + await engine.insert('sys_metadata', { + type: 'mapping', name: MAPPING, organization_id: null, package_id: `${base}.custom`, + metadata: JSON.stringify(sharedMapping(nsOf(base), `OVERRIDE-${nsOf(base)}`, { overrides: { package: base, basedOn: '1.0.0' } })), + state: 'active', version: 1, + }, { context: { isSystem: true } }); + } + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + let named: string[]; + try { + await (protocol as any).loadMetaFromDb(); + named = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('metadata_sealed_overlay_unserved')); + } finally { + warn.mockRestore(); + } + expect(named).toHaveLength(1); + expect(named[0]).toContain(`mapping×1 (${MAPPING})`); + }); + + + it(`${nsOf(first)} registered first: after the second holder's override is removed, every listed flow and action is its own package's, beside a package-less row of the name`, async () => { + const { engine, protocol } = await bootTwo(first); + const second = first === ALPHA ? BETA : ALPHA; + for (const [type, name, body] of [['flow', FLOW, flowBody], ['action', SHARED, sharedAction]] as const) { + // A package-less row of the name, laid down by the store's own write. + await engine.insert('sys_metadata', { + type, name, organization_id: null, package_id: null, metadata: JSON.stringify(body('PACKAGE-LESS')), state: 'active', version: 1, + }, { context: { isSystem: true } }); + const removed: any = await protocol.deleteMetaItem({ type, name, packageId: `${second}.custom` } as any); + expect(removed.success, type).toBe(true); + for (const face of ['served', 'execution'] as const) { + const res: any = face === 'served' + ? await protocol.getMetaItems({ type }) + : await (protocol as any).getMetaItemsForExecution({ type }); + const entries = (res.items as any[]).filter((i) => i?.name === name); + expect(entries.length, `${type} ${face}`).toBeGreaterThan(0); + for (const entry of entries) { + expect([`SHIPPED-${nsOf(entry._packageId)}`, `OVERRIDE-${nsOf(entry._packageId)}`], `${type} ${face}: ${entry._packageId} lists '${entry.label}'`) + .toContain(entry.label); + } + expect(entries.map((e) => e._packageId), `${type} ${face}`).toContain(second); + } + } + }); + } + + // [ADR-0150 D3] One holder disabled after its override was declared. The + // bare-name lookup still answers the first-registered holder, disabled or + // not, so the second-registered holder's pair was judged against the + // wrong base whichever of the two is disabled. Each pair is judged + // against its own base, the disabled holder's pair included: a binding + // never moves with a reversible disable. + for (const first of [ALPHA, BETA]) { + for (const disabled of [ALPHA, BETA]) { + it(`${nsOf(first)} registered first, ${nsOf(disabled)} disabled: each holder's pair removal and commit revert are admitted, and the census names neither`, async () => { + for (const target of [ALPHA, BETA]) { + const other = target === ALPHA ? BETA : ALPHA; + const { engine, protocol, active } = await bootTwo(first); + await protocol.saveMetaItem({ + type: 'flow', name: FLOW, item: flowBody('EDITED', { overrides: { package: target, basedOn: '1.0.0' } }), + mode: 'draft', packageId: `${target}.custom`, + } as any); + const commit: any = await protocol.publishPackageDrafts({ packageId: `${target}.custom` } as any); + engine.registry.disablePackage(disabled); + const census = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + await (protocol as any).loadMetaFromDb(); + expect(census.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('metadata_sealed_overlay_unserved')), nsOf(target)).toEqual([]); + } finally { + census.mockRestore(); + } + + const reverted: any = await (protocol as any).revertCommit({ commitId: commit.commitId, packageId: `${target}.custom` }); + expect({ target: nsOf(target), success: reverted.success, failed: reverted.failed ?? [] }) + .toEqual({ target: nsOf(target), success: true, failed: [] }); + + const removed: any = await protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: `${target}.custom` } as any); + expect([nsOf(target), removed.success]).toEqual([nsOf(target), true]); + expect(active()).toEqual([`${other}.custom`]); + } + }); + } + } + + // CONTROLS — one holder: each moved answer answers as it did before. + it('CONTROL, one holder disabled: its pair\'s removal and its commit revert are admitted as before', async () => { + const { engine, protocol, active } = await bootHolders([ALPHA]); + await protocol.saveMetaItem({ + type: 'flow', name: FLOW, item: flowBody('EDITED', { overrides: { package: ALPHA, basedOn: '1.0.0' } }), + mode: 'draft', packageId: `${ALPHA}.custom`, + } as any); + const commit: any = await protocol.publishPackageDrafts({ packageId: `${ALPHA}.custom` } as any); + engine.registry.disablePackage(ALPHA); + const reverted: any = await (protocol as any).revertCommit({ commitId: commit.commitId, packageId: `${ALPHA}.custom` }); + expect([reverted.success, reverted.failed ?? []]).toEqual([true, []]); + const removed: any = await protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: `${ALPHA}.custom` } as any); + expect(removed.success).toBe(true); + expect(active()).toEqual([]); + }); + + it('CONTROL, one holder: its pair\'s removal, its commit revert and the boot census answer as before', async () => { + const { engine, protocol, active, labelAt } = await bootHolders([ALPHA]); + const census = async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + await (protocol as any).loadMetaFromDb(); + return warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('metadata_sealed_overlay_unserved')); + } finally { + warn.mockRestore(); + } + }; + expect(await census()).toEqual([]); + + await protocol.saveMetaItem({ + type: 'flow', name: FLOW, item: flowBody('EDITED', { overrides: { package: ALPHA, basedOn: '1.0.0' } }), + mode: 'draft', packageId: `${ALPHA}.custom`, + } as any); + const commit: any = await protocol.publishPackageDrafts({ packageId: `${ALPHA}.custom` } as any); + const reverted: any = await (protocol as any).revertCommit({ commitId: commit.commitId, packageId: `${ALPHA}.custom` }); + expect([reverted.success, reverted.failed ?? []]).toEqual([true, []]); + expect(await labelAt(ALPHA)).toBe('OVERRIDE-alpha'); + + const removed: any = await protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: `${ALPHA}.custom` } as any); + expect(removed.success).toBe(true); + expect(active()).toEqual([]); + expect(await labelAt(ALPHA)).toBe('SHIPPED-alpha'); + + await engine.insert('sys_metadata', { + type: 'flow', name: FLOW, organization_id: null, package_id: STRANGER, + metadata: JSON.stringify(flowBody('STRANGER', { overrides: { package: ALPHA, basedOn: '1.0.0' } })), state: 'active', version: 1, + }, { context: { isSystem: true } }); + await expect(protocol.deleteMetaItem({ type: 'flow', name: FLOW, packageId: STRANGER } as any)) + .rejects.toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(await census()).toHaveLength(1); + }); +});