From 797bd5bb4828b55fc8f2e2db45267db969a96f29 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:24:34 +0000 Subject: [PATCH 1/4] wip(metadata-protocol): the diff door reads one holder's versions of a by-package name Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../src/protocol-diff-delete-load.ts | 79 ++++++++++++++++--- .../src/sys-metadata-repository.ts | 48 +++++++---- packages/rest/src/meta-item-history-routes.ts | 33 +++++--- .../rest-server-meta-door-closed-sets.test.ts | 3 +- packages/rest/src/rest-server.ts | 13 +-- packages/spec/src/api/protocol.zod.ts | 30 +++++++ 6 files changed, 163 insertions(+), 43 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 235e44294da..793d3afc0ad 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -26,9 +26,12 @@ import { overlayMemberWhere } from './migrations/overlay-index.js'; import { historyRowsOfMember, + isVersionOf, packagelessAddressAmbiguityRefusal, versionNotFoundError, + versionOfAnotherSlotError, } from './sys-metadata-repository.js'; +import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; import { ConflictError, findUndeclarableFieldType, @@ -64,13 +67,24 @@ import { captureStoredExpressionChange, fillStoredExpressionChange } from './pro import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; +/** + * [#33308] The row slot a `sys_metadata` row is: its bound package, or `null` + * for the package-less row — the binding {@link historySlotOf} reads off the + * row a read naming a package serves. + */ +function rowSlotOf(row: { package_id?: unknown }): string | null { + return typeof row.package_id === 'string' && row.package_id !== '' ? row.package_id : null; +} + export class ProtocolDiffDeleteLoadFacet { /** The body of `ObjectStackProtocolImplementation#diffMetaItem`; the method's docblock there is its contract. */ - static async diffMetaItem(host: Pick, request: { + static async diffMetaItem(host: Pick, request: { type: string; name: string; fromVersion?: number; toVersion?: number; + /** [ADR-0150 D3/D4, #33308] The package whose versions to compare — {@link historySlotOf}; omitted, the name's. */ + packageId?: string; }): Promise<{ type: string; name: string; @@ -118,6 +132,10 @@ export class ProtocolDiffDeleteLoadFacet { // the read below reads it as "the key the row is stored under" — the same // shape {@link rollbackMetaItem} keeps. const singularType = request.type; + // [#33308] `?package=` addresses a holder of a type stored per + // `(package, name)` only; on any other type it is refused first, as + // the history and rollback doors refuse it, never accepted and dropped. + refusePackageSelectorOutsideSlottedTypes(singularType, request.packageId); // [#21442] A view name with no stored row of its own that a stored // view container in this caller's scope expands — a name the by-name // read answers with the container's expansion — has no versions of its @@ -132,6 +150,21 @@ export class ProtocolDiffDeleteLoadFacet { if (expandedFrom !== undefined) { return host.diffMetaItem({ ...request, name: expandedFrom.container.name }); } + // [ADR-0150 D3/D4, #33308] The third door of the history family reads + // the slot the history and rollback doors read ({@link historySlotOf}): + // for a type stored per `(package, name)` the name's versions + // interleave every holder's, so a name two holders hold is refused + // `409` naming both when no package is named, before any version is + // read, and `?package=` compares that holder's versions alone — its + // own versions on both sides, its own active row as the default `to` + // side, and the default `from` side found among its own versions. + // ⛔ Never a version of another holder compared as this one's earlier + // or later body. A name one slot holds, named bare, diffs as before. + const slot = await historySlotOf(host, { + type: singularType, name: request.name, + ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), + }); + const versionsOf = slot?.addressed ? slot.owner : undefined; // [#8798] Read the history rows DIRECTLY, once. `historyMetaItem` // cannot serve this function: its `MetadataEvent` shape doesn't carry // the per-(type,name) `version` a diff selects versions by, so its @@ -155,6 +188,9 @@ export class ProtocolDiffDeleteLoadFacet { // so removing the call makes every type take it. Pinned in // `protocol.diff-dead-history-read.test.ts`. const histRows: Array<{ version: number; body: Record | null }> = []; + // [#33308] The rows of another slot, by version: named, they are + // refused saying whose they are, never compared. + const otherSlotRows = new Map>(); try { // [#21908, ADR-0096 D5] The explicit system opt-in: the history // lineage is a platform store the diff door already authorized. @@ -173,6 +209,10 @@ export class ProtocolDiffDeleteLoadFacet { })); rows.sort((a: any, b: any) => (a.version ?? 0) - (b.version ?? 0)); for (const r of rows) { + if (versionsOf !== undefined && !isVersionOf(r, versionsOf)) { + otherSlotRows.set(r.version ?? 0, r); + continue; + } const body = r.metadata == null ? null : (typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata); @@ -221,6 +261,15 @@ export class ProtocolDiffDeleteLoadFacet { } const byVersion = new Map | null>(); for (const r of histRows) byVersion.set(r.version, r.body); + // [#26462] A named version with no row of this item is a miss; + // [#33308] one another holder's slot owns is refused saying whose it + // is (the rollback door's sentence), and nothing is compared. + const namedVersionMiss = (version: number): Error => { + const other = otherSlotRows.get(version); + return other !== undefined && versionsOf !== undefined + ? versionOfAnotherSlotError({ type: singularType, name: request.name }, version, versionsOf, other, 'Nothing was compared.') + : versionNotFoundError({ type: singularType, name: request.name }, version); + }; let fromBody: Record | null = null; let toBody: Record | null = null; @@ -239,7 +288,7 @@ export class ProtocolDiffDeleteLoadFacet { // served. const named = byVersion.get(request.toVersion); if (named === undefined) { - throw versionNotFoundError({ type: singularType, name: request.name }, request.toVersion); + throw namedVersionMiss(request.toVersion); } toBody = named; } else { @@ -270,14 +319,22 @@ export class ProtocolDiffDeleteLoadFacet { // bodies repeat earlier ones. // [#21908, ADR-0096 D5] The explicit system opt-in, as the history // read above. - const current = (await host.findEnvironmentRow('sys_metadata', { - where: { - type: singularType, name: request.name, state: 'active', - // [#22877] The canonical member, as the by-name read serves. - ...overlayMemberWhere(singularType), - }, - context: { isSystem: true }, - })) as { metadata?: unknown; version?: unknown } | null; + const currentWhere = { + type: singularType, name: request.name, state: 'active', + // [#22877] The canonical member, as the by-name read serves. + ...overlayMemberWhere(singularType), + }; + // [#33308] Addressed, the to side is the addressed slot's own + // active row (bound to its package, or the package-less row for + // the environment's slot), never another holder's row of the + // name; a slot no row holds has no active side. + const current = (versionsOf !== undefined + ? ((await host.findEnvironmentRows('sys_metadata', { where: currentWhere, context: { isSystem: true } })) + .find((row: { package_id?: unknown }) => rowSlotOf(row) === versionsOf.packageId) ?? null) + : await host.findEnvironmentRow('sys_metadata', { + where: currentWhere, + context: { isSystem: true }, + })) as { metadata?: unknown; version?: unknown } | null; toBody = current?.metadata == null ? null : (typeof current.metadata === 'string' @@ -290,7 +347,7 @@ export class ProtocolDiffDeleteLoadFacet { // [#26462] The same miss on the from side — see the to side above. const named = byVersion.get(request.fromVersion); if (named === undefined) { - throw versionNotFoundError({ type: singularType, name: request.name }, request.fromVersion); + throw namedVersionMiss(request.fromVersion); } fromBody = named; } else if (toVersion !== null) { diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index e76b3df80e2..c6060aab47f 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -594,13 +594,44 @@ export interface HistoryVersionOwner { sole: boolean; } -/** [#32905] Whether history row `row` is a version of `owner`'s slot. */ -function isVersionOf(row: Record, owner: HistoryVersionOwner): boolean { +/** + * [#32905] Whether history row `row` is a version of `owner`'s slot. [#33308] + * The diff door (`diffMetaItem`) filters the rows it compares by this same + * predicate, so the three doors of the family read one rule. + */ +export function isVersionOf(row: Record, owner: HistoryVersionOwner): boolean { const attributed = historyRowAttribution(row); if (attributed === undefined) return owner.sole; return attributed === owner.packageId || (attributed === null && owner.sole); } +/** + * [#32905] The `404 VERSION_NOT_FOUND` for a version that is not `owner`'s + * slot's ({@link isVersionOf} answered false for history row `row`), saying + * whose it is. [#33308] One sentence for the rollback (`outcome`: nothing was + * restored) and the diff door (nothing was compared). + */ +export function versionOfAnotherSlotError( + ref: { type: string; name: string }, + version: number, + owner: HistoryVersionOwner, + row: Record, + outcome: string, +): Error & { code: 'VERSION_NOT_FOUND'; status: 404 } { + const attributed = historyRowAttribution(row); + const whose = (id: string | null) => (id === null ? 'the environment\'s own row' : `package '${id}'`); + const err = new Error( + `No history row at version ${version} for ${ref.type}/${ref.name} of ${whose(owner.packageId)}: ` + + (attributed === 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(attributed)}.`) + + ` ${outcome}`, + ) as Error & { code: 'VERSION_NOT_FOUND'; status: 404 }; + err.code = 'VERSION_NOT_FOUND'; + err.status = 404; + return err; +} + /** * [#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 @@ -1791,18 +1822,7 @@ export class SysMetadataRepository implements MetadataRepository { }); 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; + throw versionOfAnotherSlotError(ref, targetVersion, opts.versionOf, row as Record, 'Nothing was restored.'); } const raw = (row as any).metadata; if (raw === null || raw === undefined) { diff --git a/packages/rest/src/meta-item-history-routes.ts b/packages/rest/src/meta-item-history-routes.ts index 3b838cadb7e..933b8b42146 100644 --- a/packages/rest/src/meta-item-history-routes.ts +++ b/packages/rest/src/meta-item-history-routes.ts @@ -165,8 +165,8 @@ 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, RollbackMetaItemRequestSchema } from '@objectstack/spec/api'; -import type { AuditMetaItemRequest, HistoryMetaItemRequest, PublishMetaItemRequest } from '@objectstack/spec/api'; +import { AuditMetaItemRequestSchema, DiffMetaItemRequestSchema, HistoryMetaItemRequestSchema, RollbackMetaItemRequestSchema } from '@objectstack/spec/api'; +import type { AuditMetaItemRequest, DiffMetaItemRequest, HistoryMetaItemRequest, PublishMetaItemRequest } from '@objectstack/spec/api'; import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import { handleRouteError, sendFieldVisibilityFault, thrownAnswerIsBareNotFound } from './error-response.js'; import type { MetaRouteScope, TransportScopedMetaRequest } from './meta-collection-routes.js'; @@ -179,7 +179,6 @@ import { META_ITEM_HISTORY_PARAMS, META_ITEM_PUBLISH_PARAMS, META_ITEM_ROLLBACK_PARAMS, - UNDECLARED_WHOLE_NUMBER_PARAM, metaItemPackageBinding, readDeclaredQueryNumber, refuseNonAuthoringCaller, @@ -221,7 +220,8 @@ export interface MetaItemHistoryRouteHost { * [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. + * reads, or whose row it restores. [#33308] And the diff door's: the holder + * whose versions it compares. */ function historyPackageSelector(query: unknown): { packageId?: string } { const packageId = metaItemPackageBinding((query as { package?: unknown } | undefined)?.package); @@ -949,15 +949,16 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc // pair of versions and answered 200. // [#23072] Recognition first, over the measured closed set. if (refuseUnknownQueryParams(req, res, META_ITEM_DIFF_PARAMS)) return; - if (refuseRepeatedQueryParams(req, res, ['from', 'fromVersion', 'to', 'toVersion'])) return; + if (refuseRepeatedQueryParams(req, res, ['from', 'fromVersion', 'to', 'toVersion', 'package'])) return; // [#20139] The same drop for a SINGLE unreadable value: the // `parseV` helper that stood here answered `undefined` for // `?from=abc` (and `Infinity`), so `diffMetaItem` substituted // "the version before `to`" — or, for `?to=abc`, the CURRENT // body — and the door answered 200 with a comparison nobody // asked for; `?from=1.5` was forwarded and diffed against a - // version that cannot exist. No request schema is declared for - // this door, so a version reads as a whole number. The name the + // version that cannot exist. [#33308] A version reads through + // the door's declaration (`DiffMetaItemRequestSchema`), a whole + // number, as it read before the request was declared. The name the // caller used is the one read (and the one a refusal names): // `from` / `to` win over `fromVersion` / `toVersion` exactly as // the old `??` had it, and an empty value stays absent, as @@ -965,9 +966,9 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc const fromParam = req.query?.from != null ? 'from' : 'fromVersion'; const toParam = req.query?.to != null ? 'to' : 'toVersion'; const fromVersion = readDeclaredQueryNumber(req.query, fromParam, - UNDECLARED_WHOLE_NUMBER_PARAM, { emptyIsAbsent: true }); + DiffMetaItemRequestSchema.shape.fromVersion, { emptyIsAbsent: true }); const toVersion = readDeclaredQueryNumber(req.query, toParam, - UNDECLARED_WHOLE_NUMBER_PARAM, { emptyIsAbsent: true }); + DiffMetaItemRequestSchema.shape.toVersion, { emptyIsAbsent: true }); // [#20156] A diff discloses BOTH versions' values — for a // doc its `content`, for an app its `navigation`, for an // object its `fields` — so it owes the plain read's @@ -1031,13 +1032,20 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc // `version` is a per-(org, type, name) lineage counter, so // the environment lineage is the one every `/meta` write // now extends. - const result = await (p as any).diffMetaItem({ + // [#33308] Compiled against the declared request, as the + // history twin's is: an undeclared member is a type error. + const diffRequest: TransportScopedMetaRequest = { type: req.params.type, name: req.params.name, ...(environmentId ? { environmentId } : {}), ...(fromVersion !== undefined ? { fromVersion } : {}), ...(toVersion !== undefined ? { toVersion } : {}), - }); + // [ADR-0150 D3/D4, #33308] ONE holder's versions, for a type + // stored per `(package, name)`, as the history door reads + // them: naming none of two holders is refused 409. + ...historyPackageSelector(req.query), + }; + const result = await (p as any).diffMetaItem(diffRequest); // [#20156] Judge the current document and both sides, with // ONE judge (one books read, one holdings resolution): a // side the caller may not read is not served beside one @@ -1101,7 +1109,8 @@ export function registerMetaItemHistoryRoutes(this: MetaItemHistoryRouteHost, sc } res.json(served); } catch (error: any) { - handleRouteError(res, error); + // [#33308] A two-holder refusal names its holders (`details.candidates`), as the history door renders it. + handleRouteError(res, error, undefined, { packageScopedCandidates: true }); } }, metadata: { diff --git a/packages/rest/src/rest-server-meta-door-closed-sets.test.ts b/packages/rest/src/rest-server-meta-door-closed-sets.test.ts index 9d29589c80d..c803dd70b23 100644 --- a/packages/rest/src/rest-server-meta-door-closed-sets.test.ts +++ b/packages/rest/src/rest-server-meta-door-closed-sets.test.ts @@ -129,7 +129,8 @@ describe('[#23072] each by-name /meta door outside the ruling\'s list declares a expect([...META_ITEM_REFERENCES_PARAMS]).toEqual([]); expect([...META_ITEM_LAYERS_PARAMS]).toEqual(['package', 'member']); expect([...META_ITEM_AUDIT_PARAMS]).toEqual(['limit']); - expect([...META_ITEM_DIFF_PARAMS].sort()).toEqual(['from', 'fromVersion', 'to', 'toVersion']); + // [#33308] `package`: the holder whose versions a by-package name's diff compares. + expect([...META_ITEM_DIFF_PARAMS].sort()).toEqual(['from', 'fromVersion', 'package', 'to', 'toVersion']); expect([...META_ITEM_PUBLISHED_PARAMS]).toEqual([]); for (const entry of DOORS) { if ('readsMember' in entry) expect(entry.set).toContain('member'); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 244bca4ec64..01004f10025 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -809,17 +809,20 @@ export const META_ITEM_AUDIT_PARAMS: readonly string[] = ['limit']; * and `to`, and the `fromVersion` / `toVersion` the door falls back to when the * short name is absent — each read through `readDeclaredQueryNumber`. The same * four names the door's multiplicity guard declares; the authoring-door and - * per-caller refusals read the session. + * per-caller refusals read the session. [ADR-0150 D3/D4, #33308] And + * `package`, the holder whose versions to compare, through + * {@link metaItemPackageBinding}, as the history door reads it. */ -export const META_ITEM_DIFF_PARAMS: readonly string[] = ['from', 'fromVersion', 'to', 'toVersion']; +export const META_ITEM_DIFF_PARAMS: readonly string[] = ['from', 'fromVersion', 'to', 'toVersion', 'package']; /** * [#20062 / #20139] The reading of a numeric query parameter on a door whose * request has no declared schema: a whole number, and nothing about range. - * Every such parameter in this file counts or addresses whole things — rows + * Every such parameter in this file counts whole things — rows * (`GET /data/:object/export` `limit`; `GET /search` `limit` / `perObject`; - * `GET /approvals/requests` `limit` / `offset`) or history versions - * (`GET /meta/:type/:name/diff` `from` / `to`). Range stays each door's own + * `GET /approvals/requests` `limit` / `offset`). (`GET /meta/:type/:name/diff` + * `from` / `to` read the same whole number through the door's declared + * request, `DiffMetaItemRequestSchema`, since #33308.) Range stays each door's own * business — the export route's `Math.max(1, …)` floor and 50000 cap, * `searchAll`'s `[1, 100]` / `[1, 25]` clamps, the approvals service's * `[1, 200]` — because no card this closes takes a position on bounds; it only diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 678dfe64b16..28a0561cc34 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2750,6 +2750,33 @@ export const RollbackMetaItemResponseSchema = lazySchema(() => z.object({ ), })); +/** + * Diff Metadata Item Request + * + * Request shape for `GET /api/v1/meta/:type/:name/diff` (the `diffMetaItem` + * protocol method): the two bounds from the query (`from` / `to`, or their + * `fromVersion` / `toVersion` spellings), both read through this declaration, + * and `package` from the query. Mirrors the implementation's parameter type + * in `@objectstack/metadata-protocol` member for member — a declared-surface + * catch-up (#33308), as `RollbackMetaItemRequestSchema` is for the rollback + * door. + */ +export const DiffMetaItemRequestSchema = lazySchema(() => z.object({ + type: z.string().describe('Metadata type name'), + name: z.string().describe('Item name'), + fromVersion: z.number().int().optional().describe( + 'The older side\'s history version, a whole number as the history lists it. Absent, the nearest ' + + 'earlier version whose body differs from the `to` side\'s. A version with no history row of the ' + + 'item (or, with `packageId`, of that holder) is refused 404 `VERSION_NOT_FOUND`.', + ), + toVersion: z.number().int().optional().describe( + 'The newer side\'s history version, a whole number as the history lists it. Absent, the active ' + + 'row (with `packageId`, that holder\'s own active row). Refused 404 `VERSION_NOT_FOUND` as ' + + '`fromVersion` is.', + ), + packageId: z.string().optional().describe(HISTORY_PACKAGE_SELECTOR_DESCRIPTION), +})); + /** * `GET /meta/:type/:name/diff` — structural diff between two history * versions (`from`/`to`). An omitted `to` is the active version; an omitted @@ -4584,6 +4611,9 @@ export type RollbackMetaItemRequestParsed = z.infer; /** Post-parse shape of {@link RollbackMetaItemResponse} — defaults applied, transforms run (ADR-0122). */ export type RollbackMetaItemResponseParsed = z.infer; +export type DiffMetaItemRequest = z.input; +/** Post-parse shape of {@link DiffMetaItemRequest} — defaults applied, transforms run (ADR-0122). */ +export type DiffMetaItemRequestParsed = z.infer; export type DiffMetaItemResponse = z.input; /** Post-parse shape of {@link DiffMetaItemResponse} — defaults applied, transforms run (ADR-0122). */ export type DiffMetaItemResponseParsed = z.infer; From 444bebb26287175ea4586570a7bcb611eb6d3504 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:18:10 +0000 Subject: [PATCH 2/4] fix(metadata-protocol)!: the diff door reads the history slot, declares its request and takes ?package= Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .changeset/33308-diff-door-package-address.md | 21 ++ content/docs/references/api/protocol.mdx | 21 +- content/docs/references/index.mdx | 10 +- .../api.md | 2 +- .../protocol-diff-history-slots.33308.test.ts | 150 +++++++++++++ packages/metadata-protocol/src/protocol.ts | 20 ++ ...ory-diff-two-holders-33308.dogfood.test.ts | 205 ++++++++++++++++++ ...meta-item-history-package-selector.test.ts | 63 +++++- packages/spec/api-surface/api.json | 3 + packages/spec/authorable-surface/api.json | 5 + packages/spec/declaration-map/api.json | 2 + packages/spec/export-origins/api.json | 3 + packages/spec/json-schema.manifest/api.json | 1 + packages/spec/src/api/protocol.test.ts | 23 ++ 14 files changed, 519 insertions(+), 10 deletions(-) create mode 100644 .changeset/33308-diff-door-package-address.md create mode 100644 packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts create mode 100644 packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts diff --git a/.changeset/33308-diff-door-package-address.md b/.changeset/33308-diff-door-package-address.md new file mode 100644 index 00000000000..b760222f54c --- /dev/null +++ b/.changeset/33308-diff-door-package-address.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +--- + +fix(metadata-protocol)!: the diff door of a by-package name refuses the bare name two holders hold, and `?package=` compares one holder's versions (ADR-0150 D3/D4, #33308) + +Clause-②: yes (narrowing) — narrowed: for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`), `GET /meta/:type/:name/diff` naming no package is refused `409 RESOURCE_CONFLICT` before any version is read wherever the history and rollback doors refuse the name (two or more row slots hold it, `details.candidates` naming every holder, or the bare plain read refuses it), where it answered one holder's version compared against another holder's as one item's change; an addressed diff (`?package=`) naming a version of another holder, or a version attributed to no package while two hold the name, is refused `404 VERSION_NOT_FOUND` saying whose it is, and nothing is compared. Widened: the door accepts `?package=` on a by-package type (the `/layers?package=` spelling), which compares that holder's versions only, its own active row as the default `to` side and its own nearest earlier differing version as the default `from` side; 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 diffs bare exactly as on `main`. +Metadata-protocol: added +Skills-docs: none — no skill under `skills/` names the diff door, and the docs that do (`content/docs/api/client-sdk.mdx`, `content/docs/permissions/system-context.mdx`, `content/docs/ui/apps.mdx`) name the route 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 `DiffMetaItemRequest` with its `packageId`. + + + +**BREAKING** for a bare diff 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/diff?from=N&to=M` TO `GET /meta/TYPE/NAME/diff?package=PKG&from=N&to=M`, with both versions that holder's (its `?package=` history lists them), once per holder the `409` names. + +`?package=` names a holder exactly as the history and rollback doors read it (`historySlotOf`): the row a read naming that package serves, else the package's own slot when it ships the name; a package that neither holds nor ships the name is refused `409` (`not-held-by-qualifier`). `all` and the empty string name no package. + +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 (the new `DiffMetaItemRequestSchema`, declaring the diff door's request with its two whole-number bounds and `packageId`), and the level `Check Changeset` demands for `Metadata-protocol: added`. Every other package is `patch` under the BREAKING banner above: `@objectstack/metadata-protocol` (`diffMetaItem` takes `packageId`) and `@objectstack/rest` (the diff door accepts `?package=` and reads its bounds through the declaration). diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 7b082da542c..48d3fc552d2 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 144 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 145 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, 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'; +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, DiffMetaItemRequestSchema, 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, DiffMetaItemRequest, 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); @@ -772,6 +772,21 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **userMessage** | `string` | optional | The finding's user-facing sentence, composed by its producer in the request's locale (else the workspace default locale, else `en`) — the same field name and producer-marked meaning as `ApiErrorSchema.userMessage`. Present only when the producer authors a user sentence for this `rule`; absent, a consumer renders `message` as before. Consumers render it as received; `rule` stays the stable id and `message` / `hint` stay the developer-facing text. | +--- + +## DiffMetaItemRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type name | +| **name** | `string` | ✅ | Item name | +| **fromVersion** | `integer` | optional | The older side's history version, a whole number as the history lists it. Absent, the nearest earlier version whose body differs from the `to` side's. A version with no history row of the item (or, with `packageId`, of that holder) is refused 404 `VERSION_NOT_FOUND`. | +| **toVersion** | `integer` | optional | The newer side's history version, a whole number as the history lists it. Absent, the active row (with `packageId`, that holder's own active row). Refused 404 `VERSION_NOT_FOUND` as `fromVersion` is. | +| **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). | + + --- ## DiffMetaItemResponse diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 00bb26d3cc6..ce61fbe6692 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 — 1662 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1663 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 | 493 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 36 | 494 | 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** | **1662** | 14 protocol modules | +| **Total** | **218** | **1663** | 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, 493 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **36 pages, 494 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`, `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` | +| [`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`, `DiffMetaItemRequest`, `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 0db232128e9..e8153829ee9 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/` | 508 | +| `api/` | 509 | diff --git a/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts new file mode 100644 index 00000000000..c4b89edb6cd --- /dev/null +++ b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts @@ -0,0 +1,150 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D3/D4, #33308] `diffMetaItem`, the third door of the history + * family, reads the row slot the history and rollback doors read + * (`historySlotOf`), judged against a fake host so each arm is pinned on its + * own: + * + * - bare, a name two row slots hold is refused `409` naming both, before any + * version is read; + * - `?package=P` compares P's versions alone: the default `to` side is P's + * own active row, the default `from` side is found among P's versions, and + * a named version another holder owns (or one attributed to no package, + * while two hold the name) is refused `404 VERSION_NOT_FOUND` saying whose; + * - CONTROL: a name one slot holds diffs bare as before, its whole log; + * - `?package=` on a type not stored per package is refused `400`. + * + * The real-boot pins live in `history-diff-two-holders-33308.dogfood.test.ts`. + */ + +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 } from '@objectstack/core'; +import { ProtocolDiffDeleteLoadFacet } from './protocol-diff-delete-load.js'; + +const ALPHA = 'com.acme.alpha.custom'; +const BETA = 'com.acme.beta.custom'; +const body = (label: string) => ({ name: 'shared_flow', label }); + +/** v1 alpha, v2 beta, v3 alpha, v4 beta, v5 attributed to no package. */ +const HISTORY = [ + { version: 1, package_id: ALPHA, metadata: JSON.stringify(body('alpha r1')) }, + { version: 2, package_id: BETA, metadata: JSON.stringify(body('beta r1')) }, + { version: 3, package_id: ALPHA, metadata: JSON.stringify(body('alpha r2')) }, + { version: 4, package_id: BETA, metadata: JSON.stringify(body('beta r2')) }, + { version: 5, metadata: JSON.stringify(body('legacy')) }, +]; + +/** Beta's row first, so a read that picks the name's first active row picks the wrong holder for alpha. */ +const ACTIVE = [ + { package_id: BETA, version: 4, state: 'active', metadata: JSON.stringify(body('beta r2')) }, + { package_id: ALPHA, version: 3, state: 'active', metadata: JSON.stringify(body('alpha r2')) }, +]; + +function fakeHost(options: { candidates: string[]; history?: unknown[]; active?: unknown[] }) { + const reads: string[] = []; + const host: any = { + engine: { registry: { readsByPackage: () => true, resolveItem: () => ({ status: 'resolved' }) } }, + packagelessAddress: async () => ({ candidates: options.candidates, unbound: false }), + findServedOverlayRow: async (q: { packageId: string }) => { + const row = (options.active ?? ACTIVE).find((r: any) => r.package_id === q.packageId); + return row === undefined ? undefined : { row }; + }, + shippedArtifactsOf: () => [], + resolveRowlessExpandedView: async () => undefined, + rethrowUnlessMetadataStoreUnprovisioned: (error: unknown) => { throw error; }, + findEnvironmentRows: async (table: string) => { + reads.push(table); + return table === 'sys_metadata_history' + ? (options.history ?? HISTORY).map((r: any) => ({ type: 'flow', name: 'shared_flow', ...r })) + : (options.active ?? ACTIVE); + }, + findEnvironmentRow: async (table: string) => { + reads.push(table); + return (options.active ?? ACTIVE)[0] ?? null; + }, + }; + host.diffMetaItem = (request: any) => ProtocolDiffDeleteLoadFacet.diffMetaItem(host, request); + return { host, reads }; +} + +async function refusalOf(p: Promise): Promise { + return p.then(() => null, (e: unknown) => e); +} + +const label = (answer: any) => answer.changed.find((e: any) => e.path === 'label'); + +describe('diffMetaItem reads one holder\'s versions of a by-package name (#33308)', () => { + it('bare, a name two row slots hold is refused 409 naming both, before any version is read', async () => { + const { host, reads } = fakeHost({ candidates: [ALPHA, BETA] }); + for (const request of [{}, { fromVersion: 1, toVersion: 2 }]) { + const err = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow', ...request })); + expect(err, JSON.stringify(request)).toBeInstanceOf(PackageScopedNameRefusedError); + expect(err.code).toBe('RESOURCE_CONFLICT'); + expect(err.status).toBe(409); + expect(err.refusal.candidates.map((c: any) => c.packageId)).toEqual([ALPHA, BETA]); + } + expect(reads).toEqual([]); + }); + + it('?package= compares that holder\'s own active row against its own nearest earlier version', async () => { + const { host } = fakeHost({ candidates: [ALPHA, BETA] }); + const alpha = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: ALPHA }); + expect([alpha.fromVersion, alpha.toVersion]).toEqual([1, 3]); + expect(label(alpha)).toEqual({ path: 'label', from: 'alpha r1', to: 'alpha r2' }); + const beta = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: BETA }); + expect([beta.fromVersion, beta.toVersion]).toEqual([2, 4]); + expect(label(beta)).toEqual({ path: 'label', from: 'beta r1', to: 'beta r2' }); + }); + + it('?package= with a named range of its own versions answers it', async () => { + const { host } = fakeHost({ candidates: [ALPHA, BETA] }); + const answer = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: ALPHA, fromVersion: 1, toVersion: 3 }); + expect(label(answer)).toEqual({ path: 'label', from: 'alpha r1', to: 'alpha r2' }); + }); + + it('?package= refuses a version another holder owns 404 saying whose, on either side', async () => { + const { host } = fakeHost({ candidates: [ALPHA, BETA] }); + for (const request of [{ fromVersion: 2, toVersion: 3 }, { fromVersion: 1, toVersion: 4 }, { fromVersion: 2 }]) { + const err = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: ALPHA, ...request })); + expect(err?.code, JSON.stringify(request)).toBe('VERSION_NOT_FOUND'); + expect(err.status).toBe(404); + expect(err.message).toContain(`package '${BETA}'`); + } + }); + + it('?package= refuses a version attributed to no package while two hold the name', async () => { + const { host } = fakeHost({ candidates: [ALPHA, BETA] }); + const err = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: ALPHA, fromVersion: 5 })); + expect(err?.code).toBe('VERSION_NOT_FOUND'); + expect(err.status).toBe(404); + }); + + it('?package= on a slot no row holds compares nothing on the to side and finds no earlier version', async () => { + const { host } = fakeHost({ candidates: [ALPHA, BETA], active: [ACTIVE[0]] }); + const answer = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: ALPHA }); + expect([answer.fromVersion, answer.toVersion]).toEqual([null, null]); + }); + + it('CONTROL: a name one slot holds diffs bare across its whole log, as before', async () => { + const history = HISTORY.filter((r) => r.package_id !== BETA); + const active = [ACTIVE[1]]; + const { host } = fakeHost({ candidates: [ALPHA], history, active }); + const range = await host.diffMetaItem({ type: 'flow', name: 'shared_flow' }); + expect([range.fromVersion, range.toVersion]).toEqual([1, 3]); + // The unattributed version is the sole slot's. + const legacy = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', fromVersion: 5, toVersion: 3 }); + expect(label(legacy)).toEqual({ path: 'label', from: 'legacy', to: 'alpha r2' }); + }); + + it('?package= on a type not stored per package is refused 400 VALIDATION_ERROR naming the parameter', async () => { + const { host, reads } = fakeHost({ candidates: [] }); + const err = await refusalOf(host.diffMetaItem({ type: 'view', name: 'any_view', packageId: ALPHA })); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err.status).toBe(400); + expect(err.param).toBe('package'); + expect(reads).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 1affb8b7198..8a7efe42a2e 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -11071,12 +11071,32 @@ export class ObjectStackProtocolImplementation implements * for any item with no history. Without that * asymmetry an outage would be indistinguishable from "these two * versions are identical" (ADR-0110 D3). + * @throws {@link PackageScopedNameRefusedError} — 409 / + * `RESOURCE_CONFLICT` (ADR-0150 D3/D4, #33308), for a type stored + * per `(package, name)`, when no `packageId` is named and two or + * more row slots hold the name, or the bare plain read refuses it + * (`details.candidates` naming every holder), before any version + * is read; and when `packageId` names a package that neither + * holds a row of the name nor ships it while another slot holds + * one (`not-held-by-qualifier`). The history and rollback doors' + * rule (`historySlotOf`). + * @throws `VERSION_NOT_FOUND` — 404 (#33308), with `packageId`, when an + * explicit version belongs to another holder's slot, or is + * attributed to no package while two hold the name, saying whose + * it is: nothing is compared. With `packageId` the default `to` + * side is that holder's own active row and the default `from` + * side is found among its own versions. + * @throws `VALIDATION_ERROR` — 400 (#33308), when `packageId` is named + * on a type not stored per `(package, name)`: refused, never + * accepted and dropped. */ async diffMetaItem(request: { type: string; name: string; fromVersion?: number; toVersion?: number; + /** [ADR-0150 D3/D4, #33308] The package whose versions to compare (`?package=`); omitted, the name's. */ + packageId?: string; }): Promise<{ type: string; name: string; diff --git a/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts new file mode 100644 index 00000000000..4f741095135 --- /dev/null +++ b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts @@ -0,0 +1,205 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0150 D3/D4, #33308] The `/meta` diff door of a flow name two packages +// hold, on a booted showcase — the third door of the family whose history and +// rollback doors `history-rollback-two-holders.dogfood.test.ts` pins. +// +// A flow is stored per `(package, name)`: each holder has its own +// `sys_metadata` row, and the name's versions are numbered across them. Before +// this card the diff door read the name alone: measured, the bare +// `diff?from=&to=` answered 200, one holder's body +// compared against the other's as if one item's, and `?package=` was refused +// as an unknown parameter. Now it reads the slot the history and rollback +// doors read (`historySlotOf`): +// +// - naming no package, the two-holder name is refused `409 RESOURCE_CONFLICT` +// naming each holder (`details.candidates`), the default range and a named +// one alike, and so is a name the bare plain read refuses (two packages +// ship it, one customized); +// - `?package=` compares that holder's versions alone: its own active row as +// the default `to` side, its own nearest earlier differing version as the +// default `from` side; a version of the other holder, or one recorded +// before the history row named its package, is refused `404 +// VERSION_NOT_FOUND`, comparing nothing; +// - CONTROL: a name one package holds diffs bare as before, and so does a +// name first saved as the environment's own item and later taken over by a +// package (M1): the environment's versions are its sole slot's; +// - `?package=` on a type not stored per package is refused 400, never +// accepted and dropped. + +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.diff33308.alpha'; +const BETA = 'com.qa.diff33308.beta'; +const ALPHA_PAIR = `${ALPHA}.custom`; +const BETA_PAIR = `${BETA}.custom`; +/** A runtime flow both pairs save (no package ships it). */ +const SHARED = 'qa_diff_shared_33308'; +/** A runtime flow only alpha's pair holds: the CONTROL. */ +const SOLO = 'qa_diff_solo_33308'; +/** A flow both packages ship, only alpha's pair customizes. */ +const SHIPPED_ONE = 'qa_diff_shipped_one_33308'; +/** A runtime flow saved as the environment's own item, deleted, then saved in alpha's pair (M1). */ +const TAKEN_OVER = 'qa_diff_taken_over_33308'; + +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.diff33308.${p}`, namespace: `d33308${p}`, name: `qa_diff33308_${p}`, version: '1.0.0', type: 'app' }, + flows: [flowBody(SHIPPED_ONE, `${p} shipped one`)], + } as never); +} + +describe('the /meta diff door of a flow name two packages hold (ADR-0150 D3/D4, #33308)', () => { + 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 | 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); + }; + const candidatesOf = (json: any) => + (json?.details?.candidates ?? []).map((c: any) => c.packageId ?? c.kind).sort(); + const diffLabel = (json: any) => (json?.changed ?? []).find((e: any) => e.path === 'label'); + const ownVersions = async (name: string, pkg: string) => + versions((await call('GET', `/meta/flow/${name}/history?package=${pkg}`)).json); + + /** The versions each holder's saves wrote, read back from the history door. */ + 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); + } + // Interleaved: alpha r1, beta r1, alpha r2, beta r2. + for (const round of [1, 2]) { + for (const pair of [ALPHA_PAIR, BETA_PAIR]) await save(SHARED, pair, `${pair} r${round}`); + } + for (const pair of [ALPHA_PAIR, BETA_PAIR]) shared[pair] = await ownVersions(SHARED, pair); + 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(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'); + // A version of SHARED recorded before the history row named its package + // (a release before ADR-0150 D4's attribution): `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 diff of the two-holder name is refused 409 naming both holders, the default range and a named one alike', async () => { + expect(shared[ALPHA_PAIR]).toHaveLength(2); + expect(shared[BETA_PAIR]).toHaveLength(2); + for (const path of [ + `/meta/flow/${SHARED}/diff`, + `/meta/flow/${SHARED}/diff?from=${shared[ALPHA_PAIR]![0]}&to=${shared[BETA_PAIR]![0]}`, + ]) { + const res = await call('GET', path); + expect(res.status, `${path}: ${JSON.stringify(res.json)}`).toBe(409); + expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(res.json)).toEqual([ALPHA_PAIR, BETA_PAIR].sort()); + } + }); + + it('a name two packages ship, one customized, is refused bare at the diff door 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 diff = await call('GET', `/meta/flow/${SHIPPED_ONE}/diff`); + expect(diff.status, JSON.stringify(diff.json)).toBe(409); + expect(codeOf(diff.json)).toBe('RESOURCE_CONFLICT'); + expect(candidatesOf(diff.json)).toEqual(candidatesOf(read.json)); + }); + + it('?package= diffs that holder\'s versions alone: its own active row against its own nearest earlier version', async () => { + for (const pair of [ALPHA_PAIR, BETA_PAIR]) { + const own = shared[pair]!; + const res = await call('GET', `/meta/flow/${SHARED}/diff?package=${pair}`); + expect(res.status, `${pair}: ${JSON.stringify(res.json)}`).toBe(200); + expect([res.json.fromVersion, res.json.toVersion], pair).toEqual(own); + expect(diffLabel(res.json), pair).toEqual({ path: 'label', from: `${pair} r1`, to: `${pair} r2` }); + expect(await labelAt(SHARED, pair)).toBe(`${pair} r2`); + } + const [from, to] = shared[ALPHA_PAIR]!; + const named = await call('GET', `/meta/flow/${SHARED}/diff?package=${ALPHA_PAIR}&from=${from}&to=${to}`); + expect(named.status, JSON.stringify(named.json)).toBe(200); + expect([named.json.fromVersion, named.json.toVersion]).toEqual([from, to]); + expect(diffLabel(named.json)).toEqual({ path: 'label', from: `${ALPHA_PAIR} r1`, to: `${ALPHA_PAIR} r2` }); + }); + + it('?package= refuses another holder\'s version, and an unattributed one, 404, comparing nothing', async () => { + const [alphaFirst] = shared[ALPHA_PAIR]!; + const [betaFirst] = shared[BETA_PAIR]!; + for (const query of [`from=${betaFirst}&to=${alphaFirst}`, `to=${betaFirst}`]) { + const res = await call('GET', `/meta/flow/${SHARED}/diff?package=${ALPHA_PAIR}&${query}`); + expect(res.status, `${query}: ${JSON.stringify(res.json)}`).toBe(404); + expect(codeOf(res.json)).toBe('VERSION_NOT_FOUND'); + expect(JSON.stringify(res.json), 'names whose version it is').toContain(BETA_PAIR); + } + const unattributed = await call('GET', `/meta/flow/${SHARED}/diff?package=${BETA_PAIR}&from=${legacy}`); + expect(unattributed.status, JSON.stringify(unattributed.json)).toBe(404); + expect(codeOf(unattributed.json)).toBe('VERSION_NOT_FOUND'); + }); + + it('CONTROL: a name one holder holds diffs bare as before, and ?package= of its holder answers the same', async () => { + const bare = versions((await call('GET', `/meta/flow/${SOLO}/history`)).json); + expect(bare).toHaveLength(2); + const named = await call('GET', `/meta/flow/${SOLO}/diff?from=${bare[0]}&to=${bare[1]}`); + expect(named.status, JSON.stringify(named.json)).toBe(200); + expect(diffLabel(named.json)).toEqual({ path: 'label', from: 'solo r1', to: 'solo r2' }); + const range = await call('GET', `/meta/flow/${SOLO}/diff`); + expect(range.status, JSON.stringify(range.json)).toBe(200); + expect([range.json.fromVersion, range.json.toVersion]).toEqual(bare); + expect((await call('GET', `/meta/flow/${SOLO}/diff?package=${ALPHA_PAIR}`)).json).toEqual(range.json); + }); + + it('CONTROL (M1): the environment\'s versions of a name a package took over diff bare, as before', async () => { + const [envFirst, envSecond] = versions((await call('GET', `/meta/flow/${TAKEN_OVER}/history`)).json); + const env = await call('GET', `/meta/flow/${TAKEN_OVER}/diff?from=${envFirst}&to=${envSecond}`); + expect(env.status, JSON.stringify(env.json)).toBe(200); + expect(diffLabel(env.json)).toEqual({ path: 'label', from: 'env r1', to: 'env r2' }); + }); + + it('?package= on a type not stored per package is refused 400 at the diff door, never accepted and dropped', async () => { + const res = await call('GET', `/meta/view/qa_diff_any_view/diff?package=${ALPHA}`); + expect(res.status, JSON.stringify(res.json)).toBe(400); + expect(codeOf(res.json)).toBe('VALIDATION_ERROR'); + // The protocol's reason, not the door's unknown-parameter refusal it answered before. + expect(JSON.stringify(res.json)).toContain('not stored per package'); + }); +}); 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 fc651a0ae1d..4500f74579d 100644 --- a/packages/rest/src/meta-item-history-package-selector.test.ts +++ b/packages/rest/src/meta-item-history-package-selector.test.ts @@ -23,7 +23,7 @@ import { describe, it, expect, vi } from 'vitest'; 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'; +import { RestServer, META_ITEM_DIFF_PARAMS, 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' }; @@ -65,6 +65,8 @@ function boot(options: { refuse?: boolean; real?: boolean } = {}) { 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 }), + // [#33308] The diff door, pinned in its own describe below. + diffMetaItem: answer({ type: 'flow', name: 'shared_flow', fromVersion: 1, toVersion: 3, added: [], removed: [], changed: [] }), }; // The real protocol judges the selector; only the plain read the history // door asks first (its read-refusal gate) is answered by the stub. @@ -156,3 +158,62 @@ describe('the history and rollback doors take `?package=`, the `/layers` spellin }); } }); + +/** + * [ADR-0150 D3/D4, #33308] `GET /meta/:type/:name/diff`, the third door of the + * family, takes `?package=` the same way: the holder whose versions it + * compares. The real-boot pins live in + * `history-diff-two-holders-33308.dogfood.test.ts`. + */ +describe('the diff door takes `?package=`, the `/layers` spelling (#33308)', () => { + const DIFF = `${ITEM}/diff`; + + it('declares `package` in its closed query set', () => { + expect(META_ITEM_DIFF_PARAMS).toContain('package'); + }); + + it('PRESERVATION — the package reaches `diffMetaItem` beside both bounds, under either spelling', async () => { + for (const query of [{ from: '1', to: '3' }, { fromVersion: '1', toVersion: '3' }]) { + const { protocol, drive } = boot(); + const answer = await drive('GET', DIFF, { ...query, package: 'com.acme.alpha.custom' }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(protocol.diffMetaItem.mock.calls[0][0], JSON.stringify(query)).toEqual({ + type: 'flow', name: 'shared_flow', fromVersion: 1, toVersion: 3, packageId: 'com.acme.alpha.custom', + }); + } + }); + + it('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('GET', DIFF, query); + expect(answer.status, `${JSON.stringify(query)}: ${JSON.stringify(answer.body)}`).toBe(200); + expect(Object.keys(protocol.diffMetaItem.mock.calls[0][0]), JSON.stringify(query)).not.toContain('packageId'); + } + }); + + it('REFUSAL — a repeated `?package=` is a located 400 and the protocol is never called', async () => { + const { protocol, drive } = boot(); + const answer = await drive('GET', DIFF, { package: ['com.acme.alpha.custom', 'com.acme.beta.custom'] }); + 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.diffMetaItem).not.toHaveBeenCalled(); + }); + + it('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('GET', DIFF, {}); + 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']); + }); + + it('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('GET', DIFF, { package: 'com.acme.alpha' }, {}, { 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 f79069b6788..54ebbceded6 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -309,6 +309,9 @@ "DeviceRequestResponseSchema (const)", "DeviceTokenResponse (type)", "DeviceTokenResponseSchema (const)", + "DiffMetaItemRequest (type)", + "DiffMetaItemRequestParsed (type)", + "DiffMetaItemRequestSchema (const)", "DiffMetaItemResponse (type)", "DiffMetaItemResponseParsed (type)", "DiffMetaItemResponseSchema (const)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 5430bf051fe..f9339db675d 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -542,6 +542,11 @@ "api/DeviceRequestResponse:interval [RETIRED]", "api/DeviceRequestResponse:intervalSeconds", "api/DeviceRequestResponse:verificationUrl", + "api/DiffMetaItemRequest:fromVersion", + "api/DiffMetaItemRequest:name", + "api/DiffMetaItemRequest:packageId", + "api/DiffMetaItemRequest:toVersion", + "api/DiffMetaItemRequest:type", "api/DiffMetaItemResponse:added", "api/DiffMetaItemResponse:changed", "api/DiffMetaItemResponse:fromVersion", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 2a408c472a0..889db198d5c 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -227,6 +227,8 @@ "DeviceRequestResponseSchema": "api/DeviceRequestResponse", "DeviceTokenResponse": "api/DeviceTokenResponse", "DeviceTokenResponseSchema": "api/DeviceTokenResponse", + "DiffMetaItemRequest": "api/DiffMetaItemRequest", + "DiffMetaItemRequestSchema": "api/DiffMetaItemRequest", "DiffMetaItemResponse": "api/DiffMetaItemResponse", "DiffMetaItemResponseSchema": "api/DiffMetaItemResponse", "DiscardPackageDraftsResponse": "api/DiscardPackageDraftsResponse", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 47a245988d4..c56140db0d5 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -295,6 +295,9 @@ "DeviceRequestResponseSchema": "src/api/auth-endpoints.zod.ts#DeviceRequestResponseSchema (const)", "DeviceTokenResponse": "src/api/auth-endpoints.zod.ts#DeviceTokenResponse (type)", "DeviceTokenResponseSchema": "src/api/auth-endpoints.zod.ts#DeviceTokenResponseSchema (const)", + "DiffMetaItemRequest": "src/api/protocol.zod.ts#DiffMetaItemRequest (type)", + "DiffMetaItemRequestParsed": "src/api/protocol.zod.ts#DiffMetaItemRequestParsed (type)", + "DiffMetaItemRequestSchema": "src/api/protocol.zod.ts#DiffMetaItemRequestSchema (const)", "DiffMetaItemResponse": "src/api/protocol.zod.ts#DiffMetaItemResponse (type)", "DiffMetaItemResponseParsed": "src/api/protocol.zod.ts#DiffMetaItemResponseParsed (type)", "DiffMetaItemResponseSchema": "src/api/protocol.zod.ts#DiffMetaItemResponseSchema (const)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index 8e6b142b031..a170abe0a31 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -120,6 +120,7 @@ "api/DeleteResponse", "api/DeviceRequestResponse", "api/DeviceTokenResponse", + "api/DiffMetaItemRequest", "api/DiffMetaItemResponse", "api/DisablePackageRequest", "api/DisablePackageResponse", diff --git a/packages/spec/src/api/protocol.test.ts b/packages/spec/src/api/protocol.test.ts index dcb703404dc..cc6d1ea1e65 100644 --- a/packages/spec/src/api/protocol.test.ts +++ b/packages/spec/src/api/protocol.test.ts @@ -3183,3 +3183,26 @@ describe('RollbackMetaItemRequestSchema declares what the rollback door enforces expect(RollbackMetaItemRequestSchema.safeParse(base).success).toBe(false); }); }); + +import { DiffMetaItemRequestSchema } from './protocol.zod'; + +describe('DiffMetaItemRequestSchema declares what the diff door reads (#33308)', () => { + // The REST door reads both bounds through this declaration: a whole number, + // as it read them before the request was declared, and `packageId` names + // the holder whose versions a by-package name's diff compares. + const base = { type: 'flow', name: 'shared_flow' } as const; + + it.each([['fromVersion'], ['toVersion']])('refuses a %s that is not a whole number', (key) => { + for (const value of [1.5, '2', true]) { + expect(DiffMetaItemRequestSchema.safeParse({ ...base, [key]: value }).success, JSON.stringify(value)).toBe(false); + } + }); + + it('CONTROL: both bounds are optional, and every member is preserved through parse', () => { + expect(DiffMetaItemRequestSchema.safeParse(base).success).toBe(true); + const full = { ...base, fromVersion: 1, toVersion: 3, packageId: 'com.acme.alpha.custom' }; + const result = DiffMetaItemRequestSchema.safeParse(full); + expect(result.success).toBe(true); + if (result.success) expect(result.data).toEqual(full); + }); +}); From 8ed07410cd54bd46b042a615dfe7bcf80c1b864b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:50:32 +0000 Subject: [PATCH 3/4] test(metadata-protocol): pin the diff door's non-holder refusal, the environment's slot through a package, and the holders' wire order The changeset now says the SDK's meta.diffItem sends no package, so an SDK caller's remedy is a raw request, and states the condition of the not-held-by-qualifier refusal. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .changeset/33308-diff-door-package-address.md | 4 +- .../protocol-diff-history-slots.33308.test.ts | 46 +++++++++++++++-- ...ory-diff-two-holders-33308.dogfood.test.ts | 49 +++++++++++++++++++ 3 files changed, 94 insertions(+), 5 deletions(-) diff --git a/.changeset/33308-diff-door-package-address.md b/.changeset/33308-diff-door-package-address.md index b760222f54c..8c867d00d9c 100644 --- a/.changeset/33308-diff-door-package-address.md +++ b/.changeset/33308-diff-door-package-address.md @@ -14,8 +14,8 @@ Skills-docs: none — no skill under `skills/` names the diff door, and the docs **BREAKING** for a bare diff 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/diff?from=N&to=M` TO `GET /meta/TYPE/NAME/diff?package=PKG&from=N&to=M`, with both versions that holder's (its `?package=` history lists them), once per holder the `409` names. +- FROM `GET /meta/TYPE/NAME/diff?from=N&to=M` TO `GET /meta/TYPE/NAME/diff?package=PKG&from=N&to=M`, with both versions that holder's (its `?package=` history lists them), once per holder the `409` names. The SDK's `client.meta.diffItem` sends no `package`, so for an SDK caller the TO request is a raw request. -`?package=` names a holder exactly as the history and rollback doors read it (`historySlotOf`): the row a read naming that package serves, else the package's own slot when it ships the name; a package that neither holds nor ships the name is refused `409` (`not-held-by-qualifier`). `all` and the empty string name no package. +`?package=` names a holder exactly as the history and rollback doors read it (`historySlotOf`): the row a read naming that package serves, else the package's own slot when it ships the name; a package that neither holds nor ships the name is refused `409` (`not-held-by-qualifier`) while another row slot holds the name; with no stored row of the name it answers an empty comparison. `all` and the empty string name no package. 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 (the new `DiffMetaItemRequestSchema`, declaring the diff door's request with its two whole-number bounds and `packageId`), and the level `Check Changeset` demands for `Metadata-protocol: added`. Every other package is `patch` under the BREAKING banner above: `@objectstack/metadata-protocol` (`diffMetaItem` takes `packageId`) and `@objectstack/rest` (the diff door accepts `?package=` and reads its bounds through the declaration). diff --git a/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts index c4b89edb6cd..dc8f302c02e 100644 --- a/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts +++ b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts @@ -12,6 +12,10 @@ * own active row, the default `from` side is found among P's versions, and * a named version another holder owns (or one attributed to no package, * while two hold the name) is refused `404 VERSION_NOT_FOUND` saying whose; + * - `?package=` naming a package that neither holds nor ships the name is + * refused `409 not-held-by-qualifier`; the environment's slot addressed + * through a package (the read falls back to the package-less row) takes + * that row as its `to` side; * - CONTROL: a name one slot holds diffs bare as before, its whole log; * - `?package=` on a type not stored per package is refused `400`. * @@ -22,6 +26,7 @@ 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 } from '@objectstack/core'; +import { ENVIRONMENT_HISTORY_MARK } from '@objectstack/metadata'; import { ProtocolDiffDeleteLoadFacet } from './protocol-diff-delete-load.js'; const ALPHA = 'com.acme.alpha.custom'; @@ -43,13 +48,15 @@ const ACTIVE = [ { package_id: ALPHA, version: 3, state: 'active', metadata: JSON.stringify(body('alpha r2')) }, ]; -function fakeHost(options: { candidates: string[]; history?: unknown[]; active?: unknown[] }) { +function fakeHost(options: { candidates: string[]; unbound?: boolean; history?: unknown[]; active?: unknown[] }) { const reads: string[] = []; const host: any = { engine: { registry: { readsByPackage: () => true, resolveItem: () => ({ status: 'resolved' }) } }, - packagelessAddress: async () => ({ candidates: options.candidates, unbound: false }), + packagelessAddress: async () => ({ candidates: options.candidates, unbound: options.unbound ?? false }), + // The row a read naming the package serves: its own, else the package-less row it falls back to. findServedOverlayRow: async (q: { packageId: string }) => { - const row = (options.active ?? ACTIVE).find((r: any) => r.package_id === q.packageId); + const active: any[] = (options.active ?? ACTIVE) as any[]; + const row = active.find((r) => r.package_id === q.packageId) ?? active.find((r) => r.package_id === undefined); return row === undefined ? undefined : { row }; }, shippedArtifactsOf: () => [], @@ -139,6 +146,39 @@ describe('diffMetaItem reads one holder\'s versions of a by-package name (#33308 expect(label(legacy)).toEqual({ path: 'label', from: 'legacy', to: 'alpha r2' }); }); + it('?package= naming a package that neither holds nor ships the name is refused 409 not-held-by-qualifier, before any version is read', async () => { + const { host, reads } = fakeHost({ candidates: [ALPHA, BETA] }); + const err = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: 'com.acme.gamma' })); + expect(err).toBeInstanceOf(PackageScopedNameRefusedError); + expect(err.code).toBe('RESOURCE_CONFLICT'); + expect(err.status).toBe(409); + expect(err.refusal.reason).toBe('not-held-by-qualifier'); + expect(err.refusal.candidates).toEqual([{ kind: 'package', packageId: ALPHA }, { kind: 'package', packageId: BETA }]); + expect(reads).toEqual([]); + }); + + it('the environment\'s slot addressed through a package: the package-less row is the to side, never the bound one', async () => { + // Alpha's row first, so a read that picks the name's first active row picks the wrong slot. + const active = [ + { package_id: ALPHA, version: 3, state: 'active', metadata: JSON.stringify(body('alpha r1')) }, + { version: 2, state: 'active', metadata: JSON.stringify(body('env r2')) }, + ]; + const history = [ + { version: 1, package_id: ENVIRONMENT_HISTORY_MARK, metadata: JSON.stringify(body('env r1')) }, + { version: 2, package_id: ENVIRONMENT_HISTORY_MARK, metadata: JSON.stringify(body('env r2')) }, + { version: 3, package_id: ALPHA, metadata: JSON.stringify(body('alpha r1')) }, + ]; + const { host } = fakeHost({ candidates: [ALPHA], unbound: true, history, active }); + const bare = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow' })); + expect(bare.refusal.candidates).toEqual([{ kind: 'package', packageId: ALPHA }, { kind: 'environment' }]); + const env = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: BETA }); + expect([env.fromVersion, env.toVersion]).toEqual([1, 2]); + expect(label(env)).toEqual({ path: 'label', from: 'env r1', to: 'env r2' }); + const err = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: BETA, toVersion: 3 })); + expect(err?.code).toBe('VERSION_NOT_FOUND'); + expect(err.message).toContain(`package '${ALPHA}'`); + }); + it('?package= on a type not stored per package is refused 400 VALIDATION_ERROR naming the parameter', async () => { const { host, reads } = fakeHost({ candidates: [] }); const err = await refusalOf(host.diffMetaItem({ type: 'view', name: 'any_view', packageId: ALPHA })); diff --git a/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts index 4f741095135..69094dd00ac 100644 --- a/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts +++ b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts @@ -24,6 +24,11 @@ // - CONTROL: a name one package holds diffs bare as before, and so does a // name first saved as the environment's own item and later taken over by a // package (M1): the environment's versions are its sole slot's; +// - `?package=` naming a package that neither holds nor ships the name is +// refused `409` naming the holders, in the protocol's order with their +// `kind` at the wire; the environment's slot addressed through a package +// (the read falls back to the package-less row) compares that row's +// versions alone, its own active row the `to` side; // - `?package=` on a type not stored per package is refused 400, never // accepted and dropped. @@ -47,6 +52,8 @@ const SOLO = 'qa_diff_solo_33308'; const SHIPPED_ONE = 'qa_diff_shipped_one_33308'; /** A runtime flow saved as the environment's own item, deleted, then saved in alpha's pair (M1). */ const TAKEN_OVER = 'qa_diff_taken_over_33308'; +/** A runtime flow saved as the environment's own item, then saved in alpha's pair beside it: two row slots, one of them the environment's. */ +const ENV_BESIDE = 'qa_diff_env_beside_33308'; const flowBody = (name: string, label: string) => ({ name, label, type: 'autolaunched', status: 'active', @@ -79,6 +86,9 @@ describe('the /meta diff door of a flow name two packages hold (ADR-0150 D3/D4, }; const candidatesOf = (json: any) => (json?.details?.candidates ?? []).map((c: any) => c.packageId ?? c.kind).sort(); + /** The holders as the wire lists them: order and `kind` kept. */ + const holdersOf = (json: any) => + (json?.details?.candidates ?? []).map((c: any) => (c.kind === 'package' ? { kind: c.kind, packageId: c.packageId } : { kind: c.kind })); const diffLabel = (json: any) => (json?.changed ?? []).find((e: any) => e.path === 'label'); const ownVersions = async (name: string, pkg: string) => versions((await call('GET', `/meta/flow/${name}/history?package=${pkg}`)).json); @@ -106,6 +116,9 @@ describe('the /meta diff door of a flow name two packages hold (ADR-0150 D3/D4, 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(ENV_BESIDE, undefined, 'env beside r1'); + await save(ENV_BESIDE, undefined, 'env beside r2'); + await save(ENV_BESIDE, ALPHA_PAIR, 'alpha beside r1'); // A version of SHARED recorded before the history row named its package // (a release before ADR-0150 D4's attribution): `package_id` left NULL. const ql: any = await stack.kernel.getServiceAsync('objectql'); @@ -134,9 +147,45 @@ describe('the /meta diff door of a flow name two packages hold (ADR-0150 D3/D4, expect(res.status, `${path}: ${JSON.stringify(res.json)}`).toBe(409); expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); expect(candidatesOf(res.json)).toEqual([ALPHA_PAIR, BETA_PAIR].sort()); + // At the wire: every bound package in the protocol's order, each with its `kind`. + expect(holdersOf(res.json), path).toEqual([ + { kind: 'package', packageId: ALPHA_PAIR }, + { kind: 'package', packageId: BETA_PAIR }, + ]); } }); + it('a package that neither holds nor ships the name is refused 409 at the diff door, naming the holders, comparing nothing', async () => { + const res = await call('GET', `/meta/flow/${SHARED}/diff?package=${ALPHA}`); + expect(res.status, JSON.stringify(res.json)).toBe(409); + expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); + expect(holdersOf(res.json)).toEqual([ + { kind: 'package', packageId: ALPHA_PAIR }, + { kind: 'package', packageId: BETA_PAIR }, + ]); + expect(res.json.fromVersion).toBeUndefined(); + expect(res.json.changed).toBeUndefined(); + }); + + it('the environment\'s slot addressed through a package: the package-less row\'s versions alone, its own active row the to side', async () => { + const bare = await call('GET', `/meta/flow/${ENV_BESIDE}/diff`); + expect(bare.status, JSON.stringify(bare.json)).toBe(409); + // The bound package first, then the environment's own row. + expect(holdersOf(bare.json)).toEqual([{ kind: 'package', packageId: ALPHA_PAIR }, { kind: 'environment' }]); + // A read naming beta's pair (no row of the name, nothing shipped) falls back to the package-less row. + const env = await ownVersions(ENV_BESIDE, BETA_PAIR); + expect(env).toHaveLength(2); + const res = await call('GET', `/meta/flow/${ENV_BESIDE}/diff?package=${BETA_PAIR}`); + expect(res.status, JSON.stringify(res.json)).toBe(200); + expect([res.json.fromVersion, res.json.toVersion]).toEqual(env); + expect(diffLabel(res.json)).toEqual({ path: 'label', from: 'env beside r1', to: 'env beside r2' }); + // Alpha's own slot beside it: its one version, no earlier one of its own. + const [alphaOnly] = await ownVersions(ENV_BESIDE, ALPHA_PAIR); + const alpha = await call('GET', `/meta/flow/${ENV_BESIDE}/diff?package=${ALPHA_PAIR}`); + expect(alpha.status, JSON.stringify(alpha.json)).toBe(200); + expect([alpha.json.fromVersion, alpha.json.toVersion]).toEqual([null, alphaOnly]); + }); + it('a name two packages ship, one customized, is refused bare at the diff door 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); From 624b7ff3930c868fa9e904cbdb818182361edcc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:54:27 +0000 Subject: [PATCH 4/4] docs(references): regenerate the reference pages on the merged tree Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- content/docs/references/api/protocol.mdx | 2 +- content/docs/references/index.mdx | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 48d3fc552d2..924697cee72 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1192,7 +1192,7 @@ This schema accepts one of the following structures: | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **admin** | `boolean` | ✅ | Whether the better-auth admin family (`{routes.auth}`/admin/*: list-users, set-role, update-user, ban-user, …) is mounted. Same value as features.admin on GET `{routes.auth}`/config, read from the same source; false means those routes answer a plain 404 on this deployment. | +| **admin** | `boolean` | ✅ | Whether the better-auth admin family (`{routes.auth}`/admin/*: list-users, set-role, update-user, impersonate-user, …) is mounted. Same value as features.admin on GET `{routes.auth}`/config, read from the same source; false means those routes answer a plain 404 on this deployment. ban-user and unban-user are not in the family: they are ObjectStack mounts, served whatever this says. | --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index ce61fbe6692..f90a1e35549 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 — 1663 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1664 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/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 494 | 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. | +| [Data Protocol](/docs/references/data) | 35 | 187 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -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** | **1663** | 14 protocol modules | +| **Total** | **218** | **1664** | 14 protocol modules | --- @@ -139,7 +139,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 186 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 187 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -165,7 +165,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`driver/turso.zod.ts`](/docs/references/data/driver-turso) | `TursoConfig`, `TursoTransportMode` | | [`external-catalog.zod.ts`](/docs/references/data/external-catalog) | `ExternalCatalog`, `ExternalColumn`, `ExternalTable` | | [`feed.zod.ts`](/docs/references/data/feed) | `FeedFilterMode`, `FeedItemType` | -| [`field.zod.ts`](/docs/references/data/field) | `CurrencyConfig`, `Field`, `FieldMaskingKeep`, `FieldMaskingRule`, `FieldType`, `InlineGridColumn`, `LocationCoordinates`, `SelectOption`, `UniqueScope` | +| [`field.zod.ts`](/docs/references/data/field) | `CurrencyConfig`, `Field`, `FieldMaskingKeep`, `FieldMaskingRule`, `FieldType`, `InlineGridColumn`, `LocationCoordinates`, `LookupFilterRecordReference`, `SelectOption`, `UniqueScope` | | [`field-value.zod.ts`](/docs/references/data/field-value) | `Address`, `AddressValue`, `CalendarDateValue`, `ClockTimeValue`, `FileLikeValue`, `FileReferenceIdValue`, `FileRefusedValue`, `FileValue`, `InstantValue`, `LocationValue`, `ReferenceIdValue`, `ReferenceNameOnlyValue` | | [`filter.zod.ts`](/docs/references/data/filter) | `ComparisonOperator`, `EqualityOperator`, `FieldOperators`, `FieldReference`, `FilterArray`, `FilterCondition`, `NormalizedFilter`, `NowAnchor`, `QueryFilter`, `RangeOperator`, `SetOperator`, `SpecialOperator`, `StringOperator` | | [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal` |