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..0dfdac9304b --- /dev/null +++ b/.changeset/34059-action-save-packageless-other-object.md @@ -0,0 +1,40 @@ +--- +'@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 + +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. + +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` 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. +- 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`; 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`. + +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. + +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/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 924697cee72..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`). 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. | 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..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,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 (`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 **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/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 87683052cea..ad1cda6a64a 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,17 @@ 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}). 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; + } // [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-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 5dab07ccca0..d784f58894d 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, 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'; @@ -88,6 +89,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 type { StoredOverlayRow } from './item-lock.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; import { pairsOf } from '@objectstack/metadata-core'; @@ -815,15 +817,37 @@ 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 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. - const served = await servedPackagelessSaveAddress( - host, writeType, request.name, itemDiscriminator(writeType, request.item), address, - ); - if (served !== undefined) { + // [ADR-0150 D4] For an action some holder binds to another object, + // 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) { if (served.packageId !== null) request = { ...request, packageId: served.packageId }; } else { if (address.candidates.length > 1) { @@ -850,14 +874,27 @@ 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. + // [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] The environment's own action draft is one slot per + // 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, + ); + 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 @@ -2052,6 +2089,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; @@ -2900,11 +2940,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 @@ -2917,11 +2967,179 @@ 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] The address of a publish-mode save of an + * `action` naming no package, keyed `(package, objectName, name)`: + * + * - `'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. + * 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 + * step ({@link servedPackagelessSaveAddress}) judges the holders at the + * 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. + */ +async function packagelessActionKeyedAddress( + host: Pick, + type: string, name: string, item: unknown, + address: { readonly candidates: readonly string[] }, +): Promise<'environment' | Awaited> | undefined> { + if (type !== 'action' || address.candidates.length === 0) return undefined; + 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 = []; + } + 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 }>, + 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 ${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 ${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'}.`, + ) 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, 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, + 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) { + 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, 'draft-save'); + 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; +} + /** * [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 2da51ae7f36..89ac4f95852 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,500 @@ 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']]); + }); + + 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 }); + + 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 }); + 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([]); + }); + + 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('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('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' }); + 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(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']]); + }); + + 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' }); + 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 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 }); + 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']]); + }); + + // 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 }); + 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(); + 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 }); + + 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('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 }); + // 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') }); + + 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(); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 82a30c838f1..e2645f68b1b 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -7911,6 +7911,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 @@ -7947,6 +7953,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[] } | { @@ -7959,8 +7967,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: (...a) => this.getOverlayRepo(...a), + 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 c6060aab47f..09cb92c99cb 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'; @@ -734,6 +735,85 @@ 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 + * 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. + */ +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(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 rows.filter((row) => { + let document: unknown; + try { + document = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata; + } catch { + return true; + } + return boundObjectOf(document) === object; + }); +} + +/** 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 !== ''; +} + +/** + * [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. * @@ -900,11 +980,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 }; } @@ -948,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 @@ -977,6 +1072,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; @@ -1005,7 +1107,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 @@ -1047,6 +1154,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 } : {}) }; } @@ -1195,7 +1315,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 new file mode 100644 index 00000000000..a16c72f34de --- /dev/null +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -0,0 +1,149 @@ +// 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 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 +// `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. +// +// 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'; +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 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); + + 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='); + // 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 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}`); + 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); + + 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); + + 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); +}); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 28a0561cc34..ce4fb655a40 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1215,7 +1215,33 @@ 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): 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. ' + // 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 ' + '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`.',