From 10c5154f31b935862d59e562339cdaee18a4fecc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:19:48 +0000 Subject: [PATCH 01/14] fix(metadata-protocol): history and rollback doors address one holder of a by-package name WIP: the /meta history and rollback doors take ?package=, a bare request of a name two row slots hold is refused naming both, and the repository records whose row each history snapshot is of. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../objects/sys-metadata-history.object.ts | 11 +- .../src/protocol-door-requests.ts | 9 ++ .../src/protocol-history-and-publish.ts | 20 ++- .../src/protocol-history-slots.ts | 133 ++++++++++++++++++ .../src/protocol-package-commits.ts | 46 ++++-- packages/metadata-protocol/src/protocol.ts | 20 ++- .../src/sys-metadata-repository.ts | 79 ++++++++++- packages/metadata/src/index.ts | 8 +- .../metadata/src/loaders/database-loader.ts | 9 +- packages/rest/src/meta-item-history-routes.ts | 22 ++- packages/rest/src/rest-server.ts | 9 +- packages/spec/src/api/protocol.zod.ts | 7 + 12 files changed, 339 insertions(+), 34 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-history-slots.ts diff --git a/packages/metadata-core/src/objects/sys-metadata-history.object.ts b/packages/metadata-core/src/objects/sys-metadata-history.object.ts index 55b41a4994f..7efd6378238 100644 --- a/packages/metadata-core/src/objects/sys-metadata-history.object.ts +++ b/packages/metadata-core/src/objects/sys-metadata-history.object.ts @@ -102,10 +102,13 @@ export const SysMetadataHistoryObject = ObjectSchema.create({ * type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`, * `@objectstack/metadata`): its versions are numbered per name across the * packages' rows, so this column, not the version, says whose version it is. - * NULL for every other type, for a package-less row, for a row written - * before the column existed (its package is then the one its stored body - * names, as for a `sys_metadata` row), and for every row - * `SysMetadataRepository` writes. Nullable: adding it rewrites no row. + * NULL for every other type, and for a row written before the column + * existed (its package is then the one its stored body names, as for a + * `sys_metadata` row); a package-less row's snapshot carries the + * `sys_metadata` mark. [#32905] `SysMetadataRepository` (the `/meta` + * doors) records it as `DatabaseLoader` does, so the `/meta` history and + * rollback doors read whose version a row is; the rows it wrote before + * that carry NULL. Nullable: adding it rewrites no row. */ package_id: Field.text({ label: 'Package ID', diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 984378c69f7..6141d373dde 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -101,6 +101,15 @@ type RollbackMetaItemRequest = { * a version of ANOTHER member answers 404 `VERSION_NOT_FOUND`. */ member?: string; + /** + * [ADR-0150 D3/D4, #32905] The package whose row this rollback restores, + * as the `/layers` read names its package (`?package=` on the REST door). + * Read for a type stored per `(package, name)` only: its own row, or its + * `.custom` pair's declared override; the version must be that + * holder's. Absent, a name two row slots hold is refused `409` naming + * every holder, before anything is written. + */ + packageId?: string; }; /** The request of {@link ObjectStackProtocolImplementation.deleteMetaItem}. */ diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 86da5bb5234..e882e05f050 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -62,6 +62,8 @@ import { PROMOTION_REGISTRY_QUESTION, type RegistryQuestion } from './registry-q import { isBatchObjectType, judgeBatchObjectRegistrations, registerAdmittedBatchRows, type BatchObjectRow } from './batch-object-registration.js'; import { engineCanRollBack } from '@objectstack/core'; import type { SysMetadataRepository } from './sys-metadata-repository.js'; +import type { HistoryVersionOwner } from './sys-metadata-repository.js'; +import { historySlotOf } from './protocol-history-slots.js'; import { captureStoredExpressionChange, fillStoredExpressionChange, type StoredExpressionFillCapture } from './protocol-stored-expression-fill.js'; /** @@ -192,13 +194,15 @@ async function undoLandedPromotions(host: Pick, request: { + static async historyMetaItem(host: Pick, request: { type: string; name: string; sinceSeq?: number; limit?: number; /** [#22877] The bundle member whose lineage to read — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string; + /** [ADR-0150 D3/D4, #32905] The package whose versions to read — {@link historySlotOf}; omitted, the name's. */ + packageId?: string; }): Promise<{ events: import('@objectstack/metadata-core').MetadataEvent[] }> { // [#9157] #4432 / #7894 — CANONICAL TYPE KEY. See {@link canonicalMetaType} // and the twin comment on {@link auditMetaItem}; #9180 step ① routes all @@ -257,6 +261,15 @@ export class ProtocolHistoryAndPublishFacet { if (expandedFrom !== undefined) { return host.historyMetaItem({ ...request, name: expandedFrom.container.name }); } + // [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, + // the name's log interleaves every holder's versions: a name two + // holders' rows hold is refused naming both when no package is named, + // and `?package=` reads that holder's versions alone. A name one slot + // holds, named bare, reads its whole log as before. + const slot = await historySlotOf(host, { + type: singularType, name: request.name, ...memberOption(member), + ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + }); // [ADR-0131 D6] The environment's change log; a legacy // organization-scoped history row is not read. const repo = host.getOverlayRepo(); @@ -267,7 +280,10 @@ export class ProtocolHistoryAndPublishFacet { } as Parameters[0]; const events: import('@objectstack/metadata-core').MetadataEvent[] = []; - const opts: { sinceSeq?: number; limit?: number; member?: string } = { ...memberOption(member) }; + const opts: { sinceSeq?: number; limit?: number; member?: string; versionsOf?: HistoryVersionOwner } = { + ...memberOption(member), + ...(slot?.addressed ? { versionsOf: slot.owner } : {}), + }; if (request.sinceSeq !== undefined) opts.sinceSeq = request.sinceSeq; if (request.limit !== undefined) opts.limit = request.limit; // [#21207] Each event's hash and parent hash are served in keyed form — diff --git a/packages/metadata-protocol/src/protocol-history-slots.ts b/packages/metadata-protocol/src/protocol-history-slots.ts new file mode 100644 index 00000000000..1f53552e35c --- /dev/null +++ b/packages/metadata-protocol/src/protocol-history-slots.ts @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # Whose versions the history and rollback doors address (ADR-0150 D3/D4) + * + * A type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`) keeps + * one `sys_metadata` row per package for a name, and its versions are + * numbered per name across those rows (`sys_metadata_history`'s unique + * `(type, name, version)`). So the name's change log interleaves every + * holder's versions, and a version number alone does not say whose row it may + * be restored into. `historyMetaItem` and `rollbackMetaItem` ask this module + * which row slot they address, by the rule `DatabaseLoader` keeps for the + * metadata service's own history doors (`MetadataManager.getHistory`, + * `rollback`): + * + * - **naming no package** (the bare door): a name whose active rows are held + * by more than one row slot — two packages', or a package's beside the + * package-less row — is refused `409` naming every holder + * (`ambiguous-in-environment`), before any row is read or written: nothing + * picks one (ADR-0150 D3, epic red line 2). A name one slot holds, or none, + * answers as before; + * - **naming package `P`** (`?package=P`, the `/layers?package=` spelling): + * the slot of the row a read naming `P` serves — `P`'s own row, or its + * `.custom` pair's declared override of `P` (ADR-0146 D2) — else `P`'s own + * slot when `P` ships the name in code and holds no row of it yet. A + * package that neither holds a row of the name nor ships it is refused + * `409` naming every holder (`not-held-by-qualifier`). + * + * A version belongs to a slot by its history row's attribution + * (`historyRowAttribution`, `@objectstack/metadata`). A version attributed to + * no package (recorded before `sys_metadata_history.package_id` was written + * for this store) belongs to a slot only while the name has no other slot: + * with two holders nothing says whose it is, so it is never guessed. + * + * Every other type is not addressed here, and `?package=` leaves its doors' + * answers as they were (as `admitEnvironmentQualifier` keeps the bare read for + * the types ADR-0150 does not address). + */ + +import { + PackageScopedNameRefusedError, + packageScopedRefusalMessage, + type PackageScopedHolder, + type PackageScopedRefusal, + type PackageScopedResolvableType, +} from '@objectstack/core'; +import { PACKAGE_SLOTTED_STORE_TYPES } from '@objectstack/metadata'; +import type { ProtocolHost } from './protocol-host.js'; +import { memberOption } from './protocol-bundle-members.js'; +import { shippingPackageIds } from './protocol-environment-rows.js'; +import type { HistoryVersionOwner } from './sys-metadata-repository.js'; + +/** What {@link historySlotOf} answers for a door of a by-package type. */ +export interface HistorySlot { + /** The slot the door addresses, and which of the name's versions are its own. */ + readonly owner: HistoryVersionOwner; + /** Whether the request named the package (`?package=`). */ + readonly addressed: boolean; +} + +/** The name's row slots: each bound package, sorted, then the package-less row (`null`). */ +async function rowSlotsOf( + host: Pick, + type: string, + name: string, + member: string | undefined, +): Promise> { + const address = await host.packagelessAddress(type, name, member); + return [...address.candidates, ...(address.unbound ? [null] : [])]; +} + +function holdersOf(slots: ReadonlyArray): PackageScopedHolder[] { + return slots.map((slot) => (slot === null + ? { kind: 'environment' as const } + : { kind: 'package' as const, packageId: slot })); +} + +function slotRefusal( + type: string, + name: string, + reason: 'ambiguous-in-environment' | 'not-held-by-qualifier', + callerPackageId: string | null, + slots: ReadonlyArray, +): PackageScopedNameRefusedError { + const base: Omit = { + status: 'refused', + reason, + type: type as PackageScopedResolvableType, + name, + callerPackageId, + candidates: holdersOf(slots), + }; + return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); +} + +/** + * The row slot a history or rollback request of `(type, name)` addresses — + * see the module header. `type` is the canonical type key and `member` the + * resolved bundle member. + * + * @returns `undefined` for a type not stored per `(package, name)`, and for a + * bare request of a name no row holds: the door answers as before. + * @throws {PackageScopedNameRefusedError} `ambiguous-in-environment` for a + * bare request of a name two or more row slots hold; `not-held-by-qualifier` + * for a package that neither holds a row of the name nor ships it, while + * another slot holds one. + */ +export async function historySlotOf( + host: Pick, + request: { type: string; name: string; member?: string; packageId?: string }, +): Promise { + const { type, name, member, packageId } = request; + if (!PACKAGE_SLOTTED_STORE_TYPES.has(type)) return undefined; + const slots = await rowSlotsOf(host, type, name, member); + if (packageId === undefined) { + if (slots.length > 1) throw slotRefusal(type, name, 'ambiguous-in-environment', null, slots); + if (slots.length === 0) return undefined; + return { owner: { packageId: slots[0] ?? null, unattributed: true }, addressed: false }; + } + // The row a read naming `P` serves: its own, or its pair's declared + // override. The package-less fallback of that read is not `P`'s slot. + const served = await host.findServedOverlayRow({ + type, name, state: 'active', packageId, ...memberOption(member), servedOverride: true, + }); + const binding = (served?.row as { package_id?: unknown } | undefined)?.package_id; + const slot = typeof binding === 'string' && binding !== '' ? binding : packageId; + if (!slots.includes(slot) && slots.length > 0 + && !shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member)).has(packageId)) { + throw slotRefusal(type, name, 'not-held-by-qualifier', packageId, slots); + } + const sole = slots.length === 0 || (slots.length === 1 && slots[0] === slot); + return { owner: { packageId: slot, unattributed: sole }, addressed: true }; +} diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 4f904e0ece2..98a7320a198 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -89,6 +89,7 @@ import { } from './protocol-client-failures.js'; import { isNonCanonicalStoredType } from './protocol-stored-overlay-types.js'; import type { RollbackMetaItemRequest } from './protocol-door-requests.js'; +import { historySlotOf } from './protocol-history-slots.js'; import { withRefusalAudit } from './protocol-refusal-audit.js'; import type { ProtocolHost } from './protocol-host.js'; import type { ImportUnmanagedPackageAnswer, InstallPackageStoredRowHook, StoredPackageRow } from './protocol-package-install.js'; @@ -1876,7 +1877,7 @@ export class ProtocolPackageCommitsFacet { } /** [#28355] The body of {@link rollbackMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ + static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ success: boolean; version: string; seq: number; @@ -1962,6 +1963,17 @@ export class ProtocolPackageCommitsFacet { err.status = 403; throw err; } + // [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, + // the row slot this rollback writes ({@link historySlotOf}): a name + // two holders' rows hold is refused naming both when no package is + // named, before anything is read or written; `?package=` names the + // holder whose row is restored. The version must be that slot's + // (`versionOf` below): ⛔ never another holder's version written into + // this holder's row. + const slot = await historySlotOf(host, { + type: singularType, name: request.name, ...memberOption(member), + ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + }); // ADR-0010 L3 — lock blocks rollback (writes a new active row). // `request.type` is the CANONICAL spelling by the time it gets here // (fold above), which is what makes this gate read the same row the @@ -2009,18 +2021,24 @@ export class ProtocolPackageCommitsFacet { // refused it, naming a row the caller never meant. No row served (a // row only another package binds under the name): that row's binding, // as before. - const servedPackage = await host.packagelessReadAddress(singularType, request.name, member); - const served = await host.findServedOverlayRow({ - type: singularType, - name: request.name, - state: 'active', - ...(servedPackage !== undefined ? { packageId: servedPackage } : {}), - ...memberOption(member), - servedOverride: true, - }); - const rollbackPackageId = served !== undefined - ? ((served.row as { package_id?: string | null } | null)?.package_id ?? null) - : await host.resolveOverlayPackageBinding(singularType, request.name, member); + // [#32905] Named by the request, the slot {@link historySlotOf} resolved. + let rollbackPackageId: string | null; + if (slot?.addressed) { + rollbackPackageId = slot.owner.packageId; + } else { + const servedPackage = await host.packagelessReadAddress(singularType, request.name, member); + const served = await host.findServedOverlayRow({ + type: singularType, + name: request.name, + state: 'active', + ...(servedPackage !== undefined ? { packageId: servedPackage } : {}), + ...memberOption(member), + servedOverride: true, + }); + rollbackPackageId = served !== undefined + ? ((served.row as { package_id?: string | null } | null)?.package_id ?? null) + : await host.resolveOverlayPackageBinding(singularType, request.name, member); + } // [ADR-0146 D11, D1] A rollback writes the row its binding names, so // a rollback of a packaged item's package-less row (an overlay type's // row the ceremony has not moved, or none stored, whose restore writes @@ -2079,6 +2097,8 @@ export class ProtocolPackageCommitsFacet { // [#29848, #29414] The row the binding above names, and no other // package's row of the name: its parent hash, and the write. packageId: rollbackPackageId, + // [#32905] …and only a version of that row's slot. + ...(slot ? { versionOf: { packageId: rollbackPackageId, unattributed: slot.owner.unattributed } } : {}), }); // #4521 — a rollback is a live write like any other: the restored // body must be the one the runtime dispatches on immediately, not diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 2c2b683cbe0..99c2ee55036 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -9507,6 +9507,11 @@ export class ObjectStackProtocolImplementation implements * construction: `saveMetaItem` refuses them outright (#5086), and the one * write channel they retain — `deleteMetaItem`'s legacy raw-engine branch * on a control-plane kernel — appends no `sys_metadata_history` row. + * + * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a + * name two row slots hold is refused `409` naming every holder when no + * package is named, and `packageId` reads that holder's versions alone + * (`protocol-history-slots.ts`); a name one slot holds reads as before. */ async historyMetaItem(request: { type: string; @@ -9515,6 +9520,8 @@ export class ObjectStackProtocolImplementation implements limit?: number; /** [#22877] The bundle member whose lineage to read — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string; + /** [ADR-0150 D3/D4, #32905] The package whose versions to read; omitted, the name's (refused for two holders). */ + packageId?: string; }): Promise<{ events: import('@objectstack/metadata-core').MetadataEvent[] }> { // [#29985 codemod] The body moved to `protocol-history-and-publish.ts`; it reaches this class through `protocol-host.ts`. return ProtocolHistoryAndPublishFacet.historyMetaItem(protocolHost(this), request); @@ -10891,9 +10898,16 @@ export class ObjectStackProtocolImplementation implements * 409 (`VERSION_NOT_RESTORABLE`) when the target is a delete * tombstone (no body to bring back). * - * [#29848, ADR-0146 D8 item 2] The door names no package: it restores - * into the row the by-name read naming no package serves, a `.custom` - * pair's declared override over a row bound to its read-only base. + * [#29848, ADR-0146 D8 item 2] Naming no package, it restores into the + * row the by-name read naming no package serves, a `.custom` pair's + * declared override over a row bound to its read-only base. + * + * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a + * name two row slots hold is refused `409` naming every holder when no + * package is named, with nothing written; `packageId` restores into that + * holder's row (its own, or its pair's declared override), and the + * version must be that holder's: another holder's answers 404 + * `VERSION_NOT_FOUND` (`protocol-history-slots.ts`). * * [#32700] Then, as the save door does: the restored object's storage is * synced, and every stored computed field the restore makes compute diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 51159dcf30e..5e9ca3f9e43 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -66,6 +66,7 @@ import { isMissingTableError } from '@objectstack/metadata/errors'; // [ruling 6677709817 (c)] The snapshot body both history writers store: the // written body without what the type's redactor marks not carried forward. import { historySnapshotBody } from '@objectstack/metadata/history-snapshot'; +import { ENVIRONMENT_HISTORY_MARK, PACKAGE_SLOTTED_STORE_TYPES, historyRowAttribution } from '@objectstack/metadata'; import { readEnvWithDeprecation } from '@objectstack/types'; import type { MetadataRepository, @@ -555,6 +556,42 @@ export function versionNotFoundError( return err; } +/** + * [ADR-0150 D3/D4, #32905] The `sys_metadata_history.package_id` a snapshot of + * a row bound to `binding` is recorded with, for a type stored per + * `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`): the row's package, or the + * environment's mark for the package-less row — the column `DatabaseLoader` + * writes for the same table, so one rule ({@link historyRowAttribution}) says + * whose version a row is whichever writer recorded it. Every other type + * leaves the column out, as before. + */ +function historySnapshotPackageColumn( + type: string, + binding: string | null | undefined, +): { package_id?: string } { + if (!PACKAGE_SLOTTED_STORE_TYPES.has(type)) return {}; + return { package_id: typeof binding === 'string' && binding !== '' ? binding : ENVIRONMENT_HISTORY_MARK }; +} + +/** + * [ADR-0150 D3/D4, #32905] Whose versions a history read serves, or whose + * version a restore may write: the row slot `packageId` names (`null`: the + * package-less row), and whether a version attributed to no package + * (recorded before the column was written) is that slot's too — only when + * the name has no other row slot, so an unattributed version is never + * guessed onto one of several holders. + */ +export interface HistoryVersionOwner { + packageId: string | null; + unattributed: boolean; +} + +/** [#32905] Whether history row `row` is a version of `owner`'s slot. */ +function isVersionOf(row: Record, owner: HistoryVersionOwner): boolean { + const attributed = historyRowAttribution(row); + return attributed === undefined ? owner.unattributed : attributed === owner.packageId; +} + /** * [#23165, ADR-0048] The refusal of a save, or a delete, that names no * package, of an item whose rows at the address are bound to two or more @@ -1257,6 +1294,8 @@ export class SysMetadataRepository implements MetadataRepository { previous_checksum: existingHash, change_note: opts.message, source: opts.source ?? 'sys-metadata-repo', + // [ADR-0150 D3/D4, #32905] Whose row this snapshot is of. + ...historySnapshotPackageColumn(ref.type, parentRowData.package_id as string | null | undefined), // #4556 — `recorded_by` is a lookup('sys_user'). A write with no // actor stores NULL, never a sentinel string: an id that resolves // to no row is a foreign key that lies. @@ -1414,6 +1453,8 @@ export class SysMetadataRepository implements MetadataRepository { previous_checksum: existingHash, change_note: opts.message, source: opts.source ?? 'sys-metadata-repo', + // [ADR-0150 D3/D4, #32905] Whose row the tombstone is of. + ...historySnapshotPackageColumn(ref.type, (existing as { package_id?: string | null }).package_id), // #4556 — NULL, not a sentinel, when the delete had no actor. recorded_by: opts.actor ?? null, recorded_at: now, @@ -1711,6 +1752,16 @@ export class SysMetadataRepository implements MetadataRepository { * the unbound row, as before. A LOCAL extension, as on {@link delete}. */ packageId?: string | null; + /** + * [ADR-0150 D3/D4, #32905] The row slot whose version `targetVersion` + * must be: a version attributed to another package (or to the + * environment, for a package's slot) answers 404 `VERSION_NOT_FOUND`, + * as another member's does, and an unattributed one is restored only + * where {@link HistoryVersionOwner.unattributed} admits it — ⛔ never + * another holder's version written into this slot's row. Omitted → any + * version of the name, as before. + */ + versionOf?: HistoryVersionOwner; }, ): Promise<{ version: string; seq: number; item: MetadataItem }> { this.assertOpen(); @@ -1724,6 +1775,20 @@ export class SysMetadataRepository implements MetadataRepository { context: { isSystem: true }, }); if (!row) throw versionNotFoundError(ref, targetVersion); + if (opts.versionOf !== undefined && !isVersionOf(row as Record, opts.versionOf)) { + const owner = historyRowAttribution(row as Record); + const whose = (id: string | null) => (id === null ? 'the environment\'s own row' : `package '${id}'`); + const err: any = new Error( + `No history row at version ${targetVersion} for ${ref.type}/${ref.name} of ${whose(opts.versionOf.packageId)}: ` + + (owner === undefined + ? 'that version is attributed to no package, and more than one holds the name, so nothing says whose it is.' + : `that version belongs to ${whose(owner)}.`) + + ' Nothing was restored.', + ); + err.code = 'VERSION_NOT_FOUND'; + err.status = 404; + throw err; + } const raw = (row as any).metadata; if (raw === null || raw === undefined) { const err: any = new Error( @@ -1921,7 +1986,14 @@ export class SysMetadataRepository implements MetadataRepository { * [#22877] `member` — the bundle member whose lineage to yield; omitted, * the canonical one (see {@link get}). Ignored for every other type. */ - opts?: HistoryOptions & { member?: string | null }, + opts?: HistoryOptions & { + member?: string | null; + /** + * [ADR-0150 D3/D4, #32905] One row slot's versions only + * ({@link HistoryVersionOwner}); omitted, every version of the name. + */ + versionsOf?: HistoryVersionOwner; + }, ): AsyncIterable { this.assertOpen(); const full = this.fullRef(ref); @@ -1931,11 +2003,14 @@ export class SysMetadataRepository implements MetadataRepository { }; // [#21908] The explicit system opt-in, as `get` carries — see its note. // [#22877] One member's rows only — {@link historyRowsOfMember}. - const rows = historyRowsOfMember( + let rows = historyRowsOfMember( full.type, await this.engine.find(this.historyTable, { where, context: { isSystem: true } }), opts?.member, ); + // [#32905] …and one slot's, before the cursor and the limit page them. + const versionsOf = opts?.versionsOf; + if (versionsOf !== undefined) rows = rows.filter((row: Record) => isVersionOf(row, versionsOf)); rows.sort((a: any, b: any) => { const va = typeof a.event_seq === 'number' ? a.event_seq : 0; const vb = typeof b.event_seq === 'number' ? b.event_seq : 0; diff --git a/packages/metadata/src/index.ts b/packages/metadata/src/index.ts index 7eaf5da4dd9..66935cd8716 100644 --- a/packages/metadata/src/index.ts +++ b/packages/metadata/src/index.ts @@ -22,7 +22,13 @@ export { export { type MetadataLoader, type MetadataKeyedItem, type MetadataLoaderDeleteOptions } from './loaders/loader-interface.js'; export { MemoryLoader } from './loaders/memory-loader.js'; export { RemoteLoader } from './loaders/remote-loader.js'; -export { DatabaseLoader, type DatabaseLoaderOptions, type MetadataHistoryAddress } from './loaders/database-loader.js'; +export { + DatabaseLoader, + ENVIRONMENT_HISTORY_MARK, + historyRowAttribution, + type DatabaseLoaderOptions, + type MetadataHistoryAddress, +} from './loaders/database-loader.js'; // [commit c1d274de7] The ambiguous-stem refusal. Published from the ROOT entry, not only // from `./node` beside `FilesystemLoader`: the error reaches consumers through diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index f1d1ac41fc4..132673dea5a 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -272,9 +272,9 @@ function addressedPackage(address?: MetadataHistoryAddress): string | null | und * snapshot of the environment's (package-less) row of a by-package type: the * explicit `sys_metadata` sentinel. NULL in that column means "not * attributed" (a row written before the column, or one `SysMetadataRepository` - * wrote), never the environment. + * wrote before it recorded the column too, #32905), never the environment. */ -const ENVIRONMENT_HISTORY_MARK = 'sys_metadata'; +export const ENVIRONMENT_HISTORY_MARK = 'sys_metadata'; /** * [#32351] The `package_id` a by-package type's snapshot of `slot`'s row is @@ -293,9 +293,10 @@ function historySnapshotPackage(slot: { packageId?: string } | undefined): strin * environment (the column holds {@link ENVIRONMENT_HISTORY_MARK}), or * `undefined` when it is attributed to none. An addressed read never answers * an unattributed version, and a rollback lands one only on a name a single - * row slot holds. + * row slot holds. [#32905] `SysMetadataRepository` (the `/meta` history and + * rollback doors) attributes the rows it reads by this same rule. */ -function historyRowAttribution(row: Record): string | null | undefined { +export function historyRowAttribution(row: Record): string | null | undefined { if (row.package_id === ENVIRONMENT_HISTORY_MARK) return null; return storedRowPackageId(row); } diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 29f553008ef..2bee75b92dc 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -217,6 +217,17 @@ export interface MetaItemHistoryRouteHost { maskObjectDocument: RestServer['maskObjectDocument']; } +/** + * [ADR-0150 D3/D4, #32905] The `?package=` of the history and rollback doors, + * read as `/layers?package=` reads it ({@link metaItemPackageBinding}: `all` + * and the empty string name no package): the holder whose versions the door + * reads, or whose row it restores. + */ +function historyPackageSelector(query: unknown): { packageId?: string } { + const packageId = metaItemPackageBinding((query as { package?: unknown } | undefined)?.package); + return packageId !== undefined ? { packageId } : {}; +} + /** * Register the `/meta` history family — the change log, the audit trail, the * publish, the rollback and the version comparison, the sixth group of @@ -295,7 +306,7 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc // of the page the caller asked for. // [#22877] Recognition first, over the measured closed set. if (refuseUnknownQueryParams(req, res, META_ITEM_HISTORY_PARAMS)) return; - if (refuseRepeatedQueryParams(req, res, ['sinceSeq', 'limit', META_ITEM_MEMBER_PARAM])) return; + if (refuseRepeatedQueryParams(req, res, ['sinceSeq', 'limit', 'package', META_ITEM_MEMBER_PARAM])) return; // [#20139] `sinceSeq` is parsed through its DECLARATION // (`HistoryMetaItemRequestSchema.sinceSeq`, `z.number().optional()`), // the way `limit` is just below: `?sinceSeq=abc` used to be `NaN`, @@ -356,6 +367,10 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc ...(limit !== undefined ? { limit } : {}), // [#22877] ONE member's events of the bundle's lineage. ...metaMemberSelector(req.query), + // [ADR-0150 D3/D4, #32905] ONE holder's versions, for a type + // stored per `(package, name)`: the name's log interleaves + // every holder's, and naming none of two is refused 409. + ...historyPackageSelector(req.query), }; const result = await p.historyMetaItem(historyRequest); res.json(result); @@ -804,7 +819,7 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc // by name says what actually happened. // [#22877] Recognition first, over the measured closed set. if (refuseUnknownQueryParams(req, res, META_ITEM_ROLLBACK_PARAMS)) return; - if (refuseRepeatedQueryParams(req, res, ['toVersion', META_ITEM_MEMBER_PARAM])) return; + if (refuseRepeatedQueryParams(req, res, ['toVersion', 'package', META_ITEM_MEMBER_PARAM])) return; const body = (req.body && typeof req.body === 'object') ? req.body : {}; // [#25482] `toVersion` names a history row, so only a positive // integer is a version. A bare `Number(...)` here coerced @@ -855,6 +870,9 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc ...(message ? { message } : {}), // [#22877] Reverts ONE member of a bundled type. ...metaMemberSelector(req.query), + // [ADR-0150 D3/D4, #32905] …and ONE holder's row, for a type + // stored per `(package, name)`; naming none of two is refused 409. + ...historyPackageSelector(req.query), }); res.json(result); } catch (error: any) { diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index a13a416f975..be6f3a652c4 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -754,8 +754,10 @@ export const META_ITEM_RESET_PARAMS: readonly string[] = ['state', 'dropStorage' * **Measured**: the paging pair `sinceSeq` and `limit`, each read through its * declaration (`readDeclaredQueryNumber`); the authoring-door and per-caller * refusals read the session, not the query. Plus {@link META_ITEM_MEMBER_PARAM}. + * [ADR-0150 D3/D4, #32905] And `package`, the holder whose versions to read, + * through {@link metaItemPackageBinding} as `/layers?package=` reads it. */ -export const META_ITEM_HISTORY_PARAMS: readonly string[] = ['sinceSeq', 'limit', META_ITEM_MEMBER_PARAM]; +export const META_ITEM_HISTORY_PARAMS: readonly string[] = ['sinceSeq', 'limit', 'package', META_ITEM_MEMBER_PARAM]; /** * [#22877] The closed set of `POST {metaPath}/:type/:name/publish`. @@ -769,9 +771,10 @@ export const META_ITEM_PUBLISH_PARAMS: readonly string[] = ['package', META_ITEM * [#22877] The closed set of `POST {metaPath}/:type/:name/rollback`. * **Measured**: `toVersion`, the query fallback after the body's `toVersion` / * `version`; the message rides the body, the actor the session. Plus - * {@link META_ITEM_MEMBER_PARAM}. + * {@link META_ITEM_MEMBER_PARAM}. [ADR-0150 D3/D4, #32905] And `package`, the + * holder whose row is restored, through {@link metaItemPackageBinding}. */ -export const META_ITEM_ROLLBACK_PARAMS: readonly string[] = ['toVersion', META_ITEM_MEMBER_PARAM]; +export const META_ITEM_ROLLBACK_PARAMS: readonly string[] = ['toVersion', 'package', META_ITEM_MEMBER_PARAM]; // [#23072] The by-name `/meta` doors OUTSIDE ruling 6116165299's list, each // with the closed set measured from its own read points (AGENTS.md route rule diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 57856cf5427..015084c87b0 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2327,6 +2327,13 @@ export const HistoryMetaItemRequestSchema = lazySchema(() => z.object({ + 'verb accepts.)', ), member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), + packageId: z.string().optional().describe( + 'Optional package ID (`?package=` on the REST door, the `/layers` spelling) — ' + + 'for a type stored per (package, name), the holder whose versions to read: ' + + 'its own row\'s, or its `.custom` pair\'s declared override\'s (ADR-0150 D3/D4). ' + + 'Absent, a name two holders\' rows hold is refused 409 naming every holder. ' + + 'Every other type reads the name\'s log either way.', + ), })); /** From ec73c51254b7cfa0148ef8f3f2647db92b3610fa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:30:47 +0000 Subject: [PATCH 02/14] test(dogfood): two-holder history and rollback doors refuse bare, address one holder by package Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- ...story-rollback-two-holders.dogfood.test.ts | 195 ++++++++++++++++++ packages/rest/src/meta-item-history-routes.ts | 6 +- packages/spec/authorable-surface/api.json | 1 + 3 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts diff --git a/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts new file mode 100644 index 00000000000..eda79923c15 --- /dev/null +++ b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0150 D3/D4, epic #31527 red line 2, #32905] The `/meta` history and +// rollback doors of a flow name two packages hold, on a booted showcase. +// +// A flow is stored per `(package, name)`: each holder has its own +// `sys_metadata` row, and the name's versions are numbered across them, so its +// change log interleaves every holder's versions. Before this card the doors +// read the name alone: the bare history listed both holders' versions as one +// item's timeline, `?package=` was refused as unknown, and the bare rollback +// wrote whichever version it was given into ONE holder's row — measured: a +// version of `beta.custom`'s flow restored, answered 200, into +// `alpha.custom`'s row. Now: +// +// - naming no package, both doors refuse the two-holder name `409 +// RESOURCE_CONFLICT` naming each holder (`details.candidates`), and the +// rollback writes nothing; +// - `?package=` (the `/layers?package=` spelling) reads that holder's +// versions alone and restores only that holder's row; a version of the +// other holder is refused `404 VERSION_NOT_FOUND`, writing nothing; the +// base package a pair customizes addresses its pair's declared override; +// a package that holds nothing of the name is refused naming the holders; +// - a version recorded before the history row named its package is never +// guessed onto one of two holders: no address lists or restores it; +// - CONTROL: a name one package holds keeps its whole log and its rollback +// bare, an unattributed version included. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { AppPlugin } from '@objectstack/runtime'; +import { defineStack } from '@objectstack/spec'; +import { bootShowcase } from './showcase-boot.js'; + +const BOOT_TIMEOUT = 300_000; +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; +const ALPHA = 'com.qa.hist32905.alpha'; +const BETA = 'com.qa.hist32905.beta'; +const ALPHA_PAIR = `${ALPHA}.custom`; +const BETA_PAIR = `${BETA}.custom`; +/** A runtime flow both pairs save (no package ships it). */ +const SHARED = 'qa_hist_shared_32905'; +/** A flow both packages ship, each customized in its own pair. */ +const SHIPPED = 'qa_hist_shipped_32905'; +/** A runtime flow only alpha's pair holds: the CONTROL. */ +const SOLO = 'qa_hist_solo_32905'; + +const flowBody = (name: string, label: string) => ({ + name, label, type: 'autolaunched', status: 'active', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}); + +function holderPackage(p: 'alpha' | 'beta') { + return defineStack({ + manifest: { id: `com.qa.hist32905.${p}`, namespace: `h32905${p}`, name: `qa_hist32905_${p}`, version: '1.0.0', type: 'app' }, + flows: [flowBody(SHIPPED, `${p} shipped`)], + } as never); +} + +describe('the /meta history and rollback doors of a flow name two packages hold (ADR-0150 D3/D4, #32905)', () => { + let stack: VerifyStack; + let admin: string; + + const call = async (method: string, path: string, body?: unknown) => { + const res = await stack.apiAs(admin, method, path, body); + return { status: res.status, json: (await res.json().catch(() => null)) as any }; + }; + const codeOf = (json: any) => (json?.error && typeof json.error === 'object' ? json.error.code : undefined) ?? json?.code; + const versions = (json: any): number[] => (json?.events ?? []).map((e: any) => e.version); + const labelAt = async (name: string, pkg: string) => (await call('GET', `/meta/flow/${name}?package=${pkg}`)).json?.item?.label; + const save = async (name: string, pkg: string, label: string, overrides?: string) => { + const res = await call('PUT', `/meta/flow/${name}?package=${pkg}`, + { ...flowBody(name, label), ...(overrides ? { overrides: { package: overrides, basedOn: '1.0.0' } } : {}) }); + expect(res.status, JSON.stringify(res.json)).toBe(200); + return res.json.seq as number; + }; + const candidatesOf = (json: any) => + (json?.details?.candidates ?? []).map((c: any) => c.packageId ?? c.kind).sort(); + + /** The version each save wrote, by holder. */ + const shared: Record = { [ALPHA_PAIR]: [], [BETA_PAIR]: [] }; + let legacy: number; + + beforeAll(async () => { + stack = await bootShowcase({ extraPlugins: [new AppPlugin(holderPackage('alpha') as never), new AppPlugin(holderPackage('beta') as never)] }); + admin = await stack.signIn(); + for (const base of [ALPHA, BETA]) { + expect([200, 201]).toContain((await call('POST', `/packages/${base}/ensure-customization`)).status); + } + for (const round of [1, 2]) { + for (const pair of [ALPHA_PAIR, BETA_PAIR]) { + await save(SHARED, pair, `${pair} r${round}`); + const all = (await call('GET', `/meta/flow/${SHARED}/history?package=${pair}`)).json; + shared[pair] = versions(all); + } + } + await save(SHIPPED, ALPHA_PAIR, 'alpha custom r1', ALPHA); + await save(SHIPPED, BETA_PAIR, 'beta custom r1', BETA); + await save(SHIPPED, ALPHA_PAIR, 'alpha custom r2', ALPHA); + await save(SOLO, ALPHA_PAIR, 'solo r1'); + await save(SOLO, ALPHA_PAIR, 'solo r2'); + // A version of SHARED recorded before the history row named its package + // (a release before this card): `package_id` left NULL. + const ql: any = await stack.kernel.getServiceAsync('objectql'); + const rows: any[] = await ql.find('sys_metadata_history', { where: { type: 'flow', name: SHARED }, context: SYSTEM_CTX }); + legacy = Math.max(...rows.map((r) => Number(r.version))) + 1; + const seq = Math.max(...((await ql.find('sys_metadata_history', { where: {}, context: SYSTEM_CTX })) as any[]).map((r) => Number(r.event_seq ?? 0))) + 1; + await ql.insert('sys_metadata_history', { + id: `legacy_${SHARED}`, event_seq: seq, type: 'flow', name: SHARED, version: legacy, operation_type: 'update', + metadata: JSON.stringify(flowBody(SHARED, 'legacy unattributed')), checksum: 'legacy', previous_checksum: null, + source: 'qa.legacy', recorded_by: null, recorded_at: new Date().toISOString(), + }, { context: SYSTEM_CTX }); + }, BOOT_TIMEOUT); + + afterAll(async () => { + await stack?.stop(); + }); + + it('the bare history of the two-holder name is refused 409 naming both holders', async () => { + const res = await call('GET', `/meta/flow/${SHARED}/history`); + expect(res.status, JSON.stringify(res.json)).toBe(409); + expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(res.json)).toEqual([ALPHA_PAIR, BETA_PAIR].sort()); + }); + + it('the bare rollback of the two-holder name is refused 409 naming both, and neither holder\'s row changes', async () => { + for (const toVersion of [shared[ALPHA_PAIR]![0]!, shared[BETA_PAIR]![0]!]) { + const res = await call('POST', `/meta/flow/${SHARED}/rollback`, { toVersion }); + expect(res.status, JSON.stringify(res.json)).toBe(409); + expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(res.json)).toEqual([ALPHA_PAIR, BETA_PAIR].sort()); + } + expect(await labelAt(SHARED, ALPHA_PAIR)).toBe(`${ALPHA_PAIR} r2`); + expect(await labelAt(SHARED, BETA_PAIR)).toBe(`${BETA_PAIR} r2`); + }); + + it('?package= reads that holder\'s versions alone, never the other\'s or an unattributed one', async () => { + const alpha = versions((await call('GET', `/meta/flow/${SHARED}/history?package=${ALPHA_PAIR}`)).json); + const beta = versions((await call('GET', `/meta/flow/${SHARED}/history?package=${BETA_PAIR}`)).json); + expect(alpha).toHaveLength(2); + expect(beta).toHaveLength(2); + expect(alpha.some((v) => beta.includes(v))).toBe(false); + expect([...alpha, ...beta]).not.toContain(legacy); + }); + + it('?package= restores only that holder\'s row; the other holder\'s version and an unattributed one are refused, writing nothing', async () => { + const other = await call('POST', `/meta/flow/${SHARED}/rollback?package=${ALPHA_PAIR}`, { toVersion: shared[BETA_PAIR]![0]! }); + expect(other.status, JSON.stringify(other.json)).toBe(404); + expect(codeOf(other.json)).toBe('VERSION_NOT_FOUND'); + const unattributed = await call('POST', `/meta/flow/${SHARED}/rollback?package=${BETA_PAIR}`, { toVersion: legacy }); + expect(unattributed.status, JSON.stringify(unattributed.json)).toBe(404); + expect(codeOf(unattributed.json)).toBe('VERSION_NOT_FOUND'); + expect(await labelAt(SHARED, ALPHA_PAIR)).toBe(`${ALPHA_PAIR} r2`); + expect(await labelAt(SHARED, BETA_PAIR)).toBe(`${BETA_PAIR} r2`); + + const own = await call('POST', `/meta/flow/${SHARED}/rollback?package=${ALPHA_PAIR}`, { toVersion: shared[ALPHA_PAIR]![0]! }); + expect(own.status, JSON.stringify(own.json)).toBe(200); + expect(await labelAt(SHARED, ALPHA_PAIR)).toBe(`${ALPHA_PAIR} r1`); + expect(await labelAt(SHARED, BETA_PAIR)).toBe(`${BETA_PAIR} r2`); + // The restore is alpha's version, and only alpha's log grew. + expect(versions((await call('GET', `/meta/flow/${SHARED}/history?package=${ALPHA_PAIR}`)).json)).toHaveLength(3); + expect(versions((await call('GET', `/meta/flow/${SHARED}/history?package=${BETA_PAIR}`)).json)).toHaveLength(2); + }); + + it('the base package a pair customizes addresses its pair\'s declared override, at both doors', async () => { + expect((await call('GET', `/meta/flow/${SHIPPED}/history`)).status).toBe(409); + const alpha = versions((await call('GET', `/meta/flow/${SHIPPED}/history?package=${ALPHA}`)).json); + expect(alpha).toEqual(versions((await call('GET', `/meta/flow/${SHIPPED}/history?package=${ALPHA_PAIR}`)).json)); + expect(alpha).toHaveLength(2); + const res = await call('POST', `/meta/flow/${SHIPPED}/rollback?package=${ALPHA}`, { toVersion: alpha[0]! }); + expect(res.status, JSON.stringify(res.json)).toBe(200); + expect(await labelAt(SHIPPED, ALPHA_PAIR)).toBe('alpha custom r1'); + expect(await labelAt(SHIPPED, BETA_PAIR)).toBe('beta custom r1'); + }); + + it('a package that holds nothing of the name is refused naming the holders', async () => { + for (const path of [`/meta/flow/${SHARED}/history?package=com.qa.nobody`]) { + const res = await call('GET', path); + expect(res.status, JSON.stringify(res.json)).toBe(409); + expect(candidatesOf(res.json)).toEqual([ALPHA_PAIR, BETA_PAIR].sort()); + } + const res = await call('POST', `/meta/flow/${SHARED}/rollback?package=com.qa.nobody`, { toVersion: shared[ALPHA_PAIR]![0]! }); + expect(res.status, JSON.stringify(res.json)).toBe(409); + expect(await labelAt(SHARED, ALPHA_PAIR)).toBe(`${ALPHA_PAIR} r1`); + }); + + it('CONTROL: a name one package holds keeps its whole log and its bare rollback, as before', async () => { + const bare = versions((await call('GET', `/meta/flow/${SOLO}/history`)).json); + expect(bare).toHaveLength(2); + expect(versions((await call('GET', `/meta/flow/${SOLO}/history?package=${ALPHA_PAIR}`)).json)).toEqual(bare); + const res = await call('POST', `/meta/flow/${SOLO}/rollback`, { toVersion: bare[0]! }); + expect(res.status, JSON.stringify(res.json)).toBe(200); + expect(await labelAt(SOLO, ALPHA_PAIR)).toBe('solo r1'); + }); +}); diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 2bee75b92dc..626f9f0a174 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -375,7 +375,8 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc const result = await p.historyMetaItem(historyRequest); res.json(result); } catch (error: any) { - handleRouteError(res, error); + // [#32905] A two-holder refusal names its holders (`details.candidates`), as the by-name reads do. + handleRouteError(res, error, undefined, { packageScopedCandidates: true }); } }, metadata: { @@ -876,7 +877,8 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc }); res.json(result); } catch (error: any) { - handleRouteError(res, error); + // [#32905] A two-holder refusal names its holders (`details.candidates`), as the by-name reads do. + handleRouteError(res, error, undefined, { packageScopedCandidates: true }); } }, metadata: { diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 12942fd998e..51d38da0cce 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -914,6 +914,7 @@ "api/HistoryMetaItemRequest:limit", "api/HistoryMetaItemRequest:member", "api/HistoryMetaItemRequest:name", + "api/HistoryMetaItemRequest:packageId", "api/HistoryMetaItemRequest:sinceSeq", "api/HistoryMetaItemRequest:type", "api/HistoryMetaItemResponse:events", From 6fa74d8629f2ef6471a58ab6eec3453abe0b8cf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:32:06 +0000 Subject: [PATCH 03/14] test(rest): history and rollback doors forward ?package= and render the holder refusal with candidates Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- ...meta-item-history-package-selector.test.ts | 140 ++++++++++++++++++ .../rest-server-meta-member-selector.test.ts | 4 +- 2 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 packages/rest/src/meta-item-history-package-selector.test.ts diff --git a/packages/rest/src/meta-item-history-package-selector.test.ts b/packages/rest/src/meta-item-history-package-selector.test.ts new file mode 100644 index 00000000000..29aa159671c --- /dev/null +++ b/packages/rest/src/meta-item-history-package-selector.test.ts @@ -0,0 +1,140 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` take + * `?package=` — the `/layers?package=` spelling — naming whose versions of a + * by-package name (ADR-0150 D3/D4) the door reads or restores. Which slot a + * package names, and the `409` for a bare name two holders' rows hold, is the + * protocol's to judge (`historySlotOf`); the real-boot pins live in + * `history-rollback-two-holders.dogfood.test.ts`. This file pins the route's + * half, both ways round as route rule 5 asks: + * + * - PRESERVATION: the request the protocol received carries `packageId`, and + * the `all`/empty spellings `/layers` folds to "no package" send none; + * - REFUSAL: a repeated `?package=` is a located 400 and the protocol is never + * called; the protocol's package-scoped refusal is rendered `409` with + * `details.candidates` naming every holder, as the plain read renders it. + */ + +import { describe, it, expect, vi } from 'vitest'; +// The route modules load ObjectQL lazily; pay that load at collection, never in a clocked case. +import '@objectstack/objectql'; +import { PackageScopedNameRefusedError, packageScopedRefusalMessage, type PackageScopedRefusal } from '@objectstack/core'; +import { RestServer, META_ITEM_HISTORY_PARAMS, META_ITEM_ROLLBACK_PARAMS } from './rest-server.js'; + +const ITEM = '/api/v1/meta/:type/:name'; +const PARAMS = { type: 'flow', name: 'shared_flow' }; + +function mockRes() { + const res: any = { + statusCode: 200, + json: vi.fn(function (this: any) { return this; }), + send: vi.fn(function (this: any) { return this; }), + end: vi.fn(function (this: any) { return this; }), + setHeader: vi.fn(function (this: any) { return this; }), + header: vi.fn(function (this: any) { return this; }), + status: vi.fn(function (this: any, code: number) { this.statusCode = code; return this; }), + }; + return res; +} + +function twoHolderRefusal(): PackageScopedNameRefusedError { + const base: Omit = { + status: 'refused', + reason: 'ambiguous-in-environment', + type: 'flow', + name: 'shared_flow', + callerPackageId: null, + candidates: [ + { kind: 'package', packageId: 'com.acme.alpha.custom' }, + { kind: 'package', packageId: 'com.acme.beta.custom' }, + ], + }; + return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); +} + +function boot(options: { refuse?: boolean } = {}) { + const answer = (value: unknown) => vi.fn(() => (options.refuse ? Promise.reject(twoHolderRefusal()) : Promise.resolve(value))); + const protocol: any = { + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn().mockResolvedValue({ items: [] }), + getMetaItem: vi.fn().mockResolvedValue({ type: 'flow', name: 'shared_flow', item: { name: 'shared_flow' }, lock: 'none' }), + historyMetaItem: answer({ events: [] }), + rollbackMetaItem: answer({ success: true, version: 'v', seq: 2, restoredFromVersion: 1 }), + }; + const server = { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), + listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; + const rest = new RestServer(server as any, protocol, { api: { requireAuth: false }, metadata: { enableCache: false } } as any); + // `isSystem` clears the capability and authoring gates that run before the query is read. + (rest as any).resolveExecCtx = async () => ({ isSystem: true, userId: 'u1' }); + rest.registerRoutes(); + const drive = async (method: string, path: string, query: Record, body: unknown = {}) => { + const found = (rest as any).getRoutes().find((r: any) => r.method === method && r.path === path); + if (!found) throw new Error(`route not registered: ${method} ${path}`); + const res = mockRes(); + await found.handler({ method, path, params: PARAMS, query, headers: {}, body } as any, res); + return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] }; + }; + return { protocol, drive }; +} + +const DOORS = [ + { door: 'GET /history', method: 'GET', path: `${ITEM}/history`, call: 'historyMetaItem', body: {} }, + { door: 'POST /rollback', method: 'POST', path: `${ITEM}/rollback`, call: 'rollbackMetaItem', body: { toVersion: 1 } }, +] as const; + +describe('the history and rollback doors take `?package=`, the `/layers` spelling', () => { + it('both doors declare `package` in their closed query set', () => { + expect(META_ITEM_HISTORY_PARAMS).toContain('package'); + expect(META_ITEM_ROLLBACK_PARAMS).toContain('package'); + }); + + it('GET /history: PRESERVATION — the package reaches `historyMetaItem` beside the paging pair', async () => { + const { protocol, drive } = boot(); + const answer = await drive('GET', `${ITEM}/history`, { package: 'com.acme.alpha.custom', sinceSeq: '3', limit: '10' }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(protocol.historyMetaItem.mock.calls[0][0]).toEqual({ + type: 'flow', name: 'shared_flow', sinceSeq: 3, limit: 10, packageId: 'com.acme.alpha.custom', + }); + }); + + it('POST /rollback: PRESERVATION — the package reaches `rollbackMetaItem` beside `toVersion`', async () => { + const { protocol, drive } = boot(); + const answer = await drive('POST', `${ITEM}/rollback`, { package: 'com.acme.alpha.custom' }, { toVersion: 3 }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(protocol.rollbackMetaItem.mock.calls[0][0]).toMatchObject({ + type: 'flow', name: 'shared_flow', toVersion: 3, packageId: 'com.acme.alpha.custom', + }); + }); + + for (const { door, method, path, call, body } of DOORS) { + it(`${door}: CONTROL — no package, \`all\` and the empty string send no \`packageId\``, async () => { + for (const query of [{}, { package: 'all' }, { package: '' }]) { + const { protocol, drive } = boot(); + const answer = await drive(method, path, query, body); + expect(answer.status, `${JSON.stringify(query)}: ${JSON.stringify(answer.body)}`).toBe(200); + expect(Object.keys(protocol[call].mock.calls[0][0]), JSON.stringify(query)).not.toContain('packageId'); + } + }); + + it(`${door}: REFUSAL — a repeated \`?package=\` is a located 400 and the protocol is never called`, async () => { + const { protocol, drive } = boot(); + const answer = await drive(method, path, { package: ['com.acme.alpha.custom', 'com.acme.beta.custom'] }, body); + expect(answer.status).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(answer.body?.error?.message).toContain('"package" query parameter was supplied 2 times'); + expect(protocol[call]).not.toHaveBeenCalled(); + }); + + it(`${door}: REFUSAL — the protocol's two-holder refusal is a 409 naming every holder in \`details.candidates\``, async () => { + const { drive } = boot({ refuse: true }); + const answer = await drive(method, path, {}, body); + expect(answer.status, JSON.stringify(answer.body)).toBe(409); + expect([...(answer.body?.details?.candidates ?? [])].map((c: any) => c.packageId).sort(), JSON.stringify(answer.body)) + .toEqual(['com.acme.alpha.custom', 'com.acme.beta.custom']); + }); + } +}); diff --git a/packages/rest/src/rest-server-meta-member-selector.test.ts b/packages/rest/src/rest-server-meta-member-selector.test.ts index a14901e365b..616a390ecb4 100644 --- a/packages/rest/src/rest-server-meta-member-selector.test.ts +++ b/packages/rest/src/rest-server-meta-member-selector.test.ts @@ -146,9 +146,9 @@ describe('[#22877] each by-name /meta door declares a closed query set, the memb it('the measured sets — paging, switches and the read a frame down included', () => { expect([...META_ITEM_READ_PARAMS].sort()).toEqual(['callerPackage', 'layers', 'locale', 'member', 'package', 'preview', 'state']); expect([...META_ITEM_RESET_PARAMS].sort()).toEqual(['dropStorage', 'member', 'package', 'state']); - expect([...META_ITEM_HISTORY_PARAMS].sort()).toEqual(['limit', 'member', 'sinceSeq']); + expect([...META_ITEM_HISTORY_PARAMS].sort()).toEqual(['limit', 'member', 'package', 'sinceSeq']); expect([...META_ITEM_PUBLISH_PARAMS].sort()).toEqual(['member', 'package']); - expect([...META_ITEM_ROLLBACK_PARAMS].sort()).toEqual(['member', 'toVersion']); + expect([...META_ITEM_ROLLBACK_PARAMS].sort()).toEqual(['member', 'package', 'toVersion']); }); for (const { door, method, path, set, call, body } of DOORS) { From c7ac638dd5c5503fe4aeee71fe93f021c3116c0d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:35:14 +0000 Subject: [PATCH 04/14] feat(ui): History item tool and client name the holder of a by-package name Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- ...ceHistoryPage.holderPackage-32905.test.tsx | 83 +++++++++++++++++++ .../views/item-tools/ResourceHistoryPage.tsx | 39 ++++++++- .../src/views/item-tools/StudioItemTools.tsx | 9 +- .../views/metadata-admin/ResourceEditPage.tsx | 1 + ...udioDesignSurface.itemTools-28239.test.tsx | 5 +- ...tadata-client.historyPackage-32905.test.ts | 63 ++++++++++++++ .../data-objectstack/src/metadata-client.ts | 19 ++++- 7 files changed, 210 insertions(+), 9 deletions(-) create mode 100644 ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx create mode 100644 ui/packages/data-objectstack/src/metadata-client.historyPackage-32905.test.ts diff --git a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx new file mode 100644 index 00000000000..0d56a5d6590 --- /dev/null +++ b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#32905 — the History item tool reads and restores the versions + * of the holder its item page names. A by-package name (ADR-0150 D3) is held + * per package, and the server numbers its versions across every holder: the + * routed page sends the item page's `?package=` to `history()` and + * `rollback()`, as the item page's own layered read does. `all` and the empty + * spelling name no package, as on the server's doors; no `?package=`, no + * `packageId` (CONTROL — a name one holder holds reads as before). + * + * Real: the page, `HistoryPanel` and React Router. Stubbed: the metadata client and types. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +const client = { + history: vi.fn(async () => ({ + events: [{ seq: 1, version: 1, op: 'save', at: '2026-11-13T00:00:00Z', payload: { name: 'shared_flow' } }], + })), + rollback: vi.fn(async () => ({ success: true })), +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, + useMetadataTypes: () => ({ loading: false, error: null, entries: [{ type: 'flow', label: 'Flow', domain: 'automation' }] }), +})); +vi.mock('../metadata-admin/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); + +import { MetadataResourceHistoryPage, historyPackageOf } from './ResourceHistoryPage'; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +function renderAt(url: string) { + return render( + + + } /> + + , + ); +} + +describe('History item tool — the item page\'s `?package=` names the holder (objectstack#32905)', () => { + it('`?package=` reaches history() and rollback()', async () => { + renderAt('/metadata/flow/shared_flow/history?package=com.acme.alpha.custom'); + await waitFor(() => + expect(client.history).toHaveBeenCalledWith('flow', 'shared_flow', { limit: 100, packageId: 'com.acme.alpha.custom' }), + ); + const [button] = await screen.findAllByTitle('Rollback to this version'); + fireEvent.click(button!); + fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('history-rollback-confirm-action')); + await waitFor(() => + expect(client.rollback).toHaveBeenCalledWith('flow', 'shared_flow', 1, { packageId: 'com.acme.alpha.custom' }), + ); + }); + + it('CONTROL: no `?package=` sends no `packageId` on either door', async () => { + renderAt('/metadata/flow/solo_flow/history'); + await waitFor(() => expect(client.history).toHaveBeenCalledWith('flow', 'solo_flow', { limit: 100 })); + const [button] = await screen.findAllByTitle('Rollback to this version'); + fireEvent.click(button!); + fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('history-rollback-confirm-action')); + await waitFor(() => expect(client.rollback).toHaveBeenCalledWith('flow', 'solo_flow', 1)); + }); + + it('`all` and the empty spelling name no package, as on the server\'s doors', () => { + expect(historyPackageOf('?package=all')).toBeUndefined(); + expect(historyPackageOf('?package=')).toBeUndefined(); + expect(historyPackageOf('')).toBeUndefined(); + expect(historyPackageOf('?scope=environment&package=com.acme.beta')).toBe('com.acme.beta'); + }); +}); diff --git a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx index 04c56a1ec46..4845f4873a7 100644 --- a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx +++ b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx @@ -4,7 +4,9 @@ * MetadataResourceHistoryPage — durable change log for one item * (Phase 3c). * - * Calls `client.history(type, name)`. The framework returns + * Calls `client.history(type, name)`, naming the item page's `?package=` + * when it has one (objectstack#32905: a by-package name's versions are its + * holders' interleaved, and a bare read of a name two hold is refused). The framework returns * `{ events: MetadataEvent[] }` where each event records who saved * what, with a monotonic `seq`. We render a vertical timeline; clicking * an event expands its payload diff. @@ -104,6 +106,11 @@ export function MetadataResourceHistoryPage({ areaHost ? navigate(`${areaHost.basePath}/${encodeURIComponent(type)}/${encodeURIComponent(name)}${search}`) : navigate({ pathname: pathname.replace(/\/[^/]+\/?$/, ''), search }); + // objectstack#32905 — the item page's `?package=` names whose versions of a + // by-package name (ADR-0150 D3) the timeline reads and a rollback restores: + // the same holder the item page reads (`layered()`'s `packageId`). `all` + // and the empty spelling name no package, as on the server's doors. + const packageId = historyPackageOf(search); return ( setRefreshKey((k) => k + 1)} /> @@ -147,6 +155,16 @@ export function MetadataResourceHistoryPage({ ); } +/** + * The package a history URL's `?package=` names, or `undefined` for none: + * absent, empty or `all` — the spellings the server's history and rollback + * doors fold to "no package". + */ +export function historyPackageOf(search: string): string | undefined { + const value = new URLSearchParams(search).get('package'); + return value && value !== 'all' ? value : undefined; +} + /** * Embeddable version of the history timeline. Re-used by both the * routed full page and the right-side sheet on the edit page so we @@ -166,9 +184,17 @@ export function HistoryPanel({ rollbackConfirm, rollbackLabel, locale, + packageId, }: { type: string; name: string; + /** + * objectstack#32905 — the holder of a by-package name (ADR-0150 D3) whose + * versions to list and restore into, sent as `?package=` on both doors. + * Omitted, a name two holders hold is refused 409 naming both, and the + * refusal shows as the timeline's error; one holder reads as before. + */ + packageId?: string; refreshKey?: number; onCount?: (n: number) => void; client: ReturnType; @@ -207,7 +233,10 @@ export function HistoryPanel({ setError(null); (async () => { try { - const result = await client.history(type, name, { limit: 100 }); + const result = await client.history(type, name, { + limit: 100, + ...(packageId ? { packageId } : {}), + }); if (cancelled) return; const list = Array.isArray(result) ? result @@ -229,7 +258,7 @@ export function HistoryPanel({ return () => { cancelled = true; }; - }, [client, type, name, refreshKey, localRefresh]); + }, [client, type, name, packageId, refreshKey, localRefresh]); function rollbackMessage(version: number): string { return rollbackConfirm @@ -241,7 +270,9 @@ export function HistoryPanel({ setRollingBack(version); setError(null); try { - await (client as any).rollback(type, name, version); + await (packageId + ? (client as any).rollback(type, name, version, { packageId }) + : (client as any).rollback(type, name, version)); onRollback?.(version); // Refetch so the new revert event shows up at the top. setLocalRefresh((k) => k + 1); diff --git a/ui/packages/app-shell/src/views/item-tools/StudioItemTools.tsx b/ui/packages/app-shell/src/views/item-tools/StudioItemTools.tsx index d1cca5cfe41..b6ca601d589 100644 --- a/ui/packages/app-shell/src/views/item-tools/StudioItemTools.tsx +++ b/ui/packages/app-shell/src/views/item-tools/StudioItemTools.tsx @@ -58,7 +58,10 @@ export interface StudioItemToolsProps { type: string; /** The item's machine name. */ name: string; - /** The package the item belongs to: scopes the layers read (ADR-0048). */ + /** + * The package the item belongs to: scopes the layers read (ADR-0048), and + * the history and rollback doors' `?package=` (objectstack#32905). + */ packageId?: string | null; /** The pillar's read-only gate: no rollback, and Source is read-only. */ readOnly?: boolean; @@ -256,6 +259,10 @@ function StudioItemToolsFor({ name={name} client={client} locale={locale} + // The holder the layers read names (objectstack#32905): a + // by-package name two holders hold lists and restores this + // package's versions, never the name's interleaved log. + packageId={packageId ?? undefined} // Setup's gate: the rollback door asks the capability and wall // verdicts the save door asks, so it is offered where Save is. onRollback={ diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index ed36d0277cd..84372d965a6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -3858,6 +3858,7 @@ function MetadataResourceEditPageImpl({ name={name} client={client} locale={locale} + packageId={ownerPackageId} // The rollback door asks the capability and wall verdicts the // save door asks, so it is offered on Save's gate // (objectui#12183: a walled tenant was offered it, refused). diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx index aebd4326a8c..beac73b0d0e 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx @@ -214,7 +214,8 @@ describe('Studio item toolbar — every pillar opens the five tools (objectstack const history = await openTool('history'); expect(await within(history).findAllByTitle(ROLLBACK)).toHaveLength(2); - expect(mockClient.history).toHaveBeenCalledWith(type, name, { limit: 100 }); + // The holder the layers read names (objectstack#32905). + expect(mockClient.history).toHaveBeenCalledWith(type, name, { limit: 100, packageId: PKG }); await openTool('audit'); await waitFor(() => expect(mockClient.audit).toHaveBeenCalledWith(type, name, { limit: 100 })); @@ -240,7 +241,7 @@ describe('Studio item toolbar — rollback (objectstack#28239)', () => { expect(mockClient.rollback).not.toHaveBeenCalled(); fireEvent.click(within(dialog).getByTestId('history-rollback-confirm-action')); - await waitFor(() => expect(mockClient.rollback).toHaveBeenCalledWith('object', 'showcase_account', 1)); + await waitFor(() => expect(mockClient.rollback).toHaveBeenCalledWith('object', 'showcase_account', 1, { packageId: PKG })); expect(mockClient.rollback).toHaveBeenCalledTimes(1); await waitFor(() => expect(mockClient.layered.mock.calls.filter(([type]) => type === 'object').length).toBeGreaterThan(reads), diff --git a/ui/packages/data-objectstack/src/metadata-client.historyPackage-32905.test.ts b/ui/packages/data-objectstack/src/metadata-client.historyPackage-32905.test.ts new file mode 100644 index 00000000000..16e828d1db4 --- /dev/null +++ b/ui/packages/data-objectstack/src/metadata-client.historyPackage-32905.test.ts @@ -0,0 +1,63 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#32905 — `history()` and `rollback()` name the holder of a + * by-package name (ADR-0150 D3) as `?package=`, the spelling `layered()` + * sends: the server numbers a name's versions across every holder, so a bare + * read of a name two holders hold is refused 409, and `?package=` reads or + * restores that one holder's versions. No `packageId`, no `package` key: a + * name one holder holds is read exactly as before (CONTROL). + */ + +import { describe, it, expect, vi } from 'vitest'; +import { MetadataClient } from './metadata-client'; + +const BASE = 'http://localhost:3000/api/v1/meta'; + +function record() { + const seen: { url: string; method: string; body?: string }[] = []; + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: vi.fn(async (url: string, init?: RequestInit) => { + seen.push({ url: String(url), method: init?.method ?? 'GET', body: init?.body as string | undefined }); + const body = String(url).includes('/rollback') + ? { success: true, version: 'v', seq: 5, restoredFromVersion: 1 } + : { events: [] }; + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); + }) as unknown as typeof fetch, + }); + const door = (suffix: string) => seen.filter((s) => s.url.includes(`/${suffix}`)); + return { client, door }; +} + +function queryOf(url: string): URLSearchParams { + const q = url.indexOf('?'); + return new URLSearchParams(q === -1 ? '' : url.slice(q + 1)); +} + +describe('MetadataClient — history and rollback name the holder (objectstack#32905)', () => { + it('history() sends `?package=` beside the paging pair', async () => { + const { client, door } = record(); + await client.history('flow', 'shared_flow', { limit: 100, sinceSeq: 2, packageId: 'com.acme.alpha.custom' }); + const [call] = door('history'); + expect(call?.url.startsWith(`${BASE}/flow/shared_flow/history?`)).toBe(true); + expect(Object.fromEntries(queryOf(call!.url))).toEqual({ sinceSeq: '2', limit: '100', package: 'com.acme.alpha.custom' }); + }); + + it('rollback() sends `?package=` on the URL, and the body stays `{ toVersion }`', async () => { + const { client, door } = record(); + await client.rollback('flow', 'shared_flow', 3, { packageId: 'com.acme.alpha.custom' }); + const [call] = door('rollback'); + expect(call?.method).toBe('POST'); + expect(call?.url).toBe(`${BASE}/flow/shared_flow/rollback?package=com.acme.alpha.custom`); + expect(JSON.parse(call!.body!)).toEqual({ toVersion: 3 }); + }); + + it('CONTROL: no `packageId` sends no `package` key on either door', async () => { + const { client, door } = record(); + await client.history('flow', 'solo_flow', { limit: 100 }); + await client.rollback('flow', 'solo_flow', 1); + expect(door('history')[0]?.url).toBe(`${BASE}/flow/solo_flow/history?limit=100`); + expect(door('rollback')[0]?.url).toBe(`${BASE}/flow/solo_flow/rollback`); + }); +}); diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index 0d9de01fb6a..8c4ad143984 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -807,6 +807,14 @@ export interface MetadataHistoryOptions { sinceSeq?: number; /** Limit the number of events returned. */ limit?: number; + /** + * The package whose versions to read (`?package=`, the `layered()` + * spelling). For a type stored per `(package, name)` the server numbers a + * name's versions across every holder; naming the package reads only that + * holder's, and a bare read of a name two holders hold is refused `409` + * naming every holder. Every other type reads the name's log either way. + */ + packageId?: string; } /** A single field-anchored spec-validation issue (server `error.details.issues`). */ @@ -2015,14 +2023,20 @@ export class MetadataClient { * `{ success, version, seq, restoredFromVersion, message }`. Throws * `404 version_not_found` for unknown versions and `409 version_not_restorable` * when the target version is a delete tombstone. + * + * `packageId` (`?package=`) names whose row a by-package name's version is + * restored into, as `history()`'s does: the version must be that holder's + * (`404` otherwise), and a bare rollback of a name two holders hold is + * refused `409` naming every holder, with no row written. */ async rollback( type: string, name: string, toVersion: number, - options: { message?: string } = {}, + options: { message?: string; packageId?: string } = {}, ): Promise { - const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/rollback`; + const qs = options.packageId ? `?package=${encodeURIComponent(options.packageId)}` : ''; + const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/rollback${qs}`; const headers: Record = { ...this.headers, 'Content-Type': 'application/json', @@ -2075,6 +2089,7 @@ export class MetadataClient { const params = new URLSearchParams(); if (options.sinceSeq !== undefined) params.set('sinceSeq', String(options.sinceSeq)); if (options.limit !== undefined) params.set('limit', String(options.limit)); + if (options.packageId) params.set('package', options.packageId); const qs = params.toString(); const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/history${qs ? `?${qs}` : ''}`; const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' }); From 8ad3a499e28178ca063c1624e3c02421ed338221 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 23:39:24 +0000 Subject: [PATCH 05/14] chore: changeset and regenerated API reference for history package address Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../32905-history-rollback-package-address.md | 28 +++++++++++++++++++ content/docs/references/api/protocol.mdx | 1 + 2 files changed, 29 insertions(+) create mode 100644 .changeset/32905-history-rollback-package-address.md diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md new file mode 100644 index 00000000000..4da57ee7ce1 --- /dev/null +++ b/.changeset/32905-history-rollback-package-address.md @@ -0,0 +1,28 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/metadata': patch +'@objectstack/metadata-core': patch +'@objectstack/spec': patch +'@object-ui/data-objectstack': patch +'@object-ui/app-shell': patch +--- + +fix(metadata-protocol)!: the history and rollback doors of a by-package name refuse the bare name two holders hold, and `?package=` addresses one holder's versions (ADR-0150 D3/D4, #32905) + +Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package, of a name whose active rows are held by two or more row slots (two packages', or a package's beside the package-less row), are refused `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, `details.candidates` naming every holder) before any row is read or written, where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. A rollback to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is, and nothing is restored. Widened: both doors accept `?package=` (the `/layers?package=` spelling), which reads or restores that holder's versions only. A name one holder holds answers bare exactly as before. +Metadata-protocol: none +Skills-docs: none — no skill or doc teaches the history or rollback door of a by-package name; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. + + + +**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, or a package's row beside the environment's). The fix: + +- FROM `GET /meta/TYPE/NAME/history` TO `GET /meta/TYPE/NAME/history?package=PKG`, once per holder the `409` names. +- FROM `POST /meta/TYPE/NAME/rollback` TO `POST /meta/TYPE/NAME/rollback?package=PKG`, with `toVersion` one of that holder's versions (its `?package=` history lists them). + +`?package=` names a holder the way the item read does: a package's own row, or its `.custom` pair's declared override of it (so a base package addresses its customization pair), else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`). `all` and the empty string name no package. For every other type, `?package=` is accepted and leaves the answer as it was. + +The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution: it is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. + +The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 4f54de75b87..bc300ecdd3b 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2037,6 +2037,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **sinceSeq** | `number` | optional | Exclusive lower bound on `seq` for pagination: only events with `seq > sinceSeq` are returned. Absent means "from the beginning". | | **limit** | `number` | optional | Maximum events to return, oldest first. Forwarded to the repository unclamped and with NO default — absent means the full remaining change log. (Deliberately no declared bounds: unlike the audit twin's [1, 500] clamp, nothing on this path clamps or refuses, so declaring `.min()`/`.max()` here would refuse values the shipped verb accepts.) | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to read: its own row's, or its `.custom` pair's declared override's (ADR-0150 D3/D4). Absent, a name two holders' rows hold is refused 409 naming every holder. Every other type reads the name's log either way. | --- From 1c1a28f9ac0f7197c2049a2f7d51c3542c6c4e3b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:25:13 +0000 Subject: [PATCH 06/14] test(ui): pay the lint load at collection in the Studio item-tools pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../studio-design/StudioDesignSurface.itemTools-28239.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx index beac73b0d0e..04813d259b1 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx @@ -20,6 +20,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches `import('@objectstack/lint')`: paid here, at collection, never inside a test's clock. +import '@objectstack/lint'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; From 06d127706a24aedfc483594a34bf9105be3c5c47 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:07:28 +0000 Subject: [PATCH 07/14] chore: declare the added request key and grade the packages that carry it minor Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../32905-history-rollback-package-address.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md index 4da57ee7ce1..c4ef9b61416 100644 --- a/.changeset/32905-history-rollback-package-address.md +++ b/.changeset/32905-history-rollback-package-address.md @@ -1,20 +1,20 @@ --- -'@objectstack/metadata-protocol': patch -'@objectstack/rest': patch -'@objectstack/metadata': patch +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/rest': minor +'@objectstack/metadata': minor +'@object-ui/data-objectstack': minor '@objectstack/metadata-core': patch -'@objectstack/spec': patch -'@object-ui/data-objectstack': patch '@object-ui/app-shell': patch --- fix(metadata-protocol)!: the history and rollback doors of a by-package name refuse the bare name two holders hold, and `?package=` addresses one holder's versions (ADR-0150 D3/D4, #32905) Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package, of a name whose active rows are held by two or more row slots (two packages', or a package's beside the package-less row), are refused `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, `details.candidates` naming every holder) before any row is read or written, where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. A rollback to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is, and nothing is restored. Widened: both doors accept `?package=` (the `/layers?package=` spelling), which reads or restores that holder's versions only. A name one holder holds answers bare exactly as before. -Metadata-protocol: none -Skills-docs: none — no skill or doc teaches the history or rollback door of a by-package name; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. +Metadata-protocol: added +Skills-docs: none — no skill under `skills/` names the history or rollback door, and the docs that do (`content/docs/api/metadata-api.mdx`, `content/docs/kernel/contracts/metadata-service.mdx`, `content/docs/plugins/adding-a-metadata-type.mdx`, `content/docs/permissions/system-context.mdx`) list the routes without teaching how a name two packages hold is addressed, so no sentence there turns false; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. - + **BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, or a package's row beside the environment's). The fix: @@ -25,4 +25,6 @@ Skills-docs: none — no skill or doc teaches the history or rollback door of a The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution: it is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. +Levels: `minor` where the package carries the added surface — `@objectstack/spec` (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`), `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`) and `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`); `patch` for `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). + The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads. From 66af6464ae878b67d4bf3b4bf40da2b747c02a47 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:30:53 +0000 Subject: [PATCH 08/14] fix(metadata-protocol): address history slots the way the plain read does Bare history and rollback now also refuse where the bare plain read refuses (a second holder in code counts), and a bare rollback of a one-slot name restores what main restores. `?package=P` addresses the slot of the row a read naming P serves, including the package-less fallback; with no stored row an uninstalled package is refused like a save naming it. `?package=` on a type not stored per package is refused 400 on both doors. The rollback request gets a spec schema. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../32905-history-rollback-package-address.md | 13 +- content/docs/references/api/protocol.mdx | 24 ++- content/docs/references/index.mdx | 10 +- .../api.md | 2 +- .../src/protocol-door-requests.ts | 12 +- .../src/protocol-history-and-publish.ts | 8 +- .../src/protocol-history-slots.test.ts | 161 ++++++++++++++++++ .../src/protocol-history-slots.ts | 104 ++++++++--- .../src/protocol-package-commits.ts | 21 ++- .../src/protocol-package-scope.ts | 9 +- packages/metadata-protocol/src/protocol.ts | 25 ++- .../src/sys-metadata-repository.ts | 29 ++-- ...story-rollback-two-holders.dogfood.test.ts | 80 ++++++++- ...meta-item-history-package-selector.test.ts | 30 +++- packages/spec/api-surface/api.json | 2 + packages/spec/authorable-surface/api.json | 6 + packages/spec/declaration-map/api.json | 2 + packages/spec/export-origins/api.json | 2 + packages/spec/json-schema.manifest/api.json | 1 + packages/spec/src/api/protocol.zod.ts | 45 ++++- 20 files changed, 500 insertions(+), 86 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-history-slots.test.ts diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md index c4ef9b61416..888614febe4 100644 --- a/.changeset/32905-history-rollback-package-address.md +++ b/.changeset/32905-history-rollback-package-address.md @@ -10,21 +10,22 @@ fix(metadata-protocol)!: the history and rollback doors of a by-package name refuse the bare name two holders hold, and `?package=` addresses one holder's versions (ADR-0150 D3/D4, #32905) -Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package, of a name whose active rows are held by two or more row slots (two packages', or a package's beside the package-less row), are refused `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, `details.candidates` naming every holder) before any row is read or written, where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. A rollback to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is, and nothing is restored. Widened: both doors accept `?package=` (the `/layers?package=` spelling), which reads or restores that holder's versions only. A name one holder holds answers bare exactly as before. +Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package are refused `409 RESOURCE_CONFLICT` before any row is read or written wherever the bare plain read refuses the name: its active rows held by two or more row slots (two packages', or a package's beside the package-less row; `ambiguous-in-environment`, `details.candidates` naming every holder), or one row held while a second package ships the name in code (the read's own refusal) — where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. An addressed rollback (`?package=`) to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is; a `?package=` naming a package that neither holds a row of the name nor ships it is refused `409` (`not-held-by-qualifier`) while another slot holds one, and `422 WRITABLE_PACKAGE_REQUIRED` while no row is stored and no such package is installed; nothing is restored. `?package=` on a type not stored per package is refused `400 VALIDATION_ERROR` on both doors (param `package`), never accepted and dropped. Widened: both doors accept `?package=` on a by-package type (the `/layers?package=` spelling), which reads or restores that holder's versions only. A name one holder holds answers bare exactly as on `main`: its whole log, and its bare rollback restores any of its versions into its row, including a version saved package-less before a package took the name over. Metadata-protocol: added Skills-docs: none — no skill under `skills/` names the history or rollback door, and the docs that do (`content/docs/api/metadata-api.mdx`, `content/docs/kernel/contracts/metadata-service.mdx`, `content/docs/plugins/adding-a-metadata-type.mdx`, `content/docs/permissions/system-context.mdx`) list the routes without teaching how a name two packages hold is addressed, so no sentence there turns false; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. - + -**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, or a package's row beside the environment's). The fix: +**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, a package's row beside the environment's, or one package's row while a second package ships the name), and for `?package=` sent to a type not stored per package. The fix: - FROM `GET /meta/TYPE/NAME/history` TO `GET /meta/TYPE/NAME/history?package=PKG`, once per holder the `409` names. - FROM `POST /meta/TYPE/NAME/rollback` TO `POST /meta/TYPE/NAME/rollback?package=PKG`, with `toVersion` one of that holder's versions (its `?package=` history lists them). +- FROM `GET /meta/TYPE/NAME/history?package=PKG` (or the rollback) on a type not stored per package TO the same request without `package`: it never narrowed that type's answer. -`?package=` names a holder the way the item read does: a package's own row, or its `.custom` pair's declared override of it (so a base package addresses its customization pair), else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`). `all` and the empty string name no package. For every other type, `?package=` is accepted and leaves the answer as it was. +`?package=` names a holder the way the item read does: the row a read naming that package serves — the package's own row, its `.custom` pair's declared override of it (so a base package addresses its customization pair), or the package-less row that read falls back to — else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`); with no row stored, a package that is not installed is refused `422` as a save naming it is. `all` and the empty string name no package. For a type not stored per package, `?package=` is refused `400`. -The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution: it is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. +The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution, and an environment-attributed version stays with a package that took the package-less row over: each is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. -Levels: `minor` where the package carries the added surface — `@objectstack/spec` (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`), `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`) and `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`); `patch` for `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). +Levels: `minor` where the package carries the added surface — `@objectstack/spec` (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`, and the new `RollbackMetaItemRequestSchema` that declares the rollback door's request with its `packageId`), `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`) and `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`); `patch` for `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index bc300ecdd3b..60be42798dd 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 143 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 144 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemResponse, RuntimeAuthoringIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -2037,7 +2037,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **sinceSeq** | `number` | optional | Exclusive lower bound on `seq` for pagination: only events with `seq > sinceSeq` are returned. Absent means "from the beginning". | | **limit** | `number` | optional | Maximum events to return, oldest first. Forwarded to the repository unclamped and with NO default — absent means the full remaining change log. (Deliberately no declared bounds: unlike the audit twin's [1, 500] clamp, nothing on this path clamps or refuses, so declaring `.min()`/`.max()` here would refuse values the shipped verb accepts.) | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to read: its own row's, or its `.custom` pair's declared override's (ADR-0150 D3/D4). Absent, a name two holders' rows hold is refused 409 naming every holder. Every other type reads the name's log either way. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | --- @@ -2815,6 +2815,22 @@ Answer to a device registration: the device id the client keeps | **id** | `string` | ✅ | The rejected action id | +--- + +## RollbackMetaItemRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type name | +| **name** | `string` | ✅ | Item name | +| **toVersion** | `number` | ✅ | The history version whose body is restored as the new live row. | +| **message** | `string` | optional | Rollback note, recorded on the new history row. | +| **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | + + --- ## RollbackMetaItemResponse diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 7161e90a222..00bb26d3cc6 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1661 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1662 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -21,7 +21,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 36 | 492 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 36 | 493 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 81 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 186 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 176 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1661** | 14 protocol modules | +| **Total** | **218** | **1662** | 14 protocol modules | --- @@ -65,7 +65,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **36 pages, 492 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **36 pages, 493 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -94,7 +94,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`package-api-assembled.zod.ts`](/docs/references/api/package-api-assembled) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | | [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](/docs/references/api/plugin-rest-api) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | -| [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | +| [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](/docs/references/api/push-delivery) | `PushDeliveryData`, `PushRoute` | | [`push-relay.zod.ts`](/docs/references/api/push-relay) | `PushRelayDelivery`, `PushRelayError`, `PushRelayErrorResponse`, `PushRelayPayload`, `PushRelayPriority`, `PushRelayRequest`, `PushRelayResponse`, `PushRelayResult`, `PushRelayResultStatus` | | [`query-adapter.zod.ts`](/docs/references/api/query-adapter) | `ODataQueryAdapter`, `OperatorMapping`, `QueryAdapterConfig`, `QueryAdapterTarget`, `RestQueryAdapter` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index 443ad298405..a764782fbf3 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 506 | +| `api/` | 507 | diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 6141d373dde..68f65dadc65 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -104,10 +104,14 @@ type RollbackMetaItemRequest = { /** * [ADR-0150 D3/D4, #32905] The package whose row this rollback restores, * as the `/layers` read names its package (`?package=` on the REST door). - * Read for a type stored per `(package, name)` only: its own row, or its - * `.custom` pair's declared override; the version must be that - * holder's. Absent, a name two row slots hold is refused `409` naming - * every holder, before anything is written. + * Read for a type stored per `(package, name)` only (refused `400` on + * any other type): its own row, its `.custom` pair's declared override, + * or the package-less row its read falls back to; the version must be + * that holder's — one attributed to no package, or to the environment, + * only while it is the name's sole slot. Absent, a name two row slots + * hold, or one the bare plain read refuses, is refused `409` naming every + * holder, before anything is written; a name one holder holds restores + * any of its versions, as before. */ packageId?: string; }; diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index e882e05f050..8e76387a999 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -63,7 +63,7 @@ import { isBatchObjectType, judgeBatchObjectRegistrations, registerAdmittedBatch import { engineCanRollBack } from '@objectstack/core'; import type { SysMetadataRepository } from './sys-metadata-repository.js'; import type { HistoryVersionOwner } from './sys-metadata-repository.js'; -import { historySlotOf } from './protocol-history-slots.js'; +import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; import { captureStoredExpressionChange, fillStoredExpressionChange, type StoredExpressionFillCapture } from './protocol-stored-expression-fill.js'; /** @@ -194,7 +194,7 @@ async function undoLandedPromotions(host: Pick, request: { + static async historyMetaItem(host: Pick, request: { type: string; name: string; sinceSeq?: number; @@ -244,6 +244,10 @@ export class ProtocolHistoryAndPublishFacet { const member = resolveBundleMemberSelector(request.type, request.member); // Canonical by construction from the fold above — NOT a second fold. const singularType = request.type; + // [#32905] `?package=` addresses a holder of a type stored per + // `(package, name)` only; on any other type it is refused, before the + // early answer below, never accepted and dropped. + refusePackageSelectorOutsideSlottedTypes(singularType, request.packageId); if (!host.isOverlayAllowed(singularType) && !host.isRuntimeCreateAllowed(singularType)) { return { events: [] }; diff --git a/packages/metadata-protocol/src/protocol-history-slots.test.ts b/packages/metadata-protocol/src/protocol-history-slots.test.ts new file mode 100644 index 00000000000..7e75ed94a10 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-history-slots.test.ts @@ -0,0 +1,161 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3/D4/D5] Which row slot the history and rollback doors address + * (`historySlotOf`), judged against a fake host so each arm is pinned on its + * own: the served row's slot for `?package=P` (P's own, or the package-less + * row the read falls back to, whether or not P ships the name), the bare + * plain read's refusal counting holders in code, `?package=` refused on a + * type not stored per package, and whether the addressed slot holds a row. + */ + +import { describe, expect, it } from 'vitest'; +import { PackageScopedNameRefusedError, packageScopedRefusalMessage } from '@objectstack/core'; +import { historySlotOf } from './protocol-history-slots.js'; + +interface FakeOptions { + candidates?: string[]; + unbound?: boolean; + /** The row `findServedOverlayRow` serves for `?package=`; `undefined` serves none. */ + served?: { package_id?: string | null } | undefined; + shippers?: string[]; + /** What the registry's `resolveItem` does for a bare read. */ + resolve?: () => unknown; +} + +function fakeHost(options: FakeOptions) { + return { + engine: { + registry: { + readsByPackage: () => true, + resolveItem: options.resolve ?? (() => ({ status: 'resolved' })), + }, + }, + packagelessAddress: async () => ({ + candidates: options.candidates ?? [], + unbound: options.unbound ?? false, + }), + findServedOverlayRow: async () => (options.served === undefined ? undefined : { row: options.served }), + shippedArtifactsOf: () => (options.shippers ?? []).map((id) => ({ _packageId: id })), + } as any; +} + +function twoShipperRefusal(): PackageScopedNameRefusedError { + const base = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: 'flow' as any, + name: 'n', + callerPackageId: null, + candidates: [ + { kind: 'package' as const, packageId: 'com.a' }, + { kind: 'package' as const, packageId: 'com.b' }, + ], + }; + return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); +} + +describe('historySlotOf: ?package=P addresses the slot of the row a read naming P serves', () => { + it('P ships the name and the read falls back to the package-less row: the environment slot', async () => { + const slot = await historySlotOf( + fakeHost({ unbound: true, served: { package_id: null }, shippers: ['com.a'] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ); + expect(slot).toEqual({ owner: { packageId: null, sole: true }, addressed: true, held: true }); + }); + + it('P does not ship the name and the read falls back to the package-less row: the environment slot', async () => { + const slot = await historySlotOf( + fakeHost({ unbound: true, served: { package_id: null }, shippers: [] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ); + expect(slot).toEqual({ owner: { packageId: null, sole: true }, addressed: true, held: true }); + }); + + it("P's own row: P's slot, not sole beside the package-less row", async () => { + const slot = await historySlotOf( + fakeHost({ candidates: ['com.a'], unbound: true, served: { package_id: 'com.a' } }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ); + expect(slot).toEqual({ owner: { packageId: 'com.a', sole: false }, addressed: true, held: true }); + }); + + it('P ships the name and holds no row while another package does: P\'s own empty slot', async () => { + const slot = await historySlotOf( + fakeHost({ candidates: ['com.b'], served: undefined, shippers: ['com.a', 'com.b'] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ); + expect(slot).toEqual({ owner: { packageId: 'com.a', sole: false }, addressed: true, held: false }); + }); + + it('no row of the name is stored at all: P\'s slot, held by nothing', async () => { + const slot = await historySlotOf( + fakeHost({ served: undefined }), + { type: 'flow', name: 'n', packageId: 'com.nope' }, + ); + expect(slot).toEqual({ owner: { packageId: 'com.nope', sole: true }, addressed: true, held: false }); + }); + + it('a package that neither holds nor ships the name, while another holds it: refused not-held-by-qualifier', async () => { + const refused = await historySlotOf( + fakeHost({ candidates: ['com.b'], served: undefined, shippers: ['com.b'] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ).catch((error) => error); + expect(refused).toBeInstanceOf(PackageScopedNameRefusedError); + expect(refused.refusal.reason).toBe('not-held-by-qualifier'); + expect(refused.refusal.candidates).toEqual([{ kind: 'package', packageId: 'com.b' }]); + }); +}); + +describe('historySlotOf: naming no package', () => { + it('two row slots: refused ambiguous-in-environment naming both', async () => { + const refused = await historySlotOf( + fakeHost({ candidates: ['com.a'], unbound: true }), + { type: 'flow', name: 'n' }, + ).catch((error) => error); + expect(refused).toBeInstanceOf(PackageScopedNameRefusedError); + expect(refused.refusal.reason).toBe('ambiguous-in-environment'); + expect(refused.refusal.candidates).toEqual([ + { kind: 'package', packageId: 'com.a' }, + { kind: 'environment' }, + ]); + }); + + it('one row slot the bare plain read refuses (a second holder in code): the read\'s own refusal', async () => { + const thrown = twoShipperRefusal(); + const refused = await historySlotOf( + fakeHost({ candidates: ['com.a'], resolve: () => { throw thrown; } }), + { type: 'flow', name: 'n' }, + ).catch((error) => error); + expect(refused).toBe(thrown); + }); + + it('a resolver failure that is not a package-scoped refusal leaves the door to its row slots', async () => { + const slot = await historySlotOf( + fakeHost({ candidates: ['com.a'], resolve: () => { throw new Error('not found'); } }), + { type: 'flow', name: 'n' }, + ); + expect(slot).toEqual({ owner: { packageId: 'com.a', sole: true }, addressed: false, held: true }); + }); + + it('CONTROL: one row slot the bare read serves answers that slot as sole', async () => { + const slot = await historySlotOf(fakeHost({ unbound: true }), { type: 'flow', name: 'n' }); + expect(slot).toEqual({ owner: { packageId: null, sole: true }, addressed: false, held: true }); + }); + + it('CONTROL: no row slot answers nothing (the door answers as before)', async () => { + expect(await historySlotOf(fakeHost({}), { type: 'flow', name: 'n' })).toBeUndefined(); + }); +}); + +describe('historySlotOf: a type not stored per package', () => { + it('?package= is refused 400 VALIDATION_ERROR on param "package"', async () => { + const refused = await historySlotOf(fakeHost({}), { type: 'view', name: 'n', packageId: 'com.a' }) + .catch((error) => error); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, param: 'package' }); + }); + + it('CONTROL: named bare it answers nothing', async () => { + expect(await historySlotOf(fakeHost({}), { type: 'view', name: 'n' })).toBeUndefined(); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-history-slots.ts b/packages/metadata-protocol/src/protocol-history-slots.ts index 1f53552e35c..7c993c51b6b 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.ts @@ -17,24 +17,32 @@ * by more than one row slot — two packages', or a package's beside the * package-less row — is refused `409` naming every holder * (`ambiguous-in-environment`), before any row is read or written: nothing - * picks one (ADR-0150 D3, epic red line 2). A name one slot holds, or none, - * answers as before; + * picks one (ADR-0150 D3, epic red line 2). So is a name the bare plain + * read refuses (ADR-0150 D5: a holder in code counts, so two packages + * shipping the name are two holders while only one has saved a row): the + * registry's resolver (`resolveItem`, the one the plain read asks) throws + * that read's own refusal, naming its holders. A name one holder holds, or + * none, answers as on `main`: its whole log, and its bare rollback + * restores any of its versions; * - **naming package `P`** (`?package=P`, the `/layers?package=` spelling): - * the slot of the row a read naming `P` serves — `P`'s own row, or its - * `.custom` pair's declared override of `P` (ADR-0146 D2) — else `P`'s own - * slot when `P` ships the name in code and holds no row of it yet. A - * package that neither holds a row of the name nor ships it is refused - * `409` naming every holder (`not-held-by-qualifier`). + * the slot of the row a read naming `P` serves — `P`'s own row, its + * `.custom` pair's declared override of `P` (ADR-0146 D2), or the + * package-less row that read falls back to — else `P`'s own slot when `P` + * ships the name in code and holds no row of it yet. A package that + * neither holds a row of the name nor ships it is refused `409` naming + * every holder (`not-held-by-qualifier`). * * A version belongs to a slot by its history row's attribution * (`historyRowAttribution`, `@objectstack/metadata`). A version attributed to * no package (recorded before `sys_metadata_history.package_id` was written - * for this store) belongs to a slot only while the name has no other slot: - * with two holders nothing says whose it is, so it is never guessed. + * for this store), or to the environment (M1: a package took over the + * package-less row, or saved after it was removed), belongs to a slot only + * while the name has no other slot: with two holders nothing says whose it + * is, so it is never guessed. * - * Every other type is not addressed here, and `?package=` leaves its doors' - * answers as they were (as `admitEnvironmentQualifier` keeps the bare read for - * the types ADR-0150 does not address). + * Every other type is not addressed by package on these doors: `?package=` is + * refused `400 VALIDATION_ERROR` there, as `?member=` is on a type with no + * members, never accepted and dropped (route rule 5). */ import { @@ -45,6 +53,7 @@ import { type PackageScopedResolvableType, } from '@objectstack/core'; import { PACKAGE_SLOTTED_STORE_TYPES } from '@objectstack/metadata'; +import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; import type { ProtocolHost } from './protocol-host.js'; import { memberOption } from './protocol-bundle-members.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; @@ -56,6 +65,8 @@ export interface HistorySlot { readonly owner: HistoryVersionOwner; /** Whether the request named the package (`?package=`). */ readonly addressed: boolean; + /** Whether the addressed slot holds a stored active row of the name. */ + readonly held: boolean; } /** The name's row slots: each bound package, sorted, then the package-less row (`null`). */ @@ -93,41 +104,88 @@ function slotRefusal( return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); } +/** + * `?package=` on a type these doors do not address by package: refused, as + * `?member=` is on a type with no members, never accepted and dropped. Asked + * by both doors before any other gate, so the answer does not depend on + * which of their early returns the type meets first. + */ +export function refusePackageSelectorOutsideSlottedTypes(type: string, packageId: string | undefined): void { + if (packageId !== undefined && !PACKAGE_SLOTTED_STORE_TYPES.has(type)) throw packageSelectorRefusal(type); +} + +function packageSelectorRefusal(type: string): Error { + const err = new Error( + `The "package" selector names one holder of a name stored per package, and a '${type}' item is not ` + + 'stored per package: its history is the name\'s alone. Drop "package" from the request.', + ) as Error & { code: 'VALIDATION_ERROR'; status: 400; param: string }; + err.code = 'VALIDATION_ERROR'; + err.status = 400; + err.param = 'package'; + return err; +} + +/** + * [ADR-0150 D5] The bare plain read's own judgement of a name: the registry's + * package-scoped resolver, which counts a holder in code as one. Its refusal + * (a name two packages hold) is thrown as the read throws it; any other + * answer, or a registry that does not read the type by package, leaves the + * door to its row slots. + */ +function refuseWhereBareReadRefuses(host: Pick, type: string, name: string, member: string | undefined): void { + const registry: any = host.engine?.registry; + if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(type) !== true) return; + if (typeof registry.resolveItem !== 'function') return; + try { + registry.resolveItem(type, name, null, member); + } catch (error) { + if (packageScopedRefusalOf(error) !== undefined) throw error; + } +} + /** * The row slot a history or rollback request of `(type, name)` addresses — * see the module header. `type` is the canonical type key and `member` the * resolved bundle member. * - * @returns `undefined` for a type not stored per `(package, name)`, and for a - * bare request of a name no row holds: the door answers as before. + * @returns `undefined` for a type not stored per `(package, name)` named + * bare, and for a bare request of a name no row holds: the door answers as + * before. + * @throws a `400 VALIDATION_ERROR` for `?package=` on a type not stored per + * `(package, name)`. * @throws {PackageScopedNameRefusedError} `ambiguous-in-environment` for a - * bare request of a name two or more row slots hold; `not-held-by-qualifier` - * for a package that neither holds a row of the name nor ships it, while - * another slot holds one. + * bare request of a name two or more row slots hold, or the bare plain + * read's own refusal; `not-held-by-qualifier` for a package that neither + * holds a row of the name nor ships it, while another slot holds one. */ export async function historySlotOf( - host: Pick, + host: Pick, request: { type: string; name: string; member?: string; packageId?: string }, ): Promise { const { type, name, member, packageId } = request; + refusePackageSelectorOutsideSlottedTypes(type, packageId); if (!PACKAGE_SLOTTED_STORE_TYPES.has(type)) return undefined; const slots = await rowSlotsOf(host, type, name, member); if (packageId === undefined) { if (slots.length > 1) throw slotRefusal(type, name, 'ambiguous-in-environment', null, slots); + refuseWhereBareReadRefuses(host, type, name, member); if (slots.length === 0) return undefined; - return { owner: { packageId: slots[0] ?? null, unattributed: true }, addressed: false }; + return { owner: { packageId: slots[0] ?? null, sole: true }, addressed: false, held: true }; } - // The row a read naming `P` serves: its own, or its pair's declared - // override. The package-less fallback of that read is not `P`'s slot. + // The row a read naming `P` serves: its own, its pair's declared + // override, or the package-less row it falls back to (`null`, the + // environment's slot). const served = await host.findServedOverlayRow({ type, name, state: 'active', packageId, ...memberOption(member), servedOverride: true, }); const binding = (served?.row as { package_id?: unknown } | undefined)?.package_id; - const slot = typeof binding === 'string' && binding !== '' ? binding : packageId; + const slot: string | null = served === undefined + ? packageId + : typeof binding === 'string' && binding !== '' ? binding : null; if (!slots.includes(slot) && slots.length > 0 && !shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member)).has(packageId)) { throw slotRefusal(type, name, 'not-held-by-qualifier', packageId, slots); } const sole = slots.length === 0 || (slots.length === 1 && slots[0] === slot); - return { owner: { packageId: slot, unattributed: sole }, addressed: true }; + return { owner: { packageId: slot, sole }, addressed: true, held: slots.includes(slot) }; } diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 98a7320a198..0d39eca8799 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -89,7 +89,7 @@ import { } from './protocol-client-failures.js'; import { isNonCanonicalStoredType } from './protocol-stored-overlay-types.js'; import type { RollbackMetaItemRequest } from './protocol-door-requests.js'; -import { historySlotOf } from './protocol-history-slots.js'; +import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; import { withRefusalAudit } from './protocol-refusal-audit.js'; import type { ProtocolHost } from './protocol-host.js'; import type { ImportUnmanagedPackageAnswer, InstallPackageStoredRowHook, StoredPackageRow } from './protocol-package-install.js'; @@ -1877,7 +1877,7 @@ export class ProtocolPackageCommitsFacet { } /** [#28355] The body of {@link rollbackMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ + static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ success: boolean; version: string; seq: number; @@ -1954,6 +1954,10 @@ export class ProtocolPackageCommitsFacet { // stored under" — the same shape {@link deleteMetaItem} keeps for // `singularTypeForRepo`. const singularType = request.type; + // [#32905] `?package=` addresses a holder of a type stored per + // `(package, name)` only; on any other type it is refused first, + // never accepted and dropped ({@link historySlotOf}). + refusePackageSelectorOutsideSlottedTypes(singularType, request.packageId); if (!host.isOverlayAllowed(singularType) && !host.isRuntimeCreateAllowed(singularType)) { const err: any = new Error( @@ -2025,6 +2029,17 @@ export class ProtocolPackageCommitsFacet { let rollbackPackageId: string | null; if (slot?.addressed) { rollbackPackageId = slot.owner.packageId; + // [#32905] A slot no stored row holds is the package's own (it + // ships the name, or no row of the name is stored at all): never + // minted for an id no installed package has, as the save door + // refuses one ({@link uninstalledNamedBaseRefusal}). + if (!slot.held) { + const unbound = host.uninstalledNamedBaseRefusal( + { type: singularType, name: request.name, packageId: rollbackPackageId }, + { verb: 'rollback' }, + ); + if (unbound) throw unbound; + } } else { const servedPackage = await host.packagelessReadAddress(singularType, request.name, member); const served = await host.findServedOverlayRow({ @@ -2098,7 +2113,7 @@ export class ProtocolPackageCommitsFacet { // package's row of the name: its parent hash, and the write. packageId: rollbackPackageId, // [#32905] …and only a version of that row's slot. - ...(slot ? { versionOf: { packageId: rollbackPackageId, unattributed: slot.owner.unattributed } } : {}), + ...(slot?.addressed ? { versionOf: slot.owner } : {}), }); // #4521 — a rollback is a live write like any other: the restored // body must be the one the runtime dispatches on immediately, not diff --git a/packages/metadata-protocol/src/protocol-package-scope.ts b/packages/metadata-protocol/src/protocol-package-scope.ts index 9765fb15ec1..503bf636975 100644 --- a/packages/metadata-protocol/src/protocol-package-scope.ts +++ b/packages/metadata-protocol/src/protocol-package-scope.ts @@ -102,7 +102,7 @@ export async function resolveAppPackageIdKey, request: { type: string; name: string; packageId?: string | null }, - how: { verb?: 'save' | 'publish'; inherited?: boolean } = {}, + how: { verb?: 'save' | 'publish' | 'rollback'; inherited?: boolean } = {}, ): Error | null { const namedBase = request.packageId; if (!namedBase || namedBase === 'sys_metadata') return null; @@ -114,7 +114,12 @@ export function uninstalledNamedBaseRefusal( + `that package; discard-drafts for drafts) and save again, into an installed writable package or with ` + `no package.`; const err = new Error( - how.verb === 'publish' + how.verb === 'rollback' + ? `Cannot roll back ${type} '${request.name}' into package '${namedBase}': no row of it is stored ` + + `under that package and no package with that id is installed in this deployment, so the restored ` + + `${type} would be stored bound to a package that does not exist. Name an installed package that ` + + `holds or ships the ${type} (its history lists its versions). Nothing was restored.` + : how.verb === 'publish' ? `Cannot publish ${type} '${request.name}' into package '${namedBase}': no package with that id ` + `is installed in this deployment, so the ${type} would go live bound to a package that does ` + `not exist. ${storedWayOut} Nothing was published.` diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 99c2ee55036..25caaabfe4a 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -6865,7 +6865,7 @@ export class ObjectStackProtocolImplementation implements */ private uninstalledNamedBaseRefusal( request: { type: string; name: string; packageId?: string | null }, - how: { verb?: 'save' | 'publish'; inherited?: boolean } = {}, + how: { verb?: 'save' | 'publish' | 'rollback'; inherited?: boolean } = {}, ): Error | null { // [#25467 cut 33] The body moved to `protocol-package-scope.ts` (see `PackageScopeHost`). const host: ThisParameterType = { @@ -9509,9 +9509,12 @@ export class ObjectStackProtocolImplementation implements * on a control-plane kernel — appends no `sys_metadata_history` row. * * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a - * name two row slots hold is refused `409` naming every holder when no - * package is named, and `packageId` reads that holder's versions alone - * (`protocol-history-slots.ts`); a name one slot holds reads as before. + * name two row slots hold, or one the bare plain read refuses, is refused + * `409` naming every holder when no package is named, and `packageId` + * reads that holder's versions alone: its own, plus those attributed to + * no package or to the environment while it is the name's only slot + * (`protocol-history-slots.ts`). A name one holder holds reads as before. + * `packageId` on any other type is refused `400 VALIDATION_ERROR`. */ async historyMetaItem(request: { type: string; @@ -10904,10 +10907,16 @@ export class ObjectStackProtocolImplementation implements * * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a * name two row slots hold is refused `409` naming every holder when no - * package is named, with nothing written; `packageId` restores into that - * holder's row (its own, or its pair's declared override), and the - * version must be that holder's: another holder's answers 404 - * `VERSION_NOT_FOUND` (`protocol-history-slots.ts`). + * package is named, with nothing written (so is a name the bare plain + * read refuses); `packageId` restores into that holder's row (its own, + * its pair's declared override, or the package-less row its read falls + * back to), and the version must be that holder's: another holder's, or + * one attributed to no package or to the environment while another slot + * holds the name, answers 404 `VERSION_NOT_FOUND`. A name one holder + * holds, named bare, restores any of its versions as before. + * `packageId` on any other type is refused `400 VALIDATION_ERROR`, and + * one naming no installed package where no row is stored is refused + * `422 WRITABLE_PACKAGE_REQUIRED` (`protocol-history-slots.ts`). * * [#32700] Then, as the save door does: the restored object's storage is * synced, and every stored computed field the restore makes compute diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 5e9ca3f9e43..74759d91d7d 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -576,20 +576,23 @@ function historySnapshotPackageColumn( /** * [ADR-0150 D3/D4, #32905] Whose versions a history read serves, or whose * version a restore may write: the row slot `packageId` names (`null`: the - * package-less row), and whether a version attributed to no package - * (recorded before the column was written) is that slot's too — only when - * the name has no other row slot, so an unattributed version is never + * package-less row), and whether that slot is the name's only one (`sole`). + * A sole slot's versions include those attributed to no package (recorded + * before the column was written) and the environment's own (M1, as + * `DatabaseLoader.rollbackSlot` keeps it: a package took over the + * package-less row, or saved after it was removed), so neither is ever * guessed onto one of several holders. */ export interface HistoryVersionOwner { packageId: string | null; - unattributed: boolean; + sole: boolean; } /** [#32905] Whether history row `row` is a version of `owner`'s slot. */ function isVersionOf(row: Record, owner: HistoryVersionOwner): boolean { const attributed = historyRowAttribution(row); - return attributed === undefined ? owner.unattributed : attributed === owner.packageId; + if (attributed === undefined) return owner.sole; + return attributed === owner.packageId || (attributed === null && owner.sole); } /** @@ -1755,9 +1758,10 @@ export class SysMetadataRepository implements MetadataRepository { /** * [ADR-0150 D3/D4, #32905] The row slot whose version `targetVersion` * must be: a version attributed to another package (or to the - * environment, for a package's slot) answers 404 `VERSION_NOT_FOUND`, - * as another member's does, and an unattributed one is restored only - * where {@link HistoryVersionOwner.unattributed} admits it — ⛔ never + * environment, for a package's slot the name shares) answers 404 + * `VERSION_NOT_FOUND`, as another member's does; an unattributed one, + * or the environment's, is restored only into the name's sole slot + * ({@link HistoryVersionOwner.sole}) — ⛔ never * another holder's version written into this slot's row. Omitted → any * version of the name, as before. */ @@ -1835,9 +1839,12 @@ export class SysMetadataRepository implements MetadataRepository { // One read supplies both facts, exactly as {@link promoteDraft} does, so // the row the lock is taken on is by construction the row that is written. // A missing active row (deleted, or never published) yields `null` — the - // unbound row, which is the only defined answer: `sys_metadata_history` - // carries no `package_id` column, so a vanished binding is not recoverable. - // [#29414] …under the package the caller names, when it names one. + // unbound row, which is the only defined answer here: a history row + // records its slot's package (`package_id`, #32905) only for a type + // stored per `(package, name)`, and only since that change, so this read + // does not recover a vanished binding from it. [#29414] …under the + // package the caller names, when it names one (the rollback door names + // the addressed slot's for those types). const activeRow = await this.findEnvironmentRow({ where: this.whereFor(ref, 'active', 'packageId' in opts ? (opts.packageId ?? null) : undefined, member), context: { isSystem: true }, diff --git a/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts index eda79923c15..ef59626d48f 100644 --- a/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts +++ b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts @@ -23,7 +23,14 @@ // - a version recorded before the history row named its package is never // guessed onto one of two holders: no address lists or restores it; // - CONTROL: a name one package holds keeps its whole log and its rollback -// bare, an unattributed version included. +// bare, an unattributed version included, and so does a name first saved +// as the environment's own item and later under a package (M1): its bare +// rollback restores the environment's versions as `main` does; +// - a name two packages ship, one of them customized, is two holders to the +// bare doors as it is to the bare plain read (ADR-0150 D5); +// - `?package=` on a type not stored per package is refused 400, never +// accepted and dropped; and a rollback naming no installed package, of a +// name no row holds, is refused rather than minting a row for it. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; @@ -43,6 +50,12 @@ const SHARED = 'qa_hist_shared_32905'; const SHIPPED = 'qa_hist_shipped_32905'; /** A runtime flow only alpha's pair holds: the CONTROL. */ const SOLO = 'qa_hist_solo_32905'; +/** A flow both packages ship, only alpha's pair customizes. */ +const SHIPPED_ONE = 'qa_hist_shipped_one_32905'; +/** A runtime flow saved as the environment's own item, deleted, then saved in alpha's pair (M1). */ +const TAKEN_OVER = 'qa_hist_taken_over_32905'; +/** A runtime flow alpha's pair saved and then deleted: no row holds it. */ +const GONE = 'qa_hist_gone_32905'; const flowBody = (name: string, label: string) => ({ name, label, type: 'autolaunched', status: 'active', @@ -53,7 +66,7 @@ const flowBody = (name: string, label: string) => ({ function holderPackage(p: 'alpha' | 'beta') { return defineStack({ manifest: { id: `com.qa.hist32905.${p}`, namespace: `h32905${p}`, name: `qa_hist32905_${p}`, version: '1.0.0', type: 'app' }, - flows: [flowBody(SHIPPED, `${p} shipped`)], + flows: [flowBody(SHIPPED, `${p} shipped`), flowBody(SHIPPED_ONE, `${p} shipped one`)], } as never); } @@ -68,8 +81,8 @@ describe('the /meta history and rollback doors of a flow name two packages hold const codeOf = (json: any) => (json?.error && typeof json.error === 'object' ? json.error.code : undefined) ?? json?.code; const versions = (json: any): number[] => (json?.events ?? []).map((e: any) => e.version); const labelAt = async (name: string, pkg: string) => (await call('GET', `/meta/flow/${name}?package=${pkg}`)).json?.item?.label; - const save = async (name: string, pkg: string, label: string, overrides?: string) => { - const res = await call('PUT', `/meta/flow/${name}?package=${pkg}`, + const save = async (name: string, pkg: string | undefined, label: string, overrides?: string) => { + const res = await call('PUT', `/meta/flow/${name}${pkg ? `?package=${pkg}` : ''}`, { ...flowBody(name, label), ...(overrides ? { overrides: { package: overrides, basedOn: '1.0.0' } } : {}) }); expect(res.status, JSON.stringify(res.json)).toBe(200); return res.json.seq as number; @@ -99,6 +112,16 @@ describe('the /meta history and rollback doors of a flow name two packages hold await save(SHIPPED, ALPHA_PAIR, 'alpha custom r2', ALPHA); await save(SOLO, ALPHA_PAIR, 'solo r1'); await save(SOLO, ALPHA_PAIR, 'solo r2'); + await save(SHIPPED_ONE, ALPHA_PAIR, 'alpha one r1', ALPHA); + await save(SHIPPED_ONE, ALPHA_PAIR, 'alpha one r2', ALPHA); + await save(TAKEN_OVER, undefined, 'env r1'); + await save(TAKEN_OVER, undefined, 'env r2'); + const dropped = await call('DELETE', `/meta/flow/${TAKEN_OVER}`); + expect(dropped.status, JSON.stringify(dropped.json)).toBe(200); + await save(TAKEN_OVER, ALPHA_PAIR, 'alpha took over'); + await save(GONE, ALPHA_PAIR, 'gone r1'); + const gone = await call('DELETE', `/meta/flow/${GONE}?package=${ALPHA_PAIR}`); + expect(gone.status, JSON.stringify(gone.json)).toBe(200); // A version of SHARED recorded before the history row named its package // (a release before this card): `package_id` left NULL. const ql: any = await stack.kernel.getServiceAsync('objectql'); @@ -184,6 +207,55 @@ describe('the /meta history and rollback doors of a flow name two packages hold expect(await labelAt(SHARED, ALPHA_PAIR)).toBe(`${ALPHA_PAIR} r1`); }); + it('a name two packages ship, only one customized, is refused bare at both doors, as the bare plain read refuses it', async () => { + const read = await call('GET', `/meta/flow/${SHIPPED_ONE}`); + expect(read.status, JSON.stringify(read.json)).toBe(409); + const history = await call('GET', `/meta/flow/${SHIPPED_ONE}/history`); + expect(history.status, JSON.stringify(history.json)).toBe(409); + expect(codeOf(history.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(history.json)).toEqual(candidatesOf(read.json)); + const own = versions((await call('GET', `/meta/flow/${SHIPPED_ONE}/history?package=${ALPHA_PAIR}`)).json); + expect(own).toHaveLength(2); + const rollback = await call('POST', `/meta/flow/${SHIPPED_ONE}/rollback`, { toVersion: own[0]! }); + expect(rollback.status, JSON.stringify(rollback.json)).toBe(409); + expect(codeOf(rollback.json)).toBe('RESOURCE_CONFLICT'); + expect(await labelAt(SHIPPED_ONE, ALPHA_PAIR)).toBe('alpha one r2'); + }); + + it('?package= on a type not stored per package is refused 400 at both doors, never accepted and dropped', async () => { + const history = await call('GET', `/meta/view/qa_hist_any_view/history?package=${ALPHA}`); + expect(history.status, JSON.stringify(history.json)).toBe(400); + expect(codeOf(history.json)).toBe('VALIDATION_ERROR'); + const rollback = await call('POST', `/meta/view/qa_hist_any_view/rollback?package=${ALPHA}`, { toVersion: 1 }); + expect(rollback.status, JSON.stringify(rollback.json)).toBe(400); + expect(codeOf(rollback.json)).toBe('VALIDATION_ERROR'); + }); + + it('a rollback naming no installed package, of a name no row holds, is refused and stores nothing; an installed holder restores', async () => { + const [first] = versions((await call('GET', `/meta/flow/${GONE}/history`)).json); + expect(first, 'the deleted name keeps its log').toBeTypeOf('number'); + const stray = await call('POST', `/meta/flow/${GONE}/rollback?package=com.qa.hist32905.nope`, { toVersion: first! }); + expect(stray.status, JSON.stringify(stray.json)).toBe(422); + expect(codeOf(stray.json)).toBe('WRITABLE_PACKAGE_REQUIRED'); + expect((await call('GET', `/meta/flow/${GONE}?package=com.qa.hist32905.nope`)).status).not.toBe(200); + const own = await call('POST', `/meta/flow/${GONE}/rollback?package=${ALPHA_PAIR}`, { toVersion: first! }); + expect(own.status, JSON.stringify(own.json)).toBe(200); + expect(await labelAt(GONE, ALPHA_PAIR)).toBe('gone r1'); + }); + + it('CONTROL (M1): a name the environment saved and a package took over restores the environment\'s versions, bare and addressed, as before', async () => { + const bare = versions((await call('GET', `/meta/flow/${TAKEN_OVER}/history`)).json); + const [envFirst, envSecond] = bare; + expect(bare.length, JSON.stringify(bare)).toBeGreaterThanOrEqual(3); + const res = await call('POST', `/meta/flow/${TAKEN_OVER}/rollback`, { toVersion: envFirst! }); + expect(res.status, JSON.stringify(res.json)).toBe(200); + expect(await labelAt(TAKEN_OVER, ALPHA_PAIR)).toBe('env r1'); + expect(versions((await call('GET', `/meta/flow/${TAKEN_OVER}/history?package=${ALPHA_PAIR}`)).json)).toContain(envSecond); + const addressed = await call('POST', `/meta/flow/${TAKEN_OVER}/rollback?package=${ALPHA_PAIR}`, { toVersion: envSecond! }); + expect(addressed.status, JSON.stringify(addressed.json)).toBe(200); + expect(await labelAt(TAKEN_OVER, ALPHA_PAIR)).toBe('env r2'); + }); + it('CONTROL: a name one package holds keeps its whole log and its bare rollback, as before', async () => { const bare = versions((await call('GET', `/meta/flow/${SOLO}/history`)).json); expect(bare).toHaveLength(2); diff --git a/packages/rest/src/meta-item-history-package-selector.test.ts b/packages/rest/src/meta-item-history-package-selector.test.ts index 29aa159671c..fc651a0ae1d 100644 --- a/packages/rest/src/meta-item-history-package-selector.test.ts +++ b/packages/rest/src/meta-item-history-package-selector.test.ts @@ -13,13 +13,16 @@ * the `all`/empty spellings `/layers` folds to "no package" send none; * - REFUSAL: a repeated `?package=` is a located 400 and the protocol is never * called; the protocol's package-scoped refusal is rendered `409` with - * `details.candidates` naming every holder, as the plain read renders it. + * `details.candidates` naming every holder, as the plain read renders it; + * and, through the real protocol, `?package=` on a type not stored per + * package is a 400 naming the parameter, never accepted and dropped. */ import { describe, it, expect, vi } from 'vitest'; // The route modules load ObjectQL lazily; pay that load at collection, never in a clocked case. import '@objectstack/objectql'; import { PackageScopedNameRefusedError, packageScopedRefusalMessage, type PackageScopedRefusal } from '@objectstack/core'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { RestServer, META_ITEM_HISTORY_PARAMS, META_ITEM_ROLLBACK_PARAMS } from './rest-server.js'; const ITEM = '/api/v1/meta/:type/:name'; @@ -53,7 +56,7 @@ function twoHolderRefusal(): PackageScopedNameRefusedError { return new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); } -function boot(options: { refuse?: boolean } = {}) { +function boot(options: { refuse?: boolean; real?: boolean } = {}) { const answer = (value: unknown) => vi.fn(() => (options.refuse ? Promise.reject(twoHolderRefusal()) : Promise.resolve(value))); const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), @@ -63,22 +66,27 @@ function boot(options: { refuse?: boolean } = {}) { historyMetaItem: answer({ events: [] }), rollbackMetaItem: answer({ success: true, version: 'v', seq: 2, restoredFromVersion: 1 }), }; + // The real protocol judges the selector; only the plain read the history + // door asks first (its read-refusal gate) is answered by the stub. + const served = options.real + ? Object.assign(new ObjectStackProtocolImplementation({} as any), { getMetaItem: protocol.getMetaItem }) + : protocol; const server = { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), }; - const rest = new RestServer(server as any, protocol, { api: { requireAuth: false }, metadata: { enableCache: false } } as any); + const rest = new RestServer(server as any, served, { api: { requireAuth: false }, metadata: { enableCache: false } } as any); // `isSystem` clears the capability and authoring gates that run before the query is read. (rest as any).resolveExecCtx = async () => ({ isSystem: true, userId: 'u1' }); rest.registerRoutes(); - const drive = async (method: string, path: string, query: Record, body: unknown = {}) => { + const drive = async (method: string, path: string, query: Record, body: unknown = {}, params: Record = PARAMS) => { const found = (rest as any).getRoutes().find((r: any) => r.method === method && r.path === path); if (!found) throw new Error(`route not registered: ${method} ${path}`); const res = mockRes(); - await found.handler({ method, path, params: PARAMS, query, headers: {}, body } as any, res); + await found.handler({ method, path, params, query, headers: {}, body } as any, res); return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] }; }; - return { protocol, drive }; + return { protocol: served, drive }; } const DOORS = [ @@ -137,4 +145,14 @@ describe('the history and rollback doors take `?package=`, the `/layers` spellin .toEqual(['com.acme.alpha.custom', 'com.acme.beta.custom']); }); } + + for (const { door, method, path, body } of DOORS) { + it(`${door}: REFUSAL — \`?package=\` on a type not stored per package is a 400 naming the parameter`, async () => { + const { drive } = boot({ real: true }); + const answer = await drive(method, path, { package: 'com.acme.alpha' }, body, { type: 'view', name: 'shared_view' }); + expect(answer.status, JSON.stringify(answer.body)).toBe(400); + expect(answer.body?.code, JSON.stringify(answer.body)).toBe('VALIDATION_ERROR'); + expect(answer.body?.error, JSON.stringify(answer.body)).toContain('"package" selector'); + }); + } }); diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 6fafdf371ad..9e9d790247c 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -1056,6 +1056,8 @@ "RevertPackageCommitResponse (type)", "RevertPackageCommitResponseParsed (type)", "RevertPackageCommitResponseSchema (const)", + "RollbackMetaItemRequest (type)", + "RollbackMetaItemRequestSchema (const)", "RollbackMetaItemResponse (type)", "RollbackMetaItemResponseParsed (type)", "RollbackMetaItemResponseSchema (const)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 51d38da0cce..a03591ac192 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1702,6 +1702,12 @@ "api/RevertPackageCommitResponse:reverted", "api/RevertPackageCommitResponse:revertedCount", "api/RevertPackageCommitResponse:success", + "api/RollbackMetaItemRequest:member", + "api/RollbackMetaItemRequest:message", + "api/RollbackMetaItemRequest:name", + "api/RollbackMetaItemRequest:packageId", + "api/RollbackMetaItemRequest:toVersion", + "api/RollbackMetaItemRequest:type", "api/RollbackMetaItemResponse:advisories", "api/RollbackMetaItemResponse:message", "api/RollbackMetaItemResponse:restoredFromVersion", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 286938bd5d4..2a408c472a0 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -761,6 +761,8 @@ "RetryStrategy": "api/RetryStrategy", "RevertPackageCommitResponse": "api/RevertPackageCommitResponse", "RevertPackageCommitResponseSchema": "api/RevertPackageCommitResponse", + "RollbackMetaItemRequest": "api/RollbackMetaItemRequest", + "RollbackMetaItemRequestSchema": "api/RollbackMetaItemRequest", "RollbackMetaItemResponse": "api/RollbackMetaItemResponse", "RollbackMetaItemResponseSchema": "api/RollbackMetaItemResponse", "RollbackToPackageCommitResponse": "api/RollbackToPackageCommitResponse", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index d6018846941..e98d804310f 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -1019,6 +1019,8 @@ "RevertPackageCommitResponse": "src/api/package-lifecycle.zod.ts#RevertPackageCommitResponse (type)", "RevertPackageCommitResponseParsed": "src/api/package-lifecycle.zod.ts#RevertPackageCommitResponseParsed (type)", "RevertPackageCommitResponseSchema": "src/api/package-lifecycle.zod.ts#RevertPackageCommitResponseSchema (const)", + "RollbackMetaItemRequest": "src/api/protocol.zod.ts#RollbackMetaItemRequest (type)", + "RollbackMetaItemRequestSchema": "src/api/protocol.zod.ts#RollbackMetaItemRequestSchema (const)", "RollbackMetaItemResponse": "src/api/protocol.zod.ts#RollbackMetaItemResponse (type)", "RollbackMetaItemResponseParsed": "src/api/protocol.zod.ts#RollbackMetaItemResponseParsed (type)", "RollbackMetaItemResponseSchema": "src/api/protocol.zod.ts#RollbackMetaItemResponseSchema (const)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index ed3a4e2b62e..8e6b142b031 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -413,6 +413,7 @@ "api/ResumeFailureDetails", "api/RetryStrategy", "api/RevertPackageCommitResponse", + "api/RollbackMetaItemRequest", "api/RollbackMetaItemResponse", "api/RollbackToPackageCommitResponse", "api/RouteCategory", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 015084c87b0..e122d99c5b1 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2289,6 +2289,22 @@ export const AuditMetaItemResponseSchema = lazySchema(() => z.object({ ), })); +/** + * [ADR-0150 D3/D4, #32905] The `?package=` selector of the history and + * rollback doors, shared by their request schemas. + */ +const HISTORY_PACKAGE_SELECTOR_DESCRIPTION = + 'Optional package ID (`?package=` on the REST door, the `/layers` spelling) — ' + + 'for a type stored per (package, name), the holder whose versions to address: ' + + 'the slot of the row a read naming the package serves (its own row, its `.custom` ' + + 'pair\'s declared override, or the package-less row that read falls back to), ' + + 'else the package\'s own empty slot when it ships the name; a package that neither ' + + 'holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). ' + + 'Versions attributed to no package, or to the environment, are that slot\'s only ' + + 'while it is the name\'s sole slot. Absent, a name two holders hold (in stored rows ' + + 'or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` ' + + 'on a type not stored per (package, name).'; + /** * History Metadata Item Request * @@ -2327,13 +2343,7 @@ export const HistoryMetaItemRequestSchema = lazySchema(() => z.object({ + 'verb accepts.)', ), member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), - packageId: z.string().optional().describe( - 'Optional package ID (`?package=` on the REST door, the `/layers` spelling) — ' - + 'for a type stored per (package, name), the holder whose versions to read: ' - + 'its own row\'s, or its `.custom` pair\'s declared override\'s (ADR-0150 D3/D4). ' - + 'Absent, a name two holders\' rows hold is refused 409 naming every holder. ' - + 'Every other type reads the name\'s log either way.', - ), + packageId: z.string().optional().describe(HISTORY_PACKAGE_SELECTOR_DESCRIPTION), })); /** @@ -2585,6 +2595,26 @@ export const FindReferencesToMetaResponseSchema = lazySchema(() => z.object({ })).describe('Every found reference to the addressed item.'), })); +/** + * Rollback Metadata Item Request + * + * Request shape for `POST /api/v1/meta/:type/:name/rollback` (the + * `rollbackMetaItem` protocol method): `toVersion` from the body or the + * query, `member` and `package` from the query, `message` from the body. + * Mirrors the implementation's parameter type in + * `@objectstack/metadata-protocol` (`RollbackMetaItemRequest`) member for + * member, less the actor the door fills from the session — a + * declared-surface catch-up (#32905), as `HistoryMetaItemRequestSchema` is. + */ +export const RollbackMetaItemRequestSchema = lazySchema(() => z.object({ + type: z.string().describe('Metadata type name'), + name: z.string().describe('Item name'), + toVersion: z.number().describe('The history version whose body is restored as the new live row.'), + message: z.string().optional().describe('Rollback note, recorded on the new history row.'), + member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), + packageId: z.string().optional().describe(HISTORY_PACKAGE_SELECTOR_DESCRIPTION), +})); + /** * `POST /meta/:type/:name/rollback` — restore the body at a history version * as the new live row. @@ -4442,6 +4472,7 @@ export type GetMetaDiagnosticsResponseParsed = z.infer; /** Post-parse shape of {@link FindReferencesToMetaResponse} — defaults applied, transforms run (ADR-0122). */ export type FindReferencesToMetaResponseParsed = z.infer; +export type RollbackMetaItemRequest = z.input; export type RollbackMetaItemResponse = z.input; /** Post-parse shape of {@link RollbackMetaItemResponse} — defaults applied, transforms run (ADR-0122). */ export type RollbackMetaItemResponseParsed = z.infer; From 69839fe58fc9332d05377962cdfd935607a835b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:35:22 +0000 Subject: [PATCH 09/14] docs(changeset): say which history and rollback requests now refuse and which answer as before Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .changeset/32905-history-rollback-package-address.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md index 888614febe4..138083e1c2c 100644 --- a/.changeset/32905-history-rollback-package-address.md +++ b/.changeset/32905-history-rollback-package-address.md @@ -10,19 +10,18 @@ fix(metadata-protocol)!: the history and rollback doors of a by-package name refuse the bare name two holders hold, and `?package=` addresses one holder's versions (ADR-0150 D3/D4, #32905) -Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package are refused `409 RESOURCE_CONFLICT` before any row is read or written wherever the bare plain read refuses the name: its active rows held by two or more row slots (two packages', or a package's beside the package-less row; `ambiguous-in-environment`, `details.candidates` naming every holder), or one row held while a second package ships the name in code (the read's own refusal) — where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. An addressed rollback (`?package=`) to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is; a `?package=` naming a package that neither holds a row of the name nor ships it is refused `409` (`not-held-by-qualifier`) while another slot holds one, and `422 WRITABLE_PACKAGE_REQUIRED` while no row is stored and no such package is installed; nothing is restored. `?package=` on a type not stored per package is refused `400 VALIDATION_ERROR` on both doors (param `package`), never accepted and dropped. Widened: both doors accept `?package=` on a by-package type (the `/layers?package=` spelling), which reads or restores that holder's versions only. A name one holder holds answers bare exactly as on `main`: its whole log, and its bare rollback restores any of its versions into its row, including a version saved package-less before a package took the name over. +Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package are refused `409 RESOURCE_CONFLICT` before any row is read or written wherever the bare plain read refuses the name: its active rows held by two or more row slots (two packages', or a package's beside the package-less row; `ambiguous-in-environment`, `details.candidates` naming every holder), or one row held while a second package ships the name in code (the read's own refusal) — where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. An addressed rollback (`?package=`) to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is; a `?package=` naming a package that neither holds a row of the name nor ships it is refused `409` (`not-held-by-qualifier`) while another slot holds one, and `422 WRITABLE_PACKAGE_REQUIRED` while no row is stored and no such package is installed; nothing is restored. Widened: both doors accept `?package=` on a by-package type (the `/layers?package=` spelling), which reads or restores that holder's versions only; on any other type it stays refused `400` (now `VALIDATION_ERROR` on param `package`, saying the type is not stored per package), never accepted and dropped. A name one holder holds answers bare exactly as on `main`: its whole log, and its bare rollback restores any of its versions into its row, including a version saved package-less before a package took the name over. Metadata-protocol: added Skills-docs: none — no skill under `skills/` names the history or rollback door, and the docs that do (`content/docs/api/metadata-api.mdx`, `content/docs/kernel/contracts/metadata-service.mdx`, `content/docs/plugins/adding-a-metadata-type.mdx`, `content/docs/permissions/system-context.mdx`) list the routes without teaching how a name two packages hold is addressed, so no sentence there turns false; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. -**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, a package's row beside the environment's, or one package's row while a second package ships the name), and for `?package=` sent to a type not stored per package. The fix: +**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, a package's row beside the environment's, or one package's row while a second package ships the name). The fix: - FROM `GET /meta/TYPE/NAME/history` TO `GET /meta/TYPE/NAME/history?package=PKG`, once per holder the `409` names. - FROM `POST /meta/TYPE/NAME/rollback` TO `POST /meta/TYPE/NAME/rollback?package=PKG`, with `toVersion` one of that holder's versions (its `?package=` history lists them). -- FROM `GET /meta/TYPE/NAME/history?package=PKG` (or the rollback) on a type not stored per package TO the same request without `package`: it never narrowed that type's answer. -`?package=` names a holder the way the item read does: the row a read naming that package serves — the package's own row, its `.custom` pair's declared override of it (so a base package addresses its customization pair), or the package-less row that read falls back to — else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`); with no row stored, a package that is not installed is refused `422` as a save naming it is. `all` and the empty string name no package. For a type not stored per package, `?package=` is refused `400`. +`?package=` names a holder the way the item read does: the row a read naming that package serves — the package's own row, its `.custom` pair's declared override of it (so a base package addresses its customization pair), or the package-less row that read falls back to — else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`); with no row stored, a package that is not installed is refused `422` as a save naming it is. `all` and the empty string name no package. For a type not stored per package, `?package=` is refused `400`, as it was before this release. The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution, and an environment-attributed version stays with a package that took the package-less row over: each is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. From d7d23db10859f38b7ab22cec661687c92e8c8a93 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 03:21:08 +0000 Subject: [PATCH 10/14] fix(spec): name the parsed rollback request, and pay the lint load at collection in the slot pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- packages/metadata-protocol/src/protocol-history-slots.test.ts | 2 ++ packages/spec/api-surface/api.json | 1 + packages/spec/export-origins/api.json | 1 + packages/spec/src/api/protocol.zod.ts | 2 ++ 4 files changed, 6 insertions(+) diff --git a/packages/metadata-protocol/src/protocol-history-slots.test.ts b/packages/metadata-protocol/src/protocol-history-slots.test.ts index 7e75ed94a10..1467b004dd2 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.test.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.test.ts @@ -10,6 +10,8 @@ */ import { describe, expect, it } from 'vitest'; +// The source reaches `@objectstack/lint` lazily; pay that load at collection, never in a clocked case. +import '@objectstack/lint'; import { PackageScopedNameRefusedError, packageScopedRefusalMessage } from '@objectstack/core'; import { historySlotOf } from './protocol-history-slots.js'; diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 9e9d790247c..eb2fe197176 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -1057,6 +1057,7 @@ "RevertPackageCommitResponseParsed (type)", "RevertPackageCommitResponseSchema (const)", "RollbackMetaItemRequest (type)", + "RollbackMetaItemRequestParsed (type)", "RollbackMetaItemRequestSchema (const)", "RollbackMetaItemResponse (type)", "RollbackMetaItemResponseParsed (type)", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index e98d804310f..6f67ed43e52 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -1020,6 +1020,7 @@ "RevertPackageCommitResponseParsed": "src/api/package-lifecycle.zod.ts#RevertPackageCommitResponseParsed (type)", "RevertPackageCommitResponseSchema": "src/api/package-lifecycle.zod.ts#RevertPackageCommitResponseSchema (const)", "RollbackMetaItemRequest": "src/api/protocol.zod.ts#RollbackMetaItemRequest (type)", + "RollbackMetaItemRequestParsed": "src/api/protocol.zod.ts#RollbackMetaItemRequestParsed (type)", "RollbackMetaItemRequestSchema": "src/api/protocol.zod.ts#RollbackMetaItemRequestSchema (const)", "RollbackMetaItemResponse": "src/api/protocol.zod.ts#RollbackMetaItemResponse (type)", "RollbackMetaItemResponseParsed": "src/api/protocol.zod.ts#RollbackMetaItemResponseParsed (type)", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index e122d99c5b1..bb8c57d2e4c 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4473,6 +4473,8 @@ export type FindReferencesToMetaResponse = z.input; export type RollbackMetaItemRequest = z.input; +/** Post-parse shape of {@link RollbackMetaItemRequest} — defaults applied, transforms run (ADR-0122). */ +export type RollbackMetaItemRequestParsed = z.infer; export type RollbackMetaItemResponse = z.input; /** Post-parse shape of {@link RollbackMetaItemResponse} — defaults applied, transforms run (ADR-0122). */ export type RollbackMetaItemResponseParsed = z.infer; From c8556adf44060eb43c23ac24460423fcb85b11a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 04:13:43 +0000 Subject: [PATCH 11/14] fix(rest): read the rollback version through its declaration, a whole number of at least 1 The rollback request's spec schema now declares `toVersion` as the door enforces it, and the door reads that declaration in place of an undeclared whole-number parse. The changeset grades every package but spec `patch` under the breaking banner, names the zero-row two-shipper refusal, and states what the bare doors do not yet ask for an action. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../32905-history-rollback-package-address.md | 16 ++++++------ content/docs/references/api/protocol.mdx | 2 +- ...story-rollback-two-holders.dogfood.test.ts | 20 ++++++++++++--- packages/rest/src/meta-item-history-routes.ts | 13 +++++++--- packages/spec/src/api/protocol.test.ts | 25 +++++++++++++++++++ packages/spec/src/api/protocol.zod.ts | 5 +++- 6 files changed, 65 insertions(+), 16 deletions(-) diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md index 138083e1c2c..41553426b70 100644 --- a/.changeset/32905-history-rollback-package-address.md +++ b/.changeset/32905-history-rollback-package-address.md @@ -1,30 +1,32 @@ --- '@objectstack/spec': minor -'@objectstack/metadata-protocol': minor -'@objectstack/rest': minor -'@objectstack/metadata': minor -'@object-ui/data-objectstack': minor +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/metadata': patch +'@object-ui/data-objectstack': patch '@objectstack/metadata-core': patch '@object-ui/app-shell': patch --- fix(metadata-protocol)!: the history and rollback doors of a by-package name refuse the bare name two holders hold, and `?package=` addresses one holder's versions (ADR-0150 D3/D4, #32905) -Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package are refused `409 RESOURCE_CONFLICT` before any row is read or written wherever the bare plain read refuses the name: its active rows held by two or more row slots (two packages', or a package's beside the package-less row; `ambiguous-in-environment`, `details.candidates` naming every holder), or one row held while a second package ships the name in code (the read's own refusal) — where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. An addressed rollback (`?package=`) to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is; a `?package=` naming a package that neither holds a row of the name nor ships it is refused `409` (`not-held-by-qualifier`) while another slot holds one, and `422 WRITABLE_PACKAGE_REQUIRED` while no row is stored and no such package is installed; nothing is restored. Widened: both doors accept `?package=` on a by-package type (the `/layers?package=` spelling), which reads or restores that holder's versions only; on any other type it stays refused `400` (now `VALIDATION_ERROR` on param `package`, saying the type is not stored per package), never accepted and dropped. A name one holder holds answers bare exactly as on `main`: its whole log, and its bare rollback restores any of its versions into its row, including a version saved package-less before a package took the name over. +Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/history` and `POST /meta/:type/:name/rollback` naming no package are refused `409 RESOURCE_CONFLICT` before any row is read or written wherever the bare plain read refuses the name: its active rows held by two or more row slots (two packages', or a package's beside the package-less row; `ambiguous-in-environment`, `details.candidates` naming every holder), one row held while a second package ships the name in code, or a name two packages ship with no stored row (the read's own refusal) — where the history answered every holder's versions as one log and the rollback wrote the chosen version into whichever row the bare read served. An addressed rollback (`?package=`) to a version of another holder's row, or to a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is; a `?package=` naming a package that neither holds a row of the name nor ships it is refused `409` (`not-held-by-qualifier`) while another slot holds one, and `422 WRITABLE_PACKAGE_REQUIRED` while no row is stored and no such package is installed; nothing is restored. Widened: both doors accept `?package=` on a by-package type (the `/layers?package=` spelling), which reads or restores that holder's versions only; on any other type it stays refused `400` (now `VALIDATION_ERROR` on param `package`, saying the type is not stored per package), never accepted and dropped. A name one holder holds answers bare exactly as on `main`: its whole log, and its bare rollback restores any of its versions into its row, including a version saved package-less before a package took the name over. Metadata-protocol: added Skills-docs: none — no skill under `skills/` names the history or rollback door, and the docs that do (`content/docs/api/metadata-api.mdx`, `content/docs/kernel/contracts/metadata-service.mdx`, `content/docs/plugins/adding-a-metadata-type.mdx`, `content/docs/permissions/system-context.mdx`) list the routes without teaching how a name two packages hold is addressed, so no sentence there turns false; the generated API reference (`content/docs/references/api/protocol.mdx`) carries the new `packageId` field. -**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, a package's row beside the environment's, or one package's row while a second package ships the name). The fix: +**BREAKING** for a bare history or rollback request of a by-package name two holders hold (two `.custom` pairs, a package's row beside the environment's, one package's row while a second package ships the name, or a name two packages ship with no stored row). The fix: - FROM `GET /meta/TYPE/NAME/history` TO `GET /meta/TYPE/NAME/history?package=PKG`, once per holder the `409` names. - FROM `POST /meta/TYPE/NAME/rollback` TO `POST /meta/TYPE/NAME/rollback?package=PKG`, with `toVersion` one of that holder's versions (its `?package=` history lists them). +An `action` name is judged here by its row slots and the registry's package-scoped resolver only: the bare read's own action judges (an object-less name two packages ship, two packages binding the name to their own objects) are not asked by these doors yet, so such a name with no stored row still answers its (empty) history bare. + `?package=` names a holder the way the item read does: the row a read naming that package serves — the package's own row, its `.custom` pair's declared override of it (so a base package addresses its customization pair), or the package-less row that read falls back to — else the package's own slot when it ships the name and holds no row yet. A package that neither holds nor ships the name, while another slot holds it, is refused `409` (`not-held-by-qualifier`); with no row stored, a package that is not installed is refused `422` as a save naming it is. `all` and the empty string name no package. For a type not stored per package, `?package=` is refused `400`, as it was before this release. The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution, and an environment-attributed version stays with a package that took the package-less row over: each is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. -Levels: `minor` where the package carries the added surface — `@objectstack/spec` (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`, and the new `RollbackMetaItemRequestSchema` that declares the rollback door's request with its `packageId`), `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`) and `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`); `patch` for `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). +Levels follow the metadata protocol alone (maintainer ruling A, 2026-10-21): `minor` for `@objectstack/spec`, the one package that carries the added protocol surface (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`, and the new `RollbackMetaItemRequestSchema` that declares the rollback door's request with its `packageId` and a `toVersion` of at least 1), and the level `Check Changeset` demands for `Metadata-protocol: added`. Every other package is `patch` under the BREAKING banner above: `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`; the rollback door reads `toVersion` through its declaration), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`), `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`), `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 60be42798dd..038c902f460 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2825,7 +2825,7 @@ Answer to a device registration: the device id the client keeps | :--- | :--- | :--- | :--- | | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | -| **toVersion** | `number` | ✅ | The history version whose body is restored as the new live row. | +| **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | | **message** | `string` | optional | Rollback note, recorded on the new history row. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | | **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | diff --git a/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts index ef59626d48f..119d51e4d6b 100644 --- a/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts +++ b/packages/qa/dogfood/test/history-rollback-two-holders.dogfood.test.ts @@ -26,8 +26,8 @@ // bare, an unattributed version included, and so does a name first saved // as the environment's own item and later under a package (M1): its bare // rollback restores the environment's versions as `main` does; -// - a name two packages ship, one of them customized, is two holders to the -// bare doors as it is to the bare plain read (ADR-0150 D5); +// - a name two packages ship, one of them customized or neither, is two +// holders to the bare doors as it is to the bare plain read (ADR-0150 D5); // - `?package=` on a type not stored per package is refused 400, never // accepted and dropped; and a rollback naming no installed package, of a // name no row holds, is refused rather than minting a row for it. @@ -52,6 +52,8 @@ const SHIPPED = 'qa_hist_shipped_32905'; const SOLO = 'qa_hist_solo_32905'; /** A flow both packages ship, only alpha's pair customizes. */ const SHIPPED_ONE = 'qa_hist_shipped_one_32905'; +/** A flow both packages ship and neither customizes: no stored row. */ +const SHIPPED_NONE = 'qa_hist_shipped_none_32905'; /** A runtime flow saved as the environment's own item, deleted, then saved in alpha's pair (M1). */ const TAKEN_OVER = 'qa_hist_taken_over_32905'; /** A runtime flow alpha's pair saved and then deleted: no row holds it. */ @@ -66,7 +68,7 @@ const flowBody = (name: string, label: string) => ({ function holderPackage(p: 'alpha' | 'beta') { return defineStack({ manifest: { id: `com.qa.hist32905.${p}`, namespace: `h32905${p}`, name: `qa_hist32905_${p}`, version: '1.0.0', type: 'app' }, - flows: [flowBody(SHIPPED, `${p} shipped`), flowBody(SHIPPED_ONE, `${p} shipped one`)], + flows: [flowBody(SHIPPED, `${p} shipped`), flowBody(SHIPPED_ONE, `${p} shipped one`), flowBody(SHIPPED_NONE, `${p} shipped none`)], } as never); } @@ -222,6 +224,18 @@ describe('the /meta history and rollback doors of a flow name two packages hold expect(await labelAt(SHIPPED_ONE, ALPHA_PAIR)).toBe('alpha one r2'); }); + it('a name two packages ship and neither customized, no row stored, is refused bare at both doors, as the bare plain read refuses it', async () => { + const read = await call('GET', `/meta/flow/${SHIPPED_NONE}`); + expect(read.status, JSON.stringify(read.json)).toBe(409); + const history = await call('GET', `/meta/flow/${SHIPPED_NONE}/history`); + expect(history.status, JSON.stringify(history.json)).toBe(409); + expect(codeOf(history.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(history.json)).toEqual(candidatesOf(read.json)); + const rollback = await call('POST', `/meta/flow/${SHIPPED_NONE}/rollback`, { toVersion: 1 }); + expect(rollback.status, JSON.stringify(rollback.json)).toBe(409); + expect(codeOf(rollback.json)).toBe('RESOURCE_CONFLICT'); + }); + it('?package= on a type not stored per package is refused 400 at both doors, never accepted and dropped', async () => { const history = await call('GET', `/meta/view/qa_hist_any_view/history?package=${ALPHA}`); expect(history.status, JSON.stringify(history.json)).toBe(400); diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 626f9f0a174..683523570a4 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -165,7 +165,7 @@ import { // [#20061 / #20062 / #20139] The DECLARED request schemas the change log and the // audit trail parse their numeric parameters through — see // `readDeclaredQueryNumber` in `rest-server.ts`. -import { AuditMetaItemRequestSchema, HistoryMetaItemRequestSchema } from '@objectstack/spec/api'; +import { AuditMetaItemRequestSchema, HistoryMetaItemRequestSchema, RollbackMetaItemRequestSchema } from '@objectstack/spec/api'; import type { AuditMetaItemRequest, HistoryMetaItemRequest, PublishMetaItemRequest } from '@objectstack/spec/api'; import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import { handleRouteError, sendFieldVisibilityFault, thrownAnswerIsBareNotFound } from './error-response.js'; @@ -832,23 +832,28 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc // SDK's `rollbackItem` and the console's metadata client both // send a JSON number); only the untyped query string goes // through `readDeclaredQueryNumber`'s faithful coercion. + // [#32905] The whole-number declaration is the rollback + // request's own (`RollbackMetaItemRequestSchema.toVersion`, a + // whole number of at least 1), so the published contract and + // this door spell a version one way. // Precedence is unchanged — `toVersion`, then the `version` // alias, then `?toVersion=` — and every refusal stays this // door's own `INVALID_REQUEST`. const bodyVersion = body.toVersion ?? body.version; + const declaredVersion = RollbackMetaItemRequestSchema.shape.toVersion.optional(); let toVersion: number | undefined; if (bodyVersion !== undefined && bodyVersion !== null) { - const parsed = UNDECLARED_WHOLE_NUMBER_PARAM.safeParse(bodyVersion); + const parsed = declaredVersion.safeParse(bodyVersion); toVersion = parsed.success ? parsed.data : undefined; } else { try { toVersion = readDeclaredQueryNumber(req.query, 'toVersion', - UNDECLARED_WHOLE_NUMBER_PARAM, { emptyIsAbsent: false }); + declaredVersion, { emptyIsAbsent: false }); } catch { toVersion = undefined; } } - if (toVersion === undefined || toVersion < 1) { + if (toVersion === undefined) { res.status(400).json({ error: `'toVersion' (positive integer) is required`, code: 'INVALID_REQUEST', diff --git a/packages/spec/src/api/protocol.test.ts b/packages/spec/src/api/protocol.test.ts index 71fa6bc7a22..7da883cd260 100644 --- a/packages/spec/src/api/protocol.test.ts +++ b/packages/spec/src/api/protocol.test.ts @@ -3103,3 +3103,28 @@ describe('seedApplied.landed (#30348) — one shared schema on both publish resp expect(SeedAppliedLandedSchema.safeParse({ object: 'a', inserted: list([]) }).success).toBe(false); }); }); + +import { RollbackMetaItemRequestSchema } from './protocol.zod'; + +describe('RollbackMetaItemRequestSchema declares what the rollback door enforces', () => { + // The REST door reads `toVersion` through this declaration (body and query), + // and the protocol method refuses a version below 1 as well: a history + // version is a whole number of at least 1, so the published contract says + // so instead of a bare number the door would refuse. + const base = { type: 'flow', name: 'shared_flow' } as const; + + it.each([[0], [-1], [1.5], ['2'], [true]])('refuses toVersion %j', (toVersion) => { + expect(RollbackMetaItemRequestSchema.safeParse({ ...base, toVersion }).success).toBe(false); + }); + + it('CONTROL: accepts toVersion 1 with every optional member, preserving each through parse', () => { + const full = { ...base, toVersion: 1, message: 'back', member: 'flow', packageId: 'com.acme.alpha.custom' }; + const result = RollbackMetaItemRequestSchema.safeParse(full); + expect(result.success).toBe(true); + if (result.success) expect(result.data).toEqual(full); + }); + + it('requires toVersion', () => { + expect(RollbackMetaItemRequestSchema.safeParse(base).success).toBe(false); + }); +}); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index bb8c57d2e4c..0993278f7e1 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2609,7 +2609,10 @@ export const FindReferencesToMetaResponseSchema = lazySchema(() => z.object({ export const RollbackMetaItemRequestSchema = lazySchema(() => z.object({ type: z.string().describe('Metadata type name'), name: z.string().describe('Item name'), - toVersion: z.number().describe('The history version whose body is restored as the new live row.'), + toVersion: z.number().int().min(1).describe( + 'The history version whose body is restored as the new live row: a whole number of at least 1, ' + + 'as the history lists it. The rollback door reads this declaration and refuses anything else `400`.', + ), message: z.string().optional().describe('Rollback note, recorded on the new history row.'), member: z.string().optional().describe(BUNDLE_MEMBER_SELECTOR_DESCRIPTION), packageId: z.string().optional().describe(HISTORY_PACKAGE_SELECTOR_DESCRIPTION), From 83f41ed6d6db689638767367efec4686b94ed11a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 14:38:02 +0000 Subject: [PATCH 12/14] fix(app-shell): name the package on the history doors only for a type stored per package The console sent the item page's package to the history and rollback doors for every type, and the doors refuse it on a type not stored per package, so History broke for an object, view or page opened under a package. The list of by-package types now lives once in spec (`PACKAGE_SLOTTED_METADATA_TYPES`, `isPackageSlottedMetaType`); the metadata store set is built from it and the History panel asks it before naming a package. A pin holds the doors' refusal and the console's predicate to the same list. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../32905-history-rollback-package-address.md | 4 +-- .../src/protocol-history-slots.test.ts | 25 +++++++++++++++- .../metadata/src/package-slotted-store.ts | 10 +++---- packages/spec/api-surface/api.json | 2 ++ packages/spec/export-origins/api.json | 2 ++ packages/spec/src/api/protocol.zod.ts | 29 +++++++++++++++++-- ...ceHistoryPage.holderPackage-32905.test.tsx | 20 ++++++++++++- .../views/item-tools/ResourceHistoryPage.tsx | 15 +++++++--- ...udioDesignSurface.itemTools-28239.test.tsx | 8 +++-- .../data-objectstack/src/metadata-client.ts | 8 +++-- 10 files changed, 103 insertions(+), 20 deletions(-) diff --git a/.changeset/32905-history-rollback-package-address.md b/.changeset/32905-history-rollback-package-address.md index 41553426b70..163de597bbb 100644 --- a/.changeset/32905-history-rollback-package-address.md +++ b/.changeset/32905-history-rollback-package-address.md @@ -27,6 +27,6 @@ An `action` name is judged here by its row slots and the registry's package-scop The `/meta` doors' history rows now record whose row they snapshot (`sys_metadata_history.package_id`, the rule `DatabaseLoader` already applies; the package-less row is marked `sys_metadata`). A version recorded before this release carries no attribution, and an environment-attributed version stays with a package that took the package-less row over: each is listed and restorable while the name has one holder, and never guessed once two hold it. `@objectstack/metadata` exports that rule as `historyRowAttribution` and `ENVIRONMENT_HISTORY_MARK`. -Levels follow the metadata protocol alone (maintainer ruling A, 2026-10-21): `minor` for `@objectstack/spec`, the one package that carries the added protocol surface (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`, and the new `RollbackMetaItemRequestSchema` that declares the rollback door's request with its `packageId` and a `toVersion` of at least 1), and the level `Check Changeset` demands for `Metadata-protocol: added`. Every other package is `patch` under the BREAKING banner above: `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`; the rollback door reads `toVersion` through its declaration), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`), `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`), `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). +Levels follow the metadata protocol alone (maintainer ruling A, 2026-10-21): `minor` for `@objectstack/spec`, the one package that carries the added protocol surface (`HistoryMetaItemRequestSchema.packageId`, the authorable-surface entry `api/HistoryMetaItemRequest:packageId`, the new `RollbackMetaItemRequestSchema` that declares the rollback door's request with its `packageId` and a `toVersion` of at least 1, and `PACKAGE_SLOTTED_METADATA_TYPES` / `isPackageSlottedMetaType`, the one list of types stored per package that the doors and the console both read), and the level `Check Changeset` demands for `Metadata-protocol: added`. Every other package is `patch` under the BREAKING banner above: `@objectstack/metadata-protocol` (`historyMetaItem` and `RollbackMetaItemRequest` take `packageId`), `@objectstack/rest` (both doors accept `?package=`; the rollback door reads `toVersion` through its declaration), `@objectstack/metadata` (new exports `historyRowAttribution`, `ENVIRONMENT_HISTORY_MARK`; `PACKAGE_SLOTTED_STORE_TYPES` is now built from the spec list, same members), `@object-ui/data-objectstack` (`history()` / `rollback()` take `packageId`), `@objectstack/metadata-core` (a field description only) and `@object-ui/app-shell` (no exported signature changes: `HistoryPanel` and `StudioItemTools` are not exported, and `MetadataResourceHistoryPage` keeps its props). -The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads. +The console follows: `MetadataClient.history()` and `rollback()` take `packageId` (sent as `?package=`), and the History item tool (routed page, the edit page's sheet and Studio's item tools) names the package its item page reads, for a type stored per package only (`isPackageSlottedMetaType`): an object, view or page opened under a package reads and restores its history bare, as before, since the doors refuse `?package=` on those types. diff --git a/packages/metadata-protocol/src/protocol-history-slots.test.ts b/packages/metadata-protocol/src/protocol-history-slots.test.ts index 1467b004dd2..ac0d6af51e3 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.test.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.test.ts @@ -13,7 +13,8 @@ import { describe, expect, it } from 'vitest'; // The source reaches `@objectstack/lint` lazily; pay that load at collection, never in a clocked case. import '@objectstack/lint'; import { PackageScopedNameRefusedError, packageScopedRefusalMessage } from '@objectstack/core'; -import { historySlotOf } from './protocol-history-slots.js'; +import { PACKAGE_SLOTTED_METADATA_TYPES, isPackageSlottedMetaType } from '@objectstack/spec/api'; +import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; interface FakeOptions { candidates?: string[]; @@ -161,3 +162,25 @@ describe('historySlotOf: a type not stored per package', () => { expect(await historySlotOf(fakeHost({}), { type: 'view', name: 'n' })).toBeUndefined(); }); }); + +describe('the doors and the console read one list of by-package types', () => { + // The console names a package on the history and rollback doors only where + // `isPackageSlottedMetaType` answers true; the doors refuse `?package=` + // everywhere else. Pinned together so the two cannot disagree: a type the + // console would name a package for is never refused here, and a type it + // would not is. + it('every type the console names a package for is accepted by the doors', () => { + expect(PACKAGE_SLOTTED_METADATA_TYPES.length).toBeGreaterThan(0); + for (const type of PACKAGE_SLOTTED_METADATA_TYPES) { + expect(isPackageSlottedMetaType(type), type).toBe(true); + expect(() => refusePackageSelectorOutsideSlottedTypes(type, 'com.a'), type).not.toThrow(); + } + }); + + it('every type the console reads bare is refused the selector by the doors', () => { + for (const type of ['object', 'view', 'page', 'dashboard', 'report', 'app']) { + expect(isPackageSlottedMetaType(type), type).toBe(false); + expect(() => refusePackageSelectorOutsideSlottedTypes(type, 'com.a'), type).toThrow(/not stored per package/); + } + }); +}); diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index 2b68ba5f28c..f5bd720077f 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -127,6 +127,7 @@ import { } from '@objectstack/core'; import { ITEM_KEY_DISCRIMINATORS, SysMetadataObject, itemDiscriminator } from '@objectstack/metadata-core'; import { peelStoredEnvelope } from './stored-envelope.js'; +import { PACKAGE_SLOTTED_METADATA_TYPES } from '@objectstack/spec/api'; /** * The types whose in-memory items are stored per `(package, name)`: `api`, @@ -138,12 +139,11 @@ import { peelStoredEnvelope } from './stored-envelope.js'; * picklist family's `picklist`, `mapping` and `dataset` (#31700); then * `webhook` (#31699 PR 2), so a host with no registry lists each package's * declaration of one name; then `tool` (#31985, ADR-0150 child B), likewise - * in the change that narrows it. + * in the change that narrows it. The list itself is `@objectstack/spec`'s + * `PACKAGE_SLOTTED_METADATA_TYPES` (#32905), so a client that names a package + * on the history and rollback doors reads the same one; a type joins there. */ -export const PACKAGE_SLOTTED_STORE_TYPES: ReadonlySet = new Set([ - 'api', 'agent', 'skill', 'action', 'email_template', 'permission', 'flow', 'picklist', 'mapping', 'dataset', - 'webhook', 'tool', -]); +export const PACKAGE_SLOTTED_STORE_TYPES: ReadonlySet = new Set(PACKAGE_SLOTTED_METADATA_TYPES); /** The provenance sentinel a rehydrated row carries in place of a package. */ const OVERLAY_SENTINEL = 'sys_metadata'; diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index eb2fe197176..f79069b6788 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -796,6 +796,7 @@ "OrganizationEditionChoice (type)", "OrganizationEditionChoiceParsed (type)", "OrganizationEditionChoiceSchema (const)", + "PACKAGE_SLOTTED_METADATA_TYPES (const)", "PROVENANCE_WAIVERS (const)", "PackageApiErrorCode (const)", "PackageApiErrorCode (type)", @@ -1267,6 +1268,7 @@ "identityFreeEndpointGateFailure (function)", "isAppPackageIdKey (function)", "isMatchKeySets (function)", + "isPackageSlottedMetaType (function)", "isSubscribableChannel (function)", "makeApiErrorSchema (function)", "normalizeEndpointPath (function)", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 6f67ed43e52..47a245988d4 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -769,6 +769,7 @@ "OrganizationEditionChoice": "src/api/auth-endpoints.zod.ts#OrganizationEditionChoice (type)", "OrganizationEditionChoiceParsed": "src/api/auth-endpoints.zod.ts#OrganizationEditionChoiceParsed (type)", "OrganizationEditionChoiceSchema": "src/api/auth-endpoints.zod.ts#OrganizationEditionChoiceSchema (const)", + "PACKAGE_SLOTTED_METADATA_TYPES": "src/api/protocol.zod.ts#PACKAGE_SLOTTED_METADATA_TYPES (const)", "PROVENANCE_WAIVERS": "src/api/error-code-ledger.zod.ts#PROVENANCE_WAIVERS (const)", "PackageApiErrorCode": "src/api/package-api.zod.ts#PackageApiErrorCode (type)", "PackageExportBundle": "src/api/package-lifecycle.zod.ts#PackageExportBundle (type)", @@ -1221,6 +1222,7 @@ "identityFreeEndpointGateFailure": "src/api/endpoint-publish-gate.ts#identityFreeEndpointGateFailure (function)", "isAppPackageIdKey": "src/api/protocol.zod.ts#isAppPackageIdKey (function)", "isMatchKeySets": "src/api/export.zod.ts#isMatchKeySets (function)", + "isPackageSlottedMetaType": "src/api/protocol.zod.ts#isPackageSlottedMetaType (function)", "isSubscribableChannel": "src/api/discovery.zod.ts#isSubscribableChannel (function)", "makeApiErrorSchema": "src/api/contract.zod.ts#makeApiErrorSchema (function)", "normalizeEndpointPath": "src/api/endpoint.zod.ts#normalizeEndpointPath (function)", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 0993278f7e1..4fd48e938ed 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -79,6 +79,7 @@ import type { } from '../kernel/package-registry.zod'; import { lazySchema } from '../shared/lazy-schema'; +import { canonicalMetaUrlType } from '../meta-spelling/metadata-url-spelling'; export const AutomationTriggerRequestSchema = lazySchema(() => z.object({ trigger: z.string(), payload: z.record(z.string(), z.unknown()) @@ -2305,6 +2306,29 @@ const HISTORY_PACKAGE_SELECTOR_DESCRIPTION = + 'or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` ' + 'on a type not stored per (package, name).'; +/** + * [ADR-0150 D3/D4, #32905] The metadata types stored per `(package, name)`: + * one row per package for a name, so a name can have several holders. These + * are the types whose history and rollback doors take `?package=` (see + * {@link HistoryMetaItemRequestSchema}`.packageId`); on every other type the + * doors refuse it `400`. The one list: `@objectstack/metadata`'s + * `PACKAGE_SLOTTED_STORE_TYPES` is built from it, and a client names a + * package on those doors only for a type it holds + * ({@link isPackageSlottedMetaType}). + */ +export const PACKAGE_SLOTTED_METADATA_TYPES: readonly string[] = Object.freeze([ + 'api', 'agent', 'skill', 'action', 'email_template', 'permission', 'flow', 'picklist', 'mapping', 'dataset', + 'webhook', 'tool', +]); + +/** + * Whether `type`, in any `/meta/:type` spelling (`flows` folds to `flow`), is + * stored per `(package, name)` ({@link PACKAGE_SLOTTED_METADATA_TYPES}). + */ +export function isPackageSlottedMetaType(type: string): boolean { + return PACKAGE_SLOTTED_METADATA_TYPES.includes(canonicalMetaUrlType(type)); +} + /** * History Metadata Item Request * @@ -2599,8 +2623,9 @@ export const FindReferencesToMetaResponseSchema = lazySchema(() => z.object({ * Rollback Metadata Item Request * * Request shape for `POST /api/v1/meta/:type/:name/rollback` (the - * `rollbackMetaItem` protocol method): `toVersion` from the body or the - * query, `member` and `package` from the query, `message` from the body. + * `rollbackMetaItem` protocol method): `toVersion` from the body (or its + * `version` alias) or the query, all three read through this declaration, + * `member` and `package` from the query, `message` from the body. * Mirrors the implementation's parameter type in * `@objectstack/metadata-protocol` (`RollbackMetaItemRequest`) member for * member, less the actor the door fills from the session — a diff --git a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx index 0d56a5d6590..fe22d9a2629 100644 --- a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx +++ b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.holderPackage-32905.test.tsx @@ -7,7 +7,9 @@ * routed page sends the item page's `?package=` to `history()` and * `rollback()`, as the item page's own layered read does. `all` and the empty * spelling name no package, as on the server's doors; no `?package=`, no - * `packageId` (CONTROL — a name one holder holds reads as before). + * `packageId` (CONTROL — a name one holder holds reads as before). A type + * not stored per package (an object, a view, a page) is read and restored + * bare even under `?package=`: the doors refuse the selector `400` there. * * Real: the page, `HistoryPanel` and React Router. Stubbed: the metadata client and types. */ @@ -74,6 +76,22 @@ describe('History item tool — the item page\'s `?package=` names the holder (o await waitFor(() => expect(client.rollback).toHaveBeenCalledWith('flow', 'solo_flow', 1)); }); + it('a type not stored per package reads and restores bare under `?package=` (the doors refuse it 400 there)', async () => { + renderAt('/metadata/object/showcase_account/history?package=com.acme.alpha'); + await waitFor(() => expect(client.history).toHaveBeenCalledWith('object', 'showcase_account', { limit: 100 })); + const [button] = await screen.findAllByTitle('Rollback to this version'); + fireEvent.click(button!); + fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('history-rollback-confirm-action')); + await waitFor(() => expect(client.rollback).toHaveBeenCalledWith('object', 'showcase_account', 1)); + }); + + it('a plural spelling of a by-package type still names the package', async () => { + renderAt('/metadata/flows/shared_flow/history?package=com.acme.alpha.custom'); + await waitFor(() => + expect(client.history).toHaveBeenCalledWith('flows', 'shared_flow', { limit: 100, packageId: 'com.acme.alpha.custom' }), + ); + }); + it('`all` and the empty spelling name no package, as on the server\'s doors', () => { expect(historyPackageOf('?package=all')).toBeUndefined(); expect(historyPackageOf('?package=')).toBeUndefined(); diff --git a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx index 4845f4873a7..d681c63fab5 100644 --- a/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx +++ b/ui/packages/app-shell/src/views/item-tools/ResourceHistoryPage.tsx @@ -37,6 +37,7 @@ import { import { t, tFormat, translateConsoleValue, useMetadataLocale } from '../metadata-admin/i18n.js'; import { useHistoryActorNames, type HistoryActorName } from './historyActors.js'; import { PageShell } from '../metadata-admin/PageShell.js'; +import { isPackageSlottedMetaType } from '@objectstack/spec/api'; import { useMetadataAreaHost } from '../metadata-admin/metadataAreaHost.js'; import { useMetadataClient, @@ -193,6 +194,10 @@ export function HistoryPanel({ * versions to list and restore into, sent as `?package=` on both doors. * Omitted, a name two holders hold is refused 409 naming both, and the * refusal shows as the timeline's error; one holder reads as before. + * Sent only for a type stored per `(package, name)` + * (`isPackageSlottedMetaType`): the doors refuse `?package=` `400` on every + * other type, whose log is the name's alone, so an object, view or page + * opened under a package reads and restores bare, as before. */ packageId?: string; refreshKey?: number; @@ -219,6 +224,8 @@ export function HistoryPanel({ // the in-app AlertDialog below rather than the browser's native `confirm()`. const [confirmVersion, setConfirmVersion] = React.useState(null); const [localRefresh, setLocalRefresh] = React.useState(0); + // objectstack#32905 — the package the doors address, for a by-package type only. + const addressedPackage = packageId && isPackageSlottedMetaType(type) ? packageId : undefined; // ADR-0146 D1 — the timeline names people, not ids. const actorNames = useHistoryActorNames( React.useMemo( @@ -235,7 +242,7 @@ export function HistoryPanel({ try { const result = await client.history(type, name, { limit: 100, - ...(packageId ? { packageId } : {}), + ...(addressedPackage ? { packageId: addressedPackage } : {}), }); if (cancelled) return; const list = Array.isArray(result) @@ -258,7 +265,7 @@ export function HistoryPanel({ return () => { cancelled = true; }; - }, [client, type, name, packageId, refreshKey, localRefresh]); + }, [client, type, name, addressedPackage, refreshKey, localRefresh]); function rollbackMessage(version: number): string { return rollbackConfirm @@ -270,8 +277,8 @@ export function HistoryPanel({ setRollingBack(version); setError(null); try { - await (packageId - ? (client as any).rollback(type, name, version, { packageId }) + await (addressedPackage + ? (client as any).rollback(type, name, version, { packageId: addressedPackage }) : (client as any).rollback(type, name, version)); onRollback?.(version); // Refetch so the new revert event shows up at the top. diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx index 04813d259b1..2d30412726c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemTools-28239.test.tsx @@ -216,8 +216,9 @@ describe('Studio item toolbar — every pillar opens the five tools (objectstack const history = await openTool('history'); expect(await within(history).findAllByTitle(ROLLBACK)).toHaveLength(2); - // The holder the layers read names (objectstack#32905). - expect(mockClient.history).toHaveBeenCalledWith(type, name, { limit: 100, packageId: PKG }); + // The holder the layers read names, for a type stored per package only + // (objectstack#32905): the doors refuse `?package=` on an object or a page. + expect(mockClient.history).toHaveBeenCalledWith(type, name, type === 'flow' ? { limit: 100, packageId: PKG } : { limit: 100 }); await openTool('audit'); await waitFor(() => expect(mockClient.audit).toHaveBeenCalledWith(type, name, { limit: 100 })); @@ -243,7 +244,8 @@ describe('Studio item toolbar — rollback (objectstack#28239)', () => { expect(mockClient.rollback).not.toHaveBeenCalled(); fireEvent.click(within(dialog).getByTestId('history-rollback-confirm-action')); - await waitFor(() => expect(mockClient.rollback).toHaveBeenCalledWith('object', 'showcase_account', 1, { packageId: PKG })); + // An object is not stored per package: the rollback names none (objectstack#32905). + await waitFor(() => expect(mockClient.rollback).toHaveBeenCalledWith('object', 'showcase_account', 1)); expect(mockClient.rollback).toHaveBeenCalledTimes(1); await waitFor(() => expect(mockClient.layered.mock.calls.filter(([type]) => type === 'object').length).toBeGreaterThan(reads), diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index 8c4ad143984..ab1b7d0b7e7 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -812,7 +812,9 @@ export interface MetadataHistoryOptions { * spelling). For a type stored per `(package, name)` the server numbers a * name's versions across every holder; naming the package reads only that * holder's, and a bare read of a name two holders hold is refused `409` - * naming every holder. Every other type reads the name's log either way. + * naming every holder. On every other type both doors refuse it `400`: + * send it only for a type `isPackageSlottedMetaType` (`@objectstack/spec/api`) + * answers true for. */ packageId?: string; } @@ -2027,7 +2029,9 @@ export class MetadataClient { * `packageId` (`?package=`) names whose row a by-package name's version is * restored into, as `history()`'s does: the version must be that holder's * (`404` otherwise), and a bare rollback of a name two holders hold is - * refused `409` naming every holder, with no row written. + * refused `409` naming every holder, with no row written. As with + * `history()`, only for a type `isPackageSlottedMetaType` answers true for: + * every other type refuses it `400`. */ async rollback( type: string, From 45dca14ce18d799a18b37236eadcb7101e04ee37 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:34:10 +0000 Subject: [PATCH 13/14] test(objectql): give the two-namespace override cases room on a loaded shard Each case of that describe boots the engine, installs two or three packages and restarts it: about half a second alone, but a merge-queue shard timed one out at the 5 s default while the file took 63 s. The file's runtime is the same on main's sources and on this branch's, measured back to back, so the budget is room for load, not for a slower product. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- .../src/protocol-custom-override-bare-slot-envelope.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/protocol-custom-override-bare-slot-envelope.test.ts b/packages/objectql/src/protocol-custom-override-bare-slot-envelope.test.ts index 0625e1417d8..8369474f7d3 100644 --- a/packages/objectql/src/protocol-custom-override-bare-slot-envelope.test.ts +++ b/packages/objectql/src/protocol-custom-override-bare-slot-envelope.test.ts @@ -797,7 +797,11 @@ describe('[#30504] an app\'s packaged base carries its contributed navigation, s * email template) is measured beside them: the list filter judges those rows by * their own envelope, not the first shipper's. */ -describe('[#33131] two namespaces ship one name, one declares its override: each holder\'s address serves its own item', () => { +// Each case boots the engine, installs two or three packages and restarts it; about 0.5 s alone, +// over the 5 s default on a loaded CI shard (merge-queue run 43619123356 timed one out at 5 s while +// the file took 63 s). The budget is room for load, not for a slower product: the same file runs +// 11.5-13.3 s on main's sources and 12.2-12.6 s on this branch's, measured back to back. +describe('[#33131] two namespaces ship one name, one declares its override: each holder\'s address serves its own item', { timeout: 30_000 }, () => { const ALPHA = 'com.probe.alpha'; const BETA = 'com.probe.beta'; const STRANGER = 'com.probe.stranger'; From 952550aea38aba428e045206b01aedc104f49090 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 18:29:09 +0000 Subject: [PATCH 14/14] chore: regenerate the authorable surface after merging main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibvyhxPWfA8DsbmVYJ5 --- packages/spec/authorable-surface/api.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index a03591ac192..598544b9db7 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -215,7 +215,9 @@ "api/AuthFeaturesConfig:degradedTenancy", "api/AuthFeaturesConfig:developerEditionCreate", "api/AuthFeaturesConfig:deviceAuthorization", + "api/AuthFeaturesConfig:directSignIn", "api/AuthFeaturesConfig:emailDelivery", + "api/AuthFeaturesConfig:localSignIn", "api/AuthFeaturesConfig:magicLink [RETIRED]", "api/AuthFeaturesConfig:multiOrgEnabled", "api/AuthFeaturesConfig:oidcProvider",