diff --git a/.changeset/38753-disabled-holder-counts-nothing.md b/.changeset/38753-disabled-holder-counts-nothing.md new file mode 100644 index 00000000000..f4fd81e5850 --- /dev/null +++ b/.changeset/38753-disabled-holder-counts-nothing.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/runtime': patch +--- + +fix(metadata-protocol): a disabled package counts for nothing at the environment address, the delete naming no package and the read beside a package-less row + +Clause-②: no +Metadata-protocol: none + +A disabled package holds no name and is never named (ADR-0150 D3). Three doors still counted one. + +- **`GET /api/v1/meta/TYPE/_env/NAME`** (the plain read, `?layers=true`, `?state=draft`, `?preview=draft`, and the `_env/NAME` spelling of an import's `mappingName`), for a name the registry knows only through a disabled package while an enabled package holds it through a stored row or draft the registry has not loaded: the answer was `409 RESOURCE_CONFLICT` naming the disabled package. It is now `409 RESOURCE_CONFLICT` naming the enabled package whose row or draft the read that names no package serves (`details.candidates`), and never that row. Where that read answers 404, `_env` still answers 404. +- **`DELETE` naming no package, and the draft discard naming no package**, of an item whose stored rows are bound to a disabled package and to the one enabled package that ships the name: the answer was `409 RESOURCE_CONFLICT` naming both. Each now removes the enabled package's row or draft, as the same request with `?package=` naming it does, and leaves the disabled package's rows as they are. With two or more enabled holders the refusal still names exactly them. +- **The receipt of `DELETE` and of the draft discard**, bare or naming the enabled package, beside a disabled package's rows: it said the item "still carries another overlay: its row bound to package 'D' remains", naming the disabled package, and for a name only a disabled package ships in code it said "reset to artifact default". A disabled package's row is no remaining overlay and its code is no artifact default: the receipt now reads as it does without the disabled package ("reset to artifact default" where the enabled package ships the name, "it no longer exists" where no enabled package does). Repeating the bare delete or discard once the enabled package's row or draft is gone answered by removing the DISABLED package's row or draft (a customization hidden with it); it now answers the no-op receipt at the enabled package's address and leaves the disabled package's rows stored. A `dropStorage` delete still counts every stored row. +- **The read that names no package** (`GET /api/v1/meta/TYPE/NAME`, `/layers`, `/published`), of a name a disabled package ships in code only, beside one enabled package's stored row and a package-less row: the answer was 404. It now serves the enabled package's row, as it does when the disabled package does not ship the name. + +Not changed here: the draft save naming no package of the second case still answers `409` naming both packages. To write the enabled package's draft now, name it: `?package=PACKAGE`. diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index dce3e7b336b..5ced7d3e038 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -69,6 +69,7 @@ import { captureStoredExpressionChange, fillStoredExpressionChange } from './pro import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; import { disabledRowHoldersRefusal, packagelessHolderRefusal, packagelessRowHeldBaseAddress } from './protocol-save.js'; +import { countedRowHolders, shippedByCountedPackage, soleEnabledRowHolder } from './protocol-enabled-holders.js'; import { isPlatformRecordRow } from '@objectstack/metadata'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; @@ -728,7 +729,9 @@ export class ProtocolDiffDeleteLoadFacet { ? await host.packagelessDraftAddress(singularTypeForRepo, request.name, member) : undefined; if (draftAddress?.kind === 'ambiguous') { - const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member); + // [#38753] …or the one enabled holder beside a disabled package's draft ({@link soleEnabledRowHolder}). + const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member) + ?? soleEnabledRowHolder(host, singularTypeForRepo, request.name, member, draftAddress.candidates); if (base === undefined) { // [#34346] …naming the holders the read counts where a // row is bound to a disabled package ({@link disabledRowHoldersRefusal}). @@ -741,12 +744,26 @@ export class ProtocolDiffDeleteLoadFacet { } request = { ...request, packageId: base }; draftAddress = undefined; + } else if (draftAddress !== undefined && draftAddress.into !== null && !draftAddress.drafts.unbound) { + // [#38753 (folded delete-receipt finding), #32354] …and + // the draft address of active rows bound to a package that + // counts for nothing (a disabled one), beside the one + // enabled holder the read naming no package serves: the + // discard acts at that holder's address, as without the + // disabled package, never at the disabled package's draft. + const base = soleEnabledRowHolder(host, singularTypeForRepo, request.name, member, [draftAddress.into]); + if (base !== undefined) { + request = { ...request, packageId: base }; + draftAddress = undefined; + } } const rowsAtAddress = draftAddress?.drafts ?? await host.packagelessAddress( singularTypeForRepo, request.name, member, targetState, ); if (request.packageId == null && draftAddress === undefined && rowsAtAddress.candidates.length > 1) { - const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member); + // [#38753] …or the one enabled holder beside a disabled package's row ({@link soleEnabledRowHolder}). + const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member) + ?? soleEnabledRowHolder(host, singularTypeForRepo, request.name, member, rowsAtAddress.candidates); if (base === undefined) { // [#34346, ADR-0150 D3/D5] Rows bound to a disabled // package too are refused naming the holders the read @@ -760,6 +777,16 @@ export class ProtocolDiffDeleteLoadFacet { throw addressRefusal; } request = { ...request, packageId: base }; + } else if (request.packageId == null && draftAddress === undefined && rowsAtAddress.candidates.length === 1 && !rowsAtAddress.unbound) { + // [#38753 (folded delete-receipt finding), #32354] …and + // rows bound to ONE package that counts for nothing (a + // disabled one), beside the one enabled holder the read + // naming no package serves: the delete acts at that + // holder's address, as without the disabled package. FROM + // (`main` 645e6b15): it removed the disabled package's + // row, a customization hidden with it. + const base = soleEnabledRowHolder(host, singularTypeForRepo, request.name, member, rowsAtAddress.candidates); + if (base !== undefined) request = { ...request, packageId: base }; } // [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the // read naming no package counts, as the save door asks them @@ -818,8 +845,18 @@ export class ProtocolDiffDeleteLoadFacet { // own permission set beside sets other namespaces' packages ship // has none ({@link isOwnPermissionSetWrite}, the verdict its save // reads), so removing it removes the set, never resets one. + // + // [#38753 (folded delete-receipt finding), #32354] …nor does a + // name only disabled packages ship ({@link shippedByCountedPackage}). const shippedUnderAddress = artifactBacked - && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, packageId); + && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, packageId) + && shippedByCountedPackage(host, singularTypeForRepo, request.name, member); + // [#38753 (folded delete-receipt finding), #32354] The rows the + // receipts below say remain: a disabled package's row (or its + // pair's) is stored but served by no read, so it is never named + // there ({@link countedRowHolders}). The table drop still counts + // every stored row. + const countedCandidates = countedRowHolders(host, singularTypeForRepo, request.name, rowsAtAddress.candidates); // Probe first — "no overlay exists" is a success/no-op, not // a conflict. The repo would otherwise throw ConflictError. const current = await repo.get(ref, { state: targetState, packageId, ...memberOption(member) }); @@ -851,13 +888,13 @@ export class ProtocolDiffDeleteLoadFacet { ?? (draftAddress?.kind === 'none' && draftAddress.into !== null && rowsAtAddress.unbound ? draftAddress.into : null); - if (!current && receiptPackageId != null && (rowsAtAddress.candidates.length > 0 || rowsAtAddress.unbound)) { + if (!current && receiptPackageId != null && (countedCandidates.length > 0 || rowsAtAddress.unbound)) { return { success: true, reset: false, message: targetState === 'draft' - ? `No pending draft of ${request.type}/${request.name} is bound to package '${receiptPackageId}', so nothing was discarded: ${remainingRowsPhrase(rowsAtAddress.candidates, rowsAtAddress.unbound, 'draft')}.` - : `No row of ${request.type}/${request.name} is bound to package '${receiptPackageId}', so nothing was deleted: ${remainingRowsPhrase(rowsAtAddress.candidates, rowsAtAddress.unbound, 'row')}.`, + ? `No pending draft of ${request.type}/${request.name} is bound to package '${receiptPackageId}', so nothing was discarded: ${remainingRowsPhrase(countedCandidates, rowsAtAddress.unbound, 'draft')}.` + : `No row of ${request.type}/${request.name} is bound to package '${receiptPackageId}', so nothing was deleted: ${remainingRowsPhrase(countedCandidates, rowsAtAddress.unbound, 'row')}.`, }; } // [#23495] …and a draft discard naming no package, of an item @@ -865,11 +902,11 @@ export class ProtocolDiffDeleteLoadFacet { // address while other packages' drafts are stored: nothing is // discarded, and the receipt names what remains rather than // claiming no draft exists. - if (!current && draftAddress?.kind === 'none' && draftAddress.into !== null && rowsAtAddress.candidates.length > 0) { + if (!current && draftAddress?.kind === 'none' && draftAddress.into !== null && countedCandidates.length > 0) { return { success: true, reset: false, - message: `No pending draft of ${request.type}/${request.name} is bound to package '${draftAddress.into}', the package its published rows are bound to and the draft a discard that names no package removes, so nothing was discarded: ${remainingRowsPhrase(rowsAtAddress.candidates, rowsAtAddress.unbound, 'draft')}.`, + message: `No pending draft of ${request.type}/${request.name} is bound to package '${draftAddress.into}', the package its published rows are bound to and the draft a discard that names no package removes, so nothing was discarded: ${remainingRowsPhrase(countedCandidates, rowsAtAddress.unbound, 'draft')}.`, }; } if (!current) { @@ -915,6 +952,9 @@ export class ProtocolDiffDeleteLoadFacet { const remainingPackages = rowsAtAddress.candidates.filter((id) => id !== packageId); const unboundRemains = rowsAtAddress.unbound && packageId !== null; const remains = remainingPackages.length > 0 || unboundRemains; + // [#38753 (folded delete-receipt finding)] …and what the receipt says remains. + const remainingCounted = countedCandidates.filter((id) => id !== packageId); + const countedRemains = remainingCounted.length > 0 || unboundRemains; // [#23415] The table drop, decided ONCE, before anything is // written: an object's table goes only with its last stored // row. A `dropStorage` delete that would leave another row of @@ -1113,11 +1153,11 @@ export class ProtocolDiffDeleteLoadFacet { message: (request.state === 'draft') ? `Draft discarded${deletedPackage} — ${request.type}/${request.name}. [seq=${result.seq}]` : shippedUnderAddress - ? (remains - ? `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} still carries another overlay: ${remainingRowsPhrase(remainingPackages, unboundRemains, 'row')}. [seq=${result.seq}]` + ? (countedRemains + ? `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} still carries another overlay: ${remainingRowsPhrase(remainingCounted, unboundRemains, 'row')}. [seq=${result.seq}]` : `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} reset to artifact default. [seq=${result.seq}]`) - : (remains - ? `Deleted ${singularTypeForRepo} '${request.name}'${deletedPackage}, and it still exists: ${remainingRowsPhrase(remainingPackages, unboundRemains, 'row')}. [seq=${result.seq}]` + : (countedRemains + ? `Deleted ${singularTypeForRepo} '${request.name}'${deletedPackage}, and it still exists: ${remainingRowsPhrase(remainingCounted, unboundRemains, 'row')}. [seq=${result.seq}]` : `Deleted ${singularTypeForRepo} '${request.name}'${deletedPackage} — it no longer exists. [seq=${result.seq}]`), }; } catch (err: any) { diff --git a/packages/metadata-protocol/src/protocol-enabled-holders.ts b/packages/metadata-protocol/src/protocol-enabled-holders.ts new file mode 100644 index 00000000000..17a8eece3b9 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-enabled-holders.ts @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38753, ADR-0150 D3/D5, #32354] A disabled package holds no name and is + * never named: the holders a door naming no package (or naming the + * environment, `_env`) judges are the ENABLED ones, so each door answers as + * it answers without the disabled package. + * + * Two judgments live here, each asked by the door that used to count the + * disabled package: + * + * - {@link environmentReadRefusalOf}: the `_env` admission of a name the + * registry knows only through disabled packages. The admission cannot see + * a package that holds the name through a stored row the registry has not + * read, so its doors ask the read naming no package; this restates what + * that read answers as `_env`'s own answer, naming only enabled packages. + * - {@link soleEnabledRowHolder}: the bare delete and draft discard of an + * item whose rows are bound to a disabled package and to the one enabled + * holder the read naming no package serves: they act at that holder's + * address, as the read and the bare publish save already do. + * + * And the delete receipt's two claims about what is left + * ({@link countedRowHolders}, {@link shippedByCountedPackage}): a disabled + * package's row is no remaining overlay and its code no artifact default. + */ + +import { pairsOf } from '@objectstack/metadata-core'; +import { + PackageScopedNameRefusedError, + packageScopedRefusalMessage, + type PackageScopedResolvableType, +} from '@objectstack/core'; +import { installedManifestsOfEngine } from './installed-manifests.js'; +import { shippingPackageIds } from './protocol-environment-rows.js'; +import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; +import type { ProtocolHost } from './protocol-host.js'; + +/** The registry reads the judgments here ask, each optional-called. */ +interface EnabledHolderRegistry { + readsByPackage?(type: string): boolean; + getEnvironmentScopedItem?(type: string, name: string, member?: string): unknown; + packageScopedHoldersOf?(type: string, name: string, callerPackageId?: string | null, options?: { includeDisabledPackages?: boolean }): readonly string[] | undefined; + isPackageDisabled?(id: string): boolean; +} + +/** + * Whether `id` counts for nothing: a disabled package, or the customization + * pair of a disabled holder of the name (a pair row is its holder's item, + * withheld with it, ADR-0146 D9). + */ +function countsForNothing( + host: Pick, + registry: EnabledHolderRegistry, + disabledHolders: readonly string[], +): (id: string) => boolean { + const installed = installedManifestsOfEngine(host.engine); + return (id) => registry.isPackageDisabled?.(id) === true + || disabledHolders.some((holder) => pairsOf(holder, installed).includes(id)); +} + +/** + * [#38753, ADR-0150 D5, #32354] The `Symbol.for` key of the judgment + * `admitEnvironmentQualifier` attaches to its refusal of a name the registry + * knows only through disabled packages (the refusal marked + * `DISABLED_HOLDERS_ONLY_REFUSAL`). A registered symbol, so every copy of + * this package reads the same key and no envelope serializes it. The `_env` + * doors (`RestServer`'s qualified route and its import door, the runtime + * dispatcher) read it by the same key: none imports this package. + */ +export const ENVIRONMENT_READ_REFUSAL: unique symbol = Symbol.for('objectstack.metadata-protocol.environmentReadRefusal') as never; + +/** What the read naming no package answered a door: its answer, or what it threw. */ +export type EnvironmentReadOutcome = + | { readonly answer: unknown; readonly error?: undefined } + | { readonly error: unknown; readonly answer?: undefined }; + +/** + * [#38753, ADR-0150 D5, #32354] The judgment of `_env` for a name the + * registry knows only through disabled packages, once the read naming no + * package has NOT withheld it (that read's 404 is `_env`'s, decided at the + * door). A disabled package holds no name, so the holders are the enabled + * packages that read answers with: + * + * - it serves an item bound to an enabled package (its `packageId`, or the + * item's `_packageId` a draft read stamps: a package that holds the name + * through a stored row or draft the registry has not read): `_env` is + * refused `not-held-by-qualifier` naming that package, as for any name a + * package holds and the environment does not; + * - it refuses naming packages (its own package-scoped refusal): `_env` is + * refused naming the enabled ones among them; + * - `undefined` otherwise (an item no enabled package holds, or a failure + * that is no refusal): the door admits `_env`, which answers what the + * read naming no package answers, as it does with no disabled holder. + * + * FROM (`main` 8338d070): the door rethrew the admission's refusal, naming + * the disabled package, whenever that read served an item or failed. + */ +export function environmentReadRefusalOf( + host: Pick, + request: { type: string; name: string }, + disabledHolders: readonly string[], +): (outcome: EnvironmentReadOutcome) => PackageScopedNameRefusedError | undefined { + return (outcome) => { + const registry = host.engine?.registry as EnabledHolderRegistry | undefined; + if (!registry) return undefined; + const countsNothing = countsForNothing(host, registry, disabledHolders); + let named: string[]; + if (outcome.error !== undefined) { + const refusal = packageScopedRefusalOf(outcome.error); + named = (refusal?.candidates ?? []).flatMap((candidate) => (candidate.kind === 'package' ? [candidate.packageId] : [])); + } else { + // The plain read states its holder as `packageId`; the draft reads + // stamp it on the item only (`_packageId`). + const served = outcome.answer as { item?: { _packageId?: unknown } | null; packageId?: unknown } | null | undefined; + const holder = served?.item == null ? undefined : served.packageId ?? served.item._packageId; + named = typeof holder === 'string' && holder !== '' ? [holder] : []; + } + const enabled = [...new Set(named)].filter((id) => !countsNothing(id)).sort(); + if (enabled.length === 0) return undefined; + const base = { + status: 'refused' as const, + reason: 'not-held-by-qualifier' as const, + type: request.type as PackageScopedResolvableType, + name: request.name, + callerPackageId: null, + candidates: enabled.map((packageId) => ({ kind: 'package' as const, packageId })), + }; + return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); + }; +} + +/** + * [#38753 (folded #38769), ADR-0150 D3/D5, #32354] The one ENABLED package a + * write naming no package acts at where the item's rows are bound to two or + * more packages, a disabled one among them: the holders the read naming no + * package counts (the registry's served holders and the enabled packages the + * rows are bound to), when they are exactly one. The read serves that + * package's item and the bare publish save writes its row, so the bare + * delete and the bare draft discard remove its row or draft, as the request + * naming it does, and the disabled package's rows stay where they are. + * + * `undefined` otherwise, and the door answers as before: no row bound to a + * package that counts for nothing, a type the registry does not read by + * package, the environment's own item, or two or more enabled holders (the + * refusal naming them, `disabledRowHoldersRefusal`) or none. + * + * FROM (`main` 8338d070): both doors refused `409 RESOURCE_CONFLICT` naming + * the disabled package and the enabled one. + */ +export function soleEnabledRowHolder( + host: Pick, + type: string, + name: string, + member: string | undefined, + candidates: readonly string[], +): string | undefined { + const registry = host.engine?.registry as EnabledHolderRegistry | undefined; + if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(type) !== true) return undefined; + if (typeof registry.isPackageDisabled !== 'function' || typeof registry.packageScopedHoldersOf !== 'function') return undefined; + if (typeof registry.getEnvironmentScopedItem === 'function' && registry.getEnvironmentScopedItem(type, name, member) !== undefined) { + return undefined; + } + const every = registry.packageScopedHoldersOf(type, name, null, { includeDisabledPackages: true }) ?? []; + const countsNothing = countsForNothing(host, registry, every.filter((id) => registry.isPackageDisabled?.(id) === true)); + if (!candidates.some(countsNothing)) return undefined; + const enabled = [...new Set([...(registry.packageScopedHoldersOf(type, name, null) ?? []), ...candidates])] + .filter((id) => !countsNothing(id)); + return enabled.length === 1 ? enabled[0] : undefined; +} + +/** + * [#33385, #38753] The marked refusal `admitEnvironmentQualifier` throws for + * a name the registry knows only through `disabledHolders`: a signal to the + * `_env` doors, which ask the read naming no package and answer its 404, or + * the judgment it carries under {@link ENVIRONMENT_READ_REFUSAL} + * ({@link environmentReadRefusalOf}). `marker` is the admission's + * `DISABLED_HOLDERS_ONLY_REFUSAL` key. A disabled package holds no name, so + * the refusal names none (`candidates` is empty, ADR-0150 D3), and no door + * answers with it. FROM (`main` 8338d070): it named the disabled packages, + * and the doors rethrew it as their answer when the read did not withhold + * the name. + */ +export function disabledHoldersOnlyRefusal( + host: Pick, + request: { type: string; name: string }, + disabledHolders: readonly string[], + marker: symbol, +): PackageScopedNameRefusedError { + const error = new PackageScopedNameRefusedError({ + status: 'refused', + reason: 'not-held-by-qualifier', + type: request.type as PackageScopedResolvableType, + name: request.name, + callerPackageId: null, + candidates: [], + message: `The ${request.type} "${request.name}" is held by no enabled package in the registry, and a disabled ` + + 'package holds no name (ADR-0150 D3): the environment\'s address answers as the read naming no package does.', + }); + Object.defineProperty(error, marker, { value: true }); + Object.defineProperty(error, ENVIRONMENT_READ_REFUSAL, { value: environmentReadRefusalOf(host, request, disabledHolders) }); + return error; +} + +/** + * [#38753 (folded delete-receipt finding), ADR-0150 D3, #32354] The packages + * among `packageIds` (the packages an item's stored rows are bound to) that a + * receipt may say still hold a row: every one but a disabled package and the + * customization pair of a disabled holder of the name. Their rows stay + * stored, and a table drop still counts them, but the read naming no package + * serves none of them, so a delete receipt neither names them nor calls them + * an overlay the item still carries. FROM (`main` 645e6b15): the receipt + * said "its row bound to package 'D' remains" of a disabled D. + */ +export function countedRowHolders( + host: Pick, + type: string, + name: string, + packageIds: readonly string[], +): string[] { + const registry = host.engine?.registry as EnabledHolderRegistry | undefined; + if (typeof registry?.isPackageDisabled !== 'function') return [...packageIds]; + const every = registry.packageScopedHoldersOf?.(type, name, null, { includeDisabledPackages: true }) ?? []; + const countsNothing = countsForNothing(host, registry, every.filter((id) => registry.isPackageDisabled?.(id) === true)); + return packageIds.filter((id) => !countsNothing(id)); +} + +/** + * [#38753 (folded delete-receipt finding), ADR-0150 D2/D3, #32354] Whether + * the code-shipped item a delete receipt calls the artifact default is one a + * read serves: `false` only when every package that ships `(type, name)` is + * disabled (a disabled package holds no name, so its code is no default the + * delete resets to). A name shipped by no package (code with no package + * stamp) answers `true`, as before. FROM (`main` 645e6b15): the delete of an + * enabled package's row of a name only a disabled package ships in code + * answered "reset to artifact default", where without that code it answers + * "it no longer exists". + */ +export function shippedByCountedPackage( + host: Pick, + type: string, + name: string, + member: string | undefined, +): boolean { + const registry = host.engine?.registry as EnabledHolderRegistry | undefined; + if (typeof registry?.isPackageDisabled !== 'function') return true; + const shippers = [...shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member))]; + return shippers.length === 0 || shippers.some((id) => registry.isPackageDisabled?.(id) !== true); +} diff --git a/packages/metadata-protocol/src/protocol-exact-qualifier.ts b/packages/metadata-protocol/src/protocol-exact-qualifier.ts index 1e8ec8b19a8..afd3443ee3c 100644 --- a/packages/metadata-protocol/src/protocol-exact-qualifier.ts +++ b/packages/metadata-protocol/src/protocol-exact-qualifier.ts @@ -57,6 +57,7 @@ import { } from '@objectstack/core'; import { ENVIRONMENT_ADDRESS_SEGMENT, readNamespacePositionSegment } from '@objectstack/spec/kernel'; import { installedManifestsOfEngine } from './installed-manifests.js'; +import { disabledHoldersOnlyRefusal } from './protocol-enabled-holders.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { bundleMemberDiscriminator } from './protocol-bundle-members.js'; import type { ProtocolHost } from './protocol-host.js'; @@ -979,7 +980,9 @@ export function resolveMetaItemAddress( * (`not-held-by-qualifier`, `callerPackageId: null`); otherwise the read is a * caller with no package, which E8's resolver answers environment-first. * [#33385] A name only disabled packages hold is refused with a mark the - * doors read ({@link DISABLED_HOLDERS_ONLY_REFUSAL}). + * doors read ({@link DISABLED_HOLDERS_ONLY_REFUSAL}); [#38753] that refusal + * names no package: the doors judge the read naming no package by its + * enabled holders alone. * Types outside the covered set keep the bare read, as `?package=` does for * them. * @@ -1022,7 +1025,13 @@ export function admitEnvironmentQualifier( // once the read it would admit is judgeable: each door then asks the read // naming no package, which judges the stored rows too, and answers the // name as no package's (its 404) when that read withholds it. - if (served.length === 0) refuseUnjudgeableByNameRead(host, request, { kind: 'environment' }); + // [#38753, #32354] …and otherwise as that read answers, judged by the + // enabled packages alone ({@link disabledHoldersOnlyRefusal}): the marked + // refusal names no disabled package, and is never a door's answer. + if (served.length === 0) { + refuseUnjudgeableByNameRead(host, request, { kind: 'environment' }); + throw disabledHoldersOnlyRefusal(host, request, holders, DISABLED_HOLDERS_ONLY_REFUSAL); + } const candidates: PackageScopedHolder[] = holders.map((holder) => ({ kind: 'package' as const, packageId: holder })); const base = { status: 'refused' as const, @@ -1032,9 +1041,7 @@ export function admitEnvironmentQualifier( callerPackageId: null, candidates, }; - const error = new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); - if (served.length === 0) Object.defineProperty(error, DISABLED_HOLDERS_ONLY_REFUSAL, { value: true }); - throw error; + throw new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); } /** @@ -1053,7 +1060,12 @@ export function admitEnvironmentQualifier( * withholds every customization of its holders (the pair's row, #32814; a * package-less row of their key, #33401). The door admits `_env` and its * read answers 404, naming no package; - * - that read serves an item, or refuses: a package holds the name through - * its stored row, so the refusal stands, as before. + * - [#38753, #32354] that read serves an item, or refuses: the refusal's + * `ENVIRONMENT_READ_REFUSAL` judgment (`protocol-enabled-holders.ts`) + * restates it as `_env`'s answer, naming the ENABLED packages that read + * answers with (a package holding the name through a stored row the + * registry has not read), never the disabled one; naming none, the door + * admits `_env`, which answers as that read does. FROM (`main` + * 8338d070): the refusal stood, naming the disabled package. */ const DISABLED_HOLDERS_ONLY_REFUSAL: unique symbol = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal') as never; diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 04de7334866..b8cd409664b 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -388,6 +388,16 @@ export async function servedRowHolderOf( activeRows = []; } const rows = await host.packagelessAddress(type, name, member, 'active', activeRows); + const every: readonly string[] = registry.packageScopedHoldersOf(type, name, null, { includeDisabledPackages: true }) ?? []; + // [#38753 (folded #38771), #32354] One ENABLED package's row beside a + // package-less row, where a disabled package holds the name (in code + // alone): judged below over the served set, so every bare door serves + // that package's row, as it does without the disabled package. Left as it + // was (the two guards below), the read withheld the disabled package's + // code item and every bare read answered 404, in both save orders, with + // or without the package-less row as the environment item. + const oneEnabledBesideDisabled = rows.unbound && rows.candidates.length === 1 && !disabled(rows.candidates[0]) + && every.some(disabled); // [#33210, ADR-0150 D3] The registry's environment item of a name no // package ships is the bare slot's entry, the row hydrated last: after a // reboot that is the package-less row whenever it was saved last. Beside @@ -395,8 +405,7 @@ export async function servedRowHolderOf( // customization of a name it cannot say whose, judged with them below, so // the answer follows no save order. Otherwise the environment's own item // leaves the read as it was. - if (environmentItem && !(rows.unbound && rows.candidates.length > 1)) return undefined; - const every: readonly string[] = registry.packageScopedHoldersOf(type, name, null, { includeDisabledPackages: true }) ?? []; + if (environmentItem && !(rows.unbound && rows.candidates.length > 1) && !oneEnabledBesideDisabled) return undefined; const anyDisabled = [...every, ...rows.candidates].some(disabled); // [#33210] The no-disabled arm judges a package-less row itself // ({@link storedRowHoldersRefusal}). @@ -406,7 +415,7 @@ export async function servedRowHolderOf( // {@link storedRowHoldersRefusal} leaves it (`holding.unbound` with fewer // than two candidates): whether the bare slot holds an environment item // then moves no answer. - if (rows.unbound && rows.candidates.length < 2) return undefined; + if (rows.unbound && rows.candidates.length < 2 && !oneEnabledBesideDisabled) return undefined; // [#34440, ADR-0150 D3] Beside a disabled holder a package-less row is // judged over the served set as it is with no disabled holder (#33210): // two or more served holders are refused naming only them, one is served diff --git a/packages/objectql/src/package-scoped-exact-qualifier.test.ts b/packages/objectql/src/package-scoped-exact-qualifier.test.ts index bdfec97aa85..dc90122b83f 100644 --- a/packages/objectql/src/package-scoped-exact-qualifier.test.ts +++ b/packages/objectql/src/package-scoped-exact-qualifier.test.ts @@ -2059,16 +2059,47 @@ describe('[#32183] a name only a disabled package holds, at an address that neit expect(JSON.stringify(answer ?? null)).not.toContain('pair fr-FR'); }); - it('[#33385, row 17 / R4-B2] X disabled: `_env` at that member refuses naming X, MARKED as a name only disabled packages hold, and the read naming no package withholds it, so each door answers 404', async () => { + // [#38753, #32354] FROM (`main` 8338d070) the marked refusal named X + // (`candidates: [X]`) TO naming no package: a disabled package holds no + // name and is never named. The doors answer the read naming no package's + // 404 here, as before. + it('[#33385, row 17 / R4-B2; #38753] X disabled: `_env` at that member is refused MARKED as a name only disabled packages hold, naming no package, and the read naming no package withholds it, so each door answers 404', async () => { registry.disablePackage(X); const err = await refusalOf(() => served.admitEnvironmentQualifier({ type: 'email_template', name: 'welcome', member: 'fr-FR' })); - expect([err.status, err.refusal.reason, err.refusal.candidates]).toEqual([409, 'not-held-by-qualifier', [{ kind: 'package', packageId: X }]]); + expect([err.status, err.refusal.reason, err.refusal.candidates]).toEqual([409, 'not-held-by-qualifier', []]); + expect(JSON.stringify({ message: err.message, refusal: err.refusal })).not.toContain(X); expect((err as unknown as Record)[Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal')]).toBe(true); const bare = await served.getMetaItem({ type: 'email_template', name: 'welcome', member: 'fr-FR' } as never); expect(bare?.item).toBeUndefined(); expect(JSON.stringify(bare ?? null)).not.toContain('pair fr-FR'); }); + // [#38753, #32354] What the doors answer when the read naming no package + // does NOT withhold the name: the marked refusal's judgment restates that + // read's answer naming the ENABLED packages it answers with, never X. FROM + // (`main` 8338d070) the doors rethrew the refusal naming X. + it('[#38753] X disabled: the marked refusal\'s judgment names the enabled package the read naming no package answers with, never X; naming none, it admits', async () => { + registry.disablePackage(X); + const err = await refusalOf(() => served.admitEnvironmentQualifier({ type: 'email_template', name: 'welcome', member: 'fr-FR' })); + const judge = (err as unknown as Record)[Symbol.for('objectstack.metadata-protocol.environmentReadRefusal')] as + (outcome: { answer?: unknown; error?: unknown }) => { status: number; refusal: { reason: string; candidates: unknown[] }; message: string } | undefined; + expect(typeof judge).toBe('function'); + const namesY = (restated: ReturnType, label: string) => { + expect([label, restated?.status, restated?.refusal.reason, restated?.refusal.candidates]).toEqual([label, 409, 'not-held-by-qualifier', [{ kind: 'package', packageId: Y }]]); + expect(restated?.message, label).not.toContain(X); + }; + // The plain read states its holder as `packageId`; a draft read stamps the item only. + namesY(judge({ answer: { item: { name: 'welcome' }, packageId: Y } }), 'plain read'); + namesY(judge({ answer: { item: { name: 'welcome', _packageId: Y } } }), 'draft read'); + // The read's own refusal naming X and Y: Y alone. + const both = await refusalOf(() => { throw new PackageScopedNameRefusedError({ status: 'refused', reason: 'ambiguous-in-environment', type: 'email_template', name: 'welcome', callerPackageId: null, candidates: [{ kind: 'package', packageId: X }, { kind: 'package', packageId: Y }], message: 'm' }); }); + namesY(judge({ error: both }), 'refusal'); + // Naming no enabled package (an item of none, X's own, a failure that is no refusal): admitted. + expect(judge({ answer: { item: { name: 'welcome' } } })).toBeUndefined(); + expect(judge({ answer: { item: { name: 'welcome' }, packageId: X } })).toBeUndefined(); + expect(judge({ error: new Error('store down') })).toBeUndefined(); + }); + it('CONTROL — X enabled: `_env` refuses naming X, unmarked', async () => { const err = await refusalOf(() => served.admitEnvironmentQualifier({ type: 'email_template', name: 'welcome', member: 'fr-FR' })); expect((err as unknown as Record)[Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal')]).toBeUndefined(); diff --git a/packages/rest/src/import-mapping.ts b/packages/rest/src/import-mapping.ts index 23cbc7f45aa..5a9fb324cb4 100644 --- a/packages/rest/src/import-mapping.ts +++ b/packages/rest/src/import-mapping.ts @@ -89,6 +89,15 @@ export interface NamedMappingProtocol { */ const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal'); +/** + * [#38753, #32354] The `Symbol.for` key of the judgment that marked refusal + * carries (`ENVIRONMENT_READ_REFUSAL` in `@objectstack/metadata-protocol`), + * the key the `/meta` door's qualified route reads: handed what the read + * naming no package answered, it returns `_env`'s refusal naming the ENABLED + * packages that read answers with, or nothing, when `_env` is admitted. + */ +const ENVIRONMENT_READ_REFUSAL = Symbol.for('objectstack.metadata-protocol.environmentReadRefusal'); + /** The by-name read a `mappingName` asks for. */ type MappingRead = { type: 'mapping'; name: string; packageId?: string }; @@ -110,7 +119,9 @@ type MappingRead = { type: 'mapping'; name: string; packageId?: string }; * [#33385] Its refusal of a name only disabled packages hold is marked, * and is admitted as the `/meta` door admits it: when the read naming no * package withholds the name, which then answers not found, naming no - * package. When that read serves an item or refuses, the refusal stands. + * package. [#38753] When that read serves an item or refuses, the + * refusal's judgment answers: refused naming the ENABLED packages that + * read answers with, never the disabled one, or, naming none, admitted. * * Anything else is no address, and is read exactly as before this spelling * existed: the whole string, by name. A mapping name is snake_case, so such a @@ -140,13 +151,18 @@ async function namedMappingRead(p: NamedMappingProtocol, mappingName: string): P } catch (refusal) { if ((refusal as Record | null)?.[DISABLED_HOLDERS_ONLY_REFUSAL] !== true || typeof p.getMetaItem !== 'function') throw refusal; - let withheld: boolean; + let outcome: { readonly answer: unknown } | { readonly error: unknown }; try { - withheld = ((await p.getMetaItem(read)) as { item?: unknown } | undefined)?.item == null; - } catch { - throw refusal; + outcome = { answer: await p.getMetaItem(read) }; + } catch (error) { + outcome = { error }; } - if (!withheld) throw refusal; + if ('answer' in outcome && (outcome.answer as { item?: unknown } | undefined)?.item == null) return read; + // [#38753] Not withheld: the enabled holders that read answers with judge `_env`. + const restate = (refusal as Record)[ENVIRONMENT_READ_REFUSAL]; + if (typeof restate !== 'function') throw refusal; + const restated = (restate as (outcome: unknown) => unknown)(outcome); + if (restated !== undefined) throw restated; } return read; } diff --git a/packages/rest/src/meta-disabled-package-doors.test.ts b/packages/rest/src/meta-disabled-package-doors.test.ts index 1ff50c438bc..f2f02875947 100644 --- a/packages/rest/src/meta-disabled-package-doors.test.ts +++ b/packages/rest/src/meta-disabled-package-doors.test.ts @@ -1107,26 +1107,32 @@ describe('[#34440] RestServer: a package-less row beside a disabled holder\'s ro noTrace([read, layers, published]); }, 60_000); - // [#34440 contract review S2] CONTROL: beside rows bound to ONE package (an - // enabled package's row and a package-less row), with the disabled package - // holding the name only as code, the read is left as it was on `main`: - // every bare door answers 404, with or without an environment item in the - // registry's bare slot. The judgment above is the one beside rows bound to - // two or more packages. (With the guard removed these doors served the - // enabled package's row, a move outside the declared surface.) - it.each(ORDERS)('CONTROL %s: one bound package beside a disabled code holder is left as it was, whatever the bare slot holds', async (_order, packages) => { + // [#34440 contract review S2; #38753 (folded #38771), #32354] Beside rows + // bound to ONE enabled package (its row and a package-less row), with the + // disabled package holding the name only as code, every bare door answers + // as it does without the disabled package: the enabled package's row. + // FROM (`main` 8338d070, the CONTROL "left as it was"): every bare read + // answered 404, in both orders, with or without an environment item in + // the registry's bare slot. The answer is compared with the same fixture + // minus the disabled package's code item, so it can never pass on a 404. + it.each(ORDERS)('%s: one bound package beside a disabled code holder is served on every bare door, as without the disabled package, whatever the bare slot holds', async (_order, packages) => { for (const environmentItem of [false, true]) { - const host = setup(); - for (const pkg of packages) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); - host.registry.registerItem('dashboard', { name: 'pl_s2_dash', label: 'disabled code', widgets: [] } as any, 'name', PKG); - for (const pkg of [OTHER_PKG, null]) await lay(host, 'pl_s2_dash', pkg); - if (environmentItem) host.registry.registerItem('dashboard', { name: 'pl_s2_dash', label: 'package-less row', widgets: [] } as any, 'name'); - host.registry.disablePackage(PKG); - const read = await host.plain('dashboard', 'pl_s2_dash'); - const layers = await host.layers('dashboard', 'pl_s2_dash'); - const published = await host.published('dashboard', 'pl_s2_dash'); - expect([environmentItem, read.status, layers.status, published.status], JSON.stringify([read.body, layers.body, published.body])) - .toEqual([environmentItem, 404, 404, 404]); + const answers = []; + for (const disabledShips of [true, false]) { + const host = setup(); + for (const pkg of packages) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + if (disabledShips) host.registry.registerItem('dashboard', { name: 'pl_s2_dash', label: 'disabled code', widgets: [] } as any, 'name', PKG); + for (const pkg of [OTHER_PKG, null]) await lay(host, 'pl_s2_dash', pkg); + if (environmentItem) host.registry.registerItem('dashboard', { name: 'pl_s2_dash', label: 'package-less row', widgets: [] } as any, 'name'); + host.registry.disablePackage(PKG); + const read = await host.plain('dashboard', 'pl_s2_dash'); + const layers = await host.layers('dashboard', 'pl_s2_dash'); + const published = await host.published('dashboard', 'pl_s2_dash'); + answers.push([read.status, read.body?.item?.label, read.body?.packageId, layers.status, layers.body?.effective?.label, published.status, published.body?.label]); + if (disabledShips) noTrace([read, layers, published]); + } + expect([environmentItem, answers[0]], JSON.stringify(answers)).toEqual([environmentItem, [200, 'healthy row', OTHER_PKG, 200, 'healthy row', 200, 'healthy row']]); + expect([environmentItem, answers[0]]).toEqual([environmentItem, answers[1]]); } }, 60_000); }); @@ -1471,3 +1477,144 @@ describe('[#37915] RestServer: the history naming no package of a name only a di } }, 60_000); }); + +/** + * [#38753 (folded #38769), ADR-0150 D3/D5, #32354] Rows bound to a disabled + * package D and to E, the only ENABLED package that ships the name: the bare + * read serves E and the bare publish save writes E's row, so the bare delete + * and the bare draft discard act at E's address, as without D, and D's rows + * stay byte-unchanged. FROM (`main` 8338d070, measured on this fixture, both + * save orders, D shipping the name in code or not): both refused `409 + * RESOURCE_CONFLICT` naming D and E. The bare draft save still refuses + * naming both: its judgment sits in a file this change does not edit. + */ +describe('[#38753] RestServer: the bare delete and draft discard beside a disabled package\'s rows and the one enabled shipper', () => { + const lay = (host: ReturnType, pkg: string, label: string, state: 'active' | 'draft') => (host.protocol as any).engine.insert('sys_metadata', { + type: 'dashboard', name: 'one_shipper_dash', package_id: pkg, state, scope: 'platform', strategy: 'merge', version: 1, + metadata: JSON.stringify({ name: 'one_shipper_dash', label, widgets: [] }), + }); + const rowsOf = async (host: ReturnType) => ((await (host.protocol as any).engine.find('sys_metadata', { where: { type: 'dashboard', name: 'one_shipper_dash' } })) as any[]) + .map((row) => `${row.state}:${row.package_id}:${row.metadata}`).sort(); + const boot = async (order: readonly string[], withD: boolean, disabledShips: boolean) => { + const host = setup(); + for (const pkg of [PKG, OTHER_PKG]) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + host.registry.registerItem('dashboard', { name: 'one_shipper_dash', label: 'healthy code', widgets: [] } as any, 'name', OTHER_PKG); + if (withD && disabledShips) host.registry.registerItem('dashboard', { name: 'one_shipper_dash', label: 'disabled code', widgets: [] } as any, 'name', PKG); + for (const state of ['active', 'draft'] as const) { + for (const pkg of order) if (withD || pkg !== PKG) await lay(host, pkg, `${pkg === PKG ? 'disabled' : 'healthy'} ${state}`, state); + } + host.registry.disablePackage(PKG); + return host; + }; + const CELLS = (['disabled saved first', 'enabled saved first'] as const).flatMap((order) => [false, true].map((disabledShips) => + [`${order}, D ${disabledShips ? 'ships the name in code' : 'holds rows only'}`, order === 'disabled saved first' ? [PKG, OTHER_PKG] : [OTHER_PKG, PKG], disabledShips] as const)); + + it.each(CELLS)('%s: the bare delete and the bare draft discard remove E\'s row and draft, as without D, and D\'s rows stay', async (_label, order, disabledShips) => { + const effects: Array<{ deleted: string[]; discarded: string[] }> = []; + for (const withD of [true, false]) { + const host = await boot(order, withD, disabledShips); + const read = await host.plain('dashboard', 'one_shipper_dash'); + expect([withD, read.status, read.body?.item?.label], JSON.stringify(read.body)).toEqual([withD, 200, 'healthy active']); + const before = await rowsOf(host); + const discarded = await (host.protocol as any).deleteMetaItem({ type: 'dashboard', name: 'one_shipper_dash', state: 'draft' }); + expect([withD, discarded?.success, String(discarded?.message)], JSON.stringify(discarded)).toEqual([withD, true, expect.stringContaining(`package=${OTHER_PKG}`)]); + const afterDiscard = await rowsOf(host); + const deleted = await (host.protocol as any).deleteMetaItem({ type: 'dashboard', name: 'one_shipper_dash' }); + expect([withD, deleted?.success, String(deleted?.message)], JSON.stringify(deleted)).toEqual([withD, true, expect.stringContaining(`package=${OTHER_PKG}`)]); + const afterDelete = await rowsOf(host); + effects.push({ + discarded: before.filter((row) => !afterDiscard.includes(row)), + deleted: afterDiscard.filter((row) => !afterDelete.includes(row)), + }); + // D's rows, both states, byte-unchanged. + expect(afterDelete.filter((row) => row.includes(`:${PKG}:`)), 'D\'s rows').toEqual(before.filter((row) => row.includes(`:${PKG}:`))); + } + expect(effects[0], JSON.stringify(effects)).toEqual(effects[1]); + expect(effects[0].discarded.map((row) => row.split(':').slice(0, 2).join(':'))).toEqual([`draft:${OTHER_PKG}`]); + expect(effects[0].deleted.map((row) => row.split(':').slice(0, 2).join(':'))).toEqual([`active:${OTHER_PKG}`]); + }, 60_000); + + it('CONTROL — a second enabled shipper: the bare delete and draft discard still refuse 409 naming the two enabled shippers, never D, and nothing is removed', async () => { + const THIRD_PKG = 'app.third_demo'; + const host = await boot([PKG, OTHER_PKG], true, true); + host.registry.installPackage({ id: THIRD_PKG, name: THIRD_PKG, version: '1.0.0' } as any, 'code'); + host.registry.registerItem('dashboard', { name: 'one_shipper_dash', label: 'third code', widgets: [] } as any, 'name', THIRD_PKG); + const before = await rowsOf(host); + for (const state of [undefined, 'draft'] as const) { + let refusal: any; + try { await (host.protocol as any).deleteMetaItem({ type: 'dashboard', name: 'one_shipper_dash', ...(state ? { state } : {}) }); } catch (error) { refusal = error; } + expect([state, refusal?.code, refusal?.status ?? refusal?.httpStatus], String(refusal?.message)).toEqual([state, 'RESOURCE_CONFLICT', 409]); + for (const pkg of [OTHER_PKG, THIRD_PKG]) expect(String(refusal?.message)).toContain(pkg); + expect(String(refusal?.message)).not.toContain(PKG); + } + expect(await rowsOf(host)).toEqual(before); + }, 60_000); + + /** + * [#38753 (folded delete-receipt finding), ADR-0150 D3, #32354] The + * receipts of those writes say what the read naming no package serves + * once they land, so a disabled package's row is no remaining overlay and + * is never named: each receipt reads as it reads without D (its `[seq=N]` + * aside), the delete naming E and the no-op repeats included. FROM (`main` + * 645e6b15 with the re-address above): the delete answered "still carries + * another overlay: its row bound to package 'D' remains", and the repeats + * "so nothing was deleted (discarded): its row (draft) bound to package + * 'D' remains". + */ + const receiptsOf = async (host: ReturnType, packageId: string | undefined): Promise => { + const named = packageId === undefined ? {} : { packageId }; + const receipts: string[] = []; + for (const request of [{ state: 'draft' }, {}, { state: 'draft' }, {}]) { + const answer = await (host.protocol as any).deleteMetaItem({ type: 'dashboard', name: 'one_shipper_dash', ...named, ...request }); + receipts.push(`${answer?.success}:${answer?.reset}:${String(answer?.message).replace(/ \[seq=\d+\]$/, '')}`); + } + return receipts; + }; + it.each(CELLS)('%s: the delete and discard receipts, bare and naming E, read as without D and never name D', async (_label, order, disabledShips) => { + for (const packageId of [undefined, OTHER_PKG]) { + const answers: string[][] = []; + for (const withD of [true, false]) answers.push(await receiptsOf(await boot(order, withD, disabledShips), packageId)); + expect([packageId, answers[0]], JSON.stringify(answers)).toEqual([packageId, answers[1]]); + expect(answers[0].join('\n')).not.toContain(PKG); + expect(answers[0][1], 'the delete removed E\'s row').toContain(`package=${OTHER_PKG}`); + } + }, 60_000); +}); + +/** + * [#38753 (folded delete-receipt finding), ADR-0150 D2/D3, #32354] One + * enabled package E's row (beside a package-less row or not) of a name a + * DISABLED package ships in code only: the delete of E's row, bare or naming + * E, says what is left as it says without the disabled package's code item. + * A disabled package's code is no artifact default a delete resets to, and + * its row is no remaining overlay. FROM (`main` 645e6b15): "Customization + * overlay deleted (package=E) — reset to artifact default" (or "still carries + * another overlay"), where without the disabled code the same delete answers + * "it no longer exists" (or "and it still exists"). + */ +describe('[#38753] RestServer: the delete receipt beside a disabled package that ships the name in code only', () => { + const lay = (host: ReturnType, pkg: string | null) => (host.protocol as any).engine.insert('sys_metadata', { + type: 'dashboard', name: 'code_only_dash', package_id: pkg, state: 'active', scope: 'platform', strategy: 'merge', version: 1, + metadata: JSON.stringify({ name: 'code_only_dash', label: pkg === null ? 'package-less row' : 'healthy row', widgets: [] }), + }); + const receiptOf = async (packagelessRow: boolean, disabledShips: boolean, packageId: string | undefined): Promise => { + const host = setup(); + for (const pkg of [PKG, OTHER_PKG]) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + if (disabledShips) host.registry.registerItem('dashboard', { name: 'code_only_dash', label: 'disabled code', widgets: [] } as any, 'name', PKG); + await lay(host, OTHER_PKG); + if (packagelessRow) await lay(host, null); + host.registry.disablePackage(PKG); + const answer = await (host.protocol as any).deleteMetaItem({ type: 'dashboard', name: 'code_only_dash', ...(packageId === undefined ? {} : { packageId }) }) + .catch((error: any) => ({ refused: `${error?.code}:${error?.message}` })); + return answer?.refused ?? `${answer?.success}:${answer?.reset}:${String(answer?.message).replace(/ \[seq=\d+\]$/, '')}`; + }; + it.each([[false], [true]] as const)('package-less row %s: the delete of E\'s row reads as without the disabled code item', async (packagelessRow) => { + for (const packageId of [undefined, OTHER_PKG]) { + const withD = await receiptOf(packagelessRow, true, packageId); + const withoutD = await receiptOf(packagelessRow, false, packageId); + expect([packageId, withD]).toEqual([packageId, withoutD]); + expect(withD).toContain(`package=${OTHER_PKG}`); + expect(withD).not.toContain('artifact default'); + } + }, 60_000); +}); diff --git a/packages/rest/src/meta-qualified-item-route.test.ts b/packages/rest/src/meta-qualified-item-route.test.ts index 09e2efe176a..c3a7c2a2a23 100644 --- a/packages/rest/src/meta-qualified-item-route.test.ts +++ b/packages/rest/src/meta-qualified-item-route.test.ts @@ -416,10 +416,13 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t refusedNaming(await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }), [B], [A]); }); - // [#33385] CONTROL — an enabled package holding the name only through a - // stored row the registry has not read: `_env` keeps `main`'s 409, as - // its refusal stands whenever the read naming no package serves an item. - it(`${type}: only a disabled holder in the registry, and an enabled package's unhydrated stored row — \`_env\` refuses 409, as on main, never that row`, async () => { + // [#33385] An enabled package holding the name only through a stored + // row the registry has not read: `_env` is refused 409, never serving + // that row. [#38753, #32354] FROM (`main` 8338d070) the refusal named + // the disabled registry holder B (`candidates: [B]`, the #33385 S4 + // CONTROL) TO naming the enabled package whose row the read naming no + // package serves, C: a disabled package holds no name and is never named. + it(`${type}: only a disabled holder in the registry, and an enabled package's unhydrated stored row — \`_env\` refuses 409 naming that package, never the disabled one, never that row`, async () => { ship(type, 'solo', B); storedRows.push({ id: 'row_gamma', type, name: 'solo', state: 'active', package_id: C, metadata: JSON.stringify({ name: 'solo', label: `gamma row ${type}` }) }); @@ -434,7 +437,8 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t expect(labelOf(bare) === `gamma row ${type}`, JSON.stringify(bare.body)).toBe(ROW_SERVED_TYPES.includes(type)); if (ROW_SERVED_TYPES.includes(type)) { expect([env.status, codeOf(env)], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT']); - expect(env.body?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: B }]); + expect(env.body?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: C }]); + expect(JSON.stringify(env.body), 'the disabled holder is named nowhere').not.toContain(B); } else { expect([bare.status, env.status], JSON.stringify([bare.body, env.body])).toEqual([404, 404]); } @@ -495,10 +499,14 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t const bare = await drive(ITEM, { type, name: 'solo' }, query); expect([bare.status, labelOf(bare), query], JSON.stringify(bare.body)).toEqual([200, `gamma draft ${type}`, query]); } + // [#38753, #32354] FROM naming the disabled registry holder B TO + // naming C, the enabled package whose draft the draft read serves. for (const query of [{ state: 'draft' }, { preview: 'draft' }]) { const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query); expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]); + expect([env.body?.details?.candidates, query], JSON.stringify(env.body)).toEqual([[{ kind: 'package', packageId: C }], query]); expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma draft ${type}`); + expect(JSON.stringify(env.body ?? null)).not.toContain(B); } for (const [path, params] of [[ITEM, { type, name: 'solo' }], [QUALIFIED, { type, ns: '_env', name: 'solo' }]] as const) { const layered = await drive(path, params, { layers: 'true' }); @@ -512,7 +520,10 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, { layers: 'true' }); expect([env.status, codeOf(env)], JSON.stringify(env.body)) .toEqual(ROW_SERVED_TYPES.includes(type) ? [409, 'RESOURCE_CONFLICT'] : [404, 'RESOURCE_NOT_FOUND']); + // [#38753] …naming C, whose row the plain read serves, never the disabled B. + if (ROW_SERVED_TYPES.includes(type)) expect(env.body?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: C }]); expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma row ${type}`); + expect(JSON.stringify(env.body ?? null)).not.toContain(B); // CONTROL — an enabled registry holder's own draft is still served to // an admitted builder at the bare read, and `_env` refuses naming it. ship(type, 'own', A); diff --git a/packages/rest/src/meta-qualified-item-route.ts b/packages/rest/src/meta-qualified-item-route.ts index 7f4dd725057..13679c1f2a8 100644 --- a/packages/rest/src/meta-qualified-item-route.ts +++ b/packages/rest/src/meta-qualified-item-route.ts @@ -16,7 +16,9 @@ * - `_env`: the environment's own item, or `409` naming every served * holder (`admitEnvironmentQualifier`), read as a caller with no package; * a name only disabled packages hold answers that read's `404` (#33385), - * its draft and layered reads included (#34261). + * its draft and layered reads included (#34261), and beside an enabled + * package's stored row it is refused naming that package, never the + * disabled one (#38753). * * D5's order, as the runtime dispatcher's `/meta` domain reads the same path: * a sub-resource literal in the last position keeps its route — registered @@ -73,6 +75,18 @@ interface QualifiedAddressProtocol { */ const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal'); +/** + * [#38753, #32354] The `Symbol.for` key of the judgment that marked refusal + * carries (`ENVIRONMENT_READ_REFUSAL` in `@objectstack/metadata-protocol`): + * handed what the read naming no package answered, it returns `_env`'s + * refusal naming the ENABLED packages that read answers with, or nothing, + * when `_env` is admitted. The runtime dispatcher reads the same key. + */ +const ENVIRONMENT_READ_REFUSAL = Symbol.for('objectstack.metadata-protocol.environmentReadRefusal'); + +/** What the read naming no package answered: its answer, or what it threw. */ +type EnvironmentReadOutcome = { readonly answer: unknown } | { readonly error: unknown }; + /** * [#34261] The switches of the read the item read answers this caller, beyond * the plain read: an admitted draft switch (`?state=draft` is `state`, @@ -91,8 +105,12 @@ interface EnvironmentReadSwitches { * marked {@link DISABLED_HOLDERS_ONLY_REFUSAL} is admitted when the read * naming no package withholds the name: a disabled package holds no name, * so `_env` answers the read's own 404, naming no package. When that read - * serves an item or refuses, a package holds the name through a stored row - * the registry has not read, and the refusal stands. + * serves an item or refuses, [#38753, #32354] the refusal's + * {@link ENVIRONMENT_READ_REFUSAL} judgment answers: `409` naming the + * ENABLED packages that read answers with (a package holding the name + * through a stored row the registry has not read), never the disabled one, + * or, naming none, `_env` admitted, answering as that read does. FROM + * (`main` 8338d070): the refusal stood, naming the disabled package. * * [#34261, ADR-0150 2026-11-26 note] The read judged is the one the caller is * answered. An admitted draft read (`?state=draft`, `?preview=draft`) is @@ -113,19 +131,31 @@ async function admitEnvironmentAddress( if ((refusal as Record | null)?.[DISABLED_HOLDERS_ONLY_REFUSAL] !== true || typeof p.getMetaItem !== 'function') throw refusal; const getMetaItem = p.getMetaItem.bind(p); - const withholds = async (switches: EnvironmentReadSwitches): Promise => { + const read = async (switches: EnvironmentReadSwitches): Promise => { try { - return (await getMetaItem({ ...request, ...switches }))?.item == null; + return { answer: await getMetaItem({ ...request, ...switches }) }; } catch (error) { - // The strict draft read's absence is its `404 NO_DRAFT` (no - // other read throws it); any other failure is no withheld name. - if ((error as { code?: unknown } | null)?.code === 'NO_DRAFT') return true; - return false; + return { error }; } }; - if (!(await withholds({}))) throw refusal; + // The strict draft read's absence is its `404 NO_DRAFT` (no other read + // throws it); any other failure is no withheld name. + const withheld = (outcome: EnvironmentReadOutcome): boolean => ('error' in outcome + ? (outcome.error as { code?: unknown } | null)?.code === 'NO_DRAFT' + : (outcome.answer as { item?: unknown } | undefined)?.item == null); + // [#38753] Not withheld: the enabled holders that read answers with judge `_env`. + const judge = (outcome: EnvironmentReadOutcome): void => { + const restate = (refusal as Record)[ENVIRONMENT_READ_REFUSAL]; + if (typeof restate !== 'function') throw refusal; + const restated = (restate as (outcome: EnvironmentReadOutcome) => unknown)(outcome); + if (restated !== undefined) throw restated; + }; + const plain = await read({}); + if (!withheld(plain)) return judge(plain); const switches = await answeredRead(); - if (Object.keys(switches).length > 0 && !(await withholds(switches))) throw refusal; + if (Object.keys(switches).length === 0) return; + const answered = await read(switches); + if (!withheld(answered)) judge(answered); } } diff --git a/packages/runtime/src/domains/meta-qualified-item-read.test.ts b/packages/runtime/src/domains/meta-qualified-item-read.test.ts index 9125eb5ff4c..9aae678249e 100644 --- a/packages/runtime/src/domains/meta-qualified-item-read.test.ts +++ b/packages/runtime/src/domains/meta-qualified-item-read.test.ts @@ -466,10 +466,13 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t refusedNaming(await read(`/${type}/_env/solo`), [B], [A]); }); - // [#33385] CONTROL — an enabled package holding the name only through a - // stored row the registry has not read: `_env` keeps `main`'s 409, as - // its refusal stands whenever the read naming no package serves an item. - it(`${type}: only a disabled holder in the registry, and an enabled package's unhydrated stored row — \`_env\` refuses 409, as on main, never that row`, async () => { + // [#33385] An enabled package holding the name only through a stored + // row the registry has not read: `_env` is refused 409, never serving + // that row. [#38753, #32354] FROM (`main` 8338d070) the refusal named + // the disabled registry holder B (`candidates: [B]`) TO naming the + // enabled package whose row the read naming no package serves, C, as + // `RestServer` pins: a disabled package holds no name and is never named. + it(`${type}: only a disabled holder in the registry, and an enabled package's unhydrated stored row — \`_env\` refuses 409 naming that package, never the disabled one, never that row`, async () => { ship(type, 'solo', B); storedRows.push({ id: 'row_gamma', type, name: 'solo', state: 'active', package_id: C, metadata: JSON.stringify({ name: 'solo', label: `gamma row ${type}` }) }); @@ -484,7 +487,8 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t expect(labelOf(bare) === `gamma row ${type}`, JSON.stringify(bare.body)).toBe(ROW_SERVED_TYPES.includes(type)); if (ROW_SERVED_TYPES.includes(type)) { expect([env.status, env.body?.error?.code], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT']); - expect(env.body?.error?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: B }]); + expect(env.body?.error?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: C }]); + expect(JSON.stringify(env.body), 'the disabled holder is named nowhere').not.toContain(B); } else { expect([bare.status, env.status], JSON.stringify([bare.body, env.body])).toEqual([404, 404]); } @@ -544,10 +548,14 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t const bare = await read(`/${type}/solo`, query); expect([bare.status, labelOf(bare), query], JSON.stringify(bare.body)).toEqual([200, `gamma draft ${type}`, query]); } + // [#38753, #32354] FROM naming the disabled registry holder B TO + // naming C, the enabled package whose draft the draft read serves. for (const query of [{ state: 'draft' }, { preview: 'draft' }]) { const env = await read(`/${type}/_env/solo`, query); expect([env.status, env.body?.error?.code, query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]); + expect([env.body?.error?.details?.candidates, query], JSON.stringify(env.body)).toEqual([[{ kind: 'package', packageId: C }], query]); expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma draft ${type}`); + expect(JSON.stringify(env.body ?? null)).not.toContain(B); } for (const path of [`/${type}/solo`, `/${type}/_env/solo`]) { const layered = await read(path, { layers: 'true' }); @@ -561,7 +569,10 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t const env = await read(`/${type}/_env/solo`, { layers: 'true' }); expect([env.status, env.body?.error?.code], JSON.stringify(env.body)) .toEqual(ROW_SERVED_TYPES.includes(type) ? [409, 'RESOURCE_CONFLICT'] : [404, 'RESOURCE_NOT_FOUND']); + // [#38753] …naming C, whose row the plain read serves, never the disabled B. + if (ROW_SERVED_TYPES.includes(type)) expect(env.body?.error?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: C }]); expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma row ${type}`); + expect(JSON.stringify(env.body ?? null)).not.toContain(B); // CONTROL — an enabled registry holder's own draft is still served to // an admitted builder at the bare read, and `_env` refuses naming it. ship(type, 'own', A); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 41db7c07026..42f56f2bb08 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1189,6 +1189,18 @@ function queryRefusalAnswer( */ const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal'); +/** + * [#38753, #32354] The `Symbol.for` key of the judgment that marked refusal + * carries (`ENVIRONMENT_READ_REFUSAL` in `@objectstack/metadata-protocol`): + * handed what the read naming no package answered, it returns `_env`'s + * refusal naming the ENABLED packages that read answers with, or nothing, + * when `_env` is admitted. `RestServer`'s qualified route reads the same key. + */ +const ENVIRONMENT_READ_REFUSAL = Symbol.for('objectstack.metadata-protocol.environmentReadRefusal'); + +/** What the read naming no package answered: its answer, or what it threw. */ +type EnvironmentReadOutcome = { readonly answer: unknown } | { readonly error: unknown }; + /** * [#34261] The switches of the read the item read answers the caller, beyond * the plain read: an ADMITTED draft switch (`?state=draft` is `state`, @@ -1208,8 +1220,12 @@ interface EnvironmentReadSwitches { * marked {@link DISABLED_HOLDERS_ONLY_REFUSAL} is admitted when the read naming * no package withholds the name: a disabled package holds no name, so `_env` * answers the read's own 404, naming no package. When that read serves an - * item or refuses, a package holds the name through a stored row the - * registry has not read, and the refusal stands. + * item or refuses, [#38753, #32354] the refusal's + * {@link ENVIRONMENT_READ_REFUSAL} judgment answers: refused naming the + * ENABLED packages that read answers with (a package holding the name + * through a stored row the registry has not read), never the disabled one, + * or, naming none, `_env` admitted, answering as that read does. FROM + * (`main` 8338d070): the refusal stood, naming the disabled package. * * [#34261, ADR-0150 2026-11-26 note] The read judged is the one the caller is * answered (`switches`). An admitted draft read is admitted when the plain @@ -1232,18 +1248,30 @@ async function admitEnvironmentAddress( if ((refusal as Record | null)?.[DISABLED_HOLDERS_ONLY_REFUSAL] !== true || typeof protocol?.getMetaItem !== 'function') throw refusal; const getMetaItem = protocol.getMetaItem.bind(protocol); - const withholds = async (read: EnvironmentReadSwitches): Promise => { + const read = async (asked: EnvironmentReadSwitches): Promise => { try { - return ((await getMetaItem({ ...request, ...read } as never)) as { item?: unknown } | undefined)?.item == null; + return { answer: await getMetaItem({ ...request, ...asked } as never) }; } catch (error) { - // The strict draft read's absence is its `404 NO_DRAFT` (no - // other read throws it); any other failure is no withheld name. - if ((error as { code?: unknown } | null)?.code === 'NO_DRAFT') return true; - return false; + return { error }; } }; - if (!(await withholds({}))) throw refusal; - if (Object.keys(switches).length > 0 && !(await withholds(switches))) throw refusal; + // The strict draft read's absence is its `404 NO_DRAFT` (no other read + // throws it); any other failure is no withheld name. + const withheld = (outcome: EnvironmentReadOutcome): boolean => ('error' in outcome + ? (outcome.error as { code?: unknown } | null)?.code === 'NO_DRAFT' + : (outcome.answer as { item?: unknown } | undefined)?.item == null); + // [#38753] Not withheld: the enabled holders that read answers with judge `_env`. + const judge = (outcome: EnvironmentReadOutcome): void => { + const restate = (refusal as Record)[ENVIRONMENT_READ_REFUSAL]; + if (typeof restate !== 'function') throw refusal; + const restated = (restate as (outcome: EnvironmentReadOutcome) => unknown)(outcome); + if (restated !== undefined) throw restated; + }; + const plain = await read({}); + if (!withheld(plain)) return judge(plain); + if (Object.keys(switches).length === 0) return; + const answered = await read(switches); + if (!withheld(answered)) judge(answered); } }