diff --git a/.changeset/34681-bare-write-doors-follow-base.md b/.changeset/34681-bare-write-doors-follow-base.md new file mode 100644 index 00000000000..7c9ec519e80 --- /dev/null +++ b/.changeset/34681-bare-write-doors-follow-base.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): the save, delete, publish, draft, history, diff and rollback doors naming no package write and read the base's row where the read naming no package serves it + +Clause-②: yes (widening) +Metadata-protocol: none + +A bundled item (an email template's locale, for example) that no package ships in code can be stored as a row by a base package and, at the same member, by a package that declares that base. The read naming no package already serves the base's row there. The write doors naming no package now resolve the same address: the save (publish and draft mode), the per-item publish, the delete and the draft discard act on the base's row or draft, and the history, the diff and the rollback read and restore the base's own versions, as the same request naming the base (`?package=` on the REST door, `packageId` in process) does. The base is judged as named: bound to an id no installed package has, the save in either mode is refused `422 WRITABLE_PACKAGE_REQUIRED`. (The per-item publish naming no package still states no package to the runtime authoring gate, as every publish naming no package does.) Before, each was refused `409 RESOURCE_CONFLICT` naming both packages, so an item that opened fine could not be saved. + +The dependent package's row stays where it is and is still read and written at its own `?package=`. Where the base is read-only, the save, the delete, the draft discard and the rollback now answer what naming the base answers (for the save, `422 WRITABLE_PACKAGE_REQUIRED` naming the base) instead of the `409`. After a delete naming no package removes the base's row, the read naming no package serves the dependent's row, and the delete's receipt names it as still stored; a second delete naming no package removes the dependent's row too, and the base's copy comes back only by saving it again. The rollback's receipt now names the package of the row it restored, as the delete's receipt does. + +Unchanged: two packages holding the member with neither declaring the other, a package-less row beside the holders, and a type with no members are still refused `409` naming every holder. diff --git a/.changeset/34681-spec-bare-doors-follow-base.md b/.changeset/34681-spec-bare-doors-follow-base.md new file mode 100644 index 00000000000..3b4126fefb0 --- /dev/null +++ b/.changeset/34681-spec-bare-doors-follow-base.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +docs(spec): the request texts state that a request naming no package follows the row-held base + +Clause-②: yes (widening) +Metadata-protocol: none + +The `packageId` descriptions of the save, draft save, per-item publish, delete and history/diff/rollback requests (`HISTORY_PACKAGE_SELECTOR_DESCRIPTION`) said a request naming no package is refused `409 RESOURCE_CONFLICT` wherever an item's active rows are bound to two or more packages. They now state the exception the server answers: a bundled type's member that a base package and a package declaring it both hold, with no package-unbound row beside them, is the row-held base's, as the read naming no package serves it, and the request addresses the base's row, draft or versions as naming the base does. Two packages neither of which declares the other are still refused `409`. The delete text states the consequence: the dependent's row is served next, a second delete naming no package removes it too, and the base's copy comes back only by saving it again. Description text only; no schema shape, key or accepted value moves. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 33b50fb99a8..a43a896187d 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -783,7 +783,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **state** | `Enum<'active' \| 'draft'>` | optional | Which lifecycle row to discard: `draft` discards the pending draft overlay only (the still-active overlay, if any, keeps serving); `active` or absent resets the live row. Absent defaults to `active`. | | **dropStorage** | `boolean` | optional | Destructive opt-in, default false: also drop the object's physical table after the metadata row is removed (`object` type + `active` state only; never `sys_` tables). Used by the "discard a previewed object" flow so a publish-to-preview leaves no orphan table. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package whose row this delete removes (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package), as a save names the row it writes. Named, the delete removes that package's row and no other; a package that holds no row removes nothing. Absent or `null` names no package: the delete of the `active` row then removes the row of the one package the item's active rows are bound to, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none removes the env-local row (no package stamp); the discard of the `draft` removes the draft a draft save naming no package writes, the one the per-item publish naming none promotes, and is refused where that publish is (see `PublishMetaItemRequestSchema.packageId`). That row is the one `parentVersion` is judged against. When another row of the item is still stored afterwards, the receipt `message` names it. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package whose row this delete removes (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package), as a save names the row it writes. Named, the delete removes that package's row and no other; a package that holds no row removes nothing. Absent or `null` names no package: the delete of the `active` row then removes the row of the one package the item's active rows are bound to, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none removes the env-local row (no package stamp). Bound to two or more, one exception: a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them, is the row-held base's, as the read naming no package serves it, and the delete removes the base's row as naming the base does (two packages neither of which declares the other are still refused `409`). The dependent's row is then the item's only row at that address: the read naming no package serves it next, and a second delete naming no package removes it too; the base's copy comes back only by saving it again. The discard of the `draft` removes the draft a draft save naming no package writes, the one the per-item publish naming none promotes, and is refused where that publish is (see `PublishMetaItemRequestSchema.packageId`). That row is the one `parentVersion` is judged against. When another row of the item is still stored afterwards, the receipt `message` names it. | --- @@ -857,7 +857,7 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **name** | `string` | ✅ | Item name | | **fromVersion** | `integer` | optional | The older side's history version, a whole number as the history lists it. Absent, the nearest earlier version whose body differs from the `to` side's. A version with no history row of the item (or, with `packageId`, of that holder) is refused 404 `VERSION_NOT_FOUND`. | | **toVersion** | `integer` | optional | The newer side's history version, a whole number as the history lists it. Absent, the active row (with `packageId`, that holder's own active row). Refused 404 `VERSION_NOT_FOUND` as `fromVersion` is. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | --- @@ -2159,7 +2159,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **sinceSeq** | `number` | optional | Exclusive lower bound on `seq` for pagination: only events with `seq > sinceSeq` are returned. Absent means "from the beginning". | | **limit** | `number` | optional | Maximum events to return, oldest first. Forwarded to the repository unclamped and with NO default — absent means the full remaining change log. (Deliberately no declared bounds: unlike the audit twin's [1, 500] clamp, nothing on this path clamps or refuses, so declaring `.min()`/`.max()` here would refuse values the shipped verb accepts.) | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | --- @@ -2645,7 +2645,7 @@ The authoring surface of a metadata write. Closed: `copilot` is an AI assistant' | **name** | `string` | ✅ | Item name — lowercase snake_case segments, optionally dot-qualified (`crm_lead`, `crm_lead.pipeline`). The promotion door enforces the same grammar as `saveMetaItem`. | | **actor** | `string` | optional | Identity recorded on the `op='publish'` history event. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. | | **message** | `string` | optional | Optional human-readable note recorded with the publish history event. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's 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. ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package the draft being promoted was listed under, when the caller has one to state (`?package=` on the REST door). Named, the publish promotes that package's draft and no other. ABSENT names no package: the publish promotes the draft a draft save that names no package writes — the draft of the one package the item's active rows are bound to, else its package-unbound draft, promoted into that package — and answers `404 NO_DRAFT` when neither exists, as the strict draft read does. For an item never published into a package it is the package-unbound draft, else the one package's 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, except a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them: the read naming no package serves the base's row, and the publish promotes the base's draft into it, as naming the base does (two packages neither of which declares the other are still refused). ⚠️ `null` is NOT the same as absent: the implementation branches on the KEY BEING PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread it in conditionally; a present-and-`undefined` key coerces to `null` downstream and makes a package-bound draft unfindable — a silent `no_draft`. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | | **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of this write's findings (`advisories[].userMessage`, and `issues[].userMessage` on its 422) are composed in, in ladder order: the locale the request names, then the workspace default. Each is read against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over, and `en` is the last rung. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a wire body. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: what is judged, refused or saved does not depend on it. | @@ -2967,7 +2967,7 @@ Answer to a device registration: the device id the client keeps | **toVersion** | `integer` | ✅ | The history version whose body is restored as the new live row: a whole number of at least 1, as the history lists it. The rollback door reads this declaration and refuses anything else `400`. | | **message** | `string` | optional | Rollback note, recorded on the new history row. | | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | -| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | +| **packageId** | `string` | optional | Optional package ID (`?package=` on the REST door, the `/layers` spelling) — for a type stored per (package, name), the holder whose versions to address: the slot of the row a read naming the package serves (its own row, its `.custom` pair's declared override, or the package-less row that read falls back to), else the package's own empty slot when it ships the name; a package that neither holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). Versions attributed to no package, or to the environment, are that slot's only while it is the name's sole slot. Absent, a name two holders hold (in stored rows or in code) is refused 409 naming every holder, except where the read naming no package serves the row-held base (a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them): there the base's slot is addressed, as naming the base addresses it. Two packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` on a type not stored per (package, name). | --- @@ -3063,7 +3063,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): when one or more packages' active rows hold the name and none of those rows binds the object the body binds (object-less is its own key), the save writes the environment's own package-unbound row (`active`) or draft (`draft`), never a package's item. The environment keeps one package-unbound row and one package-unbound draft per action name: such a save over the environment's own row or draft bound to another object rewrites it onto the body's object, and over one bound to an object a package's active row binds (that package's customization) it is refused `409 RESOURCE_CONFLICT`; 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`. | +| **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). Bound to two or more, one exception: a bundled type's member whose active rows a base package and a package declaring it both hold, with no package-unbound row beside them, is the row-held base's, as the read naming no package serves it, and the save (either mode) writes the base's row or draft as a save naming the base does; two packages neither of which declares the other are still refused `409`. 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, but for the row-held base above, 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/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 6ff0a8b003b..a45178b4d0b 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -66,7 +66,7 @@ import { withRefusalAudit } from './protocol-refusal-audit.js'; import { captureStoredExpressionChange, fillStoredExpressionChange } from './protocol-stored-expression-fill.js'; import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; -import { packagelessHolderRefusal } from './protocol-save.js'; +import { packagelessHolderRefusal, packagelessRowHeldBaseAddress } from './protocol-save.js'; /** * [#33308] The row slot a `sys_metadata` row is: its bound package, or `null` @@ -79,7 +79,7 @@ function rowSlotOf(row: { package_id?: unknown }): string | null { export class ProtocolDiffDeleteLoadFacet { /** The body of `ObjectStackProtocolImplementation#diffMetaItem`; the method's docblock there is its contract. */ - static async diffMetaItem(host: Pick, request: { + static async diffMetaItem(host: Pick, request: { type: string; name: string; fromVersion?: number; @@ -454,7 +454,7 @@ export class ProtocolDiffDeleteLoadFacet { } /** [#28355] The body of {@link deleteMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ + static async deleteMetaItemUnaudited(host: Pick, request: DeleteMetaItemRequest): Promise<{ success: boolean; message?: string; reset?: boolean; @@ -713,23 +713,39 @@ export class ProtocolDiffDeleteLoadFacet { // door orders it. The rows read here are also what the receipt // below tells the truth about: what is still stored, and so // still served, once this row is gone. - const draftAddress = request.packageId == null && targetState === 'draft' + // + // [#34681] …except where the read naming no package serves the + // row-held base of rows bound to two or more packages + // ({@link packagelessRowHeldBaseAddress}): the delete and the + // draft discard remove the base's row or draft, as the request + // naming that base does, and the dependents' rows stay (the + // receipt below names them). + let draftAddress = request.packageId == null && targetState === 'draft' ? await host.packagelessDraftAddress(singularTypeForRepo, request.name, member) : undefined; if (draftAddress?.kind === 'ambiguous') { - addressRefusal = packagelessAddressAmbiguityRefusal( - 'delete', request.type, request.name, draftAddress.candidates, - ); - throw addressRefusal; + const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member); + if (base === undefined) { + addressRefusal = packagelessAddressAmbiguityRefusal( + 'delete', request.type, request.name, draftAddress.candidates, + ); + throw addressRefusal; + } + request = { ...request, packageId: base }; + draftAddress = undefined; } const rowsAtAddress = draftAddress?.drafts ?? await host.packagelessAddress( singularTypeForRepo, request.name, member, targetState, ); if (request.packageId == null && draftAddress === undefined && rowsAtAddress.candidates.length > 1) { - addressRefusal = packagelessAddressAmbiguityRefusal( - 'delete', request.type, request.name, rowsAtAddress.candidates, - ); - throw addressRefusal; + const base = await packagelessRowHeldBaseAddress(host, singularTypeForRepo, request.name, member); + if (base === undefined) { + addressRefusal = packagelessAddressAmbiguityRefusal( + 'delete', request.type, request.name, rowsAtAddress.candidates, + ); + throw addressRefusal; + } + request = { ...request, packageId: base }; } // [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the // read naming no package counts, as the save door asks them diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 925ab97c77c..d505a64561f 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -45,7 +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 { environmentActionPublishSlotRefusal, packagelessRowHeldBaseAddress } 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'; @@ -202,7 +202,7 @@ async function undoLandedPromotions(host: Pick, request: { + static async historyMetaItem(host: Pick, request: { type: string; name: string; sinceSeq?: number; @@ -278,6 +278,8 @@ export class ProtocolHistoryAndPublishFacet { // holders' rows hold is refused naming both when no package is named, // and `?package=` reads that holder's versions alone. A name one slot // holds, named bare, reads its whole log as before. + // [#34681] A row-held base's name, named bare, reads that base's + // versions, as `?package=` naming it does ({@link historySlotOf}). const slot = await historySlotOf(host, { type: singularType, name: request.name, ...memberOption(member), ...(request.packageId !== undefined ? { packageId: request.packageId } : {}), @@ -671,7 +673,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -834,7 +836,17 @@ export class ProtocolHistoryAndPublishFacet { // is the 503 the lock read raised before this read moved above it // ({@link packagelessAddress} discriminates both). const address = await host.packagelessDraftAddress(singularType, request.name, request.member); - if (address.kind === 'ambiguous') { + // [#34681] Active rows bound to two or more packages where the read + // naming no package serves the row-held base: the base's draft, as + // the publish naming that base promotes it + // ({@link packagelessRowHeldBaseAddress}). + const base = address.kind === 'ambiguous' + ? await packagelessRowHeldBaseAddress(host, singularType, request.name, request.member) + : undefined; + if (base !== undefined) { + draftKey = base; + promoteInto = base; + } else if (address.kind === 'ambiguous') { draftKey = null; promoteInto = null; addressRefusal = packagelessAddressAmbiguityRefusal('publish', request.type, request.name, address.candidates); diff --git a/packages/metadata-protocol/src/protocol-history-slots.ts b/packages/metadata-protocol/src/protocol-history-slots.ts index 7c993c51b6b..8e63d8249a6 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.ts @@ -17,7 +17,10 @@ * by more than one row slot — two packages', or a package's beside the * package-less row — is refused `409` naming every holder * (`ambiguous-in-environment`), before any row is read or written: nothing - * picks one (ADR-0150 D3, epic red line 2). So is a name the bare plain + * picks one (ADR-0150 D3, epic red line 2), except where the bare read + * serves the row-held base (#34441 cell 2): there the door addresses the + * base's slot, as naming the base does (#34681, + * `packagelessRowHeldBaseAddress`). So is a name the bare plain * read refuses (ADR-0150 D5: a holder in code counts, so two packages * shipping the name are two holders while only one has saved a row): the * registry's resolver (`resolveItem`, the one the plain read asks) throws @@ -58,6 +61,7 @@ import type { ProtocolHost } from './protocol-host.js'; import { memberOption } from './protocol-bundle-members.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; import type { HistoryVersionOwner } from './sys-metadata-repository.js'; +import { packagelessRowHeldBaseAddress } from './protocol-save.js'; /** What {@link historySlotOf} answers for a door of a by-package type. */ export interface HistorySlot { @@ -153,13 +157,19 @@ function refuseWhereBareReadRefuses(host: Pick, type: st * before. * @throws a `400 VALIDATION_ERROR` for `?package=` on a type not stored per * `(package, name)`. + * [#34681, epic ruling 6781691009] A bare request of a name whose rows at the + * member the read naming no package serves at the row-held base + * ({@link packagelessRowHeldBaseAddress}) addresses that base's slot, as the + * same request naming it does: the history, diff and rollback naming no + * package read and restore the base's versions, never another holder's. + * * @throws {PackageScopedNameRefusedError} `ambiguous-in-environment` for a - * bare request of a name two or more row slots hold, or the bare plain - * read's own refusal; `not-held-by-qualifier` for a package that neither + * bare request of a name two or more row slots hold (other than a row-held + * base's, above), or the bare plain read's own refusal; `not-held-by-qualifier` for a package that neither * holds a row of the name nor ships it, while another slot holds one. */ export async function historySlotOf( - host: Pick, + host: Pick, request: { type: string; name: string; member?: string; packageId?: string }, ): Promise { const { type, name, member, packageId } = request; @@ -167,7 +177,11 @@ export async function historySlotOf( if (!PACKAGE_SLOTTED_STORE_TYPES.has(type)) return undefined; const slots = await rowSlotsOf(host, type, name, member); if (packageId === undefined) { - if (slots.length > 1) throw slotRefusal(type, name, 'ambiguous-in-environment', null, slots); + if (slots.length > 1) { + const base = await packagelessRowHeldBaseAddress(host, type, name, member); + if (base !== undefined) return historySlotOf(host, { ...request, packageId: base }); + throw slotRefusal(type, name, 'ambiguous-in-environment', null, slots); + } refuseWhereBareReadRefuses(host, type, name, member); if (slots.length === 0) return undefined; return { owner: { packageId: slots[0] ?? null, sole: true }, addressed: false, held: true }; diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 88118a285d0..b824cb199d7 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -671,11 +671,11 @@ export async function declaredMemberOverrideAddressOf( * row holders ({@link storedRowHoldersRefusal}) and the layered door's * (`packagelessLayeredReadRefusal`) ask this first, so the plain read, * `/layers` and the execution face serve the base's row where they refused - * naming both; beside a package-less row they still refuse (#33210). The - * writes naming no package do not ask it: the save, delete, publish, draft - * and history doors still refuse these rows naming base and dependent - * (`packagelessAddress`), so the read serves the base's stack where the - * write it would send is refused (#34441 contract review S1). + * naming both; beside a package-less row they still refuse (#33210). + * [#34681] The writes naming no package ask it too, where their rows' address + * names two or more packages (`packagelessRowHeldBaseAddress`): the save, + * delete, draft discard, publish, history, diff and rollback doors act on the + * base's row, as the read serves it. * `preread` is the item's active rows when the caller read them already. */ export async function rowHeldBaseAddressOf( diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 7cf034bec00..b6236849abc 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -2021,7 +2021,7 @@ export class ProtocolPackageCommitsFacet { } /** [#28355] The body of {@link rollbackMetaItem} before its refusal audit; that method's docblock is the contract. */ - static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ + static async rollbackMetaItemUnaudited(host: Pick, request: RollbackMetaItemRequest): Promise<{ success: boolean; version: string; seq: number; @@ -2354,7 +2354,9 @@ export class ProtocolPackageCommitsFacet { version: await host.receiptVersion(result.version), seq: result.seq, restoredFromVersion: request.toVersion, - message: `Reverted to version ${request.toVersion} — type=${request.type}, name=${request.name} [seq=${result.seq}]`, + // [#34681 rider 1] Naming the package of the row it restored, + // as the delete's receipt names the row it removed. + message: `Reverted to version ${request.toVersion}${rollbackPackageId !== null ? ` (package=${rollbackPackageId})` : ''} — type=${request.type}, name=${request.name} [seq=${result.seq}]`, // Omitted, never `[]`, when there is nothing to report: a clean // rollback's answer bytes are unchanged. ...(advisories.length > 0 ? { advisories } : {}), diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index c0347df1bc1..f81dfd23da7 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -88,7 +88,8 @@ import type { ProtocolHost } from './protocol-host.js'; import type { ObjectStackProtocolImplementation } from './protocol.js'; 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 { rowHeldBaseAddressOf, servedAddressJudgment } from './protocol-meta-item-face.js'; +import { overlayMemberValue } from './migrations/overlay-index.js'; import { packagelessContentPackage, shippingPackageIds } from './protocol-environment-rows.js'; import type { StoredOverlayRow } from './item-lock.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; @@ -850,10 +851,15 @@ export class ProtocolSaveFacet { // 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) { + // [#34681] …where the read naming no package serves the + // row-held base, the save writes the base's row + // ({@link packagelessRowHeldBaseAddress}); otherwise refused + // naming every package the rows are bound to. + const base = await packagelessRowHeldBaseAddress(host, writeType, request.name, member); + if (base === undefined) throw packagelessAddressAmbiguityRefusal('save', request.type, request.name, address.candidates); + request = { ...request, packageId: base }; } else { - if (address.candidates.length > 1) { - throw packagelessAddressAmbiguityRefusal('save', request.type, request.name, address.candidates); - } // [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the // read naming no package counts ({@link packagelessHolderRefusal}): // two or more enabled holders are refused naming them, and a name @@ -878,7 +884,7 @@ export class ProtocolSaveFacet { // [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' + let draftAddress = mode === 'draft' && request.packageId == null && request.source === undefined && request.writeFace !== 'package-duplicate' @@ -886,6 +892,26 @@ export class ProtocolSaveFacet { singularType, request.name, itemDiscriminator(singularType, request.item), request.item, ) : undefined; + // [#34681] An item whose active rows are bound to two or more packages + // where the read naming no package serves the row-held base: the + // draft save writes the base's draft, as the save naming that base + // does ({@link packagelessRowHeldBaseAddress}). Otherwise the + // ambiguous address is left to the repository's `409`, as before. + // `followedBase` keeps the base for the two rules below that judge a + // draft save's inherited package (the named-base rule and the late + // override re-judgment): the base is judged exactly as the save + // naming it is, an id no installed package has refused `422`. + let followedBase: string | undefined; + if (draftAddress?.kind === 'ambiguous') { + const base = await packagelessRowHeldBaseAddress( + host, singularType, request.name, itemDiscriminator(singularType, request.item), + ); + if (base !== undefined) { + request = { ...request, packageId: base }; + draftAddress = undefined; + followedBase = base; + } + } // [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 @@ -925,7 +951,7 @@ export class ProtocolSaveFacet { // repository's `409`, as before. See {@link uninstalledNamedBaseRefusal}. if (namedNoPackage && request.source === undefined && request.writeFace !== 'package-duplicate') { const inherited = mode === 'draft' - ? draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into : null + ? followedBase ?? (draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into : null) : request.packageId ?? null; const unboundInherited = host.uninstalledNamedBaseRefusal( { type: singularType, name: request.name, packageId: inherited }, @@ -1992,7 +2018,7 @@ export class ProtocolSaveFacet { && request.writeFace !== 'package-duplicate' ) { const inheritedPackage = mode === 'draft' - ? draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into : null + ? followedBase ?? (draftAddress && draftAddress.kind !== 'ambiguous' ? draftAddress.into : null) : request.packageId ?? null; if (typeof inheritedPackage === 'string' && inheritedPackage.length > 0) { lateOverrideVerdict = host.overrideWriteVerdict({ ...request, packageId: inheritedPackage }); @@ -3193,6 +3219,63 @@ export function disabledHoldersOnlyRefusal( return err; } +/** + * [#34681, epic ruling 6781691009, #34348 ruling (b), ADR-0150 D3/D5] THE + * ROW-HELD BASE a write naming no package takes, where the stored rows at the + * member are bound to two or more packages: the base whose dependents' rows + * there are bundle additions to it ({@link rowHeldBaseAddressOf}), the one + * holder the read naming no package serves at that address (the plain read, + * `/layers` and the execution read, since the read half of #34441 cell 2). + * "A write resolves its address exactly as the read at the same address + * resolves it", so the bare save (publish and draft mode), the bare delete + * and draft discard, the bare per-item publish, and the bare history, diff + * and rollback (through `historySlotOf`) answer as the same request naming + * that base does, and every dependent's row stays where it is, read and + * written at its own `?package=`. + * + * Asked only where those doors would refuse naming two or more packages, and + * answered over the item's ACTIVE rows at `member`, as the read judges them: + * + * - the base, when two or more packages hold a row there, none of them + * package-less (#33210: a package-less row beside them is a customization + * of no one holder, and the refusal stands), and one is the row-held base; + * - `undefined` otherwise, and the door refuses as before: a type with no + * members (#34441 contract review M1: no bundle additions), a name a + * package ships, holders with no base relation, a disabled holder (the + * served-holder judgment's), and a member the base holds no row of (the + * read takes the base's address there and answers 404; that cell is not + * moved here). + * + * FROM (`main` 8596c80eda): each of those doors refused `409 + * RESOURCE_CONFLICT` naming the base and the dependent while the read + * naming no package served the base's row (`200`); the diff and the rollback + * refused the same way (measured on branch head 90d943c7f5). + */ +export async function packagelessRowHeldBaseAddress( + host: Pick, + type: string, + name: string, + member: string | undefined, +): Promise { + const singular = PLURAL_TO_SINGULAR[type] ?? type; + const registry = host.engine?.registry as { readsByPackage?: (type: string) => boolean } | undefined; + // The judgment's own first two exclusions, asked before any row is read. + if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(singular) !== true) return undefined; + if (overlayMemberValue(singular, member) === undefined) return undefined; + let activeRows: Awaited>; + try { + activeRows = await host.readItemActiveRows(singular, name); + } catch (error) { + // [#5532] An unprovisioned store holds no row, so no holder. + host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); + return undefined; + } + const address = await host.packagelessAddress(singular, name, member, 'active', activeRows); + if (address.candidates.length < 2 || address.unbound) return undefined; + const base = await rowHeldBaseAddressOf(host, singular, name, member, activeRows); + return base !== undefined && address.candidates.includes(base) ? base : undefined; +} + /** * [ADR-0150 D3/D5 and red line 2] THE HOLDERS a write naming no package * counts before it takes its address from the stored rows' bindings diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index a41ea1fd0f2..28232aec71b 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -4272,11 +4272,11 @@ export class ObjectStackProtocolImplementation implements * (`rowHeldBaseAddressOf`) are no ambiguity here, as the registry names * the base the one holder there; {@link getMetaItemLayered} reads the * base's stack, as the plain read serves the base's row. Beside a - * package-less row they are still refused (#33210). The writes naming no - * package are not moved: the save, delete, publish, draft and history - * doors still refuse the same rows naming base and dependent, so here the - * view loads where the save it then sends is refused (a follow-up card - * judges whether the writes follow the base). + * package-less row they are still refused (#33210). [#34681] The writes + * naming no package follow the same base + * (`packagelessRowHeldBaseAddress`): the save, delete, draft discard, + * publish, history, diff and rollback doors act on the base's row, so the + * view loads where the save it then sends lands. */ async packagelessLayeredReadRefusal(request: { type: string; @@ -7870,13 +7870,13 @@ export class ObjectStackProtocolImplementation implements } /** - * [#23165, ADR-0048] THE package-less write address: which row of an item a - * write that names no package addresses, read from the item's stored rows - * at `state`. The item's own package when those rows are bound to exactly - * one, else the package-unbound row. `candidates` is every distinct - * binding, sorted; two or more is a name several packages hold, which the - * doors refuse ({@link packagelessAddressAmbiguityRefusal}) and for which - * `packageId` is `null`. `unbound` says whether a package-unbound row sits + * [#23165, ADR-0048] THE package-less write address: which row of an item a write that + * names no package addresses, read from the item's stored rows at `state`. The item's + * own package when those rows are bound to exactly one, else the package-unbound row. + * `candidates` is every distinct binding, sorted; two or more is a name several + * packages hold, which the doors refuse ({@link packagelessAddressAmbiguityRefusal}) + * and for which `packageId` is `null`, unless the bare read serves the row-held base, + * whose row they address (#34681). `unbound` says whether a package-unbound row sits * beside them, which is what a delete of a package's row leaves served. * * The one resolution its three readers take, so they cannot disagree: @@ -7964,9 +7964,9 @@ export class ObjectStackProtocolImplementation implements * next. Neither present: no draft (`none`), whatever other packages' * drafts are stored; the strict draft read answers `404 NO_DRAFT` here * too, and those drafts are addressed by naming their package. - * - bound to two or more packages: `ambiguous`, refused by both doors - * with the refusal the draft save answers - * ({@link packagelessAddressAmbiguityRefusal}, `409 RESOURCE_CONFLICT`). + * - bound to two or more packages: `ambiguous`, refused by both doors with + * the draft save's {@link packagelessAddressAmbiguityRefusal} (`409`), + * unless the bare read serves the row-held base, whose draft they address (#34681). * - bound to none (an item never published into a package): the * package-unbound draft. With no such draft, the one package's draft * when exactly one package holds a draft (the only draft the read @@ -9619,11 +9619,11 @@ export class ObjectStackProtocolImplementation implements * on a control-plane kernel — appends no `sys_metadata_history` row. * * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a - * name two row slots hold, or one the bare plain read refuses, is refused - * `409` naming every holder when no package is named, and `packageId` - * reads that holder's versions alone: its own, plus those attributed to - * no package or to the environment while it is the name's only slot - * (`protocol-history-slots.ts`). A name one holder holds reads as before. + * name two row slots hold, or one the bare plain read refuses, is refused `409` naming + * every holder when no package is named (but the row-held base the bare read serves is + * read as named, #34681), and `packageId` reads that holder's versions alone: its own, + * plus those attributed to no package or to the environment while it is the name's + * only slot (`protocol-history-slots.ts`). A name one holder holds reads as before. * `packageId` on any other type is refused `400 VALIDATION_ERROR`. */ async historyMetaItem(request: { @@ -11059,16 +11059,16 @@ export class ObjectStackProtocolImplementation implements * declared override over a row bound to its read-only base. * * [ADR-0150 D3/D4, #32905] For a type stored per `(package, name)`, a - * name two row slots hold is refused `409` naming every holder when no - * package is named, with nothing written (so is a name the bare plain - * read refuses); `packageId` restores into that holder's row (its own, - * its pair's declared override, or the package-less row its read falls - * back to), and the version must be that holder's: another holder's, or - * one attributed to no package or to the environment while another slot - * holds the name, answers 404 `VERSION_NOT_FOUND`. A name one holder - * holds, named bare, restores any of its versions as before. - * `packageId` on any other type is refused `400 VALIDATION_ERROR`, and - * one naming no installed package where no row is stored is refused + * name two row slots hold is refused `409` naming every holder when no package is + * named, with nothing written (so is a name the bare plain read refuses), but the + * row-held base the bare read serves is restored as named (#34681); `packageId` + * restores into that holder's row (its own, its pair's declared override, or the + * package-less row its read falls back to), and the version must be that + * holder's: another holder's, or one attributed to no package or to the + * environment while another slot holds the name, answers 404 `VERSION_NOT_FOUND`. + * A name one holder holds, named bare, restores any of its versions as before. + * `packageId` on any other type is refused `400 VALIDATION_ERROR`, and one naming + * no installed package where no row is stored is refused * `422 WRITABLE_PACKAGE_REQUIRED` (`protocol-history-slots.ts`). * * [#32700] Then, as the save door does: the restored object's storage is diff --git a/packages/runtime/src/domains/meta-bare-write-doors-follow-base-34681.test.ts b/packages/runtime/src/domains/meta-bare-write-doors-follow-base-34681.test.ts new file mode 100644 index 00000000000..a685ea6132b --- /dev/null +++ b/packages/runtime/src/domains/meta-bare-write-doors-follow-base-34681.test.ts @@ -0,0 +1,370 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34681, epic ruling 6781691009, #34348 ruling (b), ADR-0150 D3/D5] A +// bundled type's name no package ships, held as stored rows at one member by a +// base package and a package that declares it (#34441 cell 2): the read naming +// no package serves the base's row, and the seven doors naming no package +// that write or address one row now answer as the same request naming that +// base does. The bare save (the REST door and in process, publish and draft +// mode), the bare per-item publish, the bare delete and draft discard, and +// the bare history, diff and rollback each land in, or answer for, the base's +// row; the dependent's row stays where it is, read and written at its own +// `?package=`. A read-only base is answered for as named, at every door. The base is judged as named: +// bound to an id no installed package has, the bare save in either mode is +// refused 422 WRITABLE_PACKAGE_REQUIRED as `?package=` is. Driven on a +// booted kernel (the real protocol, metadata service, registry and +// `sys_metadata` store). +// +// FROM (measured through these doors before the change, `main` 8596c80eda; +// the diff and rollback at `main` 90d943c7f5): with the read serving the +// base's row (200), the bare save, draft save, publish, history, diff, +// rollback, delete and draft discard each refused 409 RESOURCE_CONFLICT +// naming both packages. +// +// Measured beside it, unchanged by this change and pinned as they read: +// - after the bare delete removes the base's row, the bare read serves the +// dependent's row, and the delete's receipt names that row as remaining; +// - a read-only (code) base: the bare save answers what `?package=` +// answers, 422 WRITABLE_PACKAGE_REQUIRED naming the base, not 409 naming both; +// - the shipped-base neighbour (the base ships the member in code, the +// dependent stores a row of it): the bare read serves the base's code item +// and the bare save is refused 403 NOT_OVERRIDABLE toward the base's pair, +// writing nothing (the package-less write is closed there, ADR-0146 D11); +// - CONTROLS: two holders with no base relation, a package-less row beside the +// holders (#33210), and a type with no members (#34441 contract review M1) +// still refuse 409 naming both holders; an explicit `?package=` write still +// lands where it names. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { resolveThrownHttpError } from '@objectstack/types'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { HttpDispatcher } from '../http-dispatcher.js'; + +const CALLER = { userId: 'u_write_follows_base', tenantId: 'org_qa', isSystem: true, positions: [], permissions: [], systemPermissions: ['manage_metadata'] }; +// Code packages (read-only bases): A ships `shipmail`, D declares A, U declares nothing. +const A = 'com.qa.writebase'; +const D = 'com.qa.writeaddon'; +const U = 'com.qa.writeother'; +// Authored (writable) packages: WD declares WA. +const WA = 'com.qa.authoredbase'; +const WD = 'com.qa.authoredaddon'; +// An id no installed package has, declared by the installed authored package GD. +const GHOST = 'com.qa.ghostbase'; +const GD = 'com.qa.ghostaddon'; + +interface ManifestDoor { register(artifact: unknown): Promise | void } +interface Booted { kernel: ObjectKernel; engine: ObjectQL; root: string; protocol: any } +interface Answer { status?: number; body: any } + +const template = (locale: string, subject: string) => ({ label: subject, locale, subject, bodyHtml: `

${subject}

` }); +const appManifest = (id: string, extra: Record = {}) => ({ + id, name: id.split('.').pop(), namespace: id.split('.').pop()!.replace(/[^a-z]/g, ''), version: '1.0.0', type: 'app', objects: [], ...extra, +}); +const MANIFESTS = [ + appManifest(A, { emailTemplates: [{ name: 'shipmail', ...template('en-US', 'base code en') }] }), + appManifest(D, { dependencies: { [A]: '*' } }), + appManifest(U), +]; + +async function boot(file: string): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const root = mkdtempSync(join(tmpdir(), 'os-meta-write-follows-base-')); + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }) as any, true); + await kernel.use(new MetadataPlugin({ watch: false, rootDir: root })); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + const host: Plugin = { + name: 'qa.write-follows-base-host', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + for (const manifest of MANIFESTS) await ctx.getService('manifest').register(manifest); + }, + }; + await kernel.use(host); + await kernel.bootstrap(); + await engine.syncSchemas(); + engine.registry.installPackage({ id: WA, name: WA, version: '1.0.0', type: 'app' } as any, 'authored'); + engine.registry.installPackage({ id: WD, name: WD, version: '1.0.0', type: 'app', dependencies: { [WA]: '*' } } as any, 'authored'); + engine.registry.installPackage({ id: GD, name: GD, version: '1.0.0', type: 'app', dependencies: { [GHOST]: '*' } } as any, 'authored'); + return { kernel, engine, root, protocol: kernel.getService('protocol') }; +} + +// A bundled type's non-canonical member carries its `bundle_member` key column, as the save door writes it. +const layRow = (engine: ObjectQL, type: string, name: string, packageId: string | null, metadata: Record, state: 'active' | 'draft' = 'active') => engine.insert('sys_metadata', { + type, name, namespace: 'default', package_id: packageId, scope: 'platform', strategy: 'merge', state, version: 1, + ...(type === 'email_template' && metadata.locale !== 'en-US' ? { bundle_member: metadata.locale } : {}), + metadata: JSON.stringify({ name, ...metadata }), +}, { context: { isSystem: true } } as any); +const layPair = async (engine: ObjectQL, name: string, base: string, dependent: string) => { + await layRow(engine, 'email_template', name, base, template('en-US', 'base en')); + await layRow(engine, 'email_template', name, dependent, template('en-US', 'addon en')); +}; + +/** Every stored row of the name, `state:binding:subject`. */ +const rowsOf = async (engine: ObjectQL, name: string, type = 'email_template') => ((await engine.find('sys_metadata', { where: { type, name }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .map((row) => { + const body = JSON.parse(String(row.metadata)); + return `${row.state}:${row.package_id ?? null}:${body.subject ?? body.label}`; + }).sort(); + +const codeOf = (body: any): unknown => (body?.error && typeof body.error === 'object' ? body.error.code : body?.code); +const unwrap = (body: any) => body?.data ?? body; + +async function dispatch(kernel: ObjectKernel, method: 'GET' | 'PUT', path: string, query: Record = {}, body?: unknown): Promise { + const dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false }); + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER }); + const search = new URLSearchParams(query).toString(); + const raw = new Request(`http://localhost/api/v1${path}${search ? `?${search}` : ''}`, body === undefined + ? { method } + : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + try { + const out: any = await dispatcher.dispatch(method, path, body ?? {}, query, { request: raw } as any, '/api/v1'); + return { status: out.response?.status as number | undefined, body: out.response?.body }; + } catch (e) { + const thrown = resolveThrownHttpError(e); + return { status: thrown.status, body: { error: { code: thrown.code, message: String((e as Error)?.message ?? '') } } }; + } +} +/** The bare read's answer: `[status, subject, packageId]`, or `[status, code]` when refused. */ +const bareRead = async (b: Booted, name: string, query: Record = {}) => { + const r = await dispatch(b.kernel, 'GET', `/meta/email_template/${name}`, query); + return r.status === 200 ? [200, unwrap(r.body)?.item?.subject, unwrap(r.body)?.packageId ?? null] : [r.status, codeOf(r.body)]; +}; +/** What `call` resolves to, or the `{ code, status, message }` it rejects with. */ +const settle = (call: Promise): Promise => call.then( + (resolved) => ({ resolved }), + (error: any) => ({ code: error?.code, status: error?.status ?? error?.httpStatus, message: String(error?.message ?? '') }), +); +/** Refused 409 RESOURCE_CONFLICT, the message naming every one of `ids`. */ +const expectRefusedNaming = (answer: any, ids: readonly string[], where: string) => { + expect([where, answer.code, answer.status], JSON.stringify(answer)).toEqual([where, 'RESOURCE_CONFLICT', 409]); + for (const id of ids) expect(answer.message, where).toContain(id); +}; +const saveOf = (b: Booted, name: string, subject: string, extra: Record = {}) => + settle(b.protocol.saveMetaItem({ type: 'email_template', name, item: { name, ...template('en-US', subject) }, ...extra })); + +describe('[#34681] the bare write doors follow the row-held base the bare read serves', () => { + const dirs: string[] = []; + afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); }); + const freshFile = () => { + const dir = mkdtempSync(join(tmpdir(), 'os-meta-write-follows-base-db-')); + dirs.push(dir); + return join(dir, 'meta.sqlite'); + }; + const down = async (b: Booted) => { + if (b.kernel.getState() === 'running') await b.kernel.shutdown(); + dirs.push(b.root); + }; + + it('save (REST door and in process), draft save, publish and history land in and answer for the base\'s row, as ?package= does, before and after a restart', async () => { + const file = freshFile(); + let b = await boot(file); + try { + await layPair(b.engine, 'w_mail', WA, WD); + expect(await bareRead(b, 'w_mail')).toEqual([200, 'base en', WA]); + // The REST door: PUT naming no package writes the base's row. + const put = await dispatch(b.kernel, 'PUT', '/meta/email_template/w_mail', {}, { name: 'w_mail', ...template('en-US', 'edited') }); + expect(put.status, JSON.stringify(put.body)).toBe(200); + expect(await rowsOf(b.engine, 'w_mail')).toEqual([`active:${WD}:addon en`, `active:${WA}:edited`]); + expect(await bareRead(b, 'w_mail')).toEqual([200, 'edited', WA]); + // The draft save writes the base's draft; the publish promotes it into the base's row. + const drafted = await saveOf(b, 'w_mail', 'drafted', { mode: 'draft' }); + expect(drafted.resolved, JSON.stringify(drafted)).toMatchObject({ success: true, state: 'draft' }); + expect(await rowsOf(b.engine, 'w_mail')).toEqual([`active:${WD}:addon en`, `active:${WA}:edited`, `draft:${WA}:drafted`]); + const published = await settle(b.protocol.publishMetaItem({ type: 'email_template', name: 'w_mail' })); + expect(published.resolved, JSON.stringify(published)).toMatchObject({ success: true }); + expect(await rowsOf(b.engine, 'w_mail')).toEqual([`active:${WD}:addon en`, `active:${WA}:drafted`]); + expect(await bareRead(b, 'w_mail')).toEqual([200, 'drafted', WA]); + // The history naming no package is the base's versions, as `?package=` naming it reads them. + const bare = await settle(b.protocol.historyMetaItem({ type: 'email_template', name: 'w_mail' })); + const named = await settle(b.protocol.historyMetaItem({ type: 'email_template', name: 'w_mail', packageId: WA })); + expect(bare.resolved?.events?.length, JSON.stringify(bare)).toBeGreaterThan(0); + expect(bare).toEqual(named); + // The dependent's own address still reads and writes its own row. + expect(await bareRead(b, 'w_mail', { package: WD })).toEqual([200, 'addon en', WD]); + const own = await saveOf(b, 'w_mail', 'addon edited', { packageId: WD }); + expect(own.resolved, JSON.stringify(own)).toMatchObject({ success: true }); + expect(await rowsOf(b.engine, 'w_mail')).toEqual([`active:${WD}:addon edited`, `active:${WA}:drafted`]); + } finally { + await down(b); + } + b = await boot(file); + try { + expect(await bareRead(b, 'w_mail')).toEqual([200, 'drafted', WA]); + const saved = await saveOf(b, 'w_mail', 'after restart'); + expect(saved.resolved, JSON.stringify(saved)).toMatchObject({ success: true }); + expect(await rowsOf(b.engine, 'w_mail')).toEqual([`active:${WD}:addon edited`, `active:${WA}:after restart`]); + expect(await bareRead(b, 'w_mail')).toEqual([200, 'after restart', WA]); + } finally { + await down(b); + } + }, 120_000); + + describe('one boot', () => { + let b: Booted; + beforeAll(async () => { b = await boot(freshFile()); }, 120_000); + afterAll(async () => { if (b) await down(b); }); + + it('the draft discard and the delete remove the base\'s draft and row; the bare read then serves the dependent\'s row, which the receipt names', async () => { + await layPair(b.engine, 'w_del', WA, WD); + expect((await saveOf(b, 'w_del', 'drafted', { mode: 'draft' })).resolved).toMatchObject({ success: true }); + const discarded = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'w_del', state: 'draft' })); + expect(discarded.resolved, JSON.stringify(discarded)).toMatchObject({ success: true, reset: true }); + expect(await rowsOf(b.engine, 'w_del')).toEqual([`active:${WD}:addon en`, `active:${WA}:base en`]); + const deleted = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'w_del' })); + expect(deleted.resolved, JSON.stringify(deleted)).toMatchObject({ success: true, reset: true }); + expect(deleted.resolved.message).toContain(WD); + expect(await rowsOf(b.engine, 'w_del')).toEqual([`active:${WD}:addon en`]); + // Read after the delete: the dependent's row is the only row of the member left. + expect(await bareRead(b, 'w_del')).toEqual([200, 'addon en', WD]); + }); + + it('a base bound to an id no installed package has, which an installed dependent declares: the bare draft save is refused 422 as ?package= and the bare publish-mode save are, writing nothing', async () => { + await layPair(b.engine, 'ghost_mail', GHOST, GD); + expect(await bareRead(b, 'ghost_mail')).toEqual([200, 'base en', GHOST]); + for (const mode of ['publish', 'draft'] as const) { + const named = await saveOf(b, 'ghost_mail', 'edited', { mode, packageId: GHOST }); + const bare = await saveOf(b, 'ghost_mail', 'edited', { mode }); + expect([mode, 'named', named.code, named.status], JSON.stringify(named)).toEqual([mode, 'named', 'WRITABLE_PACKAGE_REQUIRED', 422]); + expect([mode, 'bare', bare.code, bare.status], JSON.stringify(bare)).toEqual([mode, 'bare', 'WRITABLE_PACKAGE_REQUIRED', 422]); + expect(bare.message).toContain(GHOST); + } + expect(await rowsOf(b.engine, 'ghost_mail')).toEqual([`active:${GD}:addon en`, `active:${GHOST}:base en`]); + }); + + it('two bare deletes in a row: the first removes the base\'s row and the read then serves the dependent\'s, the second removes the dependent\'s', async () => { + await layPair(b.engine, 'w_del2', WA, WD); + const first = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'w_del2' })); + expect(first.resolved, JSON.stringify(first)).toMatchObject({ success: true, reset: true }); + expect(first.resolved.message).toContain(`(package=${WA})`); + expect(await rowsOf(b.engine, 'w_del2')).toEqual([`active:${WD}:addon en`]); + expect(await bareRead(b, 'w_del2')).toEqual([200, 'addon en', WD]); + const second = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'w_del2' })); + expect(second.resolved, JSON.stringify(second)).toMatchObject({ success: true, reset: true }); + expect(second.resolved.message).toContain(`(package=${WD})`); + expect(await rowsOf(b.engine, 'w_del2')).toEqual([]); + expect((await bareRead(b, 'w_del2'))[0]).toBe(404); + }); + + it('the bare draft read and the bare discard address the same draft, the base\'s, with the dependent\'s draft beside it', async () => { + await layPair(b.engine, 'w_drafts', WA, WD); + // The dependent's draft is stored FIRST, so a first-match read would meet it before the base's. + expect((await saveOf(b, 'w_drafts', 'addon drafted', { mode: 'draft', packageId: WD })).resolved).toMatchObject({ success: true }); + expect((await saveOf(b, 'w_drafts', 'base drafted', { mode: 'draft' })).resolved).toMatchObject({ success: true }); + expect(await rowsOf(b.engine, 'w_drafts')).toEqual([`active:${WD}:addon en`, `active:${WA}:base en`, `draft:${WD}:addon drafted`, `draft:${WA}:base drafted`]); + const readDraft = await settle(b.protocol.getMetaItem({ type: 'email_template', name: 'w_drafts', state: 'draft' })); + expect([readDraft.resolved?.item?.subject, readDraft.resolved?.item?._packageId], JSON.stringify(readDraft)).toEqual(['base drafted', WA]); + expect(readDraft.resolved?.version, 'the address a save pins to, never the best-effort null').toEqual(expect.any(String)); + const discarded = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'w_drafts', state: 'draft' })); + expect(discarded.resolved, JSON.stringify(discarded)).toMatchObject({ success: true, reset: true }); + expect(await rowsOf(b.engine, 'w_drafts')).toEqual([`active:${WD}:addon en`, `active:${WA}:base en`, `draft:${WD}:addon drafted`]); + }); + + it('a read-only base: the bare delete, draft discard and rollback answer what ?package= answers, never 409 naming both', async () => { + const outcome = (answer: any) => (answer.resolved !== undefined ? ['resolved', answer.resolved.success] : [answer.code, answer.status]); + const seen: Record = {}; + for (const [label, packageId] of [['bare', undefined], ['named', A]] as const) { + const name = `ro_destroy_${label}`; + await layPair(b.engine, name, A, D); + await layRow(b.engine, 'email_template', name, A, template('en-US', 'base drafted'), 'draft'); + const at = packageId === undefined ? {} : { packageId }; + const discard = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name, state: 'draft', ...at })); + const rollback = await settle(b.protocol.rollbackMetaItem({ type: 'email_template', name, toVersion: 1, ...at })); + const remove = await settle(b.protocol.deleteMetaItem({ type: 'email_template', name, ...at })); + seen[label] = { discard: outcome(discard), rollback: outcome(rollback), remove: outcome(remove), rows: await rowsOf(b.engine, name) }; + if (label === 'bare') { + for (const answer of [discard, rollback, remove]) expect(answer.code, JSON.stringify(answer)).not.toBe('RESOURCE_CONFLICT'); + } + } + expect(seen.bare, JSON.stringify(seen)).toEqual(seen.named); + }); + + const versionedPair = async (name: string) => { + await layPair(b.engine, name, WA, WD); + for (const subject of ['v1', 'v2']) { + expect((await saveOf(b, name, subject, { packageId: WA })).resolved).toMatchObject({ success: true }); + } + expect((await saveOf(b, name, 'addon v1', { packageId: WD })).resolved).toMatchObject({ success: true }); + }; + + it('the diff naming no package compares the base\'s versions, as ?package= does', async () => { + await versionedPair('df_mail'); + const bare = await settle(b.protocol.diffMetaItem({ type: 'email_template', name: 'df_mail' })); + const named = await settle(b.protocol.diffMetaItem({ type: 'email_template', name: 'df_mail', packageId: WA })); + expect(bare.resolved, JSON.stringify(bare)).toBeDefined(); + expect(bare).toEqual(named); + expect(JSON.stringify(bare.resolved.changed)).toContain('v2'); + expect(JSON.stringify(bare.resolved)).not.toContain('addon'); + }); + + it('the rollback naming no package restores the base\'s row to the base\'s own version, as ?package= does', async () => { + await versionedPair('rb_mail'); + const versions = ((await b.engine.find('sys_metadata_history', { where: { type: 'email_template', name: 'rb_mail' }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .filter((row) => JSON.parse(String(row.metadata)).subject === 'v1').map((row) => Number(row.version)); + expect(versions.length, 'one stored version of the base\'s v1').toBe(1); + const rolled = await settle(b.protocol.rollbackMetaItem({ type: 'email_template', name: 'rb_mail', toVersion: versions[0] })); + expect(rolled.resolved, JSON.stringify(rolled)).toMatchObject({ success: true }); + // [rider 1] The receipt names the package of the row it restored, as the delete's names the row it removed. + expect(rolled.resolved.message).toContain(`(package=${WA})`); + expect(await rowsOf(b.engine, 'rb_mail')).toEqual([`active:${WD}:addon v1`, `active:${WA}:v1`]); + expect(await bareRead(b, 'rb_mail')).toEqual([200, 'v1', WA]); + }); + + it('a read-only base: the bare save and draft save answer what ?package= answers, never 409 naming both', async () => { + await layPair(b.engine, 'ro_mail', A, D); + expect(await bareRead(b, 'ro_mail')).toEqual([200, 'base en', A]); + for (const mode of ['publish', 'draft'] as const) { + const bare = await saveOf(b, 'ro_mail', 'edited', { mode }); + const named = await saveOf(b, 'ro_mail', 'edited', { mode, packageId: A }); + expect([mode, bare.code, bare.status], JSON.stringify(bare)).toEqual([mode, 'WRITABLE_PACKAGE_REQUIRED', 422]); + expect(bare.message).toContain(A); + expect(bare.message).not.toContain(D); + expect([bare.code, bare.status]).toEqual([named.code, named.status]); + } + expect(await rowsOf(b.engine, 'ro_mail')).toEqual([`active:${D}:addon en`, `active:${A}:base en`]); + }); + + it('the shipped-base neighbour reads as it did: the bare read serves the base\'s code item and the bare save is refused toward the base\'s pair, writing nothing', async () => { + await layRow(b.engine, 'email_template', 'shipmail', D, template('en-US', 'addon en')); + expect(await bareRead(b, 'shipmail')).toEqual([200, 'base code en', A]); + const saved = await saveOf(b, 'shipmail', 'edited'); + expect([saved.code, saved.status], JSON.stringify(saved)).toEqual(['NOT_OVERRIDABLE', 403]); + expect(saved.message).toContain(`${A}.custom`); + expect(await rowsOf(b.engine, 'shipmail')).toEqual([`active:${D}:addon en`]); + expect(await bareRead(b, 'shipmail')).toEqual([200, 'base code en', A]); + }); + + it('CONTROLS: holders with no base relation, a package-less row beside them and a type with no members still refuse naming both; ?package= still lands where it names', async () => { + // Two holders, neither declaring the other. + await layPair(b.engine, 'unrel_mail', A, U); + expect(await bareRead(b, 'unrel_mail')).toEqual([409, 'RESOURCE_CONFLICT']); + expectRefusedNaming(await saveOf(b, 'unrel_mail', 'x'), [A, U], 'unrelated: save'); + expectRefusedNaming(await settle(b.protocol.deleteMetaItem({ type: 'email_template', name: 'unrel_mail' })), [A, U], 'unrelated: delete'); + expect(await settle(b.protocol.historyMetaItem({ type: 'email_template', name: 'unrel_mail' }))).toMatchObject({ code: 'RESOURCE_CONFLICT' }); + // A package-less row beside a base and its dependent (#33210). + await layPair(b.engine, 'loose_mail', WA, WD); + await layRow(b.engine, 'email_template', 'loose_mail', null, template('en-US', 'loose en')); + expect(await bareRead(b, 'loose_mail')).toEqual([409, 'RESOURCE_CONFLICT']); + expectRefusedNaming(await saveOf(b, 'loose_mail', 'x'), [WA, WD], 'package-less row: save'); + // A type with no members: a base and its dependent stay two holders (#34441 contract review M1). + await layRow(b.engine, 'dashboard', 'follow_dash', WA, { label: 'base row', widgets: [] }); + await layRow(b.engine, 'dashboard', 'follow_dash', WD, { label: 'addon row', widgets: [] }); + expectRefusedNaming( + await settle(b.protocol.saveMetaItem({ type: 'dashboard', name: 'follow_dash', item: { name: 'follow_dash', label: 'x', widgets: [] } })), + [WA, WD], 'no members: save', + ); + expect(await rowsOf(b.engine, 'follow_dash', 'dashboard')).toEqual([`active:${WD}:addon row`, `active:${WA}:base row`]); + // `?package=` naming the dependent writes the dependent's row, in the cell this change moves. + await layPair(b.engine, 'named_mail', WA, WD); + expect((await saveOf(b, 'named_mail', 'addon edited', { packageId: WD })).resolved).toMatchObject({ success: true }); + expect(await rowsOf(b.engine, 'named_mail')).toEqual([`active:${WD}:addon edited`, `active:${WA}:base en`]); + }); + }); +}); diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index c1322f3f6b3..5f800eeba05 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1219,7 +1219,13 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + '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 ' + + 'package stamp). Bound to two or more, one exception: a bundled type\'s ' + + 'member whose active rows a base package and a package declaring it ' + + 'both hold, with no package-unbound row beside them, is the row-held ' + + 'base\'s, as the read naming no package serves it, and the save (either ' + + 'mode) writes the base\'s row or draft as a save naming the base does; ' + + 'two packages neither of which declares the other are still refused ' + + '`409`. 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. ' @@ -1227,7 +1233,8 @@ export const SaveMetaItemRequestSchema = lazySchema(() => z.object({ + '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 ' + + 'drafts) are bound to two or more packages, but for the row-held base ' + + 'above, 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 ' @@ -1559,7 +1566,12 @@ export const PublishMetaItemRequestSchema = lazySchema(() => z.object({ + 'a package it is the package-unbound draft, else the one package\'s ' + '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. ⚠️ `null` is ' + + 'more packages, except a bundled type\'s member whose active rows a base ' + + 'package and a package declaring it both hold, with no package-unbound ' + + 'row beside them: the read naming no package serves the base\'s row, and ' + + 'the publish promotes the base\'s draft into it, as naming the base does ' + + '(two packages neither of which declares the other are still refused). ' + + '⚠️ `null` is ' + 'NOT the same as absent: the implementation branches on the KEY BEING ' + 'PRESENT, and `null` pins the lookup to the package-UNBOUND row. Spread ' + 'it in conditionally; a present-and-`undefined` key coerces to `null` ' @@ -2433,7 +2445,16 @@ export const DeleteMetaItemRequestSchema = lazySchema(() => z.object({ + 'package: the delete of the `active` row then removes the row of the ' + 'one package the item\'s active rows are bound to, is refused `409 ' + 'RESOURCE_CONFLICT` when they are bound to two or more, and with none ' - + 'removes the env-local row (no package stamp); the discard of the ' + + 'removes the env-local row (no package stamp). Bound to two or more, ' + + 'one exception: a bundled type\'s member whose active rows a base ' + + 'package and a package declaring it both hold, with no package-unbound ' + + 'row beside them, is the row-held base\'s, as the read naming no ' + + 'package serves it, and the delete removes the base\'s row as naming ' + + 'the base does (two packages neither of which declares the other are ' + + 'still refused `409`). The dependent\'s row is then the item\'s only ' + + 'row at that address: the read naming no package serves it next, and a ' + + 'second delete naming no package removes it too; the base\'s copy comes ' + + 'back only by saving it again. The discard of the ' + '`draft` removes the draft a draft save naming no package writes, the ' + 'one the per-item publish naming none promotes, and is refused where ' + 'that publish is (see `PublishMetaItemRequestSchema.packageId`). That ' @@ -2653,7 +2674,11 @@ const HISTORY_PACKAGE_SELECTOR_DESCRIPTION = + 'holds nor ships the name is refused 409 `not-held-by-qualifier` (ADR-0150 D3/D4). ' + 'Versions attributed to no package, or to the environment, are that slot\'s only ' + 'while it is the name\'s sole slot. Absent, a name two holders hold (in stored rows ' - + 'or in code) is refused 409 naming every holder. Refused with 400 `VALIDATION_ERROR` ' + + 'or in code) is refused 409 naming every holder, except where the read naming no ' + + 'package serves the row-held base (a bundled type\'s member whose active rows a base ' + + 'package and a package declaring it both hold, with no package-unbound row beside ' + + 'them): there the base\'s slot is addressed, as naming the base addresses it. Two ' + + 'packages neither of which declares the other are still refused. Refused with 400 `VALIDATION_ERROR` ' + 'on a type not stored per (package, name).'; /**