From 4cf5ca3996f7c4e2bca82b55a68936c89baaeb7f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:45:47 +0000 Subject: [PATCH 01/24] fix(metadata-protocol): a package-less action save on an object no holder binds writes the environment's own row ADR-0150 D4 keys an action (package, objectName, name). The publish-mode save door re-addressed a package-less action save into the one package holding the name, whatever object that package binds it to, so the package's declaration moved to the saved object. When every holder binds the name to another object, the save now writes the package-unbound row on its own object and leaves each package's item where it is. The same-object save, other types and managed packages answer as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../metadata-protocol/src/protocol-save.ts | 68 +++++++++- .../protocol.packageless-save-address.test.ts | 125 ++++++++++++++++++ 2 files changed, 191 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 9408c41a463..4d8a68ee3fa 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -88,6 +88,8 @@ import { saveRegistryQuestion } from './registry-question.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import { servedAddressJudgment } from './protocol-meta-item-face.js'; import { packagelessContentPackage, shippingPackageIds } from './protocol-environment-rows.js'; +import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; +import { storedRowDocument, type StoredOverlayRow } from './item-lock.js'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; export class ProtocolSaveFacet { @@ -812,15 +814,26 @@ export class ProtocolSaveFacet { const address = await host.packagelessAddress( writeType, request.name, itemDiscriminator(writeType, request.item), ); + // [ADR-0150 D4, ruling 6902014292] An action is keyed + // `(package, objectName, name)`: when every package that holds the + // name binds it to an object other than the one this body binds, + // no package holds this item, so the save writes the + // environment's own row on this object and every package's item + // stays where it is ({@link actionHeldOnlyOnOtherObjects}). + const environmentOwnAction = await actionHeldOnlyOnOtherObjects( + host, writeType, request.name, request.item, address, + ); // [#32605, epic ruling 6781691009] A name a disabled package also // holds is written where the read naming no package serves it // ({@link servedPackagelessSaveAddress}): never the disabled // package's row, never a new package-unbound row beside an // enabled holder, and a refusal names only the served holders. - const served = await servedPackagelessSaveAddress( + const served = environmentOwnAction ? undefined : await servedPackagelessSaveAddress( host, writeType, request.name, itemDiscriminator(writeType, request.item), address, ); - if (served !== undefined) { + if (environmentOwnAction) { + // The package-unbound row: `packageId` stays empty. + } else if (served !== undefined) { if (served.packageId !== null) request = { ...request, packageId: served.packageId }; } else { if (address.candidates.length > 1) { @@ -2849,3 +2862,54 @@ async function servedPackagelessSaveAddress( const content = packagelessContentPackage({ packageId: null, candidates: [] }, shippers.map((id) => ({ _packageId: id }))); return typeof content === 'string' ? { packageId: content } : undefined; } + +/** + * [ADR-0150 D4, ruling 6902014292] Whether a publish-mode save of an `action` + * naming no package writes the ENVIRONMENT'S OWN item: every package the + * item's active rows are bound to (`address.candidates`, + * {@link packagelessAddress}) binds the name to an object other than the one + * `item` binds ({@link boundObjectOf}; object-less is its own key). + * + * D4 keys an action `(package, objectName, name)`, so a package's action on + * object A is not the item a body bound to object B addresses. ADR-0150's + * "a package-less row that bears a package-held name is a customization" + * (D4, R15) is read at that key for an action: such a body customizes no + * package's item, and re-addressing it into the one holder moved that + * package's declaration onto B. The read side and the execution route + * already key an action this way (`lookupArtifactItem`'s owner key). + * + * `false` — the address stands, as before — for every other type, for a + * name no package's row holds, and as soon as one holder binds the name to + * `item`'s object: the same-object save is still that package's + * customization, and two such holders are still refused. A stored body that + * does not parse is read as binding `item`'s object, so it never drops a + * holder from the key. + */ +async function actionHeldOnlyOnOtherObjects( + host: Pick, + type: string, name: string, item: unknown, + address: { readonly candidates: readonly string[] }, +): Promise { + if (type !== 'action' || address.candidates.length === 0) return false; + const object = boundObjectOf(item); + let activeRows: readonly StoredOverlayRow[]; + try { + activeRows = await host.readItemActiveRows(type, name); + } catch (error) { + // [#5532] An unprovisioned store holds no row; any other failure is a + // read that did not happen, never "no holder on this object". + host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); + activeRows = []; + } + const bindsObject = (row: StoredOverlayRow): boolean => { + let document: unknown; + try { + document = storedRowDocument(row); + } catch { + return true; + } + return boundObjectOf(document) === object; + }; + const atObject = await host.packagelessAddress(type, name, undefined, 'active', activeRows.filter(bindsObject)); + return atObject.candidates.length === 0; +} diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 2da51ae7f36..879dd21f2e4 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -332,6 +332,131 @@ describe('a package-less direct save of an item ONE package owns writes that pac }); }); +/** + * [ADR-0150 D4, ruling 6902014292] An ACTION is keyed `(package, objectName, + * name)`, so the re-address above (the generic one, pinned for a type-agnostic + * item) does not reach an action body bound to an object no package binds the + * name to: that save writes the environment's own row on that object, and the + * package's item stays where it is. Save, read and execution then key the + * action alike. + * + * FROM (main): the save was re-addressed into the one holder, so its receipt + * named the package and the package's action moved to the other object. + */ +describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder does not bind', () => { + const action = (name: string, label: string, objectName?: string) => ({ + name, label, type: 'url', target: `https://example.invalid/${label}`, ...(objectName ? { objectName } : {}), + }); + const NAME = 'approve_p'; + /** The stored rows of the action, by binding: `[package or null, objectName, label]`. */ + const stored = (rows: Row[]) => rows + .map((r) => [r.package_id ?? null, JSON.parse(r.metadata).objectName ?? null, JSON.parse(r.metadata).label]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))); + + it('FROM/TO: P holds the name on `invoice`; the save on `task` writes the environment\'s row, and P\'s row is untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + // FROM: `(env-wide, package=com.qa.lanebapp, …)` and ONE row, P's, on `task`. + expect(saved.message).toBe(`Saved action '${NAME}' (env-wide, state=active) [seq=${saved.seq}]`); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); + }); + + it('the read after the save: `?package=P` still answers P\'s item on `invoice`', async () => { + const { protocol } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + // FROM: `['task', 'env']`, the environment's body under P. The bare + // read is pinned over HTTP on a real boot (its served item is the + // registry's), `action-save-packageless-other-object.dogfood.test.ts`. + const atPackage = (await protocol.getMetaItem({ type: 'action', name: NAME, packageId: WRITABLE })).item; + expect([atPackage.objectName, atPackage.label]).toEqual(['invoice', 'p']); + }); + + it('a second package-less save on `task` edits the environment\'s row again; P\'s row is still untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'task') }); + + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env2']]); + }); + + it('an object-less body is its own key too: the environment\'s row, P\'s row untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env') }); + + expect(saved.message).not.toContain('package='); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, null, 'env']]); + }); + + it('two packages holding the name on two other objects: the environment\'s row (FROM: 409 naming both)', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'product'), packageId: OTHER_WRITABLE }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + expect(saved.success).toBe(true); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q'], [null, 'task', 'env']]); + }); + + describe('CONTROLs (unchanged)', () => { + it('the same save on `invoice`, the object P binds: re-addressed into P, as the generic pin above', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice') }); + + expect(saved.message).toBe(`Saved action '${NAME}' (env-wide, package=${WRITABLE}, state=active) [seq=${saved.seq}]`); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'edited']]); + }); + + it('with the environment\'s row on `task` stored too, a save on `invoice` is still P\'s customization', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice') }); + + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'edited'], [null, 'task', 'env']]); + }); + + it('a package on `invoice` and another on `task`: the save on `task` is still refused 409 naming both', async () => { + const { protocol, rows, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'task'), packageId: OTHER_WRITABLE }); + const before = metadataWrites().length; + + const envelope = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }))); + + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(metadataWrites()).toHaveLength(before); + expect(stored(rows('action', NAME))).toEqual([[OTHER_WRITABLE, 'task', 'q'], [WRITABLE, 'invoice', 'p']].sort((a, b) => String(a[0]).localeCompare(String(b[0])))); + }); + + it('a managed (code) package\'s action on `invoice`: the package-less save on `task` is still refused 403 NOT_OVERRIDABLE, and nothing is written', async () => { + const item: Record = action('showcase_approve', 'managed', 'invoice'); + applyProtection(item, { packageId: CODE_PACKAGE, packageVersion: '1.0.0' }); + const { protocol, rows, metadataWrites } = makeProtocol([{ type: 'action', item }]); + + const envelope = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({ + type: 'action', name: 'showcase_approve', item: action('showcase_approve', 'env', 'task'), + }))); + + expect([envelope.status, envelope.code]).toEqual([403, 'NOT_OVERRIDABLE']); + expect(rows('action', 'showcase_approve')).toEqual([]); + expect(metadataWrites()).toEqual([]); + }); + }); +}); + describe('an item TWO packages hold: a save naming neither is refused', () => { async function twoPackageItem(name: string) { const fixture = makeProtocol(); From 5245830914f972e91f9d067477a622e2176fd1c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:06:06 +0000 Subject: [PATCH 02/24] test(dogfood): pin the package-less action save on another object over HTTP, and its changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...59-action-save-packageless-other-object.md | 23 +++++ ...e-packageless-other-object.dogfood.test.ts | 99 +++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 .changeset/34059-action-save-packageless-other-object.md create mode 100644 packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md new file mode 100644 index 00000000000..a8cd87bb20e --- /dev/null +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -0,0 +1,23 @@ +--- +'@objectstack/metadata-protocol': minor +--- + +fix(metadata-protocol)!: a package-less action save on an object no package binds the name to writes the environment's own action + +Clause-②: yes (narrowing) +Metadata-protocol: semantic +Skills-docs: none — no skill under `skills/**` teaches where a package-less save of a writable package's item is written; `skills/objectstack-platform` teaches only the managed base's `.custom` pair, whose refusals do not move. + + + +**BREAKING** (ADR-0150 D4, maintainer ruling 6902014292): an action is keyed `(package, objectName, name)`. A package-less `PUT /api/v1/meta/action/NAME` (no `?package=`) whose body binds an object that no package holding the name binds it to now writes the environment's own action on that object. Every package's action of that name stays where it is. + +FROM → TO, writable package `P` holding `approve` on `invoice`: + +- package-less save of `approve` bound to `task`: FROM written into `P` (receipt `package=P`), moving `P`'s action from `invoice` to `task` · TO the environment's own row on `task` (receipt with no package); `P`'s action on `invoice` is untouched, `GET /meta/action/approve?package=P` still serves it, and `/actions/invoice/approve` still runs it. +- the same save object-less: the same move · TO the environment's own object-less row. +- two packages holding `approve` on two other objects: FROM `409 RESOURCE_CONFLICT` naming both · TO the environment's own row. + +Unchanged: the same save on `invoice` (the object `P` binds) is still `P`'s customization; a package on `invoice` and another on `task` still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`; a draft save (`?mode=draft`) still inherits the package of the item's active rows. + +What to do: to move a package's own action to another object, save it naming the package (`?package=P`). A row an older build moved into a package is not moved back; save it again naming the package with its original object to restore it. diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts new file mode 100644 index 00000000000..869e65e1349 --- /dev/null +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -0,0 +1,99 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0150 D4, ruling 6902014292] Over HTTP, on a real boot of the showcase: +// a package-less `PUT /meta/action/NAME` of a name a writable package P binds +// to `showcase_invoice`, saved on `showcase_task`, writes the environment's own +// item on `showcase_task`. P's item on `showcase_invoice` stays where it is, +// and the save, the reads and the action route key the two items alike. +// +// FROM (main 571cf9082a, measured on this boot): the save answered +// `Saved action 'NAME' (env-wide, package=P, …)`, P's item moved to +// `showcase_task` (`?package=P` served the environment's body), and +// `/actions/_env/showcase_task/NAME` answered 404. +// +// CONTROLs: the same save on `showcase_invoice` is still P's customization, +// and a managed package's action name is still refused 403 NOT_OVERRIDABLE. +// +// The file is ISOLATED: it writes `/meta` and creates a package. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootShowcase } from './showcase-boot.js'; + +const PKG = 'com.example.qasaveother'; +const action = (name: string, label: string, objectName: string) => ({ + name, label, objectName, type: 'url', target: `https://example.invalid/${label}`, locations: ['record_more'], +}); + +describe('[ADR-0150 D4] a package-less action save on an object the package does not bind', () => { + let stack: VerifyStack; + let admin: string; + + beforeAll(async () => { + stack = await bootShowcase(); + admin = await stack.signIn(); + const created = await stack.apiAs(admin, 'POST', '/packages', { + manifest: { id: PKG, name: 'QA save other object', version: '0.1.0', type: 'app', namespace: 'qasaveother' }, + }); + expect(created.status, await created.clone().text()).toBe(201); + }, 240_000); + + afterAll(async () => { await stack?.stop(); }); + + const put = async (path: string, body: unknown) => { + const res = await stack.apiAs(admin, 'PUT', path, body); + const text = await res.text(); + return { status: res.status, message: String((JSON.parse(text) as any)?.message ?? (JSON.parse(text) as any)?.data?.message ?? ''), text }; + }; + /** The identity a client reads off a served action: its object, label and package. */ + const read = async (path: string) => { + const res = await stack.apiAs(admin, 'GET', path); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body).slice(0, 400)).toBe(200); + const item = body?.data?.item ?? body?.item ?? body?.data; + return [item?.objectName ?? null, item?.label ?? null, item?._packageId ?? null]; + }; + /** The declaration the action route judges: a `url` action is refused naming its own target. */ + const routeTarget = async (path: string) => { + const res = await stack.apiAs(admin, 'POST', path, {}); + const text = await res.text(); + return [res.status, /example\.invalid\/(\w+)/.exec(text)?.[1] ?? text.slice(0, 200)]; + }; + + it('writes the environment\'s item on `showcase_task`; P\'s item on `showcase_invoice` is untouched, and reads and the route agree', async () => { + const name = 'qa_save_other_p'; + const own = await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice')); + expect(own.status, own.text).toBe(200); + + const saved = await put(`/meta/action/${name}`, action(name, 'env', 'showcase_task')); + + expect(saved.status, saved.text).toBe(200); + // FROM: `(env-wide, package=com.example.qasaveother, state=active)`. + expect(saved.message).not.toContain('package='); + expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); + expect(await read(`/meta/action/${name}`)).toEqual(['showcase_task', 'env', null]); + expect(await routeTarget(`/actions/showcase_invoice/${name}`)).toEqual([400, 'pkg']); + expect(await routeTarget(`/actions/showcase_task/${name}`)).toEqual([400, 'env']); + // FROM: 404, the environment held no item of the name. + expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); + }, 120_000); + + it('CONTROL: the same save on `showcase_invoice`, the object P binds, is still P\'s customization', async () => { + const name = 'qa_save_same_p'; + expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); + + const saved = await put(`/meta/action/${name}`, action(name, 'edited', 'showcase_invoice')); + + expect(saved.status, saved.text).toBe(200); + expect(saved.message).toContain(`package=${PKG}`); + expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'edited', PKG]); + }, 120_000); + + it('CONTROL: a managed package\'s action name saved package-less on another object is still refused 403 NOT_OVERRIDABLE', async () => { + // `showcase_mark_done` is the showcase's own action on `showcase_task`. + const refused = await put('/meta/action/showcase_mark_done', action('showcase_mark_done', 'env', 'showcase_product')); + expect(refused.status, refused.text).toBe(403); + expect(refused.text).toContain('NOT_OVERRIDABLE'); + expect(await read('/meta/action/showcase_mark_done')).toEqual(['showcase_task', 'Mark Done', 'com.example.showcase']); + }, 120_000); +}); From 91615517745d0662ac24d0e357ad14a37d534c2f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:16:26 +0000 Subject: [PATCH 03/24] test(dogfood): pin the read naming the package and the route, not the bare read Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../action-save-packageless-other-object.dogfood.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index 869e65e1349..04dd9cbb06e 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -4,7 +4,7 @@ // a package-less `PUT /meta/action/NAME` of a name a writable package P binds // to `showcase_invoice`, saved on `showcase_task`, writes the environment's own // item on `showcase_task`. P's item on `showcase_invoice` stays where it is, -// and the save, the reads and the action route key the two items alike. +// and the save, the read naming P and the action route key the two items alike. // // FROM (main 571cf9082a, measured on this boot): the save answered // `Saved action 'NAME' (env-wide, package=P, …)`, P's item moved to @@ -60,7 +60,7 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does return [res.status, /example\.invalid\/(\w+)/.exec(text)?.[1] ?? text.slice(0, 200)]; }; - it('writes the environment\'s item on `showcase_task`; P\'s item on `showcase_invoice` is untouched, and reads and the route agree', async () => { + it('writes the environment\'s item on `showcase_task`; P\'s item on `showcase_invoice` is untouched, and the read naming P and the route agree', async () => { const name = 'qa_save_other_p'; const own = await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice')); expect(own.status, own.text).toBe(200); @@ -70,8 +70,11 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does expect(saved.status, saved.text).toBe(200); // FROM: `(env-wide, package=com.example.qasaveother, state=active)`. expect(saved.message).not.toContain('package='); + // FROM: `['showcase_task', 'env', PKG]`, the environment's body under P. expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); - expect(await read(`/meta/action/${name}`)).toEqual(['showcase_task', 'env', null]); + // The by-name read naming no package is not pinned here: with P's row and + // the environment's row both stored it serves P's item, in either save + // order (the read side's own seam, not this save door's). expect(await routeTarget(`/actions/showcase_invoice/${name}`)).toEqual([400, 'pkg']); expect(await routeTarget(`/actions/showcase_task/${name}`)).toEqual([400, 'env']); // FROM: 404, the environment held no item of the name. From 41980e3778f6b7612e7b1618aa03f888d24e9dc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:17:20 +0000 Subject: [PATCH 04/24] test(metadata-protocol): seed the environment's row for the same-object control Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../src/protocol.packageless-save-address.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 879dd21f2e4..dabba6e4eaf 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -419,9 +419,10 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder }); it('with the environment\'s row on `task` stored too, a save on `invoice` is still P\'s customization', async () => { - const { protocol, rows } = makeProtocol(); + const { protocol, rows, seedRow } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); - await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + // Stored as the other save order leaves it (the environment's save first). + seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'env', 'task')), checksum: 'sha-env' }); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice') }); From 32c7a1ca8e9a8113b5332941789301cca0f2371b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:51:58 +0000 Subject: [PATCH 05/24] chore(changeset): state the moved answers without a migration block Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../34059-action-save-packageless-other-object.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index a8cd87bb20e..3b84d3f67a9 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -12,12 +12,12 @@ Skills-docs: none — no skill under `skills/**` teaches where a package-less sa **BREAKING** (ADR-0150 D4, maintainer ruling 6902014292): an action is keyed `(package, objectName, name)`. A package-less `PUT /api/v1/meta/action/NAME` (no `?package=`) whose body binds an object that no package holding the name binds it to now writes the environment's own action on that object. Every package's action of that name stays where it is. -FROM → TO, writable package `P` holding `approve` on `invoice`: +The moved answers, for a writable package `P` holding `approve` on `invoice`: -- package-less save of `approve` bound to `task`: FROM written into `P` (receipt `package=P`), moving `P`'s action from `invoice` to `task` · TO the environment's own row on `task` (receipt with no package); `P`'s action on `invoice` is untouched, `GET /meta/action/approve?package=P` still serves it, and `/actions/invoice/approve` still runs it. -- the same save object-less: the same move · TO the environment's own object-less row. -- two packages holding `approve` on two other objects: FROM `409 RESOURCE_CONFLICT` naming both · TO the environment's own row. +- a package-less save of `approve` bound to `task` was written into `P` (receipt `package=P`) and moved `P`'s action from `invoice` to `task`; it now writes the environment's own row on `task` (a receipt with no package), and `P`'s action on `invoice` is untouched: `GET /meta/action/approve?package=P` still serves it and `/actions/invoice/approve` still runs it. +- the same save with an object-less body: it now writes the environment's own object-less row. +- with two packages holding `approve` on two other objects, the save was refused `409 RESOURCE_CONFLICT` naming both; it now writes the environment's own row. Unchanged: the same save on `invoice` (the object `P` binds) is still `P`'s customization; a package on `invoice` and another on `task` still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`; a draft save (`?mode=draft`) still inherits the package of the item's active rows. -What to do: to move a package's own action to another object, save it naming the package (`?package=P`). A row an older build moved into a package is not moved back; save it again naming the package with its original object to restore it. +Nothing to do for the environment's own actions. A package's own action is moved to another object by a save naming the package (`?package=P`), as before. A package's action that an older build moved to another object stays where it was stored. From 2d3729948c7be61d7599225a7084c05bba2865ce Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:17:26 +0000 Subject: [PATCH 06/24] fix(metadata-protocol): key the package-less draft save and its publish of an action by object The draft address and the per-item publish read the same owner-key rule as the publish-mode save: an action draft whose body binds an object no package's active row binds the name to is the environment's own draft, and its publish naming no package promotes it into the package-unbound row. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../src/protocol-history-and-publish.ts | 20 +++++- .../metadata-protocol/src/protocol-save.ts | 47 ++++---------- .../protocol.packageless-save-address.test.ts | 34 +++++++++++ .../src/sys-metadata-repository.ts | 61 ++++++++++++++++++- ...e-packageless-other-object.dogfood.test.ts | 24 ++++++++ 5 files changed, 148 insertions(+), 38 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 2f82d0b0e1c..483a0357d9b 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -25,7 +25,7 @@ import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; -import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { DraftConflictError, actionHeldOnlyOnOtherObjects, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; import { ConflictError } from '@objectstack/metadata-core'; import type { MetadataItem } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; @@ -664,7 +664,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -834,6 +834,22 @@ export class ProtocolHistoryAndPublishFacet { } else { draftKey = address.key; promoteInto = address.into; + // [ADR-0150 D4, ruling 6902014292] An unbound action draft + // whose body binds an object no package's active row binds + // the name to is the environment's own draft (the draft save + // wrote it unbound for that reason): it is promoted into the + // package-unbound active row, never adopted into the holder, + // whose item on its own object stays as it is. The one rule + // the save and the draft save read ({@link actionHeldOnlyOnOtherObjects}). + if (singularType === 'action' && draftKey === null && promoteInto !== null && address.kind === 'draft') { + const unboundDraft = await repo.get( + { type: singularType, name: request.name, org: 'env' } as Parameters[0], + { state: 'draft', packageId: null, ...memberOption(request.member) }, + ); + if (unboundDraft && actionHeldOnlyOnOtherObjects(singularType, unboundDraft.body, await host.readItemActiveRows(singularType, request.name))) { + promoteInto = null; + } + } // No draft at the address while another package's draft is // stored: the promotion's `NO_DRAFT`, naming the drafts that // remain and the request that reaches them. diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 1c57da52f84..eafccaa17ac 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -25,7 +25,7 @@ import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; -import { SysMetadataRepository, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { SysMetadataRepository, actionHeldOnlyOnOtherObjects, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; import { ConflictError, itemDiscriminator, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { authoringClientOf } from './draft-changes.js'; @@ -88,8 +88,7 @@ import { saveRegistryQuestion } from './registry-question.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import { servedAddressJudgment } from './protocol-meta-item-face.js'; import { packagelessContentPackage, shippingPackageIds } from './protocol-environment-rows.js'; -import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; -import { storedRowDocument, type StoredOverlayRow } from './item-lock.js'; +import type { StoredOverlayRow } from './item-lock.js'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; export class ProtocolSaveFacet { @@ -819,8 +818,8 @@ export class ProtocolSaveFacet { // name binds it to an object other than the one this body binds, // no package holds this item, so the save writes the // environment's own row on this object and every package's item - // stays where it is ({@link actionHeldOnlyOnOtherObjects}). - const environmentOwnAction = await actionHeldOnlyOnOtherObjects( + // stays where it is ({@link packagelessActionSaveIsEnvironmentOwn}). + const environmentOwnAction = await packagelessActionSaveIsEnvironmentOwn( host, writeType, request.name, request.item, address, ); // [#32605, epic ruling 6781691009] A name a disabled package also @@ -2902,33 +2901,23 @@ async function servedPackagelessSaveAddress( /** * [ADR-0150 D4, ruling 6902014292] Whether a publish-mode save of an `action` - * naming no package writes the ENVIRONMENT'S OWN item: every package the - * item's active rows are bound to (`address.candidates`, - * {@link packagelessAddress}) binds the name to an object other than the one - * `item` binds ({@link boundObjectOf}; object-less is its own key). - * - * D4 keys an action `(package, objectName, name)`, so a package's action on - * object A is not the item a body bound to object B addresses. ADR-0150's - * "a package-less row that bears a package-held name is a customization" - * (D4, R15) is read at that key for an action: such a body customizes no - * package's item, and re-addressing it into the one holder moved that - * package's declaration onto B. The read side and the execution route - * already key an action this way (`lookupArtifactItem`'s owner key). + * naming no package writes the ENVIRONMENT'S OWN item: the package-less + * address has a holder (`address.candidates`, {@link packagelessAddress}) and + * the one owner-key rule, {@link actionHeldOnlyOnOtherObjects}, reads the + * item's active rows as holding the name only on objects other than the one + * `item` binds. The draft save and the per-item publish read the same rule. * * `false` — the address stands, as before — for every other type, for a * name no package's row holds, and as soon as one holder binds the name to * `item`'s object: the same-object save is still that package's - * customization, and two such holders are still refused. A stored body that - * does not parse is read as binding `item`'s object, so it never drops a - * holder from the key. + * customization, and two such holders are still refused. */ -async function actionHeldOnlyOnOtherObjects( - host: Pick, +async function packagelessActionSaveIsEnvironmentOwn( + host: Pick, type: string, name: string, item: unknown, address: { readonly candidates: readonly string[] }, ): Promise { if (type !== 'action' || address.candidates.length === 0) return false; - const object = boundObjectOf(item); let activeRows: readonly StoredOverlayRow[]; try { activeRows = await host.readItemActiveRows(type, name); @@ -2938,15 +2927,5 @@ async function actionHeldOnlyOnOtherObjects( host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); activeRows = []; } - const bindsObject = (row: StoredOverlayRow): boolean => { - let document: unknown; - try { - document = storedRowDocument(row); - } catch { - return true; - } - return boundObjectOf(document) === object; - }; - const atObject = await host.packagelessAddress(type, name, undefined, 'active', activeRows.filter(bindsObject)); - return atObject.candidates.length === 0; + return actionHeldOnlyOnOtherObjects(type, item, activeRows); } diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index dabba6e4eaf..86705431405 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -407,7 +407,41 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q'], [null, 'task', 'env']]); }); + it('the DRAFT save on `task` writes the environment\'s draft (FROM: P\'s draft), and P\'s rows are untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + }); + + it('the per-item publish naming no package promotes that draft into the environment\'s row (FROM: over P\'s item on `invoice`)', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + const published = await protocol.publishMetaItem({ type: 'action', name: NAME }); + + expect(published.success).toBe(true); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); + expect(rows('action', NAME, 'draft')).toEqual([]); + }); + describe('CONTROLs (unchanged)', () => { + it('the draft save on `invoice`, the object P binds: P\'s draft, and its publish is P\'s row', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice'), mode: 'draft' }); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[WRITABLE, 'invoice', 'edited']]); + + await protocol.publishMetaItem({ type: 'action', name: NAME }); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'edited']]); + expect(rows('action', NAME, 'draft')).toEqual([]); + }); + it('the same save on `invoice`, the object P binds: re-addressed into P, as the generic pin above', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index e76b3df80e2..8f869286d80 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -63,6 +63,7 @@ import { hashSpec, orderedMapKeys, ConflictError, readLegacyOrganizationRows } f // #4825 deliberately retired. See `@objectstack/metadata/errors` for why that // leaf subpath exists. import { isMissingTableError } from '@objectstack/metadata/errors'; +import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; // [ruling 6677709817 (c)] The snapshot body both history writers store: the // written body without what the type's redactor marks not carried forward. import { historySnapshotBody } from '@objectstack/metadata/history-snapshot'; @@ -703,6 +704,50 @@ export function unboundItemDraftAddress( return only !== undefined ? { kind: 'draft', key: only } : { kind: 'none', key: null }; } +/** + * [ADR-0150 D4, ruling 6902014292] THE owner-key rule of the package-less + * write address for an `action`: whether `item`, written naming no package, + * is the ENVIRONMENT'S OWN item rather than a customization of a package's. + * D4 keys an action `(package, objectName, name)`, so a package's action on + * object A is not the item a body bound to object B addresses. + * + * `true` when `activeRows` (the item's active rows, every binding) hold a row + * bound to a package and no such row binds the object `item` binds + * ({@link boundObjectOf}; object-less is its own key): no package holds this + * item, so the write is the package-unbound row and every package's row stays + * where it is. `false` for every other type, for an item no package's row + * holds, and as soon as one package's row binds `item`'s object: that write is + * still the package's customization (ADR-0150 D4, R15). A stored body that + * does not parse is read as binding `item`'s object, so it never drops a + * holder from the key. + * + * One rule for every door that writes an action naming no package: the + * publish-mode save (`protocol-save.ts`), the draft save + * ({@link SysMetadataRepository.put}, through `resolveWriteHead`), and the + * per-item publish of the draft that save wrote (`protocol-history-and-publish.ts`). + * + * Deliberately NOT exported from the package entry. + */ +export function actionHeldOnlyOnOtherObjects( + type: string, + item: unknown, + activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, +): boolean { + if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'action') return false; + const held = activeRows.filter((row) => typeof row?.package_id === 'string' && row.package_id !== ''); + if (held.length === 0) return false; + const object = boundObjectOf(item); + return !held.some((row) => { + let document: unknown; + try { + document = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata; + } catch { + return true; + } + return boundObjectOf(document) === object; + }); +} + /** * One live `watch()` subscription, as a record rather than a bare listener. * @@ -946,6 +991,13 @@ export class SysMetadataRepository implements MetadataRepository { packageId: string | null | undefined, ctx?: Record, member?: string | null, + /** + * [ADR-0150 D4] The body the write carries, when the caller has it + * ({@link put}); it keys an action's inherited binding by its object + * ({@link actionHeldOnlyOnOtherObjects}). Omitted, the binding is inherited + * by name, as before. + */ + body?: unknown, ): Promise<{ row: any | null; targetPackageId: string | null; ambiguousPackages?: readonly string[] }> { const context = { ...ctx, isSystem: true }; let targetPackageId: string | null = packageId ?? null; @@ -974,7 +1026,12 @@ export class SysMetadataRepository implements MetadataRepository { for (const activeRow of (activeRows ?? []) as Array<{ package_id?: unknown }>) { if (typeof activeRow?.package_id === 'string' && activeRow.package_id !== '') bindings.add(activeRow.package_id); } - if (bindings.size === 1) targetPackageId = [...bindings][0] ?? null; + // [ADR-0150 D4, ruling 6902014292] An action draft whose body binds an + // object no package's active row binds the name to is the environment's + // own draft: it inherits no package, and no package's row is touched. + if (body !== undefined && actionHeldOnlyOnOtherObjects(ref.type, body, (activeRows ?? []) as ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>)) { + targetPackageId = null; + } else if (bindings.size === 1) targetPackageId = [...bindings][0] ?? null; else if (bindings.size > 1) ambiguousPackages = [...bindings].sort(); else { // [#23657, ADR-0070 TL;DR 1] No active row bound to a package (an @@ -1164,7 +1221,7 @@ export class SysMetadataRepository implements MetadataRepository { // the one {@link headAt} answers too, so the head a caller was served // for this address is the head this lock judges. const { row: existing, targetPackageId, ambiguousPackages } = await this.resolveWriteHead( - ref, state, opts.packageId, ctx, member, + ref, state, opts.packageId, ctx, member, body, ); // [#23297] A draft that names no package, of an item whose active rows // are bound to two or more packages, has no single row to write: refused diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index 04dd9cbb06e..b40dfd50f35 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -11,6 +11,11 @@ // `showcase_task` (`?package=P` served the environment's body), and // `/actions/_env/showcase_task/NAME` answered 404. // +// The draft door keys the action alike: a package-less `?mode=draft` save on +// `showcase_task` writes the environment's draft, and the per-item publish +// naming no package promotes it into the environment's item (FROM: the draft +// was adopted into P and its publish overwrote P's item on `showcase_invoice`). +// // CONTROLs: the same save on `showcase_invoice` is still P's customization, // and a managed package's action name is still refused 403 NOT_OVERRIDABLE. // @@ -81,6 +86,25 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); }, 120_000); + it('the DRAFT save on `showcase_task` and its per-item publish write the environment\'s item; P\'s item on `showcase_invoice` is untouched', async () => { + const name = 'qa_draft_other_p'; + expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); + + const drafted = await put(`/meta/action/${name}?mode=draft`, action(name, 'env', 'showcase_task')); + expect(drafted.status, drafted.text).toBe(200); + // FROM: `package=com.example.qasaveother`, the draft adopted into P. + expect(drafted.message).not.toContain('package='); + expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); + + const published = await stack.apiAs(admin, 'POST', `/meta/action/${name}/publish`, {}); + expect(published.status, await published.clone().text()).toBe(200); + + // FROM: `['showcase_task', 'env', PKG]`, the publish wrote P's row. + expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); + expect(await routeTarget(`/actions/showcase_invoice/${name}`)).toEqual([400, 'pkg']); + expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); + }, 120_000); + it('CONTROL: the same save on `showcase_invoice`, the object P binds, is still P\'s customization', async () => { const name = 'qa_save_same_p'; expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); From 187a683baa8e9b28c8c6a5dda1ba45b4c36ce325 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:22:28 +0000 Subject: [PATCH 07/24] fix(metadata-protocol): judge the served save address of an action at the body's object The served step of the package-less save judges an action's holders at the object the body binds when another holder binds the name to another object: an enabled holder's item on another object no longer answers for a disabled holder at the body's object. Pins the moved rows for a sole disabled holder and for a sole binding to a package that is not installed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../metadata-protocol/src/protocol-save.ts | 68 +++++++++++++------ .../protocol.packageless-save-address.test.ts | 36 ++++++++++ .../src/sys-metadata-repository.ts | 21 +++++- 3 files changed, 102 insertions(+), 23 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index eafccaa17ac..5893f30dd21 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -25,7 +25,7 @@ import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; -import { SysMetadataRepository, actionHeldOnlyOnOtherObjects, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { SysMetadataRepository, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; import { ConflictError, itemDiscriminator, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { authoringClientOf } from './draft-changes.js'; @@ -818,17 +818,20 @@ export class ProtocolSaveFacet { // name binds it to an object other than the one this body binds, // no package holds this item, so the save writes the // environment's own row on this object and every package's item - // stays where it is ({@link packagelessActionSaveIsEnvironmentOwn}). - const environmentOwnAction = await packagelessActionSaveIsEnvironmentOwn( + // stays where it is ({@link packagelessActionKeyedAddress}). + const keyed = await packagelessActionKeyedAddress( host, writeType, request.name, request.item, address, ); + const environmentOwnAction = keyed === 'environment'; // [#32605, epic ruling 6781691009] A name a disabled package also // holds is written where the read naming no package serves it // ({@link servedPackagelessSaveAddress}): never the disabled // package's row, never a new package-unbound row beside an // enabled holder, and a refusal names only the served holders. + // [ADR-0150 D4] For an action some holder binds to another object, + // judged over the holders at the body's object only. const served = environmentOwnAction ? undefined : await servedPackagelessSaveAddress( - host, writeType, request.name, itemDiscriminator(writeType, request.item), address, + host, writeType, request.name, itemDiscriminator(writeType, request.item), keyed ?? address, keyed !== undefined, ); if (environmentOwnAction) { // The package-unbound row: `packageId` stays empty. @@ -2877,11 +2880,21 @@ async function servedPackagelessSaveAddress( host: Pick, type: string, name: string, member: string | undefined, address: { readonly packageId: string | null; readonly candidates: readonly string[]; readonly unbound: boolean }, + /** + * [ADR-0150 D4, ruling 6902014292] `address` is an action's address at + * the body's object ({@link packagelessActionKeyedAddress}): some holder + * binds the name to another object. The read's by-name judgment and the + * by-name content package are not asked (they key the name, not the + * item), and with only disabled holders at the object the address is + * theirs, as `packagelessAddress` answers a name only disabled packages + * hold. + */ + atObject = false, ): Promise<{ packageId: string | null } | undefined> { const registry = host.engine?.registry as { isPackageDisabled?: (id: string) => boolean } | undefined; if (typeof registry?.isPackageDisabled !== 'function') return undefined; const disabled = (id: string): boolean => registry.isPackageDisabled?.(id) === true; - const judged = await servedAddressJudgment(host, type, name, member); + const judged = atObject ? undefined : await servedAddressJudgment(host, type, name, member); if (judged?.kind === 'served') return { packageId: judged.packageId }; if (judged?.kind === 'refused') { const served = judged.error.refusal.candidates @@ -2894,30 +2907,41 @@ async function servedPackagelessSaveAddress( if (enabled.length > 1) throw packagelessAddressAmbiguityRefusal('save', type, name, enabled); if (enabled.length === 1) return { packageId: enabled[0] ?? null }; if (address.unbound) return { packageId: null }; + if (atObject) { + if (address.candidates.length > 1) throw packagelessAddressAmbiguityRefusal('save', type, name, address.candidates); + return { packageId: address.candidates[0] ?? null }; + } const shippers = [...shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member))].filter((id) => !disabled(id)); const content = packagelessContentPackage({ packageId: null, candidates: [] }, shippers.map((id) => ({ _packageId: id }))); return typeof content === 'string' ? { packageId: content } : undefined; } /** - * [ADR-0150 D4, ruling 6902014292] Whether a publish-mode save of an `action` - * naming no package writes the ENVIRONMENT'S OWN item: the package-less - * address has a holder (`address.candidates`, {@link packagelessAddress}) and - * the one owner-key rule, {@link actionHeldOnlyOnOtherObjects}, reads the - * item's active rows as holding the name only on objects other than the one - * `item` binds. The draft save and the per-item publish read the same rule. + * [ADR-0150 D4, ruling 6902014292] The address of a publish-mode save of an + * `action` naming no package, keyed `(package, objectName, name)`: * - * `false` — the address stands, as before — for every other type, for a - * name no package's row holds, and as soon as one holder binds the name to - * `item`'s object: the same-object save is still that package's - * customization, and two such holders are still refused. + * - `'environment'` — the ENVIRONMENT'S OWN item: the package-less address + * has a holder (`address.candidates`, {@link packagelessAddress}) and the + * one owner-key rule, {@link actionHeldOnlyOnOtherObjects}, reads the + * item's active rows as holding the name only on objects other than the + * one `item` binds. The draft save and the per-item publish read the same + * rule. The save writes the package-unbound row; every package's row stays. + * - the address over the rows at `item`'s object + * ({@link actionRowsBindingObjectOf}) — some holder binds the name to + * `item`'s object and another binds it to another object: the served + * step ({@link servedPackagelessSaveAddress}) judges the holders at the + * object only, so a disabled holder there is never answered by an enabled + * holder's item on another object. + * - `undefined` — the address stands, as before: every other type, a name + * no package's row holds, and an action every holder binds to `item`'s + * object. */ -async function packagelessActionSaveIsEnvironmentOwn( - host: Pick, +async function packagelessActionKeyedAddress( + host: Pick, type: string, name: string, item: unknown, address: { readonly candidates: readonly string[] }, -): Promise { - if (type !== 'action' || address.candidates.length === 0) return false; +): Promise<'environment' | Awaited> | undefined> { + if (type !== 'action' || address.candidates.length === 0) return undefined; let activeRows: readonly StoredOverlayRow[]; try { activeRows = await host.readItemActiveRows(type, name); @@ -2927,5 +2951,9 @@ async function packagelessActionSaveIsEnvironmentOwn( host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); activeRows = []; } - return actionHeldOnlyOnOtherObjects(type, item, activeRows); + if (actionHeldOnlyOnOtherObjects(type, item, activeRows)) return 'environment'; + const atObject = actionRowsBindingObjectOf(item, activeRows); + const held = activeRows.filter(isPackageBoundRow); + if (actionRowsBindingObjectOf(item, held).length === held.length) return undefined; + return host.packagelessAddress(type, name, undefined, 'active', atObject); } diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 86705431405..36d8e603e78 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -407,6 +407,42 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q'], [null, 'task', 'env']]); }); + it('a SOLE DISABLED holder on `invoice`: the save on `task` writes the environment\'s row (FROM: into the disabled package\'s row)', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + protocol.engine.registry.isPackageDisabled = (id: string) => id === WRITABLE; + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + expect(saved.message).not.toContain('package='); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); + }); + + it('a SOLE binding on `invoice` to a package that is NOT INSTALLED: the save on `task` writes the environment\'s row (FROM: 422 naming the package)', async () => { + const { protocol, rows, seedRow } = makeProtocol(); + const GONE = 'com.qa.uninstalled'; + seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + expect(saved.success).toBe(true); + expect(stored(rows('action', NAME))).toEqual([[GONE, 'invoice', 'gone'], [null, 'task', 'env']]); + }); + + it('an ENABLED holder on `invoice` beside a DISABLED holder on `task`: the save on `task` is the disabled holder\'s, never the enabled holder\'s item moved (FROM: into P, its action moved to `task`)', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'task'), packageId: OTHER_WRITABLE }); + protocol.engine.registry.isPackageDisabled = (id: string) => id === OTHER_WRITABLE; + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'task') }); + + // The address at `task` holds only the disabled holder, and a name + // only disabled packages hold keeps naming that package. + expect(saved.message).toBe(`Saved action '${NAME}' (env-wide, package=${OTHER_WRITABLE}, state=active) [seq=${saved.seq}]`); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'task', 'edited']]); + }); + it('the DRAFT save on `task` writes the environment\'s draft (FROM: P\'s draft), and P\'s rows are untouched', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 8f869286d80..f623a461d4e 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -734,10 +734,20 @@ export function actionHeldOnlyOnOtherObjects( activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, ): boolean { if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'action') return false; - const held = activeRows.filter((row) => typeof row?.package_id === 'string' && row.package_id !== ''); - if (held.length === 0) return false; + const held = activeRows.filter(isPackageBoundRow); + return held.length > 0 && actionRowsBindingObjectOf(item, held).length === 0; +} + +/** + * [ADR-0150 D4] The rows of `rows` that bind the object `item` binds + * ({@link boundObjectOf}; object-less is its own key): the rows of the action + * item a body bound to that object addresses. A stored body that does not + * parse is read as binding `item`'s object, so it never drops a row from the + * key. The filter {@link actionHeldOnlyOnOtherObjects} reads. + */ +export function actionRowsBindingObjectOf(item: unknown, rows: readonly R[]): R[] { const object = boundObjectOf(item); - return !held.some((row) => { + return rows.filter((row) => { let document: unknown; try { document = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata; @@ -748,6 +758,11 @@ export function actionHeldOnlyOnOtherObjects( }); } +/** A row bound to a package (a non-empty `package_id`). */ +export function isPackageBoundRow(row: { package_id?: unknown }): boolean { + return typeof row?.package_id === 'string' && row.package_id !== ''; +} + /** * One live `watch()` subscription, as a record rather than a bare listener. * From a953b87874fc2e01d67309140479f2808fb54650 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:28:20 +0000 Subject: [PATCH 08/24] docs(adr-0150): read the customization rule at the action key; state it on the save request The D4 amendment note and the R15 pointer: a package-less action row bound to an object no holder binds the name to is the environment's own item. `SaveMetaItemRequest.packageId` names the action exception. The dogfood file pins today's by-name read and package-less delete answers as FROM. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- content/docs/references/api/protocol.mdx | 2 +- ...-by-package-objects-keep-the-literal-prefix.md | 4 +++- ...-save-packageless-other-object.dogfood.test.ts | 15 ++++++++++++--- packages/spec/src/api/protocol.zod.ts | 7 ++++++- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 3e1ee93144a..0746f002d3e 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2915,7 +2915,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index 14698465a1c..0c81982ad16 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -180,6 +180,8 @@ Hooks bind by event and object and already carry `packageId`. Only `isArtifactSh **A package-less row that bears a package-held name is a customization, never a second item.** A `sys_metadata` row with `package_id` NULL hydrates into the bare slot today (`registerItem`). Where a package holds that `(type, name)`, the row is the ADR-0005 overlay of that one phase-1 holder (`bare-name-one-holder.ts` already counts it as no holder). It is not a bucket-4 item, so it never arms beside the item it shadows (E1) and never makes the name ambiguous. Its migration into a declared override in the holder's paired `.custom` package is [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D11's, and this record does not repeat it (R15). A bucket-4 item is therefore one whose `(type, name)` no package holds. If a package installed later takes such a name, the row reads as that holder's overlay, which is what the bare slot does today. The D10 upgrade report names the row. +> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save's address (`resolveWriteHead`), and the per-item publish of that draft; the save's served address judges only the holders at the body's object. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). + ### D5 — Addresses: an optional namespace segment, `409` on ambiguity **The grammar.** A by-name door accepts the qualified form, with the namespace before the name, and keeps the bare form: @@ -308,7 +310,7 @@ This replaces #30806 S3's name rewrite. Nothing is renamed, so nothing is rewrit | R11 | `sys_connector_connection.connector_name` | `connector_package` | per-organization OAuth connections | | R13 | `sys_assignment_cursor.rule` | `rule_package` | | | R14 | `sys_job.name` | follows the aligned `jobKeyFor` key | the run history stays as written | -| R15 | package-less `sys_metadata` overlay rows over a package-held name | `package_id` bound to the one phase-1 holder by ADR-0146 D11's migration (a declared override in that holder's `.custom` pair); two holders → the ambiguous set, reported | D4: a customization, never a bucket-4 item | +| R15 | package-less `sys_metadata` overlay rows over a package-held name | `package_id` bound to the one phase-1 holder by ADR-0146 D11's migration (a declared override in that holder's `.custom` pair); two holders → the ambiguous set, reported | D4: a customization, never a bucket-4 item; for an action, over a holder's `(objectName, name)` only (amendment note under D4) | | R16 | `.custom` pair overrides | already carry the package | the overlay slot binds per package (D4) | | R17 | `sys_metadata` bodies that name another item | nothing stored | resolved by D3; an ambiguous one is reported, and so is a package item's reference whose only holder is the environment (D3 (a), D10) | | R20 | `sys_email_template` overlays | `package_id` | | diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index b40dfd50f35..57c7d2da2b3 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -77,13 +77,22 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does expect(saved.message).not.toContain('package='); // FROM: `['showcase_task', 'env', PKG]`, the environment's body under P. expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); - // The by-name read naming no package is not pinned here: with P's row and - // the environment's row both stored it serves P's item, in either save - // order (the read side's own seam, not this save door's). expect(await routeTarget(`/actions/showcase_invoice/${name}`)).toEqual([400, 'pkg']); expect(await routeTarget(`/actions/showcase_task/${name}`)).toEqual([400, 'env']); // FROM: 404, the environment held no item of the name. expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); + + // FROM pins: what does NOT move yet (#33904, the read, list and delete + // half). Each turns when that card keys its door by object. + // FROM: the by-name read naming no package serves P's item, never the + // environment's row on `showcase_task`. + expect(await read(`/meta/action/${name}`)).toEqual(['showcase_invoice', 'pkg', PKG]); + // FROM: a package-less DELETE of the name removes P's row on + // `showcase_invoice`, and leaves the environment's row. + const deleted = await stack.apiAs(admin, 'DELETE', `/meta/action/${name}`); + expect(deleted.status, await deleted.clone().text()).toBe(200); + expect((await stack.apiAs(admin, 'GET', `/meta/action/${name}?package=${PKG}`)).status).toBe(404); + expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); }, 120_000); it('the DRAFT save on `showcase_task` and its per-item publish write the environment\'s item; P\'s item on `showcase_invoice` is untouched', async () => { diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 678dfe64b16..f773b508190 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1215,7 +1215,12 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` ' + 'when the active rows (or, with none and no package-unbound draft, the ' + 'drafts) are bound to two or more packages, as that publish is (see ' - + '`PublishMetaItemRequestSchema.packageId`). The row written is also the one the parent-version ' + + '`PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the ' + + 'object it binds (ADR-0150 D4): its rows are read at the body\'s object ' + + 'only, so a body bound to an object no package\'s active row binds the ' + + 'name to writes the environment\'s own row (or draft, which the per-item ' + + 'publish naming no package promotes there), never a package\'s item. ' + + 'The row written is also the one the parent-version ' + 'resolution reads: an unpinned save takes its version as the parent ' + '(last-write-wins), a pinned one is judged against it, and the item ' + 'read at the same scope serves it as `version`.', From 016a90bd9d8088cd5847c069e65b2040926aa38f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:41:15 +0000 Subject: [PATCH 09/24] fix(metadata-protocol): key the draft save's head and gates of an action by object The draft save's write head (its parent and its receipt) and the gates that judge the package a draft lands in read the action's object, as the repository's put does: the environment's own draft is answered and judged as the package-unbound draft it is. The dogfood file pins today's package-less delete answer as FROM. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- packages/metadata-protocol/src/protocol-save.ts | 16 +++++++++++++++- .../protocol.packageless-save-address.test.ts | 16 +++++++++++++++- .../src/sys-metadata-repository.ts | 15 +++++++++++++-- ...save-packageless-other-object.dogfood.test.ts | 11 +++++++++-- 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 5893f30dd21..58a57512b64 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -853,7 +853,7 @@ export class ProtocolSaveFacet { // read here for the two gates below that judge the row it lands in. // Read once, for the same authoring saves the publish-mode address // above is resolved for. - const draftAddress = mode === 'draft' + const packagelessDraft = mode === 'draft' && request.packageId == null && request.source === undefined && request.writeFace !== 'package-duplicate' @@ -861,6 +861,17 @@ export class ProtocolSaveFacet { singularType, request.name, itemDiscriminator(singularType, request.item), ) : undefined; + // [ADR-0150 D4, ruling 6902014292] …and an action draft whose body + // binds an object no package's active row binds the name to is the + // environment's own draft, as the repository writes it + // (`resolveWriteHead`, the one rule {@link actionHeldOnlyOnOtherObjects}): + // the gates below judge the package-unbound draft it lands in. + const draftAddress = packagelessDraft !== undefined + && packagelessDraft.kind !== 'ambiguous' + && packagelessDraft.into !== null + && await packagelessActionKeyedAddress(host, singularType, request.name, request.item, { candidates: [packagelessDraft.into] }) === 'environment' + ? { ...packagelessDraft, key: null, into: null } + : packagelessDraft; // [#26921] THE NAMED-BASE RULE for the binding a save naming no // package INHERITS: the package its address gives (the resolved @@ -2039,6 +2050,9 @@ export class ProtocolSaveFacet { // [#22877] The write's bundle member, from the body it writes — // the member the repository's `put` keys this save by. member: itemDiscriminator(singularTypeForRepo, request.item), + // [ADR-0150 D4] …and its body, so an action draft's head is + // keyed by its object, as the put's is. + body: request.item, }); const currentStored = writeHead.head?.hash ?? null; if (mode === 'draft' && request.packageId == null) inheritedDraftPackageId = writeHead.packageId; diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 36d8e603e78..bccfdf354c3 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -447,12 +447,26 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); - await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + // FROM: `(env-wide, package=com.qa.lanebapp, state=draft)`. + expect(drafted.message).toBe(`Saved action '${NAME}' (env-wide, state=draft) [seq=${drafted.seq}]`); expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); }); + it('the DRAFT save on `task` beside a sole binding on `invoice` to a package that is NOT INSTALLED: the environment\'s draft (FROM: 422 naming the package)', async () => { + const { protocol, rows, seedRow } = makeProtocol(); + const GONE = 'com.qa.uninstalled'; + seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' }); + + const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + expect(drafted.success).toBe(true); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[GONE, 'invoice', 'gone']]); + }); + it('the per-item publish naming no package promotes that draft into the environment\'s row (FROM: over P\'s item on `invoice`)', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index f623a461d4e..cfd49743d25 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -929,11 +929,22 @@ export class SysMetadataRepository implements MetadataRepository { * it from the body it writes, so a caller asking for that save's head * passes the body's member (see {@link get} for the rest). */ - opts: { state?: OverlayState; packageId?: string | null; member?: string | null }, + opts: { + state?: OverlayState; + packageId?: string | null; + member?: string | null; + /** + * [ADR-0150 D4] The body the write carries, as {@link put} is handed it: + * an action draft's inherited binding is keyed by its object + * ({@link actionHeldOnlyOnOtherObjects}), so the head is the row that + * put writes. Omitted, the binding is inherited by name. + */ + body?: unknown; + }, ): Promise<{ head: MetadataItem | null; packageId: string | null }> { this.assertOpen(); const { row, targetPackageId } = await this.resolveWriteHead( - ref, opts.state ?? 'active', opts.packageId, undefined, overlayMemberValue(ref.type, opts.member), + ref, opts.state ?? 'active', opts.packageId, undefined, overlayMemberValue(ref.type, opts.member), opts.body, ); return { head: row ? this.rowToItem(ref, row) : null, packageId: targetPackageId }; } diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index 57c7d2da2b3..16dd6753e4a 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -90,8 +90,15 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does // FROM: a package-less DELETE of the name removes P's row on // `showcase_invoice`, and leaves the environment's row. const deleted = await stack.apiAs(admin, 'DELETE', `/meta/action/${name}`); - expect(deleted.status, await deleted.clone().text()).toBe(200); - expect((await stack.apiAs(admin, 'GET', `/meta/action/${name}?package=${PKG}`)).status).toBe(404); + const deletedText = await deleted.text(); + expect(deleted.status, deletedText).toBe(200); + expect(deletedText).toContain(`package=${PKG}`); + // …so P no longer holds the name: the read naming P is refused 409, the + // name held by the environment only. + const afterDelete = await stack.apiAs(admin, 'GET', `/meta/action/${name}?package=${PKG}`); + const afterText = await afterDelete.text(); + expect(afterDelete.status, afterText).toBe(409); + expect(afterText).toContain('RESOURCE_CONFLICT'); expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); }, 120_000); From 499f9b47be26b156d97c9f4dff3eef20692bd73f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:42:05 +0000 Subject: [PATCH 10/24] chore(changeset): state the draft door, the disabled and uninstalled rows, and what does not move yet Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../34059-action-save-packageless-other-object.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index 3b84d3f67a9..e06f9c7a212 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -1,5 +1,6 @@ --- '@objectstack/metadata-protocol': minor +'@objectstack/spec': patch --- fix(metadata-protocol)!: a package-less action save on an object no package binds the name to writes the environment's own action @@ -17,7 +18,13 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - a package-less save of `approve` bound to `task` was written into `P` (receipt `package=P`) and moved `P`'s action from `invoice` to `task`; it now writes the environment's own row on `task` (a receipt with no package), and `P`'s action on `invoice` is untouched: `GET /meta/action/approve?package=P` still serves it and `/actions/invoice/approve` still runs it. - the same save with an object-less body: it now writes the environment's own object-less row. - with two packages holding `approve` on two other objects, the save was refused `409 RESOURCE_CONFLICT` naming both; it now writes the environment's own row. +- with `P` the sole holder and `P` disabled, the save was written into `P`'s row; it now writes the environment's own row on `task`. +- with the sole row on `invoice` bound to a package that is not installed, the save was refused `422`; it now writes the environment's own row on `task`. +- with `P` (enabled) on `invoice` and a disabled package `Q` on `task`, the save on `task` was written into `P` and moved its action to `task`; it is now judged over the holders on `task` only, so it writes `Q`'s row (as a save over a name only a disabled package holds does), and `P`'s action on `invoice` is untouched. +- a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft. -Unchanged: the same save on `invoice` (the object `P` binds) is still `P`'s customization; a package on `invoice` and another on `task` still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`; a draft save (`?mode=draft`) still inherits the package of the item's active rows. +Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. -Nothing to do for the environment's own actions. A package's own action is moved to another object by a save naming the package (`?package=P`), as before. A package's action that an older build moved to another object stays where it was stored. +Not moved yet (#33904, the read, list and delete half): the environment's row on `task` has no by-name read, since `GET /meta/action/approve` naming no package still serves `P`'s action; it is not in `GET /meta/action`; and a package-less `DELETE /meta/action/approve` removes `P`'s row on `invoice`, not the environment's. The one address that reaches the environment's row today is the action route `/actions/_env/task/approve`; a read or delete naming `P` (`?package=P`) reaches `P`'s. + +Until #33904 lands, no meta address deletes only the environment's own action: do not send a package-less delete of the name to remove it, because that removes the package's action. A package's own action is moved to another object by a save naming the package (`?package=P`), as before. A package's action that an older build moved to another object stays where it was stored. From 0ed4158ef6643cccb1ce31758d33deb36aac1530 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 04:55:45 +0000 Subject: [PATCH 11/24] 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 | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 0746f002d3e..2b561a110d2 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 From 1b08a46eec9e560ef228aa65118bb5f430965155 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:53:05 +0000 Subject: [PATCH 12/24] fix(metadata-protocol): read the action owner-key rule above the draft doors' two-holder refusal The draft address the per-item publish, the draft discard and the draft save read asks the one rule of the package-unbound draft's body (or of the saved body) before refusing two holders, so the environment's own action draft is published and discarded where it is saved. The orphan-draft adoption no longer takes the environment's action draft of another object. States the version-conflict answer the bare read leads to. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...59-action-save-packageless-other-object.md | 9 +- content/docs/references/api/protocol.mdx | 2 +- ...package-objects-keep-the-literal-prefix.md | 2 +- .../src/protocol-history-and-publish.ts | 20 +--- .../src/protocol-lock-version-gates.ts | 62 ++++++++++-- .../metadata-protocol/src/protocol-save.ts | 18 +--- .../protocol.packageless-save-address.test.ts | 95 +++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 6 +- .../src/sys-metadata-repository.ts | 13 +++ ...e-packageless-other-object.dogfood.test.ts | 32 +++++++ packages/spec/src/api/protocol.zod.ts | 5 +- 11 files changed, 218 insertions(+), 46 deletions(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index e06f9c7a212..365e8fd2f1e 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -20,11 +20,16 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - with two packages holding `approve` on two other objects, the save was refused `409 RESOURCE_CONFLICT` naming both; it now writes the environment's own row. - with `P` the sole holder and `P` disabled, the save was written into `P`'s row; it now writes the environment's own row on `task`. - with the sole row on `invoice` bound to a package that is not installed, the save was refused `422`; it now writes the environment's own row on `task`. +- with `P` on `invoice` and `Q` on `product`, a draft save bound to `task` was refused `409` naming both; it now writes the environment's own draft, the per-item publish naming no package promotes it into the environment's own row, and the draft discard naming no package removes it (each was `409` naming both). - with `P` (enabled) on `invoice` and a disabled package `Q` on `task`, the save on `task` was written into `P` and moved its action to `task`; it is now judged over the holders on `task` only, so it writes `Q`'s row (as a save over a name only a disabled package holds does), and `P`'s action on `invoice` is untouched. -- a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft. +- with `P` (enabled) on `invoice`, and on `task` an enabled `Q` and a disabled `R`, the save on `task` was refused `409` naming `P` and `Q`; it is now judged over the holders on `task` only, so it writes `Q`'s row, and `P`'s action on `invoice` is untouched. Without `R` the same save is still refused `409` naming `P` and `Q` (below). +- a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft, and its publish the environment's own row. +- with the environment's draft on `task` stored, a package-less draft save on `invoice` adopted that draft into `P` and rewrote it on `invoice`, so the environment's pending draft was gone; it now writes `P`'s draft on `invoice` and the environment's draft on `task` stays. Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. -Not moved yet (#33904, the read, list and delete half): the environment's row on `task` has no by-name read, since `GET /meta/action/approve` naming no package still serves `P`'s action; it is not in `GET /meta/action`; and a package-less `DELETE /meta/action/approve` removes `P`'s row on `invoice`, not the environment's. The one address that reaches the environment's row today is the action route `/actions/_env/task/approve`; a read or delete naming `P` (`?package=P`) reaches `P`'s. +The two modes still differ for one enabled and one disabled holder with the body on the disabled holder's object: the publish-mode save writes the disabled holder's row, while the draft save is refused `409` naming both, as it was. + +Not moved yet (#33904, the read, list and delete half): the environment's row on `task` has no by-name read, since `GET /meta/action/approve` naming no package still serves `P`'s action; it is not in `GET /meta/action`; and a package-less `DELETE /meta/action/approve` removes `P`'s row on `invoice`, not the environment's. The version the bare read serves is `P`'s, so a save on `task` that carries it as its parent (`If-Match`) is refused as a version conflict, before and after the environment's row exists; send the save without `If-Match`. The one address that reaches the environment's row today is the action route `/actions/_env/task/approve`; a read or delete naming `P` (`?package=P`) reaches `P`'s. Until #33904 lands, no meta address deletes only the environment's own action: do not send a package-less delete of the name to remove it, because that removes the package's action. A package's own action is moved to another object by a save naming the package (`?package=P`), as before. A package's action that an older build moved to another object stays where it was stored. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 2b561a110d2..35a2b5809a7 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2930,7 +2930,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item; until the read naming no package keys an action by object (#33904), the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index 0c81982ad16..d7729da33b2 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -180,7 +180,7 @@ Hooks bind by event and object and already carry `packageId`. Only `isArtifactSh **A package-less row that bears a package-held name is a customization, never a second item.** A `sys_metadata` row with `package_id` NULL hydrates into the bare slot today (`registerItem`). Where a package holds that `(type, name)`, the row is the ADR-0005 overlay of that one phase-1 holder (`bare-name-one-holder.ts` already counts it as no holder). It is not a bucket-4 item, so it never arms beside the item it shadows (E1) and never makes the name ambiguous. Its migration into a declared override in the holder's paired `.custom` package is [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D11's, and this record does not repeat it (R15). A bucket-4 item is therefore one whose `(type, name)` no package holds. If a package installed later takes such a name, the row reads as that holder's overlay, which is what the bare slot does today. The D10 upgrade report names the row. -> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save's address (`resolveWriteHead`), and the per-item publish of that draft; the save's served address judges only the holders at the body's object. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). +> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges only the holders at the body's object, and the orphan-draft adoption never takes the environment's draft of another object. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). ### D5 — Addresses: an optional namespace segment, `409` on ambiguity diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 483a0357d9b..2f82d0b0e1c 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -25,7 +25,7 @@ import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; -import { DraftConflictError, actionHeldOnlyOnOtherObjects, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { DraftConflictError, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; import { ConflictError } from '@objectstack/metadata-core'; import type { MetadataItem } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; @@ -664,7 +664,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -834,22 +834,6 @@ export class ProtocolHistoryAndPublishFacet { } else { draftKey = address.key; promoteInto = address.into; - // [ADR-0150 D4, ruling 6902014292] An unbound action draft - // whose body binds an object no package's active row binds - // the name to is the environment's own draft (the draft save - // wrote it unbound for that reason): it is promoted into the - // package-unbound active row, never adopted into the holder, - // whose item on its own object stays as it is. The one rule - // the save and the draft save read ({@link actionHeldOnlyOnOtherObjects}). - if (singularType === 'action' && draftKey === null && promoteInto !== null && address.kind === 'draft') { - const unboundDraft = await repo.get( - { type: singularType, name: request.name, org: 'env' } as Parameters[0], - { state: 'draft', packageId: null, ...memberOption(request.member) }, - ); - if (unboundDraft && actionHeldOnlyOnOtherObjects(singularType, unboundDraft.body, await host.readItemActiveRows(singularType, request.name))) { - promoteInto = null; - } - } // No draft at the address while another package's draft is // stored: the promotion's `NO_DRAFT`, naming the drafts that // remain and the request that reaches them. diff --git a/packages/metadata-protocol/src/protocol-lock-version-gates.ts b/packages/metadata-protocol/src/protocol-lock-version-gates.ts index d22a105b9e1..ba98e4c14c2 100644 --- a/packages/metadata-protocol/src/protocol-lock-version-gates.ts +++ b/packages/metadata-protocol/src/protocol-lock-version-gates.ts @@ -49,7 +49,7 @@ import type { ObjectStackProtocolImplementation, MetadataAuditEntry } from './protocol.js'; import { canonicalMetaType } from './protocol.js'; -import { SysMetadataRepository, unboundItemDraftAddress } from './sys-metadata-repository.js'; +import { SysMetadataRepository, actionHeldOnlyOnOtherObjects, unboundItemDraftAddress } from './sys-metadata-repository.js'; import { packagelessContentPackage } from './protocol-environment-rows.js'; import { resolveItemLockLazily } from './item-lock.js'; import { ConflictError } from '@objectstack/metadata-core'; @@ -108,6 +108,7 @@ export interface LockVersionGateHost { overlayLockLayerAt: ObjectStackProtocolImplementation['overlayLockLayerAt']; packagelessAddress: ObjectStackProtocolImplementation['packagelessAddress']; packagelessDraftAddress: ObjectStackProtocolImplementation['packagelessDraftAddress']; + readItemActiveRows: ObjectStackProtocolImplementation['readItemActiveRows']; readLockGateOverlayLayer: ObjectStackProtocolImplementation['readLockGateOverlayLayer']; receiptVersion: ObjectStackProtocolImplementation['receiptVersion']; recordMetadataAudit: ObjectStackProtocolImplementation['recordMetadataAudit']; @@ -459,11 +460,17 @@ export async function strictDraftReadAddress( /** The body of `ObjectStackProtocolImplementation#packagelessDraftAddress`; the method's docblock there is its contract. */ export async function packagelessDraftAddress( - this: Pick, + this: Pick, type: string, name: string, /** [#22877] The bundle member the door addresses; omitted, the canonical one. */ member?: string, + /** + * [ADR-0150 D4] The body a draft SAVE writes. Omitted (the per-item + * publish, the draft discard and the draft read), the body of the stored + * package-unbound draft is the one judged. + */ + body?: unknown, ): Promise< | { kind: 'ambiguous'; candidates: readonly string[] } | { @@ -474,19 +481,56 @@ export async function packagelessDraftAddress( } > { const active = await this.packagelessAddress(type, name, member, 'active'); - if (active.candidates.length > 1) return { kind: 'ambiguous', candidates: active.candidates }; - const drafts = await this.packagelessAddress(type, name, member, 'draft'); + // [ADR-0150 D4, ruling 6902014292] An action draft whose body binds an + // object no package's active row binds the name to is the environment's + // own draft: the package-unbound draft, promoted into the package-unbound + // row, whatever packages hold the name on other objects (the one rule, + // {@link actionHeldOnlyOnOtherObjects}, which the repository's draft + // write asks too). A save asks it of the body it writes, first, as the + // repository does; the doors that act on a stored draft ask it of the + // package-unbound draft, where no package's own draft is the address. + const drafts = active.candidates.length > 0 && type === 'action' + ? await this.packagelessAddress(type, name, member, 'draft') + : undefined; + const environmentOwnDraft = async (): Promise => { + if (drafts === undefined) return false; + let item = body; + if (item === undefined) { + if (!drafts.unbound) return false; + const repo = this.getOverlayRepo(); + const stored = await repo.get( + { type, name, org: 'env' } as Parameters[0], + { state: 'draft', packageId: null, ...(member !== undefined ? { member } : {}) }, + ); + if (!stored) return false; + item = stored.body; + } + return actionHeldOnlyOnOtherObjects(type, item, await this.readItemActiveRows(type, name)); + }; + const environmentDraft = () => ({ + kind: drafts?.unbound ? 'draft' as const : 'none' as const, key: null, into: null, + drafts: drafts ?? { packageId: null, candidates: [], unbound: false }, + }); + if (body !== undefined && await environmentOwnDraft()) return environmentDraft(); + if (active.candidates.length > 1) { + if (body === undefined && await environmentOwnDraft()) return environmentDraft(); + return { kind: 'ambiguous', candidates: active.candidates }; + } + const draftRows = drafts ?? await this.packagelessAddress(type, name, member, 'draft'); const own = active.packageId; if (own !== null) { - if (drafts.candidates.includes(own)) return { kind: 'draft', key: own, into: own, drafts }; - if (drafts.unbound) return { kind: 'draft', key: null, into: own, drafts }; - return { kind: 'none', key: own, into: own, drafts }; + if (draftRows.candidates.includes(own)) return { kind: 'draft', key: own, into: own, drafts: draftRows }; + if (draftRows.unbound) { + if (body === undefined && await environmentOwnDraft()) return environmentDraft(); + return { kind: 'draft', key: null, into: own, drafts: draftRows }; + } + return { kind: 'none', key: own, into: own, drafts: draftRows }; } // [#23657] Bound to none: the rule the draft save's address takes too // ({@link unboundItemDraftAddress}, in `resolveWriteHead`). - const address = unboundItemDraftAddress(drafts); + const address = unboundItemDraftAddress(draftRows); if (address.kind === 'ambiguous') return address; - return { kind: address.kind, key: address.key, into: address.key, drafts }; + return { kind: address.kind, key: address.key, into: address.key, drafts: draftRows }; } /** The body of `ObjectStackProtocolImplementation#storedParentForToken`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 58a57512b64..4df551bbcf5 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -853,25 +853,17 @@ export class ProtocolSaveFacet { // read here for the two gates below that judge the row it lands in. // Read once, for the same authoring saves the publish-mode address // above is resolved for. - const packagelessDraft = mode === 'draft' + // [ADR-0150 D4] …asked of the body this save writes, so an action + // draft the environment owns is judged as the package-unbound draft + // the repository writes it as. + const draftAddress = mode === 'draft' && request.packageId == null && request.source === undefined && request.writeFace !== 'package-duplicate' ? await host.packagelessDraftAddress( - singularType, request.name, itemDiscriminator(singularType, request.item), + singularType, request.name, itemDiscriminator(singularType, request.item), request.item, ) : undefined; - // [ADR-0150 D4, ruling 6902014292] …and an action draft whose body - // binds an object no package's active row binds the name to is the - // environment's own draft, as the repository writes it - // (`resolveWriteHead`, the one rule {@link actionHeldOnlyOnOtherObjects}): - // the gates below judge the package-unbound draft it lands in. - const draftAddress = packagelessDraft !== undefined - && packagelessDraft.kind !== 'ambiguous' - && packagelessDraft.into !== null - && await packagelessActionKeyedAddress(host, singularType, request.name, request.item, { candidates: [packagelessDraft.into] }) === 'environment' - ? { ...packagelessDraft, key: null, into: null } - : packagelessDraft; // [#26921] THE NAMED-BASE RULE for the binding a save naming no // package INHERITS: the package its address gives (the resolved diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index bccfdf354c3..c50937689bc 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -479,6 +479,74 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(rows('action', NAME, 'draft')).toEqual([]); }); + it('the per-item publish of the draft beside a sole binding to a package that is NOT INSTALLED: the environment\'s row', async () => { + const { protocol, rows, seedRow } = makeProtocol(); + const GONE = 'com.qa.uninstalled'; + seedRow({ type: 'action', name: NAME, package_id: GONE, metadata: JSON.stringify(action(NAME, 'gone', 'invoice')), checksum: 'sha-gone' }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + await protocol.publishMetaItem({ type: 'action', name: NAME }); + + expect(stored(rows('action', NAME))).toEqual([[GONE, 'invoice', 'gone'], [null, 'task', 'env']]); + expect(rows('action', NAME, 'draft')).toEqual([]); + }); + + describe('two packages holding the name on two other objects: the draft save, its publish and its discard (FROM: 409 naming both at each door)', () => { + async function twoHolders() { + const fixture = makeProtocol(); + await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'product'), packageId: OTHER_WRITABLE }); + return fixture; + } + + it('the draft save writes the environment\'s draft', async () => { + const { protocol, rows } = await twoHolders(); + + const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + expect(drafted.message).toBe(`Saved action '${NAME}' (env-wide, state=draft) [seq=${drafted.seq}]`); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q']]); + }); + + it('the per-item publish naming no package promotes it into the environment\'s row', async () => { + const { protocol, rows } = await twoHolders(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + const published = await protocol.publishMetaItem({ type: 'action', name: NAME }); + + expect(published.success).toBe(true); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q'], [null, 'task', 'env']]); + expect(rows('action', NAME, 'draft')).toEqual([]); + }); + + it('the draft discard naming no package removes it; both packages\' rows untouched', async () => { + const { protocol, rows } = await twoHolders(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + const receipt = await protocol.deleteMetaItem({ type: 'action', name: NAME, state: 'draft' }); + + expect(receipt.success).toBe(true); + expect(rows('action', NAME, 'draft')).toEqual([]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q']]); + }); + }); + + it('an ENABLED holder on `invoice`, and an ENABLED and a DISABLED holder on `task`: the save on `task` is the enabled holder\'s at `task`', async () => { + const { protocol, rows } = makeProtocol(); + const THIRD = 'com.qa.thirdapp'; + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'task'), packageId: OTHER_WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'r', 'task'), packageId: THIRD }); + protocol.engine.registry.isPackageDisabled = (id: string) => id === THIRD; + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'task') }); + + // Without the disabled holder the same save is the `409` CONTROL below. + expect(saved.message).toBe(`Saved action '${NAME}' (env-wide, package=${OTHER_WRITABLE}, state=active) [seq=${saved.seq}]`); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'task', 'edited'], [THIRD, 'task', 'r']]); + }); + describe('CONTROLs (unchanged)', () => { it('the draft save on `invoice`, the object P binds: P\'s draft, and its publish is P\'s row', async () => { const { protocol, rows } = makeProtocol(); @@ -502,6 +570,33 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'edited']]); }); + it('an enabled holder on `invoice` and a disabled holder on `task`: the DRAFT save on `task` is still refused 409 naming both (the publish-mode save writes the disabled holder\'s row)', async () => { + const { protocol, rows, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'task'), packageId: OTHER_WRITABLE }); + protocol.engine.registry.isPackageDisabled = (id: string) => id === OTHER_WRITABLE; + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' })); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(metadataWrites().length).toBe(before); + expect(rows('action', NAME, 'draft')).toEqual([]); + }); + + it('with the environment\'s DRAFT on `task` stored, a draft save on `invoice` is P\'s draft, and the environment\'s draft stays (FROM: adopted into P and rewritten on `invoice`)', async () => { + const { protocol, rows, seedRow } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + seedRow({ type: 'action', name: NAME, state: 'draft', package_id: null, metadata: JSON.stringify(action(NAME, 'env', 'task')), checksum: 'sha-env-draft' }); + + const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'invoice'), mode: 'draft' }); + + expect(drafted.message).toBe(`Saved action '${NAME}' (env-wide, package=${WRITABLE}, state=draft) [seq=${drafted.seq}]`); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[WRITABLE, 'invoice', 'edited'], [null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + }); + it('with the environment\'s row on `task` stored too, a save on `invoice` is still P\'s customization', async () => { const { protocol, rows, seedRow } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index b55648aea92..3316320584b 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -7927,6 +7927,8 @@ export class ObjectStackProtocolImplementation implements name: string, /** [#22877] The bundle member the door addresses; omitted, the canonical one. */ member?: string, + /** [ADR-0150 D4] The body a draft save writes; omitted, the stored package-unbound draft's. */ + body?: unknown, ): Promise< | { kind: 'ambiguous'; candidates: readonly string[] } | { @@ -7939,8 +7941,10 @@ export class ObjectStackProtocolImplementation implements // [#25467 cut 5] The body moved to `protocol-lock-version-gates.ts` (see `LockVersionGateHost`). const host: ThisParameterType = { packagelessAddress: (...a) => this.packagelessAddress(...a), + getOverlayRepo: () => this.getOverlayRepo(), + readItemActiveRows: (...a) => this.readItemActiveRows(...a), }; - return packagelessDraftAddress.call(host, type, name, member); + return packagelessDraftAddress.call(host, type, name, member, body); } /** diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index ef3d4d23306..396d11c912d 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -1130,6 +1130,19 @@ export class SysMetadataRepository implements MetadataRepository { where: this.whereFor(ref, state, null, member), context, }); + // [ADR-0150 D4, ruling 6902014292] …but never an action draft bound to + // another object than the body: that is the environment's own pending + // draft of its own item, not a pre-fix draft of the package's, and it + // stays where it is (the one rule's object filter, + // {@link actionRowsBindingObjectOf}). + if ( + row + && body !== undefined + && (PLURAL_TO_SINGULAR[ref.type] ?? ref.type) === 'action' + && actionRowsBindingObjectOf(body, [row as { metadata?: unknown }]).length === 0 + ) { + row = null; + } } return { row: row ?? null, targetPackageId, ...(ambiguousPackages ? { ambiguousPackages } : {}) }; } diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index 16dd6753e4a..b5f95605e92 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -102,6 +102,38 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); }, 120_000); + it('FROM (#33904): a save on `showcase_task` carrying the version the bare read served is refused as a version conflict, before and after the environment\'s row exists', async () => { + const name = 'qa_version_other_p'; + expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); + /** The version the by-name read naming no package serves: P's item's, until #33904. */ + const bareVersion = async () => { + const res = await stack.apiAs(admin, 'GET', `/meta/action/${name}`); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body).slice(0, 300)).toBe(200); + const version = body?.data?.version ?? body?.version; + expect(typeof version).toBe('string'); + return version as string; + }; + const putIfMatch = async (version: string) => { + const res = await stack.api(`/meta/action/${name}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${admin}`, 'If-Match': version }, + body: JSON.stringify(action(name, 'env', 'showcase_task')), + }); + return { status: res.status, text: await res.text() }; + }; + + // The parent is read at the environment's row, which the bare read does not serve. + const first = await putIfMatch(await bareVersion()); + expect(first.status, first.text).toBe(409); + expect(first.text).toContain('CONFLICT'); + + expect((await put(`/meta/action/${name}`, action(name, 'env', 'showcase_task'))).status).toBe(200); + const again = await putIfMatch(await bareVersion()); + expect(again.status, again.text).toBe(409); + expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); + }, 120_000); + it('the DRAFT save on `showcase_task` and its per-item publish write the environment\'s item; P\'s item on `showcase_invoice` is untouched', async () => { const name = 'qa_draft_other_p'; expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index d03fcf6d36a..f7c5912e2e7 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1219,7 +1219,10 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'object it binds (ADR-0150 D4): its rows are read at the body\'s object ' + 'only, so a body bound to an object no package\'s active row binds the ' + 'name to writes the environment\'s own row (or draft, which the per-item ' - + 'publish naming no package promotes there), never a package\'s item. ' + + 'publish naming no package promotes there), never a package\'s item; ' + + 'until the read naming no package keys an action by object (#33904), ' + + 'the version it serves is the package\'s item\'s, so a save carrying ' + + 'it as the parent is refused as a version conflict. ' + 'The row written is also the one the parent-version ' + 'resolution reads: an unpinned save takes its version as the parent ' + '(last-write-wins), a pinned one is judged against it, and the item ' From a8e34adfa28435d459278596bfb2c84c87f17c11 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:31:03 +0000 Subject: [PATCH 13/24] docs(spec): keep the internal card id out of the packageId description Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- content/docs/references/api/protocol.mdx | 2 +- packages/spec/src/api/protocol.zod.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 35a2b5809a7..4ae0bd7c5d9 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2930,7 +2930,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item; until the read naming no package keys an action by object (#33904), the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item; until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index f7c5912e2e7..49f2fb48808 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1220,7 +1220,8 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'only, so a body bound to an object no package\'s active row binds the ' + 'name to writes the environment\'s own row (or draft, which the per-item ' + 'publish naming no package promotes there), never a package\'s item; ' - + 'until the read naming no package keys an action by object (#33904), ' + // The read half that keys an action by object is #33904. + + 'until the read naming no package keys an action by object, ' + 'the version it serves is the package\'s item\'s, so a save carrying ' + 'it as the parent is refused as a version conflict. ' + 'The row written is also the one the parent-version ' From db96228e6c2b60ebec819bee3f208ce9a0996a5b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:02:09 +0000 Subject: [PATCH 14/24] fix(metadata-protocol): bind the draft address's repository under the census spelling The packagelessDraftAddress host binds getOverlayRepo as the other host literals do, so the stored-row census reads it. The dogfood version pin reads the served version from the body or the ETag. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- packages/metadata-protocol/src/protocol.ts | 2 +- .../test/action-save-packageless-other-object.dogfood.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 3316320584b..c008547c837 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -7941,7 +7941,7 @@ export class ObjectStackProtocolImplementation implements // [#25467 cut 5] The body moved to `protocol-lock-version-gates.ts` (see `LockVersionGateHost`). const host: ThisParameterType = { packagelessAddress: (...a) => this.packagelessAddress(...a), - getOverlayRepo: () => this.getOverlayRepo(), + getOverlayRepo: (...a) => this.getOverlayRepo(...a), readItemActiveRows: (...a) => this.readItemActiveRows(...a), }; return packagelessDraftAddress.call(host, type, name, member, body); diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index b5f95605e92..954f9f5495e 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -110,8 +110,8 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does const res = await stack.apiAs(admin, 'GET', `/meta/action/${name}`); const body: any = await res.json(); expect(res.status, JSON.stringify(body).slice(0, 300)).toBe(200); - const version = body?.data?.version ?? body?.version; - expect(typeof version).toBe('string'); + const version = body?.data?.version ?? body?.version ?? res.headers.get('etag'); + expect(typeof version, `${JSON.stringify(Object.keys(body?.data ?? body ?? {}))} etag=${res.headers.get('etag')}`).toBe('string'); return version as string; }; const putIfMatch = async (version: string) => { From 2396f22385313a8a89251771061567b68d7109a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:48:28 +0000 Subject: [PATCH 15/24] fix(metadata-protocol): the environment's action slot refuses a holder's customization; the spec clause states the code (contract review S4, M2, S2, S5, N3) - An environment-own action save (publish or draft) over the one package-unbound row or draft of the name, when that stored row binds an object a package's active row binds, is refused 409 RESOURCE_CONFLICT naming the holder, never moved (S4). Over the environment's own row on another object it still rewrites it, declared. - The SaveMetaItemRequest.packageId clause states the rule as the code has it (M2). - The version-conflict FROM is pinned in the unit harness and the dogfood leg that could not read a version is dropped (S2). - The per-item publish and the draft discard over the holder's own draft and the environment's draft are declared and pinned (S5). - Stale docblocks (N3). Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- ...59-action-save-packageless-other-object.md | 7 +- ...package-objects-keep-the-literal-prefix.md | 2 +- .../metadata-protocol/src/protocol-save.ts | 99 ++++++++++++- .../protocol.packageless-save-address.test.ts | 133 ++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 6 + .../src/sys-metadata-repository.ts | 26 +++- ...e-packageless-other-object.dogfood.test.ts | 39 +---- packages/spec/src/api/protocol.zod.ts | 22 ++- 8 files changed, 292 insertions(+), 42 deletions(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index 365e8fd2f1e..ee4ab82d430 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -25,11 +25,16 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - with `P` (enabled) on `invoice`, and on `task` an enabled `Q` and a disabled `R`, the save on `task` was refused `409` naming `P` and `Q`; it is now judged over the holders on `task` only, so it writes `Q`'s row, and `P`'s action on `invoice` is untouched. Without `R` the same save is still refused `409` naming `P` and `Q` (below). - a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft, and its publish the environment's own row. - with the environment's draft on `task` stored, a package-less draft save on `invoice` adopted that draft into `P` and rewrote it on `invoice`, so the environment's pending draft was gone; it now writes `P`'s draft on `invoice` and the environment's draft on `task` stays. +- with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. The two modes still differ for one enabled and one disabled holder with the body on the disabled holder's object: the publish-mode save writes the disabled holder's row, while the draft save is refused `409` naming both, as it was. -Not moved yet (#33904, the read, list and delete half): the environment's row on `task` has no by-name read, since `GET /meta/action/approve` naming no package still serves `P`'s action; it is not in `GET /meta/action`; and a package-less `DELETE /meta/action/approve` removes `P`'s row on `invoice`, not the environment's. The version the bare read serves is `P`'s, so a save on `task` that carries it as its parent (`If-Match`) is refused as a version conflict, before and after the environment's row exists; send the save without `If-Match`. The one address that reaches the environment's row today is the action route `/actions/_env/task/approve`; a read or delete naming `P` (`?package=P`) reaches `P`'s. +One slot per name, as before: the environment's own action row (and its draft) is one package-unbound row per name, so a package-less save of the environment's action bound to another object that no package binds the name to (`product`, with the environment's row on `task`) rewrites that row onto `product`, as a save of a name no package holds always has; `/actions/_env/task/approve` then answers nothing. The same for the environment's draft and a draft save. + +Not moved yet (#33904, the read, list and delete half): the environment's row on `task` has no by-name read, since `GET /meta/action/approve` naming no package still serves `P`'s action; it is not in `GET /meta/action`; and a package-less `DELETE /meta/action/approve` removes `P`'s row on `invoice`, not the environment's. The version the read naming no package serves in process (`getMetaItem`) is `P`'s, so a save on `task` that carries it as its parent (`parentVersion`) is refused `409 METADATA_CONFLICT`, before and after the environment's row exists; send the save without a parent. Over REST the bare read of an action carries no `version` to send. The one address that reaches the environment's row today is the action route `/actions/_env/task/approve`; a read or delete naming `P` (`?package=P`) reaches `P`'s. + +With `P`'s own draft and the environment's draft both stored, the per-item publish naming no package promotes `P`'s draft (its receipt names `P`) and the draft discard naming no package removes `P`'s draft; the environment's draft stays, and those doors reach it once `P` has no draft. With two or more packages holding the name on other objects, they act on the environment's draft (above). Until #33904 lands, no meta address deletes only the environment's own action: do not send a package-less delete of the name to remove it, because that removes the package's action. A package's own action is moved to another object by a save naming the package (`?package=P`), as before. A package's action that an older build moved to another object stays where it was stored. diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index d7729da33b2..80169e450af 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -180,7 +180,7 @@ Hooks bind by event and object and already carry `packageId`. Only `isArtifactSh **A package-less row that bears a package-held name is a customization, never a second item.** A `sys_metadata` row with `package_id` NULL hydrates into the bare slot today (`registerItem`). Where a package holds that `(type, name)`, the row is the ADR-0005 overlay of that one phase-1 holder (`bare-name-one-holder.ts` already counts it as no holder). It is not a bucket-4 item, so it never arms beside the item it shadows (E1) and never makes the name ambiguous. Its migration into a declared override in the holder's paired `.custom` package is [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D11's, and this record does not repeat it (R15). A bucket-4 item is therefore one whose `(type, name)` no package holds. If a package installed later takes such a name, the row reads as that holder's overlay, which is what the bare slot does today. The D10 upgrade report names the row. -> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges only the holders at the body's object, and the orphan-draft adoption never takes the environment's draft of another object. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). +> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges only the holders at the body's object, and the orphan-draft adoption never takes the environment's draft of another object. The environment keeps one package-less row and one package-less draft per action name, so an environment-own write over a holder's customization stored there is refused (`409 RESOURCE_CONFLICT`), never moved. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). ### D5 — Addresses: an optional namespace segment, `409` on ambiguity diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index a596fda5915..f649a2e8206 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -25,7 +25,8 @@ import { MetadataAuthoringSurfaceSchema } from '@objectstack/spec/api'; import { stampHtmlPageRequires } from './runtime-authoring-gate.js'; -import { SysMetadataRepository, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { SysMetadataRepository, actionCustomizationHoldersOf, actionHeldOnlyOnOtherObjects, actionRowsBindingObjectOf, isPackageBoundRow, packagelessAddressAmbiguityRefusal } from './sys-metadata-repository.js'; +import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; import { ConflictError, itemDiscriminator, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { authoringClientOf } from './draft-changes.js'; @@ -876,6 +877,15 @@ export class ProtocolSaveFacet { singularType, request.name, itemDiscriminator(singularType, request.item), request.item, ) : undefined; + // [ADR-0150 D4] The environment's own action draft is one slot per + // name: a holder's customization stored there is refused, never + // moved ({@link environmentActionDraftSlotRefusal}). + if (draftAddress !== undefined && draftAddress.kind === 'draft' && draftAddress.key === null && draftAddress.into === null) { + const slotRefusal = await environmentActionDraftSlotRefusal( + host, singularType, request.name, itemDiscriminator(singularType, request.item), request.item, + ); + if (slotRefusal) throw slotRefusal; + } // [ADR-0150 D3/D5, red line 2, ruling A] The draft save naming no // package answers the holders as the publish-mode save above does // ({@link packagelessHolderRefusal}), judged over the item's active rows @@ -2967,6 +2977,10 @@ async function servedPackagelessSaveAddress( * item's active rows as holding the name only on objects other than the * one `item` binds. The draft save and the per-item publish read the same * rule. The save writes the package-unbound row; every package's row stays. + * That row is one slot per name: the environment's own row bound to + * another object is rewritten onto `item`'s, and a holder's customization + * stored there is refused ({@link environmentActionSlotRefusal}), never + * moved. * - the address over the rows at `item`'s object * ({@link actionRowsBindingObjectOf}) — some holder binds the name to * `item`'s object and another binds it to another object: the served @@ -2992,13 +3006,94 @@ async function packagelessActionKeyedAddress( host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); activeRows = []; } - if (actionHeldOnlyOnOtherObjects(type, item, activeRows)) return 'environment'; + if (actionHeldOnlyOnOtherObjects(type, item, activeRows)) { + // The one package-unbound row is the slot this save writes: a + // holder's customization there is refused, never moved. + const slot = activeRows.filter((row) => !isPackageBoundRow(row)); + for (const row of slot) { + const refusal = environmentActionSlotRefusal('active', type, name, item, storedBodyOf(row.metadata), activeRows); + if (refusal) throw refusal; + } + return 'environment'; + } const atObject = actionRowsBindingObjectOf(item, activeRows); const held = activeRows.filter(isPackageBoundRow); if (actionRowsBindingObjectOf(item, held).length === held.length) return undefined; return host.packagelessAddress(type, name, undefined, 'active', atObject); } +/** A stored row's `metadata` as a body: parsed when a string, `undefined` when it does not parse. */ +function storedBodyOf(metadata: unknown): unknown { + if (typeof metadata !== 'string') return metadata ?? undefined; + try { + return JSON.parse(metadata) as unknown; + } catch { + return undefined; + } +} + +/** + * [ADR-0150 D4, ruling 6902014292] The refusal of a write of the + * environment's own action ({@link actionHeldOnlyOnOtherObjects}) over the one + * package-unbound row (`active`) or draft (`draft`) of the name when that + * stored row or draft is a holder's customization: it binds an object a + * package's active row binds ({@link actionCustomizationHoldersOf}). The + * environment keeps one package-unbound row and one draft per action name, so + * the write would move that customization off the holder's object, which the + * ruling forbids ("P's item on A is untouched"). `409 RESOURCE_CONFLICT`, + * with no new code. `undefined` when the stored row or draft is the + * environment's own (bound to an object no holder binds): the write rewrites + * it onto the body's object, as a save of a name no package holds does. + */ +export function environmentActionSlotRefusal( + state: 'active' | 'draft', + type: string, + name: string, + item: unknown, + storedBody: unknown, + activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, +): (Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined { + const holders = actionCustomizationHoldersOf(storedBody, activeRows); + if (holders.length === 0) return undefined; + const where = (object: string | undefined): string => (object === undefined ? 'bound to no object' : `on object '${object}'`); + const stored = storedBody === undefined ? 'unreadable' : where(boundObjectOf(storedBody)); + const slot = state === 'draft' ? 'draft' : 'row'; + const err = new Error( + `Cannot save ${type} '${name}' naming no package ${where(boundObjectOf(item))}: the environment keeps one ` + + `package-less ${slot} of this name, and the stored one (${stored}) is the customization of ` + + `${holders.map((id) => `'${id}'`).join(', ')}, so this save would move it. Nothing was written. ` + + `To edit that customization, save it ${stored === 'unreadable' ? 'naming the package' : stored}; for the ` + + `environment's own ${type} ${where(boundObjectOf(item))}, use another name.`, + ) as Error & { code: 'RESOURCE_CONFLICT'; status: 409 }; + err.code = 'RESOURCE_CONFLICT'; + err.status = 409; + return err; +} + +/** + * [ADR-0150 D4] {@link environmentActionSlotRefusal} for a DRAFT save naming + * no package whose draft address is the environment's own package-unbound + * draft (`key` and `into` both `null`): the stored package-unbound draft it + * would rewrite, judged against the item's active rows. `undefined` for every + * other type, when the body is not the environment's own, and when no + * package-unbound draft is stored. + */ +async function environmentActionDraftSlotRefusal( + host: Pick, + type: string, name: string, member: string | undefined, item: unknown, +): Promise<(Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined> { + if (type !== 'action') return undefined; + const activeRows = await host.readItemActiveRows(type, name); + if (!actionHeldOnlyOnOtherObjects(type, item, activeRows)) return undefined; + const repo = host.getOverlayRepo(); + const stored = await repo.get( + { type, name, org: 'env' } as Parameters[0], + { state: 'draft', packageId: null, ...(member !== undefined ? { member } : {}) }, + ); + if (!stored) return undefined; + return environmentActionSlotRefusal('draft', type, name, item, stored.body, activeRows); +} + /** * [ADR-0150 D3, ruling A on the disabled-only name] The refusal of a write * naming no package of a name every holder of which is disabled. A disabled diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index c50937689bc..c975c065880 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -547,6 +547,139 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'task', 'edited'], [THIRD, 'task', 'r']]); }); + describe('the one package-unbound slot per name: an environment-own write over a holder\'s customization is refused, over the environment\'s own item on another object it moves it', () => { + it('P on `invoice` and a package-unbound row on `invoice` (P\'s customization): the save on `task` is refused 409, and nothing is written (FROM: that row rewritten onto `task`)', async () => { + const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' }); + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') })); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(err.message)).toContain(`'${WRITABLE}'`); + expect(metadataWrites()).toHaveLength(before); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); + }); + + it('P on `invoice` and a package-unbound DRAFT on `invoice` (P\'s pending change): the draft save on `task` is refused 409, and nothing is written (FROM: that draft rewritten onto `task`)', async () => { + const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + seedRow({ type: 'action', name: NAME, state: 'draft', package_id: null, metadata: JSON.stringify(action(NAME, 'pending', 'invoice')), checksum: 'sha-pending' }); + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' })); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(err.message)).toContain(`'${WRITABLE}'`); + expect(metadataWrites()).toHaveLength(before); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'invoice', 'pending']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + }); + + it('the environment\'s own row on `task`: a package-less save on `product` rewrites it onto `product` (one row per name, as for a name no package holds); P\'s row is untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'product') }); + + expect(saved.message).not.toContain('package='); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'product', 'env2']]); + }); + + it('the environment\'s own draft on `task`: a package-less draft save on `product` rewrites it onto `product`; P\'s row is untouched', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + + const drafted = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env2', 'product'), mode: 'draft' }); + + expect(drafted.message).toBe(`Saved action '${NAME}' (env-wide, state=draft) [seq=${drafted.seq}]`); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'product', 'env2']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + }); + }); + + describe('P\'s own draft and the environment\'s draft both stored: the per-item publish and the draft discard naming no package act on P\'s draft (not moved)', () => { + async function bothDrafts() { + const fixture = makeProtocol(); + await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p-draft', 'invoice'), packageId: WRITABLE, mode: 'draft' }); + await fixture.protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + expect(stored(fixture.rows('action', NAME, 'draft'))).toEqual([[WRITABLE, 'invoice', 'p-draft'], [null, 'task', 'env']]); + return fixture; + } + + it('the per-item publish promotes P\'s draft into P\'s row; the environment\'s draft stays', async () => { + const { protocol, rows } = await bothDrafts(); + + const published = await protocol.publishMetaItem({ type: 'action', name: NAME }); + + expect(published.success).toBe(true); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p-draft']]); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + }); + + it('the draft discard removes P\'s draft; the environment\'s draft stays', async () => { + const { protocol, rows } = await bothDrafts(); + + const receipt = await protocol.deleteMetaItem({ type: 'action', name: NAME, state: 'draft' }); + + expect(receipt.success).toBe(true); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + }); + + it('with two holders on two other objects, the publish acts on the environment\'s draft, and P\'s draft stays', async () => { + const { protocol, rows } = await bothDrafts(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'product'), packageId: OTHER_WRITABLE }); + + await protocol.publishMetaItem({ type: 'action', name: NAME }); + + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [OTHER_WRITABLE, 'product', 'q'], [null, 'task', 'env']]); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[WRITABLE, 'invoice', 'p-draft']]); + }); + }); + + it('FROM (the read half): the version the read naming no package serves is P\'s item\'s, so a save on `task` carrying it as the parent is refused as a version conflict, before and after the environment\'s row exists', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + const atPackage = await protocol.getMetaItem({ type: 'action', name: NAME, packageId: WRITABLE }); + + const before = await protocol.getMetaItem({ type: 'action', name: NAME }); + expect(before.version).toEqual(expect.any(String)); + expect(before.version).toBe(atPackage.version); + const first = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({ + type: 'action', name: NAME, item: action(NAME, 'env', 'task'), parentVersion: before.version, + }))); + expect([first.status, first.code]).toEqual([409, 'METADATA_CONFLICT']); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); + + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task') }); + const after = await protocol.getMetaItem({ type: 'action', name: NAME }); + expect(after.version).toBe(atPackage.version); + const again = resolveThrownHttpError(await refusalOf(() => protocol.saveMetaItem({ + type: 'action', name: NAME, item: action(NAME, 'env2', 'task'), parentVersion: after.version, + }))); + expect([again.status, again.code]).toEqual([409, 'METADATA_CONFLICT']); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); + }); + + it('PROBE: an ENABLED holder on `task` beside a DISABLED holder on `invoice`: the save on `task` is the enabled holder\'s', async () => { + const { protocol, rows } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'task'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'invoice'), packageId: OTHER_WRITABLE }); + protocol.engine.registry.isPackageDisabled = (id: string) => id === OTHER_WRITABLE; + + const saved = await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'edited', 'task') }); + + expect(saved.message).toBe(`Saved action '${NAME}' (env-wide, package=${WRITABLE}, state=active) [seq=${saved.seq}]`); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'task', 'edited'], [OTHER_WRITABLE, 'invoice', 'q']]); + }); + describe('CONTROLs (unchanged)', () => { it('the draft save on `invoice`, the object P binds: P\'s draft, and its publish is P\'s row', async () => { const { protocol, rows } = makeProtocol(); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index a7346b58858..317da769b4e 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -7891,6 +7891,12 @@ export class ObjectStackProtocolImplementation implements * The address is the draft save's, read from the item's ACTIVE rows * ({@link packagelessAddress}): * + * - [ADR-0150 D4] an `action` whose body (the saved body, else the + * stored package-unbound draft's) binds an object none of those rows + * binds: the environment's own package-unbound draft, promoted into + * the package-unbound row, whatever the number of bindings, except + * that a package-unbound draft is judged only where no package's own + * draft is the address (the cases below); * - bound to one package `P`: `P`'s draft, else the package-unbound draft, * which the draft save adopts into `P` on its next write and the read * serves in `P`'s place (ADR-0048 prefer-local). A publish promotes such diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 396d11c912d..09cb92c99cb 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -755,7 +755,9 @@ export function unboundItemDraftAddress( * One rule for every door that writes an action naming no package: the * publish-mode save (`protocol-save.ts`), the draft save * ({@link SysMetadataRepository.put}, through `resolveWriteHead`), and the - * per-item publish of the draft that save wrote (`protocol-history-and-publish.ts`). + * draft address the save's draft gates, the per-item publish, the draft + * discard and the draft read take (`packagelessDraftAddress`, + * `protocol-lock-version-gates.ts`). * * Deliberately NOT exported from the package entry. */ @@ -794,6 +796,24 @@ export function isPackageBoundRow(row: { package_id?: unknown }): boolean { return typeof row?.package_id === 'string' && row.package_id !== ''; } +/** + * [ADR-0150 D4] The packages a stored package-unbound action row or draft is + * the customization of: those whose rows in `activeRows` (the item's active + * rows, every binding) bind the object `storedBody` binds + * ({@link actionRowsBindingObjectOf}). Empty when it binds an object no + * package's row binds: then it is the environment's own item. A stored body + * that does not parse (`undefined`) counts every package's row, so it never + * drops a holder. Sorted, each package once. + */ +export function actionCustomizationHoldersOf( + storedBody: unknown, + activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, +): string[] { + const held = activeRows.filter(isPackageBoundRow); + const at = storedBody === undefined ? held : actionRowsBindingObjectOf(storedBody, held); + return [...new Set(at.map((row) => String(row.package_id)))].sort(); +} + /** * One live `watch()` subscription, as a record rather than a bare listener. * @@ -1019,6 +1039,10 @@ export class SysMetadataRepository implements MetadataRepository { * - bound to one package (a package-less row beside it is not a second * package, #23165's rule for the direct save): the draft inherits it, * whatever order the store returns the rows in; + * - [ADR-0150 D4] an action draft whose body (`body`, when the caller + * hands it) binds an object none of those rows binds: the environment's + * own draft, inheriting no package, whatever the number of bindings + * ({@link actionHeldOnlyOnOtherObjects}); the cases below are the rest; * - bound to two or more: the draft has no single package to go into, so * the resolution names no package and reports the bindings in * `ambiguousPackages`. {@link put} refuses the write diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index 954f9f5495e..a16c72f34de 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -19,6 +19,13 @@ // CONTROLs: the same save on `showcase_invoice` is still P's customization, // and a managed package's action name is still refused 403 NOT_OVERRIDABLE. // +// The version-conflict FROM (a save carrying the version the read naming no +// package serves) is pinned in process, where that read serves `version`: +// `protocol.packageless-save-address.test.ts`. The bare REST read of an action +// is served from a cached branch that carries no `version` (its `ETag` is a +// representation hash, which no save resolves as a parent), so no leg here +// reads that token. +// // The file is ISOLATED: it writes `/meta` and creates a package. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -102,38 +109,6 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does expect(await routeTarget(`/actions/_env/showcase_task/${name}`)).toEqual([400, 'env']); }, 120_000); - it('FROM (#33904): a save on `showcase_task` carrying the version the bare read served is refused as a version conflict, before and after the environment\'s row exists', async () => { - const name = 'qa_version_other_p'; - expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); - /** The version the by-name read naming no package serves: P's item's, until #33904. */ - const bareVersion = async () => { - const res = await stack.apiAs(admin, 'GET', `/meta/action/${name}`); - const body: any = await res.json(); - expect(res.status, JSON.stringify(body).slice(0, 300)).toBe(200); - const version = body?.data?.version ?? body?.version ?? res.headers.get('etag'); - expect(typeof version, `${JSON.stringify(Object.keys(body?.data ?? body ?? {}))} etag=${res.headers.get('etag')}`).toBe('string'); - return version as string; - }; - const putIfMatch = async (version: string) => { - const res = await stack.api(`/meta/action/${name}`, { - method: 'PUT', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${admin}`, 'If-Match': version }, - body: JSON.stringify(action(name, 'env', 'showcase_task')), - }); - return { status: res.status, text: await res.text() }; - }; - - // The parent is read at the environment's row, which the bare read does not serve. - const first = await putIfMatch(await bareVersion()); - expect(first.status, first.text).toBe(409); - expect(first.text).toContain('CONFLICT'); - - expect((await put(`/meta/action/${name}`, action(name, 'env', 'showcase_task'))).status).toBe(200); - const again = await putIfMatch(await bareVersion()); - expect(again.status, again.text).toBe(409); - expect(await read(`/meta/action/${name}?package=${PKG}`)).toEqual(['showcase_invoice', 'pkg', PKG]); - }, 120_000); - it('the DRAFT save on `showcase_task` and its per-item publish write the environment\'s item; P\'s item on `showcase_invoice` is untouched', async () => { const name = 'qa_draft_other_p'; expect((await put(`/meta/action/${name}?package=${PKG}`, action(name, 'pkg', 'showcase_invoice'))).status).toBe(200); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 49f2fb48808..9ebaa8ef256 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1216,12 +1216,24 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'when the active rows (or, with none and no package-unbound draft, the ' + 'drafts) are bound to two or more packages, as that publish is (see ' + '`PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the ' - + 'object it binds (ADR-0150 D4): its rows are read at the body\'s object ' - + 'only, so a body bound to an object no package\'s active row binds the ' - + 'name to writes the environment\'s own row (or draft, which the per-item ' - + 'publish naming no package promotes there), never a package\'s item; ' + + 'object it binds (ADR-0150 D4): when one or more packages\' active rows ' + + 'hold the name and none of those rows binds the object the body binds ' + + '(object-less is its own key), the save writes the environment\'s own ' + + 'package-unbound row (`active`) or draft (`draft`), never a package\'s ' + + 'item. The environment keeps one package-unbound row and one ' + + 'package-unbound draft per action name: such a save over the ' + + 'environment\'s own row or draft bound to another object rewrites it ' + + 'onto the body\'s object, and over one bound to an object a package\'s ' + + 'active row binds (that package\'s customization) it is refused `409 ' + + 'RESOURCE_CONFLICT`. Otherwise the address above stands, judged over ' + + 'every holder of the name, except that an `active` save is judged over ' + + 'the holders at the body\'s object only when a disabled package is one ' + + 'of them and another holder binds another object. The per-item publish ' + + 'and the draft discard naming no package act on the environment\'s ' + + 'draft so written, except that with one package holding the name, that ' + + 'package\'s own draft, when one is stored, comes first. ' // The read half that keys an action by object is #33904. - + 'until the read naming no package keys an action by object, ' + + 'Until the read naming no package keys an action by object, ' + 'the version it serves is the package\'s item\'s, so a save carrying ' + 'it as the parent is refused as a version conflict. ' + 'The row written is also the one the parent-version ' From 61f86b4c85ee2dc0cecbeb4d81f5becfdb0cb922 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:53:01 +0000 Subject: [PATCH 16/24] fix(metadata-protocol): an action save at an object whose holders are all enabled falls back to the name's own served judgment The at-object served judgment declines when no holder at the body's object is disabled; the save then fell to the full-name two-binding refusal, answering 409 naming an enabled holder on the body's object and a disabled holder on another. The name's own judgment answers it, as on main: the disabled holder is no served holder. Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- packages/metadata-protocol/src/protocol-save.ts | 16 ++++++++++++---- .../protocol.packageless-save-address.test.ts | 6 +++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index f649a2e8206..9cc4061878b 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -833,10 +833,18 @@ export class ProtocolSaveFacet { // package's row, never a new package-unbound row beside an // enabled holder, and a refusal names only the served holders. // [ADR-0150 D4] For an action some holder binds to another object, - // judged over the holders at the body's object only. - const served = environmentOwnAction ? undefined : await servedPackagelessSaveAddress( - host, writeType, request.name, itemDiscriminator(writeType, request.item), keyed ?? address, keyed !== undefined, - ); + // judged over the holders at the body's object first. When no + // holder there is disabled, that judgment declines, and the + // name's own judgment answers as it does for every other save: a + // disabled holder on another object is never a served holder, so + // the one enabled holder on the body's object takes the write. + const member = itemDiscriminator(writeType, request.item); + const served = environmentOwnAction + ? undefined + : (keyed !== undefined + ? await servedPackagelessSaveAddress(host, writeType, request.name, member, keyed, true) + : undefined) + ?? await servedPackagelessSaveAddress(host, writeType, request.name, member, address); if (environmentOwnAction) { // The package-unbound row: `packageId` stays empty. } else if (served !== undefined) { diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index c975c065880..c5a171e6d6c 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -668,7 +668,11 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'task', 'env']]); }); - it('PROBE: an ENABLED holder on `task` beside a DISABLED holder on `invoice`: the save on `task` is the enabled holder\'s', async () => { + // The at-object judgment declines here (no disabled holder on `task`), so + // the name's own judgment answers, as on main: the disabled holder on + // `invoice` is not a served holder. Read through the at-object address + // alone, the save fell to the two-binding refusal (409 naming both). + it('an ENABLED holder on `task` beside a DISABLED holder on `invoice`: the save on `task` is the enabled holder\'s, as on main (never 409 naming both)', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'task'), packageId: WRITABLE }); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'q', 'invoice'), packageId: OTHER_WRITABLE }); From 9a1c3b501128001950180166f844b4c925669496 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:00:48 +0000 Subject: [PATCH 17/24] docs(references): regenerate the protocol reference page on the merged spec Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 4ae0bd7c5d9..c389af07a21 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2930,7 +2930,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): its rows are read at the body's object only, so a body bound to an object no package's active row binds the name to writes the environment's own row (or draft, which the per-item publish naming no package promotes there), never a package's item; until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): when one or more packages' active rows hold the name and none of those rows binds the object the body binds (object-less is its own key), the save writes the environment's own package-unbound row (`active`) or draft (`draft`), never a package's item. The environment keeps one package-unbound row and one package-unbound draft per action name: such a save over the environment's own row or draft bound to another object rewrites it onto the body's object, and over one bound to an object a package's active row binds (that package's customization) it is refused `409 RESOURCE_CONFLICT`. Otherwise the address above stands, judged over every holder of the name, except that an `active` save is judged over the holders at the body's object only when a disabled package is one of them and another holder binds another object. The per-item publish and the draft discard naming no package act on the environment's draft so written, except that with one package holding the name, that package's own draft, when one is stored, comes first. Until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | From f2d1b67f73baa3995f6a4c80b69070a309a91a96 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:42:58 +0000 Subject: [PATCH 18/24] docs(changeset): declare the enabled-on-the-body's-object beside a disabled holder elsewhere cell as unchanged Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- .changeset/34059-action-save-packageless-other-object.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index ee4ab82d430..ce5a2eef096 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -27,7 +27,7 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - with the environment's draft on `task` stored, a package-less draft save on `invoice` adopted that draft into `P` and rewrote it on `invoice`, so the environment's pending draft was gone; it now writes `P`'s draft on `invoice` and the environment's draft on `task` stays. - with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. -Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. +Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; an enabled package on `task` beside a disabled package on `invoice` still answers a save on `task` by writing the enabled package's row; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. The two modes still differ for one enabled and one disabled holder with the body on the disabled holder's object: the publish-mode save writes the disabled holder's row, while the draft save is refused `409` naming both, as it was. From 5f635f1e5cf1f532ce531c4899b0c9041d6fae6f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:20:29 +0000 Subject: [PATCH 19/24] docs(adr-0150): the D4 note states the at-object served judgment as the code has it Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- ...data-addressed-by-package-objects-keep-the-literal-prefix.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index 80169e450af..56ed9bf882b 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -180,7 +180,7 @@ Hooks bind by event and object and already carry `packageId`. Only `isArtifactSh **A package-less row that bears a package-held name is a customization, never a second item.** A `sys_metadata` row with `package_id` NULL hydrates into the bare slot today (`registerItem`). Where a package holds that `(type, name)`, the row is the ADR-0005 overlay of that one phase-1 holder (`bare-name-one-holder.ts` already counts it as no holder). It is not a bucket-4 item, so it never arms beside the item it shadows (E1) and never makes the name ambiguous. Its migration into a declared override in the holder's paired `.custom` package is [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D11's, and this record does not repeat it (R15). A bucket-4 item is therefore one whose `(type, name)` no package holds. If a package installed later takes such a name, the row reads as that holder's overlay, which is what the bare slot does today. The D10 upgrade report names the row. -> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges only the holders at the body's object, and the orphan-draft adoption never takes the environment's draft of another object. The environment keeps one package-less row and one package-less draft per action name, so an environment-own write over a holder's customization stored there is refused (`409 RESOURCE_CONFLICT`), never moved. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). +> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges the holders at the body's object when a disabled holder is among them, and otherwise is the name's own served judgment, and the orphan-draft adoption never takes the environment's draft of another object. The environment keeps one package-less row and one package-less draft per action name, so an environment-own write over a holder's customization stored there is refused (`409 RESOURCE_CONFLICT`), never moved. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). ### D5 — Addresses: an optional namespace segment, `409` on ambiguity From aaa08974301cc6518a54127ba76bb0f2f5822760 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:35:17 +0000 Subject: [PATCH 20/24] fix(metadata-protocol): the environment's action draft and its publish are refused over a holder's customization row The per-item publish naming no package promotes the environment's own action draft into the one package-unbound active row; when that row is a holder's customization the publish moved it off the holder's object. The publish now asks the slot refusal of the draft it promotes, and the draft save asks it of the stored package-unbound row as well as the draft. Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- .../src/protocol-history-and-publish.ts | 12 +++- .../metadata-protocol/src/protocol-save.ts | 62 +++++++++++++++---- .../protocol.packageless-save-address.test.ts | 34 ++++++++++ 3 files changed, 94 insertions(+), 14 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 87683052cea..c6674d3e871 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -45,6 +45,7 @@ import type { MutationProjectionOutcome } from './protocol-mutation-events.js'; import { PREFLIGHT_AUDIT_CODE, withPendingAudit } from './protocol-audit-entry.js'; import type { PublishMetaItemRequest } from './protocol-door-requests.js'; import { withRefusalAudit } from './protocol-refusal-audit.js'; +import { environmentActionPublishSlotRefusal } from './protocol-save.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { readPublishBackfillRequest } from './protocol-publish-backfill-request.js'; @@ -670,7 +671,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -890,6 +891,15 @@ export class ProtocolHistoryAndPublishFacet { { type: singularType, name: request.name, org: 'env' } as Parameters[0], { state: 'draft', packageId: draftKey, ...memberOption(request.member) }, ); + // [ADR-0150 D4, ruling 6902014292] The environment's own action + // draft is promoted into the one package-unbound active row of the + // name: when that row is a holder's customization, the publish would + // move it off the holder's object, so it is refused, never moved, as + // the saves are ({@link environmentActionPublishSlotRefusal}). + if (!('packageId' in request) && draftKey === null && promoteInto === null && draftForGate) { + const slotRefusal = await environmentActionPublishSlotRefusal(host, singularType, request.name, draftForGate.body); + if (slotRefusal) throw slotRefusal; + } // [ADR-0029 D9.9, #23630] …and the save door's representability // refusal, asked of the row this promotion writes: an `object` row // bound to a package that does not own the object. A draft save is diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 9cc4061878b..d937fb10042 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -886,9 +886,10 @@ export class ProtocolSaveFacet { ) : undefined; // [ADR-0150 D4] The environment's own action draft is one slot per - // name: a holder's customization stored there is refused, never - // moved ({@link environmentActionDraftSlotRefusal}). - if (draftAddress !== undefined && draftAddress.kind === 'draft' && draftAddress.key === null && draftAddress.into === null) { + // name, and its per-item publish writes the one package-unbound row: + // a holder's customization stored in either is refused, never moved + // ({@link environmentActionDraftSlotRefusal}). + if (draftAddress !== undefined && draftAddress.kind !== 'ambiguous' && draftAddress.key === null && draftAddress.into === null) { const slotRefusal = await environmentActionDraftSlotRefusal( host, singularType, request.name, itemDiscriminator(singularType, request.item), request.item, ); @@ -2993,8 +2994,10 @@ async function servedPackagelessSaveAddress( * ({@link actionRowsBindingObjectOf}) — some holder binds the name to * `item`'s object and another binds it to another object: the served * step ({@link servedPackagelessSaveAddress}) judges the holders at the - * object only, so a disabled holder there is never answered by an enabled - * holder's item on another object. + * object first, so a disabled holder there is never answered by an enabled + * holder's item on another object; with no disabled holder there that + * judgment declines and the save falls back to the name's own served + * judgment. * - `undefined` — the address stands, as before: every other type, a name * no package's row holds, and an action every holder binds to `item`'s * object. @@ -3060,6 +3063,7 @@ export function environmentActionSlotRefusal( item: unknown, storedBody: unknown, activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, + verb: 'save' | 'publish' = 'save', ): (Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined { const holders = actionCustomizationHoldersOf(storedBody, activeRows); if (holders.length === 0) return undefined; @@ -3067,11 +3071,12 @@ export function environmentActionSlotRefusal( const stored = storedBody === undefined ? 'unreadable' : where(boundObjectOf(storedBody)); const slot = state === 'draft' ? 'draft' : 'row'; const err = new Error( - `Cannot save ${type} '${name}' naming no package ${where(boundObjectOf(item))}: the environment keeps one ` + `Cannot ${verb} ${type} '${name}' naming no package ${where(boundObjectOf(item))}: the environment keeps one ` + `package-less ${slot} of this name, and the stored one (${stored}) is the customization of ` - + `${holders.map((id) => `'${id}'`).join(', ')}, so this save would move it. Nothing was written. ` + + `${holders.map((id) => `'${id}'`).join(', ')}, so this ${verb} would move it. Nothing was written. ` + `To edit that customization, save it ${stored === 'unreadable' ? 'naming the package' : stored}; for the ` - + `environment's own ${type} ${where(boundObjectOf(item))}, use another name.`, + + `environment's own ${type} ${where(boundObjectOf(item))}, ` + + `${verb === 'publish' ? 'discard this draft and save it under another name' : 'use another name'}.`, ) as Error & { code: 'RESOURCE_CONFLICT'; status: 409 }; err.code = 'RESOURCE_CONFLICT'; err.status = 409; @@ -3082,9 +3087,10 @@ export function environmentActionSlotRefusal( * [ADR-0150 D4] {@link environmentActionSlotRefusal} for a DRAFT save naming * no package whose draft address is the environment's own package-unbound * draft (`key` and `into` both `null`): the stored package-unbound draft it - * would rewrite, judged against the item's active rows. `undefined` for every - * other type, when the body is not the environment's own, and when no - * package-unbound draft is stored. + * would rewrite, then the stored package-unbound active row its per-item + * publish would rewrite, each judged against the item's active rows. + * `undefined` for every other type, when the body is not the environment's + * own, and when neither is a holder's customization. */ async function environmentActionDraftSlotRefusal( host: Pick, @@ -3098,8 +3104,38 @@ async function environmentActionDraftSlotRefusal( { type, name, org: 'env' } as Parameters[0], { state: 'draft', packageId: null, ...(member !== undefined ? { member } : {}) }, ); - if (!stored) return undefined; - return environmentActionSlotRefusal('draft', type, name, item, stored.body, activeRows); + if (stored) { + const draftRefusal = environmentActionSlotRefusal('draft', type, name, item, stored.body, activeRows); + if (draftRefusal) return draftRefusal; + } + for (const row of activeRows.filter((candidate) => !isPackageBoundRow(candidate))) { + const rowRefusal = environmentActionSlotRefusal('active', type, name, item, storedBodyOf(row.metadata), activeRows); + if (rowRefusal) return rowRefusal; + } + return undefined; +} + +/** + * [ADR-0150 D4] {@link environmentActionSlotRefusal} at the PER-ITEM PUBLISH + * naming no package of the environment's own action draft: the promotion + * writes the one package-unbound active row, so when that row is a holder's + * customization the publish is refused, never moved. Asked where the publish + * resolved the environment's own draft (`key` and `into` both `null`), of the + * draft it would promote. `undefined` for every other type, with no draft, and + * when the stored package-unbound row is the environment's own. + */ +export async function environmentActionPublishSlotRefusal( + host: Pick, + type: string, name: string, draftBody: unknown, +): Promise<(Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined> { + if (type !== 'action' || draftBody === undefined) return undefined; + const activeRows = await host.readItemActiveRows(type, name); + if (!actionHeldOnlyOnOtherObjects(type, draftBody, activeRows)) return undefined; + for (const row of activeRows.filter((candidate) => !isPackageBoundRow(candidate))) { + const refusal = environmentActionSlotRefusal('active', type, name, draftBody, storedBodyOf(row.metadata), activeRows, 'publish'); + if (refusal) return refusal; + } + return undefined; } /** diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index c5a171e6d6c..b2637956134 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -579,6 +579,40 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); }); + it('P on `invoice` and a package-unbound row on `invoice` (P\'s customization), no draft stored: the DRAFT save on `task` is refused 409, since its publish would rewrite that row, and nothing is written (FROM: the environment\'s draft written, and its publish moved that row onto `task`)', async () => { + const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' }); + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' })); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(err.message)).toContain(`'${WRITABLE}'`); + expect(metadataWrites()).toHaveLength(before); + expect(rows('action', NAME, 'draft')).toEqual([]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); + }); + + it('the environment\'s draft on `task` stored beside P\'s customization row on `invoice`: the per-item publish naming no package is refused 409, and the row and the draft stay (FROM: that row rewritten onto `task`)', async () => { + const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' }); + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.publishMetaItem({ type: 'action', name: NAME })); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(err.message)).toContain(`Cannot publish action '${NAME}'`); + expect(String(err.message)).toContain(`'${WRITABLE}'`); + expect(metadataWrites()).toHaveLength(before); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); + }); + it('the environment\'s own row on `task`: a package-less save on `product` rewrites it onto `product` (one row per name, as for a name no package holds); P\'s row is untouched', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); From 0a8bebb2efe0a6a8e4fc086cee236f9ca8f3249f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:36:24 +0000 Subject: [PATCH 21/24] docs(metadata-protocol): the ADR-0150 note, the spec clause and the changeset state the publish slot refusal Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- .../34059-action-save-packageless-other-object.md | 2 +- ...ssed-by-package-objects-keep-the-literal-prefix.md | 2 +- .../src/protocol.packageless-save-address.test.ts | 4 ++-- packages/spec/src/api/protocol.zod.ts | 11 ++++++++--- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index ce5a2eef096..2ed03e2667a 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -25,7 +25,7 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - with `P` (enabled) on `invoice`, and on `task` an enabled `Q` and a disabled `R`, the save on `task` was refused `409` naming `P` and `Q`; it is now judged over the holders on `task` only, so it writes `Q`'s row, and `P`'s action on `invoice` is untouched. Without `R` the same save is still refused `409` naming `P` and `Q` (below). - a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft, and its publish the environment's own row. - with the environment's draft on `task` stored, a package-less draft save on `invoice` adopted that draft into `P` and rewrote it on `invoice`, so the environment's pending draft was gone; it now writes `P`'s draft on `invoice` and the environment's draft on `task` stays. -- with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. +- with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. A draft save bound to `task` beside that package-unbound row on `invoice` is refused the same way, because the environment's draft would be published into that one row (it was written as `P`'s draft, whose publish moved `P`'s action onto `task`). With a package-unbound draft on `task` already stored beside that row, the per-item publish naming no package (`POST /meta/action/approve/publish`) is refused `409 RESOURCE_CONFLICT` naming `P`, and the row and the draft stay (it was promoted into `P`'s row, moving `P`'s action onto `task`). The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; an enabled package on `task` beside a disabled package on `invoice` still answers a save on `task` by writing the enabled package's row; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`. diff --git a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md index 56ed9bf882b..47aab9a8572 100644 --- a/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md +++ b/docs/adr/0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md @@ -180,7 +180,7 @@ Hooks bind by event and object and already carry `packageId`. Only `isArtifactSh **A package-less row that bears a package-held name is a customization, never a second item.** A `sys_metadata` row with `package_id` NULL hydrates into the bare slot today (`registerItem`). Where a package holds that `(type, name)`, the row is the ADR-0005 overlay of that one phase-1 holder (`bare-name-one-holder.ts` already counts it as no holder). It is not a bucket-4 item, so it never arms beside the item it shadows (E1) and never makes the name ambiguous. Its migration into a declared override in the holder's paired `.custom` package is [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md) D11's, and this record does not repeat it (R15). A bucket-4 item is therefore one whose `(type, name)` no package holds. If a package installed later takes such a name, the row reads as that holder's overlay, which is what the bare slot does today. The D10 upgrade report names the row. -> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges the holders at the body's object when a disabled holder is among them, and otherwise is the name's own served judgment, and the orphan-draft adoption never takes the environment's draft of another object. The environment keeps one package-less row and one package-less draft per action name, so an environment-own write over a holder's customization stored there is refused (`409 RESOURCE_CONFLICT`), never moved. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). +> **Amendment note (2026-11-16, #34059, PR #34238; maintainer ruling 6902014292).** For an action bound to an object, the customization rule above and R15 are read at D4's action key `(package, objectName, name)`, not at `(type, name)`. A package-less action row bound to an object that no holder of the name binds it to is the environment's own bucket-4 item on that object, beside each holder's item: it is never written into a holder, read as a holder's overlay, or moved by ADR-0146 D11's migration. An object-less action is its own key (`global`). A package-less row on the object a holder binds stays that holder's customization, and R15 is unchanged for it. Every door that writes an action naming no package reads the one rule (`actionHeldOnlyOnOtherObjects`, `packages/metadata-protocol/src/sys-metadata-repository.ts`): the publish-mode save, the draft save (`resolveWriteHead`), and the per-item publish and the draft discard of the environment's draft (`packagelessDraftAddress`, asked of the package-unbound draft wherever no package's own draft is the address), each above its two-holder refusal; the save's served address judges the holders at the body's object when a disabled holder is among them, and otherwise is the name's own served judgment, and the orphan-draft adoption never takes the environment's draft of another object. The environment keeps one package-less row and one package-less draft per action name, so an environment-own write over a holder's customization stored there is refused (`409 RESOURCE_CONFLICT`), never moved: the publish-mode save and the draft save, and the per-item publish of the environment's draft, which writes that one row. The action route already keys by object (#33898). The by-name read, the list and the package-less delete do not key by object yet (#33904); `/actions/_env/OBJECT/NAME` reaches the environment's row. Moving a package's own action to another object takes a save naming the package (`?package=P`). ### D5 — Addresses: an optional namespace segment, `409` on ambiguity diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index b2637956134..586740e264e 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -579,7 +579,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p']]); }); - it('P on `invoice` and a package-unbound row on `invoice` (P\'s customization), no draft stored: the DRAFT save on `task` is refused 409, since its publish would rewrite that row, and nothing is written (FROM: the environment\'s draft written, and its publish moved that row onto `task`)', async () => { + it('P on `invoice` and a package-unbound row on `invoice` (P\'s customization), no draft stored: the DRAFT save on `task` is refused 409, since its publish would rewrite that row, and nothing is written (FROM: written as P\'s draft, whose publish moved P\'s action onto `task`)', async () => { const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' }); @@ -595,7 +595,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); }); - it('the environment\'s draft on `task` stored beside P\'s customization row on `invoice`: the per-item publish naming no package is refused 409, and the row and the draft stay (FROM: that row rewritten onto `task`)', async () => { + it('the environment\'s draft on `task` stored beside P\'s customization row on `invoice`: the per-item publish naming no package is refused 409, and the row and the draft stay (FROM: promoted into P\'s row, moving P\'s action onto `task`; at the prior head of this change, that row rewritten onto `task`)', async () => { const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 9ebaa8ef256..ce4fb655a40 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1225,13 +1225,18 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + 'environment\'s own row or draft bound to another object rewrites it ' + 'onto the body\'s object, and over one bound to an object a package\'s ' + 'active row binds (that package\'s customization) it is refused `409 ' - + 'RESOURCE_CONFLICT`. Otherwise the address above stands, judged over ' - + 'every holder of the name, except that an `active` save is judged over ' + + 'RESOURCE_CONFLICT`; a `draft` save is refused the same way when the ' + + 'package-unbound row its publish would rewrite is that customization. ' + + 'Otherwise the address above stands, judged over every holder of the ' + + 'name (every enabled holder, for an `active` save), except that an ' + + '`active` save is judged over ' + 'the holders at the body\'s object only when a disabled package is one ' + 'of them and another holder binds another object. The per-item publish ' + 'and the draft discard naming no package act on the environment\'s ' + 'draft so written, except that with one package holding the name, that ' - + 'package\'s own draft, when one is stored, comes first. ' + + 'package\'s own draft, when one is stored, comes first; that publish ' + + 'is refused `409 RESOURCE_CONFLICT` when the package-unbound row it ' + + 'would rewrite is a package\'s customization. ' // The read half that keys an action by object is #33904. + 'Until the read naming no package keys an action by object, ' + 'the version it serves is the package\'s item\'s, so a save carrying ' From 6677a8ff1bb8e967c848f530ed6fc9b0b0e21075 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:41:24 +0000 Subject: [PATCH 22/24] docs(references): regenerate the protocol reference page for the packageId clause Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index c389af07a21..014316b7112 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2930,7 +2930,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): when one or more packages' active rows hold the name and none of those rows binds the object the body binds (object-less is its own key), the save writes the environment's own package-unbound row (`active`) or draft (`draft`), never a package's item. The environment keeps one package-unbound row and one package-unbound draft per action name: such a save over the environment's own row or draft bound to another object rewrites it onto the body's object, and over one bound to an object a package's active row binds (that package's customization) it is refused `409 RESOURCE_CONFLICT`. Otherwise the address above stands, judged over every holder of the name, except that an `active` save is judged over the holders at the body's object only when a disabled package is one of them and another holder binds another object. The per-item publish and the draft discard naming no package act on the environment's draft so written, except that with one package holding the name, that package's own draft, when one is stored, comes first. Until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): when one or more packages' active rows hold the name and none of those rows binds the object the body binds (object-less is its own key), the save writes the environment's own package-unbound row (`active`) or draft (`draft`), never a package's item. The environment keeps one package-unbound row and one package-unbound draft per action name: such a save over the environment's own row or draft bound to another object rewrites it onto the body's object, and over one bound to an object a package's active row binds (that package's customization) it is refused `409 RESOURCE_CONFLICT`; a `draft` save is refused the same way when the package-unbound row its publish would rewrite is that customization. Otherwise the address above stands, judged over every holder of the name (every enabled holder, for an `active` save), except that an `active` save is judged over the holders at the body's object only when a disabled package is one of them and another holder binds another object. The per-item publish and the draft discard naming no package act on the environment's draft so written, except that with one package holding the name, that package's own draft, when one is stored, comes first; that publish is refused `409 RESOURCE_CONFLICT` when the package-unbound row it would rewrite is a package's customization. Until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | From 017deafea716d7f98317dbce6766879017a330d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:11:42 +0000 Subject: [PATCH 23/24] fix(metadata-protocol): the publish slot refusal also judges a per-item publish stating no package A per-item publish stating packageId null promotes the same package-unbound draft into the same row, so it asks the same refusal. The draft save's refusal over the stored row says its publish would move it. Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- .../src/protocol-history-and-publish.ts | 6 ++++-- .../metadata-protocol/src/protocol-save.ts | 10 ++++++---- .../protocol.packageless-save-address.test.ts | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index c6674d3e871..ad1cda6a64a 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -895,8 +895,10 @@ export class ProtocolHistoryAndPublishFacet { // draft is promoted into the one package-unbound active row of the // name: when that row is a holder's customization, the publish would // move it off the holder's object, so it is refused, never moved, as - // the saves are ({@link environmentActionPublishSlotRefusal}). - if (!('packageId' in request) && draftKey === null && promoteInto === null && draftForGate) { + // the saves are ({@link environmentActionPublishSlotRefusal}). Asked + // whether the caller named no package or stated `packageId: null`: + // both promote the package-unbound draft into that row. + if (draftKey === null && promoteInto === null && draftForGate) { const slotRefusal = await environmentActionPublishSlotRefusal(host, singularType, request.name, draftForGate.body); if (slotRefusal) throw slotRefusal; } diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index d937fb10042..d784f58894d 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -3063,17 +3063,19 @@ export function environmentActionSlotRefusal( item: unknown, storedBody: unknown, activeRows: ReadonlyArray<{ package_id?: unknown; metadata?: unknown }>, - verb: 'save' | 'publish' = 'save', + verb: 'save' | 'publish' | 'draft-save' = 'save', ): (Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined { const holders = actionCustomizationHoldersOf(storedBody, activeRows); if (holders.length === 0) return undefined; const where = (object: string | undefined): string => (object === undefined ? 'bound to no object' : `on object '${object}'`); const stored = storedBody === undefined ? 'unreadable' : where(boundObjectOf(storedBody)); const slot = state === 'draft' ? 'draft' : 'row'; + const door = verb === 'publish' ? 'publish' : 'save'; + const mover = verb === 'draft-save' ? 'publishing this draft' : `this ${verb}`; const err = new Error( - `Cannot ${verb} ${type} '${name}' naming no package ${where(boundObjectOf(item))}: the environment keeps one ` + `Cannot ${door} ${type} '${name}' naming no package ${where(boundObjectOf(item))}: the environment keeps one ` + `package-less ${slot} of this name, and the stored one (${stored}) is the customization of ` - + `${holders.map((id) => `'${id}'`).join(', ')}, so this ${verb} would move it. Nothing was written. ` + + `${holders.map((id) => `'${id}'`).join(', ')}, so ${mover} would move it. Nothing was written. ` + `To edit that customization, save it ${stored === 'unreadable' ? 'naming the package' : stored}; for the ` + `environment's own ${type} ${where(boundObjectOf(item))}, ` + `${verb === 'publish' ? 'discard this draft and save it under another name' : 'use another name'}.`, @@ -3109,7 +3111,7 @@ async function environmentActionDraftSlotRefusal( if (draftRefusal) return draftRefusal; } for (const row of activeRows.filter((candidate) => !isPackageBoundRow(candidate))) { - const rowRefusal = environmentActionSlotRefusal('active', type, name, item, storedBodyOf(row.metadata), activeRows); + const rowRefusal = environmentActionSlotRefusal('active', type, name, item, storedBodyOf(row.metadata), activeRows, 'draft-save'); if (rowRefusal) return rowRefusal; } return undefined; diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 586740e264e..89ac4f95852 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -590,6 +590,7 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder const envelope = resolveThrownHttpError(err); expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); expect(String(err.message)).toContain(`'${WRITABLE}'`); + expect(String(err.message)).toContain('publishing this draft would move it'); expect(metadataWrites()).toHaveLength(before); expect(rows('action', NAME, 'draft')).toEqual([]); expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); @@ -613,6 +614,23 @@ describe('[ADR-0150 D4] a package-less save of an ACTION on an object the holder expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); }); + it('the same, the per-item publish stating `packageId: null` in process: refused 409 the same way, and the row and the draft stay', async () => { + const { protocol, rows, seedRow, metadataWrites } = makeProtocol(); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); + await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'env', 'task'), mode: 'draft' }); + seedRow({ type: 'action', name: NAME, package_id: null, metadata: JSON.stringify(action(NAME, 'custom', 'invoice')), checksum: 'sha-custom' }); + const before = metadataWrites().length; + + const err = await refusalOf(() => protocol.publishMetaItem({ type: 'action', name: NAME, packageId: null } as any)); + + const envelope = resolveThrownHttpError(err); + expect([envelope.status, envelope.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(err.message)).toContain(`Cannot publish action '${NAME}'`); + expect(metadataWrites()).toHaveLength(before); + expect(stored(rows('action', NAME, 'draft'))).toEqual([[null, 'task', 'env']]); + expect(stored(rows('action', NAME))).toEqual([[WRITABLE, 'invoice', 'p'], [null, 'invoice', 'custom']]); + }); + it('the environment\'s own row on `task`: a package-less save on `product` rewrites it onto `product` (one row per name, as for a name no package holds); P\'s row is untouched', async () => { const { protocol, rows } = makeProtocol(); await protocol.saveMetaItem({ type: 'action', name: NAME, item: action(NAME, 'p', 'invoice'), packageId: WRITABLE }); From fb520b2f07e2098ff3d4c128a9f50edc69d29093 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:12:02 +0000 Subject: [PATCH 24/24] docs(changeset): the publish slot refusal covers an in-process publish stating no package Claude-Session: https://claude.ai/code/session_01ADHkmQsQf9Js79MC6c1kdF Co-authored-by: Claude --- .changeset/34059-action-save-packageless-other-object.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34059-action-save-packageless-other-object.md b/.changeset/34059-action-save-packageless-other-object.md index 2ed03e2667a..0dfdac9304b 100644 --- a/.changeset/34059-action-save-packageless-other-object.md +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -25,7 +25,7 @@ The moved answers, for a writable package `P` holding `approve` on `invoice`: - with `P` (enabled) on `invoice`, and on `task` an enabled `Q` and a disabled `R`, the save on `task` was refused `409` naming `P` and `Q`; it is now judged over the holders on `task` only, so it writes `Q`'s row, and `P`'s action on `invoice` is untouched. Without `R` the same save is still refused `409` naming `P` and `Q` (below). - a draft save (`PUT …?mode=draft`) of `approve` bound to `task` was written as `P`'s draft (receipt `package=P`), and the per-item publish naming no package (`POST /meta/action/approve/publish`) promoted it over `P`'s action on `invoice`; the draft is now the environment's own draft (a receipt with no package), and its publish writes the environment's own row on `task`. Beside a sole binding to a package that is not installed, the draft save was refused `422`; it now writes the environment's own draft, and its publish the environment's own row. - with the environment's draft on `task` stored, a package-less draft save on `invoice` adopted that draft into `P` and rewrote it on `invoice`, so the environment's pending draft was gone; it now writes `P`'s draft on `invoice` and the environment's draft on `task` stays. -- with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. A draft save bound to `task` beside that package-unbound row on `invoice` is refused the same way, because the environment's draft would be published into that one row (it was written as `P`'s draft, whose publish moved `P`'s action onto `task`). With a package-unbound draft on `task` already stored beside that row, the per-item publish naming no package (`POST /meta/action/approve/publish`) is refused `409 RESOURCE_CONFLICT` naming `P`, and the row and the draft stay (it was promoted into `P`'s row, moving `P`'s action onto `task`). The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. +- with a package-unbound row on `invoice` beside `P`'s (`P`'s customization, stored by the other save order or an older build), the save bound to `task` was written into `P` and moved its action; it is now refused `409 RESOURCE_CONFLICT` naming `P`, and nothing is written. The same for a package-unbound draft on `invoice` (`P`'s pending change) and a draft save bound to `task`, which adopted that draft into `P` and rewrote it on `task`. A draft save bound to `task` beside that package-unbound row on `invoice` is refused the same way, because the environment's draft would be published into that one row (it was written as `P`'s draft, whose publish moved `P`'s action onto `task`). With a package-unbound draft on `task` already stored beside that row, the per-item publish naming no package (`POST /meta/action/approve/publish`; in process, also one stating `packageId: null`) is refused `409 RESOURCE_CONFLICT` naming `P`, and the row and the draft stay (it was promoted into `P`'s row, moving `P`'s action onto `task`). The environment keeps one package-unbound row and one package-unbound draft per action name, and here that one is `P`'s: edit it on `invoice`, or give the environment's own action on `task` another name. Unchanged: the same save or draft save on `invoice` (the object `P` binds) is still `P`'s customization, and its publish is `P`'s row; a package on `invoice` and another on `task`, both enabled, still answer a save on `task` with `409` naming both; an enabled package on `task` beside a disabled package on `invoice` still answers a save on `task` by writing the enabled package's row; a managed (code) package's action name is still refused `403 NOT_OVERRIDABLE`; every type other than `action`.